lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
mit
4600f50b5e9e98c34448e90369615a4641970c09
0
2014-Android-ITX4/RollingBALL,2014-Android-ITX4/RollingBALL
package com.example.rollingball.app; import android.opengl.GLU; import android.util.Log; import com.hackoeur.jglm.Mat4; import com.hackoeur.jglm.Matrices; import com.hackoeur.jglm.Vec; import com.hackoeur.jglm.Vec3; import com.hackoeur.jglm.Vec4; public class StageCamera extends Camera { // プレイヤーゲームオブジェクトを基準に方位角θ、仰角φ、距離distanceを保持 private float _distance = 20.0f; //r private float _theta = 0.0f; //θ private float _phi = 0.0f; //φ // 最小 distance 、 最大 distance private final float _min_distance = 1.0f; private final float _max_distance = 30.0f; // プレイヤーゲームオブジェクトを保持しておく private PlayerGameObject _player_game_object = null; public StageCamera( final Scene scene ) { super( scene ); // この時点でプレイヤーゲームオブジェクトがあればセットする find_player_game_object(); } // プレイヤーゲームオブジェクトをシーンから探す private void find_player_game_object() { _player_game_object = null; for ( GameObject o : scene.game_objects ) if ( o instanceof PlayerGameObject ) _player_game_object = (PlayerGameObject)o; } @Override public void update( float delta_time_in_seconds ) { update_swipe( delta_time_in_seconds ); update_position(); // override 元の親クラスの update も呼んでおく super.update( delta_time_in_seconds ); } private void update_position() { // プレイヤーオブジェクトに対するカメラの位置差 final Vec3 delta_position = new Vec3 ( (float)Math.sin( _theta ) * (float)Math.cos( _phi ) , (float)Math.sin( _phi ) , (float)Math.cos( _theta ) * (float)Math.cos( _phi ) ).multiply( _distance ); //Log.d( "x","="+delta_position.getX() ); //Log.d( "y","="+delta_position.getY() ); Log.d("θ, φ", "" + _theta + " " + _phi + " " + delta_position.toString() ); // プレイヤーオブジェクトが未設定の可能性があるのでテスト if ( _player_game_object == null ) { find_player_game_object(); // なおも見つからない場合は例外投げて死ぬ if ( _player_game_object == null ) throw new NullPointerException( " this scene has not player game object." ); } // プレイヤー方向を向く look_at = _player_game_object.position; // カメラの視点位置をプレイヤーゲームオブジェクトを基準に軌道上の差分位置を加算して設定 eye = look_at.add( delta_position ); } private void update_swipe( float delta_time_in_seconds ) { Vec3 screen_size = new Vec3 ( scene.scene_manager.view.screen_width() , scene.scene_manager.view.screen_height() , 0.0f ); //Log.d( "screen size" , screen_size.toString() ); Vec3 dp = scene.scene_manager.view.activity.swipe_delta_position(); Vec3 rotation_ratio = new Vec3( dp.getX() / screen_size.getX(), dp.getY() / screen_size.getY(), 0.0f ); if ( Math.abs( dp.getX() ) > Math.abs( dp.getY() ) ) { final float rotation_magnifier = (float)Math.PI / 4.0f; _theta += rotation_magnifier * rotation_ratio.getX(); } else { final float rotation_magnifier = (float)Math.PI / 8.0f; _phi += rotation_magnifier * rotation_ratio.getY(); // ジンバルロックを回避とカメラのUP反転の対応として仰角を制限します。 final float phi_min = -(float)Math.PI * 0.5f * 0.98f; final float phi_max = +(float)Math.PI * 0.5f * 0.98f; _phi = Math.min( Math.max( _phi, phi_min ), phi_max ); } //Log.d("θ, φ", "" + _theta + " " + _phi); scene.scene_manager.view.activity.attenuate_swipe_state(); //scene.scene_manager.view.activity.reset_swipe_state(); } // distance を一定値範囲内だけで設定可能とするためのプロパティーセッターアクセサー public float distance( float value ) { return _distance = Math.min( Math.max( value, _min_distance ), _max_distance ); } public float distance() { return _distance; } public float theta( float value ) { return _theta = value; } public float theta() { return _theta; } public float phi( float value ) { return _phi = value; } public float phi() { return _phi; } }
app/src/main/java/com/example/rollingball/app/StageCamera.java
package com.example.rollingball.app; import android.opengl.GLU; import android.util.Log; import com.hackoeur.jglm.Mat4; import com.hackoeur.jglm.Matrices; import com.hackoeur.jglm.Vec; import com.hackoeur.jglm.Vec3; import com.hackoeur.jglm.Vec4; public class StageCamera extends Camera { // プレイヤーゲームオブジェクトを基準に方位角θ、仰角φ、距離distanceを保持 private float _distance = 20.0f; //r private float _theta = 0.0f; //θ private float _phi = 0.0f; //φ // 最小 distance 、 最大 distance private final float _min_distance = 1.0f; private final float _max_distance = 30.0f; // プレイヤーゲームオブジェクトを保持しておく private PlayerGameObject _player_game_object = null; public StageCamera( final Scene scene ) { super( scene ); // この時点でプレイヤーゲームオブジェクトがあればセットする find_player_game_object(); } // プレイヤーゲームオブジェクトをシーンから探す private void find_player_game_object() { _player_game_object = null; for ( GameObject o : scene.game_objects ) if ( o instanceof PlayerGameObject ) _player_game_object = (PlayerGameObject)o; } @Override public void update( float delta_time_in_seconds ) { update_swipe( delta_time_in_seconds ); update_position(); // override 元の親クラスの update も呼んでおく super.update( delta_time_in_seconds ); } private void update_position() { // プレイヤーオブジェクトに対するカメラの位置差 //* final Vec3 delta_position = new Vec3 ( (float)Math.sin( _theta ) * (float)Math.cos( _phi ) , (float)Math.sin( _phi ) , (float)Math.cos( _theta ) * (float)Math.cos( _phi ) ).multiply( _distance ); //*/ //Log.d( "x","="+delta_position.getX() ); //Log.d( "y","="+delta_position.getY() ); Log.d("θ, φ", "" + _theta + " " + _phi + " " + delta_position.toString() ); // プレイヤーオブジェクトが未設定の可能性があるのでテスト if ( _player_game_object == null ) { find_player_game_object(); // なおも見つからない場合は例外投げて死ぬ if ( _player_game_object == null ) throw new NullPointerException( " this scene has not player game object." ); } // プレイヤー方向を向く look_at = _player_game_object.position; // カメラの視点位置をプレイヤーゲームオブジェクトを基準に軌道上の差分位置を加算して設定 eye = look_at.add( delta_position ); } private void update_swipe( float delta_time_in_seconds ) { Vec3 screen_size = new Vec3 ( scene.scene_manager.view.screen_width() , scene.scene_manager.view.screen_height() , 0.0f ); //Log.d( "screen size" , screen_size.toString() ); Vec3 dp = scene.scene_manager.view.activity.swipe_delta_position(); Vec3 rotation_ratio = new Vec3( dp.getX() / screen_size.getX(), dp.getY() / screen_size.getY(), 0.0f ); if ( Math.abs( dp.getX() ) > Math.abs( dp.getY() ) ) { final float rotation_magnifier = (float)Math.PI / 4.0f; _theta += rotation_magnifier * rotation_ratio.getX(); } else { final float rotation_magnifier = (float)Math.PI / 8.0f; _phi += rotation_magnifier * rotation_ratio.getY(); // ジンバルロックを回避とカメラのUP反転の対応として仰角を制限します。 final float phi_min = -(float)Math.PI * 0.5f * 0.98f; final float phi_max = +(float)Math.PI * 0.5f * 0.98f; _phi = Math.min( Math.max( _phi, phi_min ), phi_max ); } //Log.d("θ, φ", "" + _theta + " " + _phi); scene.scene_manager.view.activity.attenuate_swipe_state(); //scene.scene_manager.view.activity.reset_swipe_state(); } // distance を一定値範囲内だけで設定可能とするためのプロパティーセッターアクセサー public float distance( float value ) { return _distance = Math.min( Math.max( value, _min_distance ), _max_distance ); } public float distance() { return _distance; } public float theta( float value ) { return _theta = value; } public float theta() { return _theta; } public float phi( float value ) { return _phi = value; } public float phi() { return _phi; } }
コメント修正
app/src/main/java/com/example/rollingball/app/StageCamera.java
コメント修正
<ide><path>pp/src/main/java/com/example/rollingball/app/StageCamera.java <ide> private void update_position() <ide> { <ide> // プレイヤーオブジェクトに対するカメラの位置差 <del> //* <ide> final Vec3 delta_position = new Vec3 <ide> ( (float)Math.sin( _theta ) * (float)Math.cos( _phi ) <ide> , (float)Math.sin( _phi ) <ide> , (float)Math.cos( _theta ) * (float)Math.cos( _phi ) <ide> ).multiply( _distance ); <del> //*/ <ide> //Log.d( "x","="+delta_position.getX() ); <ide> //Log.d( "y","="+delta_position.getY() ); <ide>
Java
apache-2.0
ff31d571790b97cc9ddd1174b53f6f46307f71ad
0
1haodian/eagle,yonzhang/incubator-eagle,haoch/incubator-eagle,haoch/incubator-eagle,yonzhang/incubator-eagle,anyway1021/incubator-eagle,haoch/Eagle,haoch/incubator-eagle,1haodian/eagle,haoch/incubator-eagle,qingwen220/eagle,haoch/Eagle,zombieJ/incubator-eagle,qingwen220/eagle,yonzhang/incubator-eagle,yonzhang/incubator-eagle,yonzhang/incubator-eagle,baibaichen/eagle,haoch/Eagle,zombieJ/incubator-eagle,1haodian/eagle,haoch/incubator-eagle,baibaichen/eagle,zombieJ/incubator-eagle,anyway1021/incubator-eagle,anyway1021/incubator-eagle,1haodian/eagle,anyway1021/incubator-eagle,baibaichen/eagle,anyway1021/incubator-eagle,haoch/incubator-eagle,qingwen220/eagle,qingwen220/eagle,baibaichen/eagle,anyway1021/incubator-eagle,haoch/Eagle,1haodian/eagle,zombieJ/incubator-eagle,qingwen220/eagle,haoch/Eagle,baibaichen/eagle,zombieJ/incubator-eagle
/* * * * 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 * * <p/> * * http://www.apache.org/licenses/LICENSE-2.0 * * <p/> * * 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.eagle.security.auditlog; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichBolt; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import org.apache.eagle.security.hdfs.MAPRFSAuditLogObject; import org.apache.eagle.security.hdfs.MAPRFSAuditLogParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.Map; import java.util.TreeMap; /** * Since 8/11/16. */ public class MapRFSAuditLogParserBolt extends BaseRichBolt { private static Logger LOG = LoggerFactory.getLogger(MapRFSAuditLogParserBolt.class); private OutputCollector collector; @Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { this.collector = collector; } @Override public void execute(Tuple input) { String logLine = input.getString(0); MAPRFSAuditLogParser parser = new MAPRFSAuditLogParser(); MAPRFSAuditLogObject entity = null; try { entity = parser.parse(logLine); Map<String, Object> map = new TreeMap<String, Object>(); map.put("src", entity.src); map.put("dst", entity.dst); map.put("host", entity.host); map.put("timestamp", entity.timestamp); map.put("status", entity.status); map.put("user", entity.user); map.put("cmd", entity.cmd); map.put("volume", entity.volume); collector.emit(Arrays.asList(map)); } catch (Exception ex) { LOG.error("Failing parse audit log message", ex); } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("f1")); } }
eagle-security/eagle-security-maprfs-auditlog/src/main/java/org/apache/eagle/security/auditlog/MapRFSAuditLogParserBolt.java
/* * * * 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 * * <p/> * * http://www.apache.org/licenses/LICENSE-2.0 * * <p/> * * 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.eagle.security.auditlog; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichBolt; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import org.apache.eagle.security.hdfs.MAPRFSAuditLogObject; import org.apache.eagle.security.hdfs.MAPRFSAuditLogParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.Map; import java.util.TreeMap; /** * Since 8/11/16. */ public class MapRFSAuditLogParserBolt extends BaseRichBolt { private static Logger LOG = LoggerFactory.getLogger(HdfsAuditLogParserBolt.class); private OutputCollector collector; @Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { this.collector = collector; } @Override public void execute(Tuple input) { String logLine = input.getString(0); MAPRFSAuditLogParser parser = new MAPRFSAuditLogParser(); MAPRFSAuditLogObject entity = null; try { entity = parser.parse(logLine); Map<String, Object> map = new TreeMap<String, Object>(); map.put("src", entity.src); map.put("dst", entity.dst); map.put("host", entity.host); map.put("timestamp", entity.timestamp); map.put("status", entity.status); map.put("user", entity.user); map.put("cmd", entity.cmd); map.put("volume", entity.volume); collector.emit(Arrays.asList(map)); } catch (Exception ex) { LOG.error("Failing parse audit log message", ex); } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("f1")); } }
[EAGLE-865] correcting logger class for MapRFSAuditLogParserBolt.java Author: Jay <[email protected]> Closes #777 from jhsenjaliya/EAGLE-865.
eagle-security/eagle-security-maprfs-auditlog/src/main/java/org/apache/eagle/security/auditlog/MapRFSAuditLogParserBolt.java
[EAGLE-865] correcting logger class for MapRFSAuditLogParserBolt.java
<ide><path>agle-security/eagle-security-maprfs-auditlog/src/main/java/org/apache/eagle/security/auditlog/MapRFSAuditLogParserBolt.java <ide> * Since 8/11/16. <ide> */ <ide> public class MapRFSAuditLogParserBolt extends BaseRichBolt { <del> private static Logger LOG = LoggerFactory.getLogger(HdfsAuditLogParserBolt.class); <add> private static Logger LOG = LoggerFactory.getLogger(MapRFSAuditLogParserBolt.class); <ide> private OutputCollector collector; <ide> <ide> @Override
Java
apache-2.0
a36a19b1cc994a57b5a5092b005dc1bffec635ad
0
vivosys/orientdb,vivosys/orientdb,nengxu/OrientDB,nengxu/OrientDB,vivosys/orientdb,nengxu/OrientDB,nengxu/OrientDB,vivosys/orientdb
/* * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) * * 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.orientechnologies.orient.core.serialization.serializer.stream; import java.io.IOException; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.common.util.OArrays; import com.orientechnologies.orient.core.exception.OSerializationException; import com.orientechnologies.orient.core.serialization.OBinaryProtocol; import com.orientechnologies.orient.core.serialization.OSerializableStream; import com.orientechnologies.orient.core.sql.OCommandSQL; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; public class OStreamSerializerAnyStreamable implements OStreamSerializer { public static final OStreamSerializerAnyStreamable INSTANCE = new OStreamSerializerAnyStreamable(); public static final String NAME = "at"; /** * Re-Create any object if the class has a public constructor that accepts a String as unique parameter. */ public Object fromStream(final byte[] iStream) throws IOException { if (iStream == null || iStream.length == 0) // NULL VALUE return null; final int classNameSize = OBinaryProtocol.bytes2int(iStream); if (classNameSize <= 0) OLogManager.instance().error(this, "Class signature not found in ANY element: " + iStream, OSerializationException.class); final String className = OBinaryProtocol.bytes2string(iStream, 4, classNameSize); try { final OSerializableStream stream; // CHECK FOR ALIASES if (className.equalsIgnoreCase("q")) // QUERY stream = new OSQLSynchQuery<Object>(); else if (className.equalsIgnoreCase("c")) // SQL COMMAND stream = new OCommandSQL(); else // CREATE THE OBJECT BY INVOKING THE EMPTY CONSTRUCTOR stream = (OSerializableStream) Class.forName(className).newInstance(); return stream.fromStream(OArrays.copyOfRange(iStream, 4 + classNameSize, iStream.length)); } catch (Exception e) { OLogManager.instance().error(this, "Error on unmarshalling content. Class: " + className, e, OSerializationException.class); } return null; } /** * Serialize the class name size + class name + object content */ public byte[] toStream(final Object iObject) throws IOException { if (iObject == null) return null; if (!(iObject instanceof OSerializableStream)) throw new OSerializationException("Cannot serialize the object [" + iObject.getClass() + ":" + iObject + "] since it does not implement the OSerializableStream interface"); OSerializableStream stream = (OSerializableStream) iObject; // SERIALIZE THE CLASS NAME byte[] className = OBinaryProtocol.string2bytes(iObject.getClass().getName()); // SERIALIZE THE OBJECT CONTENT byte[] objectContent = stream.toStream(); byte[] result = new byte[4 + className.length + objectContent.length]; // COPY THE CLASS NAME SIZE + CLASS NAME + OBJECT CONTENT System.arraycopy(OBinaryProtocol.int2bytes(className.length), 0, result, 0, 4); System.arraycopy(className, 0, result, 4, className.length); System.arraycopy(objectContent, 0, result, 4 + className.length, objectContent.length); return result; } public String getName() { return NAME; } }
core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/stream/OStreamSerializerAnyStreamable.java
/* * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) * * 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.orientechnologies.orient.core.serialization.serializer.stream; import java.io.IOException; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.common.util.OArrays; import com.orientechnologies.orient.core.exception.OSerializationException; import com.orientechnologies.orient.core.serialization.OBinaryProtocol; import com.orientechnologies.orient.core.serialization.OSerializableStream; public class OStreamSerializerAnyStreamable implements OStreamSerializer { public static final OStreamSerializerAnyStreamable INSTANCE = new OStreamSerializerAnyStreamable(); public static final String NAME = "at"; /** * Re-Create any object if the class has a public constructor that accepts a String as unique parameter. */ public Object fromStream(final byte[] iStream) throws IOException { if (iStream == null || iStream.length == 0) // NULL VALUE return null; final int classNameSize = OBinaryProtocol.bytes2int(iStream); if (classNameSize <= 0) OLogManager.instance().error(this, "Class signature not found in ANY element: " + iStream, OSerializationException.class); final String className = OBinaryProtocol.bytes2string(iStream, 4, classNameSize); try { Class<?> clazz = Class.forName(className); // CREATE THE OBJECT BY INVOKING THE EMPTY CONSTRUCTOR OSerializableStream stream = (OSerializableStream) clazz.newInstance(); return stream.fromStream(OArrays.copyOfRange(iStream, 4 + classNameSize, iStream.length)); } catch (Exception e) { OLogManager.instance().error(this, "Error on unmarshalling content. Class: " + className, e, OSerializationException.class); } return null; } /** * Serialize the class name size + class name + object content */ public byte[] toStream(final Object iObject) throws IOException { if (iObject == null) return null; if (!(iObject instanceof OSerializableStream)) throw new OSerializationException("Cannot serialize the object [" + iObject.getClass() + ":" + iObject + "] since it does not implement the OSerializableStream interface"); OSerializableStream stream = (OSerializableStream) iObject; // SERIALIZE THE CLASS NAME byte[] className = OBinaryProtocol.string2bytes(iObject.getClass().getName()); // SERIALIZE THE OBJECT CONTENT byte[] objectContent = stream.toStream(); byte[] result = new byte[4 + className.length + objectContent.length]; // COPY THE CLASS NAME SIZE + CLASS NAME + OBJECT CONTENT System.arraycopy(OBinaryProtocol.int2bytes(className.length), 0, result, 0, 4); System.arraycopy(className, 0, result, 4, className.length); System.arraycopy(objectContent, 0, result, 4 + className.length, objectContent.length); return result; } public String getName() { return NAME; } }
Implemented aliases on remote command in binary protocol as asked by Anton in ML: - "q" for query (class com.orientechnologies.orient.core.sql.query.OSQLSynchQuery) - "c" for sql command (class com.orientechnologies.orient.core.sql.OCommandSQL) old mode is always supported. git-svn-id: 9ddf022f45b579842a47abc018ed2b18cdc52108@4835 3625ad7b-9c83-922f-a72b-73d79161f2ea
core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/stream/OStreamSerializerAnyStreamable.java
Implemented aliases on remote command in binary protocol as asked by Anton in ML: - "q" for query (class com.orientechnologies.orient.core.sql.query.OSQLSynchQuery) - "c" for sql command (class com.orientechnologies.orient.core.sql.OCommandSQL) old mode is always supported.
<ide><path>ore/src/main/java/com/orientechnologies/orient/core/serialization/serializer/stream/OStreamSerializerAnyStreamable.java <ide> import com.orientechnologies.orient.core.exception.OSerializationException; <ide> import com.orientechnologies.orient.core.serialization.OBinaryProtocol; <ide> import com.orientechnologies.orient.core.serialization.OSerializableStream; <add>import com.orientechnologies.orient.core.sql.OCommandSQL; <add>import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; <ide> <ide> public class OStreamSerializerAnyStreamable implements OStreamSerializer { <ide> public static final OStreamSerializerAnyStreamable INSTANCE = new OStreamSerializerAnyStreamable(); <ide> final String className = OBinaryProtocol.bytes2string(iStream, 4, classNameSize); <ide> <ide> try { <del> Class<?> clazz = Class.forName(className); <del> <del> // CREATE THE OBJECT BY INVOKING THE EMPTY CONSTRUCTOR <del> OSerializableStream stream = (OSerializableStream) clazz.newInstance(); <add> final OSerializableStream stream; <add> // CHECK FOR ALIASES <add> if (className.equalsIgnoreCase("q")) <add> // QUERY <add> stream = new OSQLSynchQuery<Object>(); <add> else if (className.equalsIgnoreCase("c")) <add> // SQL COMMAND <add> stream = new OCommandSQL(); <add> else <add> // CREATE THE OBJECT BY INVOKING THE EMPTY CONSTRUCTOR <add> stream = (OSerializableStream) Class.forName(className).newInstance(); <ide> <ide> return stream.fromStream(OArrays.copyOfRange(iStream, 4 + classNameSize, iStream.length)); <ide>
Java
apache-2.0
f97bf36ef9384d66e6186c6244251e7d7a912be2
0
b-cuts/android-maven-plugin,ashutoshbhide/android-maven-plugin,jdegroot/android-maven-plugin,Cha0sX/android-maven-plugin,simpligility/android-maven-plugin,kedzie/maven-android-plugin,Stuey86/android-maven-plugin,mitchhentges/android-maven-plugin,repanda/android-maven-plugin,xieningtao/android-maven-plugin,hgl888/android-maven-plugin,b-cuts/android-maven-plugin,psorobka/android-maven-plugin,kedzie/maven-android-plugin,Cha0sX/android-maven-plugin,greek1979/maven-android-plugin,wskplho/android-maven-plugin,psorobka/android-maven-plugin,xiaojiaqiao/android-maven-plugin,Cha0sX/android-maven-plugin,mitchhentges/android-maven-plugin,ashutoshbhide/android-maven-plugin,secondsun/maven-android-plugin,WonderCsabo/maven-android-plugin,CJstar/android-maven-plugin,secondsun/maven-android-plugin,CJstar/android-maven-plugin,Stuey86/android-maven-plugin,wskplho/android-maven-plugin,hgl888/android-maven-plugin,jdegroot/android-maven-plugin,xiaojiaqiao/android-maven-plugin,WonderCsabo/maven-android-plugin,secondsun/maven-android-plugin,xiaojiaqiao/android-maven-plugin,repanda/android-maven-plugin,greek1979/maven-android-plugin,xieningtao/android-maven-plugin
/******************************************************************************* * Copyright (c) 2008, 2011 Sonatype 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: * Sonatype Inc. - initial API and implementation *******************************************************************************/ package com.jayway.maven.plugins.android.common; import com.android.SdkConstants; import com.google.common.io.PatternFilenameFilter; import com.jayway.maven.plugins.android.phase09package.AarMojo; import com.jayway.maven.plugins.android.phase09package.ApklibMojo; import org.apache.commons.io.FileUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.UnArchiver; import org.codehaus.plexus.archiver.zip.ZipUnArchiver; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.logging.console.ConsoleLogger; import java.io.File; import java.io.IOException; import static com.jayway.maven.plugins.android.common.AndroidExtension.AAR; import static com.jayway.maven.plugins.android.common.AndroidExtension.APK; /** * Provides convenience methods for unpacking Android libraries so that their contents can be used in the build. */ public final class UnpackedLibHelper { private final ArtifactResolverHelper artifactResolverHelper; private final Logger log; // ${project.build.directory}/unpacked-libs private final File unpackedLibsDirectory; public UnpackedLibHelper( ArtifactResolverHelper artifactResolverHelper, MavenProject project, Logger log ) { this.artifactResolverHelper = artifactResolverHelper; final File targetFolder = new File( project.getBasedir(), project.getBuild().getDirectory() ); this.unpackedLibsDirectory = new File( targetFolder, "unpacked-libs" ); this.log = log; } public void extractApklib( Artifact apklibArtifact ) throws MojoExecutionException { final File apkLibFile = artifactResolverHelper.resolveArtifactToFile( apklibArtifact ); if ( apkLibFile.isDirectory() ) { log.warn( "The apklib artifact points to '" + apkLibFile + "' which is a directory; skipping unpacking it." ); return; } final UnArchiver unArchiver = new ZipUnArchiver( apkLibFile ) { @Override protected Logger getLogger() { return new ConsoleLogger( log.getThreshold(), "dependencies-unarchiver" ); } }; final File apklibDirectory = getUnpackedLibFolder( apklibArtifact ); apklibDirectory.mkdirs(); unArchiver.setDestDirectory( apklibDirectory ); log.debug( "Extracting APKLIB to " + apklibDirectory ); try { unArchiver.extract(); } catch ( ArchiverException e ) { throw new MojoExecutionException( "ArchiverException while extracting " + apklibDirectory + ". Message: " + e.getLocalizedMessage(), e ); } } public void extractAarLib( Artifact aarArtifact ) throws MojoExecutionException { final File aarFile = artifactResolverHelper.resolveArtifactToFile( aarArtifact ); if ( aarFile.isDirectory() ) { log.warn( "The aar artifact points to '" + aarFile + "' which is a directory; skipping unpacking it." ); return; } final UnArchiver unArchiver = new ZipUnArchiver( aarFile ) { @Override protected Logger getLogger() { return new ConsoleLogger( log.getThreshold(), "dependencies-unarchiver" ); } }; final File aarDirectory = getUnpackedLibFolder( aarArtifact ); aarDirectory.mkdirs(); unArchiver.setDestDirectory( aarDirectory ); log.debug( "Extracting AAR to " + aarDirectory ); try { unArchiver.extract(); } catch ( ArchiverException e ) { throw new MojoExecutionException( "ArchiverException while extracting " + aarDirectory.getAbsolutePath() + ". Message: " + e.getLocalizedMessage(), e ); } // Move native libraries from libs to jni folder for legacy AARs. // This ensures backward compatibility with older AARs where libs are in "libs" folder. final File jniFolder = new File( aarDirectory, AarMojo.NATIVE_LIBRARIES_FOLDER ); final File libsFolder = new File( aarDirectory, ApklibMojo.NATIVE_LIBRARIES_FOLDER ); if ( !jniFolder.exists() && libsFolder.isDirectory() && libsFolder.exists() ) { String[] natives = libsFolder.list( new PatternFilenameFilter( "^.*(?<!(?i)\\.jar)$" ) ); if ( natives.length > 0 ) { log.debug( "Moving AAR native libraries from libs to jni folder" ); for ( String nativeLibPath : natives ) { try { FileUtils.moveToDirectory( new File( libsFolder, nativeLibPath ), jniFolder, true ); } catch ( IOException e ) { throw new MojoExecutionException( "Could not move native libraries from " + libsFolder, e ); } } } } } public File getArtifactToFile( Artifact artifact ) throws MojoExecutionException { final File artifactFile = artifactResolverHelper.resolveArtifactToFile( artifact ); return artifactFile; } public File getUnpackedLibsFolder() { return unpackedLibsDirectory; } public File getUnpackedLibFolder( Artifact artifact ) { return new File( unpackedLibsDirectory.getAbsolutePath(), getShortenedGroupId( artifact.getGroupId() ) + "_" + artifact.getArtifactId() ); } public File getUnpackedClassesJar( Artifact artifact ) { return new File( getUnpackedLibFolder( artifact ), SdkConstants.FN_CLASSES_JAR ); } public File getUnpackedApkLibSourceFolder( Artifact artifact ) { return new File( getUnpackedLibFolder( artifact ), "src" ); } public File getUnpackedLibResourceFolder( Artifact artifact ) { return new File( getUnpackedLibFolder( artifact ), "res" ); } public File getUnpackedLibAssetsFolder( Artifact artifact ) { return new File( getUnpackedLibFolder( artifact ), "assets" ); } /** * @param artifact Android dependency that is being referenced. * @return Folder where the unpacked native libraries are located. * @see http://tools.android.com/tech-docs/new-build-system/aar-format */ public File getUnpackedLibNativesFolder( Artifact artifact ) { if ( AAR.equals( artifact.getType() ) ) { return new File( getUnpackedLibFolder( artifact ), AarMojo.NATIVE_LIBRARIES_FOLDER ); } else { return new File( getUnpackedLibFolder( artifact ), ApklibMojo.NATIVE_LIBRARIES_FOLDER ); } } public File getJarFileForApk( Artifact artifact ) { final String fileName = artifact.getFile().getName(); final String modifiedFileName = fileName.substring( 0, fileName.lastIndexOf( "." ) ) + ".jar"; return new File( artifact.getFile().getParentFile(), modifiedFileName ); } /** * @param groupId An a dot separated groupId (eg org.apache.maven) * @return A shortened (and potentially non-unique) version of the groupId, that consists of the first letter * of each part of the groupId. Eg oam for org.apache.maven */ private String getShortenedGroupId( String groupId ) { final String[] parts = groupId.split( "\\." ); final StringBuilder sb = new StringBuilder(); for ( final String part : parts ) { sb.append( part.charAt( 0 ) ); } return sb.toString(); } /** * @return True if this project constructs an APK as opposed to an AAR or APKLIB. */ public boolean isAPKBuild( MavenProject project ) { return APK.equals( project.getPackaging() ); } }
src/main/java/com/jayway/maven/plugins/android/common/UnpackedLibHelper.java
/******************************************************************************* * Copyright (c) 2008, 2011 Sonatype 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: * Sonatype Inc. - initial API and implementation *******************************************************************************/ package com.jayway.maven.plugins.android.common; import com.android.SdkConstants; import com.google.common.io.PatternFilenameFilter; import com.jayway.maven.plugins.android.phase09package.AarMojo; import com.jayway.maven.plugins.android.phase09package.ApklibMojo; import org.apache.commons.io.FileUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.UnArchiver; import org.codehaus.plexus.archiver.zip.ZipUnArchiver; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.logging.console.ConsoleLogger; import java.io.File; import java.io.IOException; import static com.jayway.maven.plugins.android.common.AndroidExtension.AAR; import static com.jayway.maven.plugins.android.common.AndroidExtension.APK; /** * Provides convenience methods for unpacking Android libraries so that their contents can be used in the build. */ public final class UnpackedLibHelper { private final ArtifactResolverHelper artifactResolverHelper; private final Logger log; // ${project.build.directory}/unpacked-libs private final File unpackedLibsDirectory; public UnpackedLibHelper( ArtifactResolverHelper artifactResolverHelper, MavenProject project, Logger log ) { this.artifactResolverHelper = artifactResolverHelper; final File targetFolder = new File( project.getBasedir(), "target" ); this.unpackedLibsDirectory = new File( targetFolder, "unpacked-libs" ); this.log = log; } public void extractApklib( Artifact apklibArtifact ) throws MojoExecutionException { final File apkLibFile = artifactResolverHelper.resolveArtifactToFile( apklibArtifact ); if ( apkLibFile.isDirectory() ) { log.warn( "The apklib artifact points to '" + apkLibFile + "' which is a directory; skipping unpacking it." ); return; } final UnArchiver unArchiver = new ZipUnArchiver( apkLibFile ) { @Override protected Logger getLogger() { return new ConsoleLogger( log.getThreshold(), "dependencies-unarchiver" ); } }; final File apklibDirectory = getUnpackedLibFolder( apklibArtifact ); apklibDirectory.mkdirs(); unArchiver.setDestDirectory( apklibDirectory ); log.debug( "Extracting APKLIB to " + apklibDirectory ); try { unArchiver.extract(); } catch ( ArchiverException e ) { throw new MojoExecutionException( "ArchiverException while extracting " + apklibDirectory + ". Message: " + e.getLocalizedMessage(), e ); } } public void extractAarLib( Artifact aarArtifact ) throws MojoExecutionException { final File aarFile = artifactResolverHelper.resolveArtifactToFile( aarArtifact ); if ( aarFile.isDirectory() ) { log.warn( "The aar artifact points to '" + aarFile + "' which is a directory; skipping unpacking it." ); return; } final UnArchiver unArchiver = new ZipUnArchiver( aarFile ) { @Override protected Logger getLogger() { return new ConsoleLogger( log.getThreshold(), "dependencies-unarchiver" ); } }; final File aarDirectory = getUnpackedLibFolder( aarArtifact ); aarDirectory.mkdirs(); unArchiver.setDestDirectory( aarDirectory ); log.debug( "Extracting AAR to " + aarDirectory ); try { unArchiver.extract(); } catch ( ArchiverException e ) { throw new MojoExecutionException( "ArchiverException while extracting " + aarDirectory.getAbsolutePath() + ". Message: " + e.getLocalizedMessage(), e ); } // Move native libraries from libs to jni folder for legacy AARs. // This ensures backward compatibility with older AARs where libs are in "libs" folder. final File jniFolder = new File( aarDirectory, AarMojo.NATIVE_LIBRARIES_FOLDER ); final File libsFolder = new File( aarDirectory, ApklibMojo.NATIVE_LIBRARIES_FOLDER ); if ( !jniFolder.exists() && libsFolder.isDirectory() && libsFolder.exists() ) { String[] natives = libsFolder.list( new PatternFilenameFilter( "^.*(?<!(?i)\\.jar)$" ) ); if ( natives.length > 0 ) { log.debug( "Moving AAR native libraries from libs to jni folder" ); for ( String nativeLibPath : natives ) { try { FileUtils.moveToDirectory( new File( libsFolder, nativeLibPath ), jniFolder, true ); } catch ( IOException e ) { throw new MojoExecutionException( "Could not move native libraries from " + libsFolder, e ); } } } } } public File getArtifactToFile( Artifact artifact ) throws MojoExecutionException { final File artifactFile = artifactResolverHelper.resolveArtifactToFile( artifact ); return artifactFile; } public File getUnpackedLibsFolder() { return unpackedLibsDirectory; } public File getUnpackedLibFolder( Artifact artifact ) { return new File( unpackedLibsDirectory.getAbsolutePath(), getShortenedGroupId( artifact.getGroupId() ) + "_" + artifact.getArtifactId() ); } public File getUnpackedClassesJar( Artifact artifact ) { return new File( getUnpackedLibFolder( artifact ), SdkConstants.FN_CLASSES_JAR ); } public File getUnpackedApkLibSourceFolder( Artifact artifact ) { return new File( getUnpackedLibFolder( artifact ), "src" ); } public File getUnpackedLibResourceFolder( Artifact artifact ) { return new File( getUnpackedLibFolder( artifact ), "res" ); } public File getUnpackedLibAssetsFolder( Artifact artifact ) { return new File( getUnpackedLibFolder( artifact ), "assets" ); } /** * @param artifact Android dependency that is being referenced. * @return Folder where the unpacked native libraries are located. * @see http://tools.android.com/tech-docs/new-build-system/aar-format */ public File getUnpackedLibNativesFolder( Artifact artifact ) { if ( AAR.equals( artifact.getType() ) ) { return new File( getUnpackedLibFolder( artifact ), AarMojo.NATIVE_LIBRARIES_FOLDER ); } else { return new File( getUnpackedLibFolder( artifact ), ApklibMojo.NATIVE_LIBRARIES_FOLDER ); } } public File getJarFileForApk( Artifact artifact ) { final String fileName = artifact.getFile().getName(); final String modifiedFileName = fileName.substring( 0, fileName.lastIndexOf( "." ) ) + ".jar"; return new File( artifact.getFile().getParentFile(), modifiedFileName ); } /** * @param groupId An a dot separated groupId (eg org.apache.maven) * @return A shortened (and potentially non-unique) version of the groupId, that consists of the first letter * of each part of the groupId. Eg oam for org.apache.maven */ private String getShortenedGroupId( String groupId ) { final String[] parts = groupId.split( "\\." ); final StringBuilder sb = new StringBuilder(); for ( final String part : parts ) { sb.append( part.charAt( 0 ) ); } return sb.toString(); } /** * @return True if this project constructs an APK as opposed to an AAR or APKLIB. */ public boolean isAPKBuild( MavenProject project ) { return APK.equals( project.getPackaging() ); } }
use the maven "project.build.directory" instead of hardcode "target"
src/main/java/com/jayway/maven/plugins/android/common/UnpackedLibHelper.java
use the maven "project.build.directory" instead of hardcode "target"
<ide><path>rc/main/java/com/jayway/maven/plugins/android/common/UnpackedLibHelper.java <ide> public UnpackedLibHelper( ArtifactResolverHelper artifactResolverHelper, MavenProject project, Logger log ) <ide> { <ide> this.artifactResolverHelper = artifactResolverHelper; <del> final File targetFolder = new File( project.getBasedir(), "target" ); <add> final File targetFolder = new File( project.getBasedir(), project.getBuild().getDirectory() ); <ide> this.unpackedLibsDirectory = new File( targetFolder, "unpacked-libs" ); <ide> this.log = log; <ide> }
Java
mit
b1efad440a30ae08fa7bc27b9af561c3f3ac6fd6
0
ONSdigital/babbage,ONSdigital/babbage,ONSdigital/babbage,ONSdigital/babbage
package com.github.onsdigital.data; import com.github.onsdigital.content.DirectoryListing; import com.github.onsdigital.content.page.base.Page; import com.github.onsdigital.content.service.ContentNotFoundException; import com.github.onsdigital.content.util.ContentUtil; import com.github.onsdigital.data.zebedee.ZebedeeDataService; import com.github.onsdigital.data.zebedee.ZebedeeRequest; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; /** * Route data requests to zebedee if required, else read from the local filesystem. */ public class DataService { private static DataService instance = new DataService(); private DataService() { } public static DataService getInstance() { return instance; } public InputStream readData(String uri, boolean resolveReferences, ZebedeeRequest zebedeeRequest) throws ContentNotFoundException, IOException { if (zebedeeRequest != null) { return ZebedeeDataService.getInstance().readData(uri, zebedeeRequest, resolveReferences); } if (resolveReferences) { try { Page page = readAsPage(uri, true, zebedeeRequest); return IOUtils.toInputStream(page.toJson()); } catch (IOException e) { e.printStackTrace(); } } else { return LocalFileDataService.getInstance().readData(uri); } throw new DataNotFoundException(uri); } public Page readAsPage(String uri, boolean resolveReferences, ZebedeeRequest zebedeeRequest) throws IOException, ContentNotFoundException { if (zebedeeRequest != null) { return ContentUtil.deserialisePage(ZebedeeDataService.getInstance().readData(uri, zebedeeRequest, resolveReferences)); } else { Page page = ContentUtil.deserialisePage(LocalFileDataService.getInstance().readData(uri)); if (resolveReferences) { page.loadReferences(LocalFileDataService.getInstance()); } return page; } } public DirectoryListing readDirectory(String uri, ZebedeeRequest zebedeeRequest) throws ContentNotFoundException { if (zebedeeRequest != null) { return ZebedeeDataService.getInstance().readDirectory(uri, zebedeeRequest); } return LocalFileDataService.getInstance().readDirectory(uri); } }
src/main/java/com/github/onsdigital/data/DataService.java
package com.github.onsdigital.data; import com.github.onsdigital.content.DirectoryListing; import com.github.onsdigital.content.page.base.Page; import com.github.onsdigital.content.service.ContentNotFoundException; import com.github.onsdigital.content.util.ContentUtil; import com.github.onsdigital.data.zebedee.ZebedeeClient; import com.github.onsdigital.data.zebedee.ZebedeeDataService; import com.github.onsdigital.data.zebedee.ZebedeeRequest; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; /** * Route data requests to zebedee if required, else read from the local filesystem. */ public class DataService { private static DataService instance = new DataService(); private DataService() { } public static DataService getInstance() { return instance; } public InputStream readData(String uri, boolean resolveReferences, ZebedeeRequest zebedeeRequest) throws ContentNotFoundException, IOException { if (zebedeeRequest != null) { return ZebedeeDataService.getInstance().readData(uri, zebedeeRequest, resolveReferences); } if (resolveReferences) { try { Page page = readAsPage(uri, true, zebedeeRequest); return IOUtils.toInputStream(page.toJson()); } catch (IOException e) { e.printStackTrace(); } } else { return LocalFileDataService.getInstance().readData(uri); } throw new DataNotFoundException(uri); } public Page readAsPage(String uri, boolean resolveReferences, ZebedeeRequest zebedeeRequest) throws IOException, ContentNotFoundException { if (zebedeeRequest != null) { return ContentUtil.deserialisePage(ZebedeeDataService.getInstance().readData(uri, zebedeeRequest, resolveReferences)); } else { Page page = ContentUtil.deserialisePage(LocalFileDataService.getInstance().readData(uri)); if (resolveReferences) { page.loadReferences(LocalFileDataService.getInstance()); } return page; } } public DirectoryListing readDirectory(String uri, ZebedeeRequest zebedeeRequest) throws ContentNotFoundException { // make request to browse api ZebedeeClient zebedeeClient = new ZebedeeClient(zebedeeRequest); DirectoryListing directoryListing; try { directoryListing = ContentUtil.deserialise(zebedeeClient.get("browse", uri, false), DirectoryListing.class); } finally { zebedeeClient.closeConnection(); } return directoryListing; } }
Fix previous releases page. Read directory contents from zebedee if its a zebedee request else read from local file system.
src/main/java/com/github/onsdigital/data/DataService.java
Fix previous releases page. Read directory contents from zebedee if its a zebedee request else read from local file system.
<ide><path>rc/main/java/com/github/onsdigital/data/DataService.java <ide> import com.github.onsdigital.content.page.base.Page; <ide> import com.github.onsdigital.content.service.ContentNotFoundException; <ide> import com.github.onsdigital.content.util.ContentUtil; <del>import com.github.onsdigital.data.zebedee.ZebedeeClient; <ide> import com.github.onsdigital.data.zebedee.ZebedeeDataService; <ide> import com.github.onsdigital.data.zebedee.ZebedeeRequest; <ide> import org.apache.commons.io.IOUtils; <ide> <ide> public DirectoryListing readDirectory(String uri, ZebedeeRequest zebedeeRequest) throws ContentNotFoundException { <ide> <del> // make request to browse api <del> ZebedeeClient zebedeeClient = new ZebedeeClient(zebedeeRequest); <del> DirectoryListing directoryListing; <del> try { <del> directoryListing = ContentUtil.deserialise(zebedeeClient.get("browse", uri, false), DirectoryListing.class); <del> } finally { <del> zebedeeClient.closeConnection(); <add> if (zebedeeRequest != null) { <add> return ZebedeeDataService.getInstance().readDirectory(uri, zebedeeRequest); <ide> } <ide> <del> return directoryListing; <add> return LocalFileDataService.getInstance().readDirectory(uri); <ide> } <ide> }
Java
mit
445750416e8175acbe6fe0159d59eb0402d77281
0
johanbrook/watchme
package se.chalmers.watchmetest.database; import junit.framework.Assert; import se.chalmers.watchme.database.HasTagTable; import se.chalmers.watchme.database.MoviesTable; import se.chalmers.watchme.database.TagsTable; import se.chalmers.watchme.database.WatchMeContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.test.ProviderTestCase2; /** * Test all public methods in WatchMeContenProvider * * From http://developer.android.com/tools/testing/contentprovider_testing.html * "Test with resolver methods: Even though you can instantiate a provider * object in ProviderTestCase2, you should always test with a resolver object * using the appropriate URI. This ensures that you are testing the provider * using the same interaction that a regular application would use. " * * @author lisastenberg * */ public class WatchMeContentProviderTest extends ProviderTestCase2<WatchMeContentProvider>{ Uri uri_movies = WatchMeContentProvider.CONTENT_URI_MOVIES; Uri uri_tags = WatchMeContentProvider.CONTENT_URI_TAGS; Uri uri_hastag = WatchMeContentProvider.CONTENT_URI_HAS_TAG; Uri[] validUris = new Uri[] { uri_movies, uri_tags, uri_hastag }; private ContentResolver contentResolver; public WatchMeContentProviderTest() { super(WatchMeContentProvider.class, WatchMeContentProvider.AUTHORITY); } /* public WatchMeContentProviderTest(Class<WatchMeContentProvider> providerClass, String providerAuthority) { super(providerClass, providerAuthority); } */ @Override protected void setUp() throws Exception { super.setUp(); contentResolver = getMockContentResolver(); } @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test valid URIs and unvalid URIs * * From http://developer.android.com/tools/testing/contentprovider_testing.html * "Test invalid URIs: Your unit tests should deliberately call the provider * with an invalid URI, and look for errors. Good provider design is to * throw an IllegalArgumentException for invalid URIs. " */ public void testURI() { Uri uri_invalid = Uri.parse("invalid"); try { contentResolver.insert(uri_invalid, new ContentValues()); Assert.fail("insert: Should have thrown IllegalArgumentException"); } catch(IllegalArgumentException e) {} try { Cursor c = contentResolver.query(uri_invalid, null, null, null, null); Assert.fail("query: Should have thrown IllegalArgumentException\n" + "c: " + c); } catch(IllegalArgumentException e) {} try { contentResolver.update(uri_invalid, new ContentValues(), null, null); Assert.fail("update: Should have thrown IllegalArgumentException"); } catch(IllegalArgumentException e) {} try { contentResolver.delete(uri_invalid, null, null); Assert.fail("delete: Should have thrown IllegalArgumentException"); } catch(IllegalArgumentException e) {} } public void testQuery() { for (Uri uri : validUris) { Cursor cursor = contentResolver.query(uri, null, null, null, null); assertNotNull(cursor); } } public void testInsert() { ContentValues values = new ContentValues(); /* * Test insert into uri_movie */ values.put(MoviesTable.COLUMN_TITLE, "batman"); values.put(MoviesTable.COLUMN_RATING, 1); values.put(MoviesTable.COLUMN_NOTE, ""); values.put(MoviesTable.COLUMN_DATE, 0); values.put(MoviesTable.COLUMN_IMDB_ID, 0); values.put(MoviesTable.COLUMN_POSTER_LARGE, ""); values.put(MoviesTable.COLUMN_POSTER_SMALL, ""); Uri tmpUri = contentResolver.insert(uri_movies, values); long movieId = Long.parseLong(tmpUri.getLastPathSegment()); // Check that the id of the movie was returned. assertTrue(movieId != 0); Cursor cursor = contentResolver.query(uri_movies, null, MoviesTable.COLUMN_MOVIE_ID + " = " + movieId, null, null); assertEquals(cursor.getCount(), 1); cursor.moveToFirst(); assertTrue(cursor.getString(1).equals("batman")); /* * Test insert the movie with the same title into uri_movie */ values = new ContentValues(); values.put(MoviesTable.COLUMN_TITLE, "batman"); values.put(MoviesTable.COLUMN_RATING, 1); values.put(MoviesTable.COLUMN_NOTE, ""); values.put(MoviesTable.COLUMN_DATE, 0); values.put(MoviesTable.COLUMN_IMDB_ID, 0); values.put(MoviesTable.COLUMN_POSTER_LARGE, ""); values.put(MoviesTable.COLUMN_POSTER_SMALL, ""); tmpUri = contentResolver.insert(uri_movies, values); long zeroId = Long.parseLong(tmpUri.getLastPathSegment()); // If the movie already existed insert should return 0. assertEquals(zeroId, 0); // Confirms that there exist one and only one movie with the title 'batman' cursor = contentResolver.query(uri_movies, null, MoviesTable.COLUMN_TITLE + " = 'batman'", null, null); assertEquals(cursor.getCount(), 1); /* * Test insert into uri_tag */ values = new ContentValues(); values.put(TagsTable.COLUMN_NAME, "tag"); try { tmpUri = contentResolver.insert(uri_tags, values); Assert.fail("Should throw UnsupportedOperationException"); } catch(UnsupportedOperationException e) {} /* * Test insert into uri_hastag */ values = new ContentValues(); values.put(MoviesTable.COLUMN_MOVIE_ID, movieId); values.put(TagsTable.COLUMN_NAME, "tag"); tmpUri = contentResolver.insert(uri_hastag, values); long tagId = Long.parseLong(tmpUri.getLastPathSegment()); cursor = contentResolver.query(uri_hastag, null, HasTagTable.COLUMN_MOVIE_ID + " = " + movieId + " AND " + HasTagTable.COLUMN_TAG_ID + " = " + tagId, null, null); assertEquals(cursor.getCount(), 1); /* * Attach a tag to a movie it is already attached to. */ tmpUri = contentResolver.insert(uri_hastag, values); zeroId = Long.parseLong(tmpUri.getLastPathSegment()); // If the attachment already existed insert should return 0. assertEquals(zeroId, 0); cursor = contentResolver .query(uri_hastag, null, HasTagTable.COLUMN_MOVIE_ID + " = " + movieId + " AND " + HasTagTable.COLUMN_TAG_ID + " = " + tagId, null, null); /* Confirms that there exist one and only one attachment between the * movie 'batman' and the tag 'tag' */ assertEquals(cursor.getCount(), 1); } /* * Precondition: testInsertMovie has passed */ public void testUpdate() { ContentValues values = new ContentValues(); /* * Update movie */ values.put(MoviesTable.COLUMN_TITLE, "batman"); values.put(MoviesTable.COLUMN_RATING, 1); values.put(MoviesTable.COLUMN_NOTE, ""); values.put(MoviesTable.COLUMN_DATE, 0); values.put(MoviesTable.COLUMN_IMDB_ID, 0); values.put(MoviesTable.COLUMN_POSTER_LARGE, ""); values.put(MoviesTable.COLUMN_POSTER_SMALL, ""); Uri tmpUri = contentResolver.insert(uri_movies, values); long movieId = Long.parseLong(tmpUri.getLastPathSegment()); values = new ContentValues(); values.put(MoviesTable.COLUMN_NOTE, "updated"); int updatedRows = contentResolver.update(uri_movies, values, "_id = " + movieId, null); assertEquals(updatedRows, 1); /* * Update attachment between movie and tag not necessary for WatchMe */ /* * Update tag */ values = new ContentValues(); values.put(MoviesTable.COLUMN_MOVIE_ID, movieId); values.put(TagsTable.COLUMN_NAME, "tag"); tmpUri = contentResolver.insert(uri_hastag, values); long tagId = Long.parseLong(tmpUri.getLastPathSegment()); updatedRows = contentResolver.update(uri_tags, values, TagsTable.COLUMN_TAG_ID + " = " + tagId, null); assertEquals(updatedRows, 1); } /* * Precondition: testInsertMovie has passed */ public void testDeleteMovie() { ContentValues values = new ContentValues(); /* * Delete a movie without a tag */ values.put(MoviesTable.COLUMN_TITLE, "batman"); values.put(MoviesTable.COLUMN_RATING, 1); values.put(MoviesTable.COLUMN_NOTE, ""); values.put(MoviesTable.COLUMN_DATE, 0); values.put(MoviesTable.COLUMN_IMDB_ID, 0); values.put(MoviesTable.COLUMN_POSTER_LARGE, ""); values.put(MoviesTable.COLUMN_POSTER_SMALL, ""); Uri tmpUri = contentResolver.insert(uri_movies, values); long movieId = Long.parseLong(tmpUri.getLastPathSegment()); int deletedRows = contentResolver.delete(uri_movies, "_id = " + movieId, null); assertEquals(deletedRows, 1); /* * Delete a movie with a tag */ values = new ContentValues(); values.put(MoviesTable.COLUMN_TITLE, "batman"); values.put(MoviesTable.COLUMN_RATING, 1); values.put(MoviesTable.COLUMN_NOTE, ""); values.put(MoviesTable.COLUMN_DATE, 0); values.put(MoviesTable.COLUMN_IMDB_ID, 0); values.put(MoviesTable.COLUMN_POSTER_LARGE, ""); values.put(MoviesTable.COLUMN_POSTER_SMALL, ""); tmpUri = contentResolver.insert(uri_movies, values); movieId = Long.parseLong(tmpUri.getLastPathSegment()); values = new ContentValues(); values.put(MoviesTable.COLUMN_MOVIE_ID, movieId); values.put(TagsTable.COLUMN_NAME, "tag"); contentResolver.insert(uri_hastag, values); /* Confirms that the movie was deleted and that the tag was attached * from the movie */ deletedRows = contentResolver.delete(uri_movies, MoviesTable.COLUMN_MOVIE_ID + " = "+ movieId, null); assertEquals(deletedRows, 1); // Confirms that the tag was deleted completely Cursor cursor = contentResolver.query(uri_tags, null, null, null, null); assertEquals(cursor.getCount(), 0); /* * Detach a tag (delete from hastag) */ values = new ContentValues(); values.put(MoviesTable.COLUMN_TITLE, "batman"); values.put(MoviesTable.COLUMN_RATING, 1); values.put(MoviesTable.COLUMN_NOTE, ""); values.put(MoviesTable.COLUMN_DATE, 0); values.put(MoviesTable.COLUMN_IMDB_ID, 0); values.put(MoviesTable.COLUMN_POSTER_LARGE, ""); values.put(MoviesTable.COLUMN_POSTER_SMALL, ""); tmpUri = contentResolver.insert(uri_movies, values); movieId = Long.parseLong(tmpUri.getLastPathSegment()); values = new ContentValues(); values.put(MoviesTable.COLUMN_MOVIE_ID, movieId); values.put(TagsTable.COLUMN_NAME, "tag"); tmpUri = contentResolver.insert(uri_hastag, values); long tagId = Long.parseLong(tmpUri.getLastPathSegment()); deletedRows = contentResolver.delete(uri_hastag, HasTagTable.COLUMN_MOVIE_ID + " = "+ movieId + " AND " + HasTagTable.COLUMN_TAG_ID + " = " + tagId, null); assertEquals(deletedRows, 1); /* * The tag should also be detached from the movie, but this can't * be tested since this is forced by a TRIGGER in the DatabaseHelper * and not in the CP */ // Confirms that the tag was deleted completely cursor = contentResolver.query(uri_tags, null, null, null, null); assertEquals(cursor.getCount(), 0); /* * Delete tag */ values = new ContentValues(); values.put(MoviesTable.COLUMN_TITLE, "batman"); values.put(MoviesTable.COLUMN_RATING, 1); values.put(MoviesTable.COLUMN_NOTE, ""); values.put(MoviesTable.COLUMN_DATE, 0); values.put(MoviesTable.COLUMN_IMDB_ID, 0); values.put(MoviesTable.COLUMN_POSTER_LARGE, ""); values.put(MoviesTable.COLUMN_POSTER_SMALL, ""); tmpUri = contentResolver.insert(uri_movies, values); movieId = Long.parseLong(tmpUri.getLastPathSegment()); values = new ContentValues(); values.put(MoviesTable.COLUMN_MOVIE_ID, movieId); values.put(TagsTable.COLUMN_NAME, "tag"); tmpUri = contentResolver.insert(uri_hastag, values); tagId = Long.parseLong(tmpUri.getLastPathSegment()); deletedRows = contentResolver.delete(uri_tags, TagsTable.COLUMN_TAG_ID + " = " + tagId, null); assertEquals(deletedRows, 1); /* * The tag should also be detached from the movie, but this can't * be tested since this is forced by a TRIGGER in the DatabaseHelper * and not in the CP */ } }
WatchMeTest/src/se/chalmers/watchmetest/database/WatchMeContentProviderTest.java
package se.chalmers.watchmetest.database; import junit.framework.Assert; import se.chalmers.watchme.database.HasTagTable; import se.chalmers.watchme.database.MoviesTable; import se.chalmers.watchme.database.TagsTable; import se.chalmers.watchme.database.WatchMeContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.test.ProviderTestCase2; /** * Test all public methods in WatchMeContenProvider * * From http://developer.android.com/tools/testing/contentprovider_testing.html * "Test with resolver methods: Even though you can instantiate a provider * object in ProviderTestCase2, you should always test with a resolver object * using the appropriate URI. This ensures that you are testing the provider * using the same interaction that a regular application would use. " * * @author lisastenberg * */ public class WatchMeContentProviderTest extends ProviderTestCase2<WatchMeContentProvider>{ Uri uri_movies = WatchMeContentProvider.CONTENT_URI_MOVIES; Uri uri_tags = WatchMeContentProvider.CONTENT_URI_TAGS; Uri uri_hastag = WatchMeContentProvider.CONTENT_URI_HAS_TAG; Uri[] validUris = new Uri[] { uri_movies, uri_tags, uri_hastag }; private ContentResolver contentResolver; public WatchMeContentProviderTest() { super(WatchMeContentProvider.class, WatchMeContentProvider.AUTHORITY); } /* public WatchMeContentProviderTest(Class<WatchMeContentProvider> providerClass, String providerAuthority) { super(providerClass, providerAuthority); } */ @Override protected void setUp() throws Exception { super.setUp(); contentResolver = getMockContentResolver(); } @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test valid URIs and unvalid URIs * * From http://developer.android.com/tools/testing/contentprovider_testing.html * "Test invalid URIs: Your unit tests should deliberately call the provider * with an invalid URI, and look for errors. Good provider design is to * throw an IllegalArgumentException for invalid URIs. " */ public void testURI() { Uri uri_invalid = Uri.parse("invalid"); try { contentResolver.insert(uri_invalid, new ContentValues()); Assert.fail("insert: Should have thrown IllegalArgumentException"); } catch(IllegalArgumentException e) {} try { contentResolver.query(uri_invalid, null, null, null, null); Assert.fail("query: Should have thrown IllegalArgumentException"); } catch(IllegalArgumentException e) {} try { contentResolver.update(uri_invalid, new ContentValues(), null, null); Assert.fail("update: Should have thrown IllegalArgumentException"); } catch(IllegalArgumentException e) {} try { contentResolver.delete(uri_invalid, null, null); Assert.fail("delete: Should have thrown IllegalArgumentException"); } catch(IllegalArgumentException e) {} } public void testQuery() { for (Uri uri : validUris) { Cursor cursor = contentResolver.query(uri, null, null, null, null); assertNotNull(cursor); } } public void testInsert() { ContentValues values = new ContentValues(); /* * Test insert into uri_movie */ values.put(MoviesTable.COLUMN_TITLE, "batman"); values.put(MoviesTable.COLUMN_RATING, 1); values.put(MoviesTable.COLUMN_NOTE, ""); values.put(MoviesTable.COLUMN_DATE, 0); values.put(MoviesTable.COLUMN_IMDB_ID, 0); values.put(MoviesTable.COLUMN_POSTER_LARGE, ""); values.put(MoviesTable.COLUMN_POSTER_SMALL, ""); Uri tmpUri = contentResolver.insert(uri_movies, values); long movieId = Long.parseLong(tmpUri.getLastPathSegment()); // Check that the id of the movie was returned. assertTrue(movieId != 0); Cursor cursor = contentResolver.query(uri_movies, null, MoviesTable.COLUMN_MOVIE_ID + " = " + movieId, null, null); assertEquals(cursor.getCount(), 1); cursor.moveToFirst(); assertTrue(cursor.getString(1).equals("batman")); /* * Test insert the movie with the same title into uri_movie */ values = new ContentValues(); values.put(MoviesTable.COLUMN_TITLE, "batman"); values.put(MoviesTable.COLUMN_RATING, 1); values.put(MoviesTable.COLUMN_NOTE, ""); values.put(MoviesTable.COLUMN_DATE, 0); values.put(MoviesTable.COLUMN_IMDB_ID, 0); values.put(MoviesTable.COLUMN_POSTER_LARGE, ""); values.put(MoviesTable.COLUMN_POSTER_SMALL, ""); tmpUri = contentResolver.insert(uri_movies, values); long zeroId = Long.parseLong(tmpUri.getLastPathSegment()); // If the movie already existed insert should return 0. assertEquals(zeroId, 0); // Confirms that there exist one and only one movie with the title 'batman' cursor = contentResolver.query(uri_movies, null, MoviesTable.COLUMN_TITLE + " = 'batman'", null, null); assertEquals(cursor.getCount(), 1); /* * Test insert into uri_tag */ values = new ContentValues(); values.put(TagsTable.COLUMN_NAME, "tag"); try { tmpUri = contentResolver.insert(uri_tags, values); Assert.fail("Should throw UnsupportedOperationException"); } catch(UnsupportedOperationException e) {} /* * Test insert into uri_hastag */ values = new ContentValues(); values.put(MoviesTable.COLUMN_MOVIE_ID, movieId); values.put(TagsTable.COLUMN_NAME, "tag"); tmpUri = contentResolver.insert(uri_hastag, values); long tagId = Long.parseLong(tmpUri.getLastPathSegment()); cursor = contentResolver.query(uri_hastag, null, HasTagTable.COLUMN_MOVIE_ID + " = " + movieId + " AND " + HasTagTable.COLUMN_TAG_ID + " = " + tagId, null, null); assertEquals(cursor.getCount(), 1); /* * Attach a tag to a movie it is already attached to. */ tmpUri = contentResolver.insert(uri_hastag, values); zeroId = Long.parseLong(tmpUri.getLastPathSegment()); // If the attachment already existed insert should return 0. assertEquals(zeroId, 0); cursor = contentResolver .query(uri_hastag, null, HasTagTable.COLUMN_MOVIE_ID + " = " + movieId + " AND " + HasTagTable.COLUMN_TAG_ID + " = " + tagId, null, null); /* Confirms that there exist one and only one attachment between the * movie 'batman' and the tag 'tag' */ assertEquals(cursor.getCount(), 1); } /* * Precondition: testInsertMovie has passed */ public void testUpdate() { ContentValues values = new ContentValues(); /* * Update movie */ values.put(MoviesTable.COLUMN_TITLE, "batman"); values.put(MoviesTable.COLUMN_RATING, 1); values.put(MoviesTable.COLUMN_NOTE, ""); values.put(MoviesTable.COLUMN_DATE, 0); values.put(MoviesTable.COLUMN_IMDB_ID, 0); values.put(MoviesTable.COLUMN_POSTER_LARGE, ""); values.put(MoviesTable.COLUMN_POSTER_SMALL, ""); Uri tmpUri = contentResolver.insert(uri_movies, values); long movieId = Long.parseLong(tmpUri.getLastPathSegment()); values = new ContentValues(); values.put(MoviesTable.COLUMN_NOTE, "updated"); int updatedRows = contentResolver.update(uri_movies, values, "_id = " + movieId, null); assertEquals(updatedRows, 1); /* * Update attachment between movie and tag not necessary for WatchMe */ /* * Update tag */ values = new ContentValues(); values.put(MoviesTable.COLUMN_MOVIE_ID, movieId); values.put(TagsTable.COLUMN_NAME, "tag"); tmpUri = contentResolver.insert(uri_hastag, values); long tagId = Long.parseLong(tmpUri.getLastPathSegment()); updatedRows = contentResolver.update(uri_tags, values, TagsTable.COLUMN_TAG_ID + " = " + tagId, null); assertEquals(updatedRows, 1); } /* * Precondition: testInsertMovie has passed */ public void testDeleteMovie() { ContentValues values = new ContentValues(); // Test movie-uri values.put(MoviesTable.COLUMN_TITLE, "batman"); values.put(MoviesTable.COLUMN_RATING, 1); values.put(MoviesTable.COLUMN_NOTE, ""); values.put(MoviesTable.COLUMN_DATE, 0); values.put(MoviesTable.COLUMN_IMDB_ID, 0); values.put(MoviesTable.COLUMN_POSTER_LARGE, ""); values.put(MoviesTable.COLUMN_POSTER_SMALL, ""); Uri tmpUri = contentResolver.insert(uri_movies, values); long movieId = Long.parseLong(tmpUri.getLastPathSegment()); int deletedRows = contentResolver.delete(uri_movies, "_id = " + movieId, null); assertEquals(deletedRows, 1); } }
Implemented fully tests for CP: delete
WatchMeTest/src/se/chalmers/watchmetest/database/WatchMeContentProviderTest.java
Implemented fully tests for CP: delete
<ide><path>atchMeTest/src/se/chalmers/watchmetest/database/WatchMeContentProviderTest.java <ide> catch(IllegalArgumentException e) {} <ide> <ide> try { <del> contentResolver.query(uri_invalid, null, null, null, null); <del> Assert.fail("query: Should have thrown IllegalArgumentException"); <add> Cursor c = contentResolver.query(uri_invalid, null, null, null, null); <add> <add> Assert.fail("query: Should have thrown IllegalArgumentException\n" + <add> "c: " + c); <ide> } <ide> catch(IllegalArgumentException e) {} <ide> <ide> <ide> ContentValues values = new ContentValues(); <ide> <del> // Test movie-uri <add> /* <add> * Delete a movie without a tag <add> */ <ide> values.put(MoviesTable.COLUMN_TITLE, "batman"); <ide> values.put(MoviesTable.COLUMN_RATING, 1); <ide> values.put(MoviesTable.COLUMN_NOTE, ""); <ide> <ide> int deletedRows = contentResolver.delete(uri_movies, "_id = " + movieId, null); <ide> assertEquals(deletedRows, 1); <add> <add> /* <add> * Delete a movie with a tag <add> */ <add> values = new ContentValues(); <add> <add> values.put(MoviesTable.COLUMN_TITLE, "batman"); <add> values.put(MoviesTable.COLUMN_RATING, 1); <add> values.put(MoviesTable.COLUMN_NOTE, ""); <add> values.put(MoviesTable.COLUMN_DATE, 0); <add> values.put(MoviesTable.COLUMN_IMDB_ID, 0); <add> values.put(MoviesTable.COLUMN_POSTER_LARGE, ""); <add> values.put(MoviesTable.COLUMN_POSTER_SMALL, ""); <add> <add> tmpUri = contentResolver.insert(uri_movies, values); <add> movieId = Long.parseLong(tmpUri.getLastPathSegment()); <add> <add> values = new ContentValues(); <add> <add> values.put(MoviesTable.COLUMN_MOVIE_ID, movieId); <add> values.put(TagsTable.COLUMN_NAME, "tag"); <add> contentResolver.insert(uri_hastag, values); <add> <add> /* Confirms that the movie was deleted and that the tag was attached <add> * from the movie <add> */ <add> deletedRows = contentResolver.delete(uri_movies, <add> MoviesTable.COLUMN_MOVIE_ID + " = "+ movieId, null); <add> assertEquals(deletedRows, 1); <add> <add> // Confirms that the tag was deleted completely <add> Cursor cursor = contentResolver.query(uri_tags, null, null, null, null); <add> assertEquals(cursor.getCount(), 0); <add> <add> /* <add> * Detach a tag (delete from hastag) <add> */ <add> values = new ContentValues(); <add> <add> values.put(MoviesTable.COLUMN_TITLE, "batman"); <add> values.put(MoviesTable.COLUMN_RATING, 1); <add> values.put(MoviesTable.COLUMN_NOTE, ""); <add> values.put(MoviesTable.COLUMN_DATE, 0); <add> values.put(MoviesTable.COLUMN_IMDB_ID, 0); <add> values.put(MoviesTable.COLUMN_POSTER_LARGE, ""); <add> values.put(MoviesTable.COLUMN_POSTER_SMALL, ""); <add> <add> tmpUri = contentResolver.insert(uri_movies, values); <add> movieId = Long.parseLong(tmpUri.getLastPathSegment()); <add> <add> values = new ContentValues(); <add> <add> values.put(MoviesTable.COLUMN_MOVIE_ID, movieId); <add> values.put(TagsTable.COLUMN_NAME, "tag"); <add> tmpUri = contentResolver.insert(uri_hastag, values); <add> long tagId = Long.parseLong(tmpUri.getLastPathSegment()); <add> <add> deletedRows = contentResolver.delete(uri_hastag, <add> HasTagTable.COLUMN_MOVIE_ID + " = "+ movieId + " AND " + <add> HasTagTable.COLUMN_TAG_ID + " = " + tagId, null); <add> assertEquals(deletedRows, 1); <add> <add> /* <add> * The tag should also be detached from the movie, but this can't <add> * be tested since this is forced by a TRIGGER in the DatabaseHelper <add> * and not in the CP <add> */ <add> <add> // Confirms that the tag was deleted completely <add> cursor = contentResolver.query(uri_tags, null, null, null, null); <add> assertEquals(cursor.getCount(), 0); <add> <add> /* <add> * Delete tag <add> */ <add> values = new ContentValues(); <add> <add> values.put(MoviesTable.COLUMN_TITLE, "batman"); <add> values.put(MoviesTable.COLUMN_RATING, 1); <add> values.put(MoviesTable.COLUMN_NOTE, ""); <add> values.put(MoviesTable.COLUMN_DATE, 0); <add> values.put(MoviesTable.COLUMN_IMDB_ID, 0); <add> values.put(MoviesTable.COLUMN_POSTER_LARGE, ""); <add> values.put(MoviesTable.COLUMN_POSTER_SMALL, ""); <add> <add> tmpUri = contentResolver.insert(uri_movies, values); <add> movieId = Long.parseLong(tmpUri.getLastPathSegment()); <add> <add> values = new ContentValues(); <add> <add> values.put(MoviesTable.COLUMN_MOVIE_ID, movieId); <add> values.put(TagsTable.COLUMN_NAME, "tag"); <add> tmpUri = contentResolver.insert(uri_hastag, values); <add> tagId = Long.parseLong(tmpUri.getLastPathSegment()); <add> <add> deletedRows = contentResolver.delete(uri_tags, <add> TagsTable.COLUMN_TAG_ID + " = " + tagId, null); <add> assertEquals(deletedRows, 1); <add> <add> /* <add> * The tag should also be detached from the movie, but this can't <add> * be tested since this is forced by a TRIGGER in the DatabaseHelper <add> * and not in the CP <add> */ <ide> } <ide> <ide> }
Java
apache-2.0
ff0c24ac793edbabb6c242e83968e0b916006ed9
0
recommenders/rival,recommenders/rival
package net.recommenders.evaluation.strategy; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import net.recommenders.evaluation.core.DataModel; import net.recommenders.evaluation.parser.SimpleParser; import net.recommenders.evaluation.strategy.EvaluationStrategy.Pair; /** * * @author Alejandro */ public class StrategyRunner { public static final String TRAINING_FILE = "split.training.file"; public static final String TEST_FILE = "split.test.file"; public static final String INPUT_FILE = "recommendation.file"; public static final String INPUT_FORMAT = "recommendation.format"; public static final String OUTPUT_FORMAT = "output.format"; public static final String OUTPUT_FILE = "output.file.ranking"; public static final String GROUNDTRUTH_FILE = "output.file.groundtruth"; public static final String STRATEGY = "strategy.class"; public static final String RELEVANCE_THRESHOLD = "strategy.relevance.threshold"; public static final String RELPLUSN_N = "strategy.relplusn.N"; public static final String RELPLUSN_SEED = "strategy.relplusn.seed"; public static void main(String[] args) throws Exception { String propertyFile = System.getProperty("propertyFile"); final Properties properties = new Properties(); try { properties.load(new FileInputStream(propertyFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException ie) { ie.printStackTrace(); } run(properties); } public static void run(Properties properties) throws IOException, ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException, NoSuchMethodException, SecurityException { // read splits System.out.println("Parsing started: training file"); File trainingFile = new File(properties.getProperty(TRAINING_FILE)); DataModel<Long, Long> trainingModel = new SimpleParser().parseData(trainingFile); System.out.println("Parsing finished: training file"); System.out.println("Parsing started: test file"); File testFile = new File(properties.getProperty(TEST_FILE)); DataModel<Long, Long> testModel = new SimpleParser().parseData(testFile); System.out.println("Parsing finished: test file"); // read other parameters File inputFile = new File(properties.getProperty(INPUT_FILE)); String inputFormat = properties.getProperty(INPUT_FORMAT); File rankingFile = new File(properties.getProperty(OUTPUT_FILE)); File groundtruthFile = new File(properties.getProperty(GROUNDTRUTH_FILE)); EvaluationStrategy.OUTPUT_FORMAT format = properties.getProperty(OUTPUT_FORMAT).equals(EvaluationStrategy.OUTPUT_FORMAT.TRECEVAL.toString()) ? EvaluationStrategy.OUTPUT_FORMAT.TRECEVAL : EvaluationStrategy.OUTPUT_FORMAT.SIMPLE; Double threshold = Double.parseDouble(properties.getProperty(RELEVANCE_THRESHOLD)); String strategyClassName = properties.getProperty(STRATEGY); Class<?> strategyClass = Class.forName(strategyClassName); // get strategy EvaluationStrategy<Long, Long> strategy = null; if (strategyClassName.contains("RelPlusN")) { Integer N = Integer.parseInt(properties.getProperty(RELPLUSN_N)); Long seed = Long.parseLong(properties.getProperty(RELPLUSN_SEED)); strategy = new RelPlusN(trainingModel, testModel, N, threshold, seed); } else { strategy = (EvaluationStrategy<Long, Long>) strategyClass.getConstructor(DataModel.class, DataModel.class, double.class).newInstance(trainingModel, testModel, threshold); } // read recommendations: user \t item \t score final Map<Long, List<Pair<Long, Double>>> mapUserRecommendations = new HashMap<Long, List<Pair<Long, Double>>>(); BufferedReader in = new BufferedReader(new FileReader(inputFile)); String line = null; while ((line = in.readLine()) != null) { readLine(line, inputFormat, mapUserRecommendations); } in.close(); // generate output PrintStream outRanking = new PrintStream(rankingFile); PrintStream outGroundtruth = new PrintStream(groundtruthFile); for (Long user : testModel.getUsers()) { final List<Pair<Long, Double>> allScoredItems = mapUserRecommendations.get(user); final Set<Long> items = strategy.getCandidateItemsToRank(user); final List<Pair<Long, Double>> scoredItems = new ArrayList<Pair<Long, Double>>(); for (Pair<Long, Double> scoredItem : allScoredItems) { if (items.contains(scoredItem.getFirst())) { scoredItems.add(scoredItem); } } strategy.printRanking(user, scoredItems, outRanking, format); strategy.printGroundtruth(user, outGroundtruth, format); } outRanking.close(); outGroundtruth.close(); } public static void readLine(String line, String format, Map<Long, List<Pair<Long, Double>>> mapUserRecommendations) { String[] toks = line.split("\t"); if (format != null || format.equals("mymedialite")) { Long user = Long.parseLong(toks[0]); String items = toks[1].replace("[", "").replace("]", ""); for (String pair : items.split(",")) { String[] pairToks = pair.split(":"); Long item = Long.parseLong(pairToks[0]); Double score = Double.parseDouble(pairToks[1]); List<Pair<Long, Double>> userRec = mapUserRecommendations.get(user); if (userRec == null) { userRec = new ArrayList<Pair<Long, Double>>(); mapUserRecommendations.put(user, userRec); } userRec.add(new Pair<Long, Double>(item, score)); } } else { Long user = Long.parseLong(toks[0]); Long item = Long.parseLong(toks[1]); Double score = Double.parseDouble(toks[2]); List<Pair<Long, Double>> userRec = mapUserRecommendations.get(user); if (userRec == null) { userRec = new ArrayList<Pair<Long, Double>>(); mapUserRecommendations.put(user, userRec); } userRec.add(new Pair<Long, Double>(item, score)); } } }
src/main/java/net/recommenders/evaluation/strategy/StrategyRunner.java
package net.recommenders.evaluation.strategy; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import net.recommenders.evaluation.core.DataModel; import net.recommenders.evaluation.parser.SimpleParser; import net.recommenders.evaluation.strategy.EvaluationStrategy.Pair; /** * * @author Alejandro */ public class StrategyRunner { public static final String TRAINING_FILE = "split.training.file"; public static final String TEST_FILE = "split.test.file"; public static final String INPUT_FILE = "recommendation.file"; public static final String OUTPUT_FORMAT = "output.format"; public static final String OUTPUT_FILE = "output.file.ranking"; public static final String GROUNDTRUTH_FILE = "output.file.groundtruth"; public static final String STRATEGY = "strategy.class"; public static final String RELEVANCE_THRESHOLD = "strategy.relevance.threshold"; public static final String RELPLUSN_N = "strategy.relplusn.N"; public static final String RELPLUSN_SEED = "strategy.relplusn.seed"; public static void main(String[] args) throws Exception { String propertyFile = System.getProperty("propertyFile"); final Properties properties = new Properties(); try { properties.load(new FileInputStream(propertyFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException ie) { ie.printStackTrace(); } run(properties); } public static void run(Properties properties) throws IOException, ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException, NoSuchMethodException, SecurityException { // read splits System.out.println("Parsing started: training file"); File trainingFile = new File(properties.getProperty(TRAINING_FILE)); DataModel<Long, Long> trainingModel = new SimpleParser().parseData(trainingFile); System.out.println("Parsing finished: training file"); System.out.println("Parsing started: test file"); File testFile = new File(properties.getProperty(TEST_FILE)); DataModel<Long, Long> testModel = new SimpleParser().parseData(testFile); System.out.println("Parsing finished: test file"); // read other parameters File inputFile = new File(properties.getProperty(INPUT_FILE)); File rankingFile = new File(properties.getProperty(OUTPUT_FILE)); File groundtruthFile = new File(properties.getProperty(GROUNDTRUTH_FILE)); EvaluationStrategy.OUTPUT_FORMAT format = properties.getProperty(OUTPUT_FORMAT).equals(EvaluationStrategy.OUTPUT_FORMAT.TRECEVAL.toString()) ? EvaluationStrategy.OUTPUT_FORMAT.TRECEVAL : EvaluationStrategy.OUTPUT_FORMAT.SIMPLE; Double threshold = Double.parseDouble(properties.getProperty(RELEVANCE_THRESHOLD)); String strategyClassName = properties.getProperty(STRATEGY); Class<?> strategyClass = Class.forName(strategyClassName); // get strategy EvaluationStrategy<Long, Long> strategy = null; if (strategyClassName.contains("RelPlusN")) { Integer N = Integer.parseInt(properties.getProperty(RELPLUSN_N)); Long seed = Long.parseLong(properties.getProperty(RELPLUSN_SEED)); strategy = new RelPlusN(trainingModel, testModel, N, threshold, seed); } else { strategy = (EvaluationStrategy<Long, Long>) strategyClass.getConstructor(DataModel.class, DataModel.class, double.class).newInstance(trainingModel, testModel, threshold); } // read recommendations: user \t item \t score final Map<Long, List<Pair<Long, Double>>> mapUserRecommendations = new HashMap<Long, List<Pair<Long, Double>>>(); BufferedReader in = new BufferedReader(new FileReader(inputFile)); String line = null; while ((line = in.readLine()) != null) { String[] toks = line.split("\t"); Long user = Long.parseLong(toks[0]); Long item = Long.parseLong(toks[1]); Double score = Double.parseDouble(toks[2]); List<Pair<Long, Double>> userRec = mapUserRecommendations.get(user); if (userRec == null) { userRec = new ArrayList<Pair<Long, Double>>(); mapUserRecommendations.put(user, userRec); } userRec.add(new Pair<Long, Double>(item, score)); } in.close(); // generate output PrintStream outRanking = new PrintStream(rankingFile); PrintStream outGroundtruth = new PrintStream(groundtruthFile); for (Long user : testModel.getUsers()) { final List<Pair<Long, Double>> allScoredItems = mapUserRecommendations.get(user); final Set<Long> items = strategy.getCandidateItemsToRank(user); final List<Pair<Long, Double>> scoredItems = new ArrayList<Pair<Long, Double>>(); for (Pair<Long, Double> scoredItem : allScoredItems) { if (items.contains(scoredItem.getFirst())) { scoredItems.add(scoredItem); } } strategy.printRanking(user, scoredItems, outRanking, format); strategy.printGroundtruth(user, outGroundtruth, format); } outRanking.close(); outGroundtruth.close(); } }
Allow MyMediaLite format as recommendation input
src/main/java/net/recommenders/evaluation/strategy/StrategyRunner.java
Allow MyMediaLite format as recommendation input
<ide><path>rc/main/java/net/recommenders/evaluation/strategy/StrategyRunner.java <ide> public static final String TRAINING_FILE = "split.training.file"; <ide> public static final String TEST_FILE = "split.test.file"; <ide> public static final String INPUT_FILE = "recommendation.file"; <add> public static final String INPUT_FORMAT = "recommendation.format"; <ide> public static final String OUTPUT_FORMAT = "output.format"; <ide> public static final String OUTPUT_FILE = "output.file.ranking"; <ide> public static final String GROUNDTRUTH_FILE = "output.file.groundtruth"; <ide> System.out.println("Parsing finished: test file"); <ide> // read other parameters <ide> File inputFile = new File(properties.getProperty(INPUT_FILE)); <add> String inputFormat = properties.getProperty(INPUT_FORMAT); <ide> File rankingFile = new File(properties.getProperty(OUTPUT_FILE)); <ide> File groundtruthFile = new File(properties.getProperty(GROUNDTRUTH_FILE)); <ide> EvaluationStrategy.OUTPUT_FORMAT format = properties.getProperty(OUTPUT_FORMAT).equals(EvaluationStrategy.OUTPUT_FORMAT.TRECEVAL.toString()) ? EvaluationStrategy.OUTPUT_FORMAT.TRECEVAL : EvaluationStrategy.OUTPUT_FORMAT.SIMPLE; <ide> BufferedReader in = new BufferedReader(new FileReader(inputFile)); <ide> String line = null; <ide> while ((line = in.readLine()) != null) { <del> String[] toks = line.split("\t"); <del> Long user = Long.parseLong(toks[0]); <del> Long item = Long.parseLong(toks[1]); <del> Double score = Double.parseDouble(toks[2]); <del> List<Pair<Long, Double>> userRec = mapUserRecommendations.get(user); <del> if (userRec == null) { <del> userRec = new ArrayList<Pair<Long, Double>>(); <del> mapUserRecommendations.put(user, userRec); <del> } <del> userRec.add(new Pair<Long, Double>(item, score)); <add> readLine(line, inputFormat, mapUserRecommendations); <ide> } <ide> in.close(); <ide> // generate output <ide> outRanking.close(); <ide> outGroundtruth.close(); <ide> } <add> <add> public static void readLine(String line, String format, Map<Long, List<Pair<Long, Double>>> mapUserRecommendations) { <add> String[] toks = line.split("\t"); <add> if (format != null || format.equals("mymedialite")) { <add> Long user = Long.parseLong(toks[0]); <add> String items = toks[1].replace("[", "").replace("]", ""); <add> for (String pair : items.split(",")) { <add> String[] pairToks = pair.split(":"); <add> Long item = Long.parseLong(pairToks[0]); <add> Double score = Double.parseDouble(pairToks[1]); <add> List<Pair<Long, Double>> userRec = mapUserRecommendations.get(user); <add> if (userRec == null) { <add> userRec = new ArrayList<Pair<Long, Double>>(); <add> mapUserRecommendations.put(user, userRec); <add> } <add> userRec.add(new Pair<Long, Double>(item, score)); <add> } <add> } else { <add> Long user = Long.parseLong(toks[0]); <add> Long item = Long.parseLong(toks[1]); <add> Double score = Double.parseDouble(toks[2]); <add> List<Pair<Long, Double>> userRec = mapUserRecommendations.get(user); <add> if (userRec == null) { <add> userRec = new ArrayList<Pair<Long, Double>>(); <add> mapUserRecommendations.put(user, userRec); <add> } <add> userRec.add(new Pair<Long, Double>(item, score)); <add> } <add> } <ide> }
JavaScript
mpl-2.0
895ae1a9653d9ee638ff03678341cf12905058f7
0
mozilla/thimble.mozilla.org,mozilla/thimble.mozilla.org,humphd/thimble.mozilla.org,humphd/thimble.mozilla.org,humphd/thimble.mozilla.org,mozilla/thimble.mozilla.org,mozilla/thimble.mozilla.org,humphd/thimble.mozilla.org
/** * Module dependencies. */ var express = require('express') , routes = require('./routes') , user = require('./routes/user') , http = require('http') , path = require('path') , ajax = require('request') , sanitize = require('htmlsanitizer'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/users', user.list); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); // HACKASAURUS API IMPLEMENTATION app.get("/remix", function(request, response) { console.error("TEST"); // this does nothing for us, since we publish to AWS. // any link that we get in /publish will point to an AWS // location, so we're not serving saved content from this app. // we only publish through it, and load up templated pages, // such as the default, and learning_projects (which can come // later. This is P.O.C.) response.send("there are no teapots here."); response.end(); }); var ALLOWED_TAGS = [ "!doctype", "html", "body", "a", "abbr", "address", "area", "article", "aside", "audio", "b", "base", "bdi", "bdo", "blockquote", "body", "br", "button", "canvas", "caption", "cite", "code", "col", "colgroup", "command", "datalist", "dd", "del", "details", "dfn", "div", "dl", "dt", "em", "embed", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "iframe", "img", "input", "ins", "keygen", "kbd", "label", "legend", "li", "link", "map", "mark", "menu", "meta", "meter", "nav", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "pre", "progress", "q", "rp", "rt", "s", "samp", "section", "select", "small", "source", "span", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "u", "ul", "var", "video", "wbr" ], ALLOWED_ATTRS = { // TODO: We should probably add to this. What meta attributes can't // be abused for SEO purposes? "meta": ["charset", "name", "content"], "*": ["class", "id", "style"], "img": ["src", "width", "height"], "a": ["href"], "base": ["href"], "iframe": ["src", "width", "height", "frameborder", "allowfullscreen"], "video": ["controls", "autoplay", "preload", "loop", "mediaGroup", "src", "poster", "muted", "width", "height"], "audio": ["controls", "autoplay", "preload", "loop", "src"], "source": ["src", "type"], "link": ["href", "rel", "type"] }; app.post('/publish', function(request, response) { console.error("FUNCTION HIT"); console.error(request.body); /* 1) get data from request 2) try to bleach it through http://htmlsanitizer.org/ 3) if we succeeded in bleaching, we save that data to AWS 3b) for P.O.C., we're actually just going to say "hurray it worked" for now */ var data = ( request.body.html ? request.body.html : "" ); sanitize({ url: 'http://htmlsanitizer.org', text: data, tags: ALLOWED_TAGS, attributes: ALLOWED_ATTRS, styles: [], strip: false, strip_comments: false }, // response callback function(err, sanitized) { // At this point, we have a sanitized, and raw unsanitized // data in "sanitized" and "buffer", respectively. We can now // push this to AWS or wherever else we want if(err) { response.end(); } else { var jsonRespose = { 'published-url' : 'http://mozilla.org/1' }; response.json(jsonRespose); response.end(); } }); });
app.js
/** * Module dependencies. */ var express = require('express') , routes = require('./routes') , user = require('./routes/user') , http = require('http') , path = require('path') , ajax = require('request') , sanitize = require('htmlsanitizer'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/users', user.list); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); // HACKASAURUS API IMPLEMENTATION app.get("/remix", function(request, response) { console.error("TEST"); // this does nothing for us, since we publish to AWS. // any link that we get in /publish will point to an AWS // location, so we're not serving saved content from this app. // we only publish through it, and load up templated pages, // such as the default, and learning_projects (which can come // later. This is P.O.C.) response.send("there are no teapots here."); response.end(); }); app.post('/publish', function(request, response) { console.error("FUNCTION HIT"); console.error(request.body); /* 1) get data from request 2) try to bleach it through http://htmlsanitizer.org/ 3) if we succeeded in bleaching, we save that data to AWS 3b) for P.O.C., we're actually just going to say "hurray it worked" for now */ var data = ( request.body.html ? request.body.html : "" ); sanitize({ url: 'http://htmlsanitizer.org', text: data, // THESE VALUES NEED TO BE ADJUSTED FOR REAL WORLD WHITELISTING tags: ['p'], attributes: {}, styles: [], strip: false, strip_comments: false }, // response callback function(err, sanitized) { // At this point, we have a sanitized, and raw unsanitized // data in "sanitized" and "buffer", respectively. We can now // push this to AWS or wherever else we want if(err) { response.end(); } else { var jsonRespose = { 'published-url' : 'http://mozilla.org/1' }; response.json(jsonRespose); response.end(); } }); });
added allowed tags and attributes.
app.js
added allowed tags and attributes.
<ide><path>pp.js <ide> response.end(); <ide> }); <ide> <add>var <add> <add>ALLOWED_TAGS = [ <add> "!doctype", "html", "body", "a", "abbr", "address", "area", "article", <add> "aside", "audio", "b", "base", "bdi", "bdo", "blockquote", "body", "br", <add> "button", "canvas", "caption", "cite", "code", "col", "colgroup", <add> "command", "datalist", "dd", "del", "details", "dfn", "div", "dl", "dt", <add> "em", "embed", "fieldset", "figcaption", "figure", "footer", "form", <add> "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", <add> "html", "i", "iframe", "img", "input", "ins", "keygen", "kbd", "label", <add> "legend", "li", "link", "map", "mark", "menu", "meta", "meter", "nav", <add> "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", <add> "pre", "progress", "q", "rp", "rt", "s", "samp", "section", "select", <add> "small", "source", "span", "strong", "style", "sub", "summary", "sup", <add> "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "time", <add> "title", "tr", "track", "u", "ul", "var", "video", "wbr" <add> ], <add> <add>ALLOWED_ATTRS = { <add> // TODO: We should probably add to this. What meta attributes can't <add> // be abused for SEO purposes? <add> "meta": ["charset", "name", "content"], <add> "*": ["class", "id", "style"], <add> "img": ["src", "width", "height"], <add> "a": ["href"], <add> "base": ["href"], <add> "iframe": ["src", "width", "height", "frameborder", "allowfullscreen"], <add> "video": ["controls", "autoplay", "preload", "loop", "mediaGroup", "src", <add> "poster", "muted", "width", "height"], <add> "audio": ["controls", "autoplay", "preload", "loop", "src"], <add> "source": ["src", "type"], <add> "link": ["href", "rel", "type"] <add>}; <add> <ide> app.post('/publish', function(request, response) { <ide> console.error("FUNCTION HIT"); <ide> console.error(request.body); <ide> sanitize({ <ide> url: 'http://htmlsanitizer.org', <ide> text: data, <del> // THESE VALUES NEED TO BE ADJUSTED FOR REAL WORLD WHITELISTING <del> tags: ['p'], <del> attributes: {}, <add> tags: ALLOWED_TAGS, <add> attributes: ALLOWED_ATTRS, <ide> styles: [], <ide> strip: false, <ide> strip_comments: false
JavaScript
mit
9a1287bea008fd2d76eb809595c4e6e47ffc231b
0
GerHobbelt/cssrule.js,Orange-OpenSource/cssrule.js,GerHobbelt/cssrule.js
/*! * Copyright 2011 France Télécom * This software is distributed under the terms of either the MIT * License or the GNU General Public License (GPL) Version 2. * See GPL-LICENSE.txt and MIT-LICENSE.txt files for more details. */ /* cssrule.js * Version : 1 * * Authors: Julien Wajsberg <[email protected]> * * This module can insert CSS rules in a cross-browser way. * It was inspired by http://code.google.com/p/doctype/wiki/ArticleInstallStyles * */ var cssrule = (function(document, undefined) { var propToSet, stylesheet; function createStylesheet() { if (document.createStyleSheet) { // in IE stylesheet = document.createStyleSheet(); } else { stylesheet = document.createElement("style"); stylesheet.id = "cssrule"; // TODO: should we test if there is a head ? document.getElementsByTagName("head")[0].appendChild(stylesheet); } } function findPropToSet() { var possibleprops = "cssText,innerText,innerHTML".split(","); for (i = 0; i < possibleprops.length; i++) { cur = possibleprops[i]; if (stylesheet[cur] !== undefined) { propToSet = cur; break; } } } function init() { var i, cur; createStylesheet(); findPropToSet(); } function add(style) { stylesheet[propToSet] += style; return cssrule; } return { /** * you must call "init" function on dom ready * TODO: should we run it automatically when "add" is used the first time ? */ init: init, add: add }; })(document);
lib.cssrule.js
/*! * Copyright 2011 France Télécom * This software is distributed under the terms of either the MIT * License or the GNU General Public License (GPL) Version 2 or later. * See GPL-LICENSE.txt and MIT-LICENSE.txt files for more details. */ /* cssrule.js * Version : 1 * * Authors: Julien Wajsberg <[email protected]> * * This module can insert CSS rules in a cross-browser way. * It was inspired by http://code.google.com/p/doctype/wiki/ArticleInstallStyles * */ var cssrule = (function(document, undefined) { var propToSet, stylesheet; function createStylesheet() { if (document.createStyleSheet) { // in IE stylesheet = document.createStyleSheet(); } else { stylesheet = document.createElement("style"); stylesheet.id = "cssrule"; // TODO: should we test if there is a head ? document.getElementsByTagName("head")[0].appendChild(stylesheet); } } function findPropToSet() { var possibleprops = "cssText,innerText,innerHTML".split(","); for (i = 0; i < possibleprops.length; i++) { cur = possibleprops[i]; if (stylesheet[cur] !== undefined) { propToSet = cur; break; } } } function init() { var i, cur; createStylesheet(); findPropToSet(); } function add(style) { stylesheet[propToSet] += style; return cssrule; } return { /** * you must call "init" function on dom ready * TODO: should we run it automatically when "add" is used the first time ? */ init: init, add: add }; })(document);
replace GPL2 or later by GPL2 only (but still MIT)
lib.cssrule.js
replace GPL2 or later by GPL2 only (but still MIT)
<ide><path>ib.cssrule.js <ide> /*! <ide> * Copyright 2011 France Télécom <ide> * This software is distributed under the terms of either the MIT <del> * License or the GNU General Public License (GPL) Version 2 or later. <add> * License or the GNU General Public License (GPL) Version 2. <ide> * See GPL-LICENSE.txt and MIT-LICENSE.txt files for more details. <ide> */ <ide>
Java
lgpl-2.1
0cd55f0559386c016342ccc2751cc4688c3b5992
0
SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer
/* * EventFilter2D.java * * Created on November 9, 2005, 8:49 AM * * To change this template, choose Tools | Options and locate the template under * the Source Creation and Management node. Right-click the template and choose * Open. You can then make changes to the template in the Source Editor. */ package net.sf.jaer.eventprocessing; import java.awt.BorderLayout; import java.awt.Component; import java.util.ArrayList; import javax.swing.JPanel; import net.sf.jaer.aemonitor.AEConstants; import net.sf.jaer.chip.*; import net.sf.jaer.event.*; import net.sf.jaer.event.EventPacket; /** * A filter that filters or otherwise processes a packet of events. * <p> * * @author tobi */ abstract public class EventFilter2D extends EventFilter { /** The built-in reference to the output packet */ protected EventPacket out = null; /** Returns reference to the built-in output packet. * * @return the out packet. */ protected EventPacket getOutputPacket(){ return out; } protected float currentUpdateIntervalMs; /** Resets the output packet to be a new packet if none has been instanced or clears the packet if it exists */ protected void resetOut() { if (out == null) { out = new EventPacket(); } else { out.clear(); } } /** Checks <code>out</code> packet to make sure it holds the same type as the input packet. This method is used for filters that must pass output that has same event type as input. Unlike the other checkOutputPacketEventType method, this also ensures that * the output EventPacket is of the correct class, e.g. if it is a subclass of EventPacket, but only if EventPacket.setNextPacket() has been * called. I.e., the user must set EventPacket.nextPacket. * <p> * This method also copies fields from the input packet to the output packet, e.g. <code>systemModificationTimeNs</code>. @param in the input packet @see #out */ protected void checkOutputPacketEventType(EventPacket in) { in.setNextPacket(out); if (out != null && out.getEventClass() == in.getEventClass() && out.getClass() == in.getClass()) { out.systemModificationTimeNs=in.systemModificationTimeNs; return; } out = in.getNextPacket(); } /** Checks <code>out</code> packet to make sure it holds the same type of events as the given class. * This method is used for filters that must pass output that has a particular output type. This method does not ensure that the output packet is of the correct subtype of EventPacket. @param outClass the output packet event type class. @see #out * @see EventPacket#getNextPacket * @see #checkOutputPacketEventType(java.lang.Class) */ protected void checkOutputPacketEventType(Class<? extends BasicEvent> outClass) { if (out == null || out.getEventClass() == null || out.getEventClass() != outClass) { // Class oldClass=out.getEventClass(); out = new EventPacket(outClass); // log.info("oldClass="+oldClass+" outClass="+outClass+"; allocated new "+out); } } /** Subclasses implement this method to define custom processing. @param in the input packet @return the output packet */ public abstract EventPacket<?> filterPacket(EventPacket<?> in); /** Subclasses should call this super initializer */ public EventFilter2D(AEChip chip) { super(chip); this.chip = chip; } /** overrides EventFilter type in EventFilter */ protected EventFilter2D enclosedFilter; /** A filter can enclose another filter and can access and process this filter. Note that this processing is not automatic. Enclosing a filter inside another filter means that it will be built into the GUI as such @return the enclosed filter */ @Override public EventFilter2D getEnclosedFilter() { return this.enclosedFilter; } /** A filter can enclose another filter and can access and process this filter. Note that this processing is not automatic. Enclosing a filter inside another filter means that it will be built into the GUI as such. @param enclosedFilter the enclosed filter */ public void setEnclosedFilter(final EventFilter2D enclosedFilter) { if(this.enclosedFilter!=null){ log.warning("replacing existing enclosedFilter= "+this.enclosedFilter+" with new enclosedFilter= "+enclosedFilter); } super.setEnclosedFilter(enclosedFilter, this); this.enclosedFilter = enclosedFilter; } /** Resets the filter @param yes true to reset */ @Override synchronized public void setFilterEnabled(boolean yes) { super.setFilterEnabled(yes); if (yes) { resetOut(); } else { out = null; // garbage collect } } private int nextUpdateTimeUs = 0; // next timestamp we should update cluster list private boolean updateTimeInitialized = false;// to initialize time for cluster list update private int lastUpdateTimeUs=0; /** Checks for passage of interval of at least updateIntervalMs since the last update and * notifies Observers if time has passed. * Observers are called with an UpdateMessage formed from the current packet and the current timestamp. * @param packet the current data * @param timestamp the timestamp to be checked. If this timestamp is greater than the nextUpdateTime (or has gone backwards, to handle rewinds), then the UpdateMessage is sent. * @return true if Observers were notified. */ public boolean maybeCallUpdateObservers(EventPacket packet, int timestamp) { if (!updateTimeInitialized || currentUpdateIntervalMs != chip.getFilterChain().getUpdateIntervalMs()) { nextUpdateTimeUs = (int) (timestamp + chip.getFilterChain().getUpdateIntervalMs() * 1000 / AEConstants.TICK_DEFAULT_US); updateTimeInitialized = true; // TODO may not be handled correctly after rewind of filter currentUpdateIntervalMs = chip.getFilterChain().getUpdateIntervalMs(); } // ensure observers are called by next event after upateIntervalUs if (timestamp >= nextUpdateTimeUs || timestamp<lastUpdateTimeUs /* handle rewind of time */) { nextUpdateTimeUs = (int) (timestamp + chip.getFilterChain().getUpdateIntervalMs() * 1000 / AEConstants.TICK_DEFAULT_US); // log.info("notifying update observers after "+(timestamp-lastUpdateTimeUs)+"us"); setChanged(); notifyObservers(new UpdateMessage(this, packet, timestamp)); lastUpdateTimeUs=timestamp; return true; } return false; } /** Observers are called with the update message as the argument of the update; the observable is the EventFilter that calls the update. * @param packet the event packet concerned with this update. * @param timestamp the time of the update in timestamp ticks (typically us). */ public void callUpdateObservers(EventPacket packet, int timestamp) { updateTimeInitialized = false; setChanged(); notifyObservers(new UpdateMessage(this, packet, timestamp)); } /** Supplied as object for update. @see #maybeCallUpdateObservers */ public class UpdateMessage{ /** The packet that needs the update. */ public EventPacket packet; /** The timestamp of this update.*/ public int timestamp; /** The source EventFilter2D. */ EventFilter2D source; /** When a filter calls for an update of listeners it supplies this object. * * @param source - the source of the update * @param packet - the EventPacket * @param timestamp - the timestamp in us (typically) of the update */ public UpdateMessage(EventFilter2D source, EventPacket packet, int timestamp ) { this.packet = packet; this.timestamp = timestamp; this.source = source; } public String toString(){ return "UpdateMessage source="+source+" packet="+packet+" timestamp="+timestamp; } } // <editor-fold defaultstate="collapsed" desc=" Peter's Bells & Whistles " > ArrayList<JPanel> customControls; // List of added controls ArrayList<Component> customDisplays=new ArrayList(); // List of added displays /** Add your own display to the display area */ public void addDisplay(Component disp) { customDisplays.add(disp); if (this.getChip().getAeViewer().globalized) this.getChip().getAeViewer().getJaerViewer().globalViewer.addDisplayWriter(disp); else this.getChip().getAeViewer().getImagePanel().add(disp,BorderLayout.EAST); } /** Remove all displays that you added */ public void removeDisplays() { if (this.getChip().getAeViewer()==null) return; if (this.getChip().getAeViewer().globalized) for (Component c:customDisplays) this.getChip().getAeViewer().getJaerViewer().globalViewer.removeDisplay(c); else for (Component c:customDisplays) this.getChip().getAeViewer().getImagePanel().remove(c); } /** Add a panel to the filter controls */ public void addControls(JPanel controls) { // this.getChip().getAeViewer().getJaerViewer().globalViewer.addControlsToFilter(controls, this); getControlPanel().addCustomControls(controls); } /** Remove all added controls */ public void removeControls() { FilterPanel p=getControlPanel(); if (p!=null) p.removeCustomControls(); } /** Retrieves the control panel for this filter, allowing you to customize it */ private FilterPanel getControlPanel() { if((this.getChip().getAeViewer())==null) return null; if (this.getChip().getAeViewer().globalized) // return this.getChip().getAeViewer().getJaerViewer().globalViewer.procNet.getControlPanelFromFilter(this); else // Backwards compatibility { if (this.getChip().getAeViewer().getFilterFrame()==null) return null; else return this.getChip().getAeViewer().getFilterFrame().getFilterPanelForFilter(this); } } // </editor-fold> }
src/net/sf/jaer/eventprocessing/EventFilter2D.java
/* * EventFilter2D.java * * Created on November 9, 2005, 8:49 AM * * To change this template, choose Tools | Options and locate the template under * the Source Creation and Management node. Right-click the template and choose * Open. You can then make changes to the template in the Source Editor. */ package net.sf.jaer.eventprocessing; import java.awt.BorderLayout; import java.awt.Component; import java.util.ArrayList; import javax.swing.JPanel; import net.sf.jaer.aemonitor.AEConstants; import net.sf.jaer.chip.*; import net.sf.jaer.event.*; import net.sf.jaer.event.EventPacket; /** * A filter that filters or otherwise processes a packet of events. * <p> * * @author tobi */ abstract public class EventFilter2D extends EventFilter { /** The built-in reference to the output packet */ protected EventPacket out = null; /** Returns reference to the built-in output packet. * * @return the out packet. */ protected EventPacket getOutputPacket(){ return out; } protected float currentUpdateIntervalMs; /** Resets the output packet to be a new packet if none has been instanced or clears the packet if it exists */ protected void resetOut() { if (out == null) { out = new EventPacket(); } else { out.clear(); } } /** Checks <code>out</code> packet to make sure it holds the same type as the input packet. This method is used for filters that must pass output that has same event type as input. Unlike the other checkOutputPacketEventType method, this also ensures that * the output EventPacket is of the correct class, e.g. if it is a subclass of EventPacket, but only if EventPacket.setNextPacket() has been * called. I.e., the user must set EventPacket.nextPacket. * <p> * This method also copies fields from the input packet to the output packet, e.g. <code>systemModificationTimeNs</code>. @param in the input packet @see #out */ protected void checkOutputPacketEventType(EventPacket in) { in.setNextPacket(out); if (out != null && out.getEventClass() == in.getEventClass() && out.getClass() == in.getClass()) { out.systemModificationTimeNs=in.systemModificationTimeNs; return; } out = in.getNextPacket(); } /** Checks <code>out</code> packet to make sure it holds the same type of events as the given class. * This method is used for filters that must pass output that has a particular output type. This method does not ensure that the output packet is of the correct subtype of EventPacket. @param outClass the output packet. @see #out * @see EventPacket#nextPacket * @see #checkOutputPacketEventType(java.lang.Class) */ protected void checkOutputPacketEventType(Class<? extends BasicEvent> outClass) { if (out == null || out.getEventClass() == null || out.getEventClass() != outClass) { // Class oldClass=out.getEventClass(); out = new EventPacket(outClass); // log.info("oldClass="+oldClass+" outClass="+outClass+"; allocated new "+out); } } /** Subclasses implement this method to define custom processing. @param in the input packet @return the output packet */ public abstract EventPacket<?> filterPacket(EventPacket<?> in); /** Subclasses should call this super initializer */ public EventFilter2D(AEChip chip) { super(chip); this.chip = chip; } /** overrides EventFilter type in EventFilter */ protected EventFilter2D enclosedFilter; /** A filter can enclose another filter and can access and process this filter. Note that this processing is not automatic. Enclosing a filter inside another filter means that it will be built into the GUI as such @return the enclosed filter */ @Override public EventFilter2D getEnclosedFilter() { return this.enclosedFilter; } /** A filter can enclose another filter and can access and process this filter. Note that this processing is not automatic. Enclosing a filter inside another filter means that it will be built into the GUI as such. @param enclosedFilter the enclosed filter */ public void setEnclosedFilter(final EventFilter2D enclosedFilter) { if(this.enclosedFilter!=null){ log.warning("replacing existing enclosedFilter= "+this.enclosedFilter+" with new enclosedFilter= "+enclosedFilter); } super.setEnclosedFilter(enclosedFilter, this); this.enclosedFilter = enclosedFilter; } /** Resets the filter @param yes true to reset */ @Override synchronized public void setFilterEnabled(boolean yes) { super.setFilterEnabled(yes); if (yes) { resetOut(); } else { out = null; // garbage collect } } private int nextUpdateTimeUs = 0; // next timestamp we should update cluster list private boolean updateTimeInitialized = false;// to initialize time for cluster list update private int lastUpdateTimeUs=0; /** Checks for passage of interval of at least updateIntervalMs since the last update and * notifies Observers if time has passed. * Observers are called with an UpdateMessage formed from the current packet and the current timestamp. * @param packet the current data * @param timestamp the timestamp to be checked. If this timestamp is greater than the nextUpdateTime (or has gone backwards, to handle rewinds), then the UpdateMessage is sent. * @return true if Observers were notified. */ public boolean maybeCallUpdateObservers(EventPacket packet, int timestamp) { if (!updateTimeInitialized || currentUpdateIntervalMs != chip.getFilterChain().getUpdateIntervalMs()) { nextUpdateTimeUs = (int) (timestamp + chip.getFilterChain().getUpdateIntervalMs() * 1000 / AEConstants.TICK_DEFAULT_US); updateTimeInitialized = true; // TODO may not be handled correctly after rewind of filter currentUpdateIntervalMs = chip.getFilterChain().getUpdateIntervalMs(); } // ensure observers are called by next event after upateIntervalUs if (timestamp >= nextUpdateTimeUs || timestamp<lastUpdateTimeUs /* handle rewind of time */) { nextUpdateTimeUs = (int) (timestamp + chip.getFilterChain().getUpdateIntervalMs() * 1000 / AEConstants.TICK_DEFAULT_US); // log.info("notifying update observers after "+(timestamp-lastUpdateTimeUs)+"us"); setChanged(); notifyObservers(new UpdateMessage(this, packet, timestamp)); lastUpdateTimeUs=timestamp; return true; } return false; } /** Observers are called with the update message as the argument of the update; the observable is the EventFilter that calls the update. * @param packet the event packet concerned with this update. * @param timestamp the time of the update in timestamp ticks (typically us). */ public void callUpdateObservers(EventPacket packet, int timestamp) { updateTimeInitialized = false; setChanged(); notifyObservers(new UpdateMessage(this, packet, timestamp)); } /** Supplied as object for update. @see #maybeCallUpdateObservers */ public class UpdateMessage{ /** The packet that needs the update. */ public EventPacket packet; /** The timestamp of this update.*/ public int timestamp; /** The source EventFilter2D. */ EventFilter2D source; /** When a filter calls for an update of listeners it supplies this object. * * @param source - the source of the update * @param packet - the EventPacket * @param timestamp - the timestamp in us (typically) of the update */ public UpdateMessage(EventFilter2D source, EventPacket packet, int timestamp ) { this.packet = packet; this.timestamp = timestamp; this.source = source; } public String toString(){ return "UpdateMessage source="+source+" packet="+packet+" timestamp="+timestamp; } } // <editor-fold defaultstate="collapsed" desc=" Peter's Bells & Whistles " > ArrayList<JPanel> customControls; // List of added controls ArrayList<Component> customDisplays=new ArrayList(); // List of added displays /** Add your own display to the display area */ public void addDisplay(Component disp) { customDisplays.add(disp); if (this.getChip().getAeViewer().globalized) this.getChip().getAeViewer().getJaerViewer().globalViewer.addDisplayWriter(disp); else this.getChip().getAeViewer().getImagePanel().add(disp,BorderLayout.EAST); } /** Remove all displays that you added */ public void removeDisplays() { if (this.getChip().getAeViewer()==null) return; if (this.getChip().getAeViewer().globalized) for (Component c:customDisplays) this.getChip().getAeViewer().getJaerViewer().globalViewer.removeDisplay(c); else for (Component c:customDisplays) this.getChip().getAeViewer().getImagePanel().remove(c); } /** Add a panel to the filter controls */ public void addControls(JPanel controls) { // this.getChip().getAeViewer().getJaerViewer().globalViewer.addControlsToFilter(controls, this); getControlPanel().addCustomControls(controls); } /** Remove all added controls */ public void removeControls() { FilterPanel p=getControlPanel(); if (p!=null) p.removeCustomControls(); } /** Retrieves the control panel for this filter, allowing you to customize it */ private FilterPanel getControlPanel() { if((this.getChip().getAeViewer())==null) return null; if (this.getChip().getAeViewer().globalized) // return this.getChip().getAeViewer().getJaerViewer().globalViewer.procNet.getControlPanelFromFilter(this); else // Backwards compatibility { if (this.getChip().getAeViewer().getFilterFrame()==null) return null; else return this.getChip().getAeViewer().getFilterFrame().getFilterPanelForFilter(this); } } // </editor-fold> }
hopefully improved javadoc for checkOutputPacketEventType: /** Checks <code>out</code> packet to make sure it holds the same type of events as the given class. * This method is used for filters that must pass output that has a particular output type. This method does not ensure that the output packet is of the correct subtype of EventPacket. @param outClass the output packet event type class. @see #out * @see EventPacket#getNextPacket * @see #checkOutputPacketEventType(java.lang.Class) */ protected void checkOutputPacketEventType(Class<? extends BasicEvent> outClass) { git-svn-id: e3d3b427d532171a6bd7557d8a4952a393b554a2@3829 b7f4320f-462c-0410-a916-d9f35bb82d52
src/net/sf/jaer/eventprocessing/EventFilter2D.java
hopefully improved javadoc for checkOutputPacketEventType:
<ide><path>rc/net/sf/jaer/eventprocessing/EventFilter2D.java <ide> /** Checks <code>out</code> packet to make sure it holds the same type of events as the given class. <ide> * This method is used for filters that must pass output <ide> that has a particular output type. This method does not ensure that the output packet is of the correct subtype of EventPacket. <del> @param outClass the output packet. <add> @param outClass the output packet event type class. <ide> @see #out <del> * @see EventPacket#nextPacket <add> * @see EventPacket#getNextPacket <ide> * @see #checkOutputPacketEventType(java.lang.Class) <ide> */ <ide> protected void checkOutputPacketEventType(Class<? extends BasicEvent> outClass) {
Java
lgpl-2.1
ee9a81512f9bd8690c70b7a80517be455dc15477
0
threerings/nenya,threerings/nenya
// // Nenya library - tools for developing networked games // Copyright (C) 2002-2012 Three Rings Design, Inc., All Rights Reserved // http://code.google.com/p/nenya/ // // 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 package com.threerings.media.sound; import java.util.Properties; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import com.samskivert.io.StreamUtil; import com.samskivert.util.Config; import com.samskivert.util.ConfigUtil; import com.samskivert.util.LRUHashMap; import com.threerings.resource.ResourceManager; import static com.threerings.media.Log.log; /** * Loads sound clips specified by package-based properties files. */ public class SoundLoader { public SoundLoader (ResourceManager rmgr, String defaultBundle, String defaultPath) { _rmgr = rmgr; _defaultClipBundle = defaultBundle; _defaultClipPath = defaultPath; } /** * Loads the sounds for key from the config in * <code>&lt;packagePath&gt;/sound.properties</code> */ public byte[][] load (String packagePath, String key) throws IOException { String[] paths = getPaths(packagePath, key); if (paths == null) { log.warning("No such sound", "key", key); return null; } byte[][] data = new byte[paths.length][]; String bundle = getBundle(packagePath); for (int ii = 0; ii < paths.length; ii++) { data[ii] = loadClipData(bundle, paths[ii]); } return data; } /** * Returns the paths to sounds for <code>key</code> in the given package. Returns null if no * sounds are found. */ public String[] getPaths (String packagePath, String key) { return getConfig(packagePath).getValue(key, (String[])null); } /** * Returns the bundle for sounds in the given package. Returns null if the bundle isn't found. */ public String getBundle (String packagePath) { return getConfig(packagePath).getValue("bundle", (String)null); } /** * Attempts to load a sound stream from the given path from the given bundle and from the * classpath. If nothing is found, a FileNotFoundException is thrown. */ public InputStream getSound (String bundle, String path) throws IOException { InputStream rsrc; try { rsrc = _rmgr.getResource(bundle, path); } catch (FileNotFoundException notFound) { // try from the classpath try { rsrc = _rmgr.getResource(path); } catch (FileNotFoundException notFoundAgain) { throw notFound; } } return rsrc; } public void shutdown () { _configs.clear(); } /** * Get the cached Config. */ protected Config getConfig (String packagePath) { Config c = _configs.get(packagePath); if (c == null) { Properties props = new Properties(); String propFilename = packagePath + Sounds.PROP_NAME + ".properties"; try { props = ConfigUtil.loadInheritedProperties(propFilename, _rmgr.getClassLoader()); } catch (IOException ioe) { log.warning("Failed to load sound properties", "filename", propFilename, ioe); } c = new Config(props); _configs.put(packagePath, c); } return c; } /** * Read the data from the resource manager. */ protected byte[] loadClipData (String bundle, String path) throws IOException { InputStream clipin = null; try { clipin = getSound(bundle, path); } catch (FileNotFoundException fnfe) { // only play the default sound if we have verbose sound debugging turned on. if (JavaSoundPlayer._verbose.getValue()) { log.warning("Could not locate sound data", "bundle", bundle, "path", path); if (_defaultClipPath != null) { try { clipin = _rmgr.getResource(_defaultClipBundle, _defaultClipPath); } catch (FileNotFoundException fnfe3) { try { clipin = _rmgr.getResource(_defaultClipPath); } catch (FileNotFoundException fnfe4) { log.warning( "Additionally, the default fallback sound could not be located", "bundle", _defaultClipBundle, "path", _defaultClipPath); } } } else { log.warning("No fallback default sound specified!"); } } // if we couldn't load the default, rethrow if (clipin == null) { throw fnfe; } } return StreamUtil.toByteArray(clipin); } protected ResourceManager _rmgr; /** The path of the default sound to use for missing sounds. */ protected String _defaultClipBundle, _defaultClipPath; /** A cache of config objects we've created. */ protected LRUHashMap<String, Config> _configs = new LRUHashMap<String, Config>(5); }
core/src/main/java/com/threerings/media/sound/SoundLoader.java
// // Nenya library - tools for developing networked games // Copyright (C) 2002-2012 Three Rings Design, Inc., All Rights Reserved // http://code.google.com/p/nenya/ // // 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 package com.threerings.media.sound; import java.util.Properties; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import com.samskivert.io.StreamUtil; import com.samskivert.util.Config; import com.samskivert.util.ConfigUtil; import com.samskivert.util.LRUHashMap; import com.threerings.resource.ResourceManager; import static com.threerings.media.Log.log; /** * Loads sound clips specified by package-based properties files. */ public class SoundLoader { public SoundLoader (ResourceManager rmgr, String defaultBundle, String defaultPath) { _rmgr = rmgr; _defaultClipBundle = defaultBundle; _defaultClipPath = defaultPath; } /** * Loads the sounds for key from the config in * <code>&lt;packagePath&gt;/sound.properties</code> */ public byte[][] load (String packagePath, String key) throws IOException { String[] paths = getPaths(packagePath, key); if (paths == null) { log.warning("No such sound", "key", key); return null; } byte[][] data = new byte[paths.length][]; String bundle = getBundle(packagePath); for (int ii = 0; ii < paths.length; ii++) { data[ii] = loadClipData(bundle, paths[ii]); } return data; } /** * Returns the paths to sounds for <code>key</code> in the given package. Returns null if no * sounds are found. */ public String[] getPaths (String packagePath, String key) { return getConfig(packagePath).getValue(key, (String[])null); } /** * Returns the bundle for sounds in the given package. Returns null if the bundle isn't found. */ public String getBundle (String packagePath) { return getConfig(packagePath).getValue("bundle", (String)null); } /** * Attempts to load a sound stream from the given path from the given bundle and from the * classpath. If nothing is found, a FileNotFoundException is thrown. */ public InputStream getSound (String bundle, String path) throws IOException { InputStream rsrc; try { rsrc = _rmgr.getResource(bundle, path); } catch (FileNotFoundException notFound) { // try from the classpath try { rsrc = _rmgr.getResource(path); } catch (FileNotFoundException notFoundAgain) { throw notFound; } } return rsrc; } public void shutdown () { _configs.clear(); } /** * Get the cached Config. */ protected Config getConfig (String packagePath) { Config c = _configs.get(packagePath); if (c == null) { String propPath = packagePath + Sounds.PROP_NAME; Properties props = new Properties(); try { props = ConfigUtil.loadInheritedProperties(propPath + ".properties", _rmgr.getClassLoader()); } catch (IOException ioe) { log.warning("Failed to load sound properties", "path", propPath, ioe); } c = new Config(propPath, props); _configs.put(packagePath, c); } return c; } /** * Read the data from the resource manager. */ protected byte[] loadClipData (String bundle, String path) throws IOException { InputStream clipin = null; try { clipin = getSound(bundle, path); } catch (FileNotFoundException fnfe) { // only play the default sound if we have verbose sound debugging turned on. if (JavaSoundPlayer._verbose.getValue()) { log.warning("Could not locate sound data", "bundle", bundle, "path", path); if (_defaultClipPath != null) { try { clipin = _rmgr.getResource(_defaultClipBundle, _defaultClipPath); } catch (FileNotFoundException fnfe3) { try { clipin = _rmgr.getResource(_defaultClipPath); } catch (FileNotFoundException fnfe4) { log.warning( "Additionally, the default fallback sound could not be located", "bundle", _defaultClipBundle, "path", _defaultClipPath); } } } else { log.warning("No fallback default sound specified!"); } } // if we couldn't load the default, rethrow if (clipin == null) { throw fnfe; } } return StreamUtil.toByteArray(clipin); } protected ResourceManager _rmgr; /** The path of the default sound to use for missing sounds. */ protected String _defaultClipBundle, _defaultClipPath; /** A cache of config objects we've created. */ protected LRUHashMap<String, Config> _configs = new LRUHashMap<String, Config>(5); }
Fix deprecation warning with move to new samskivert library.
core/src/main/java/com/threerings/media/sound/SoundLoader.java
Fix deprecation warning with move to new samskivert library.
<ide><path>ore/src/main/java/com/threerings/media/sound/SoundLoader.java <ide> { <ide> Config c = _configs.get(packagePath); <ide> if (c == null) { <del> String propPath = packagePath + Sounds.PROP_NAME; <ide> Properties props = new Properties(); <add> String propFilename = packagePath + Sounds.PROP_NAME + ".properties"; <ide> try { <del> props = ConfigUtil.loadInheritedProperties(propPath + ".properties", <del> _rmgr.getClassLoader()); <add> props = ConfigUtil.loadInheritedProperties(propFilename, _rmgr.getClassLoader()); <ide> } catch (IOException ioe) { <del> log.warning("Failed to load sound properties", "path", propPath, ioe); <add> log.warning("Failed to load sound properties", "filename", propFilename, ioe); <ide> } <del> c = new Config(propPath, props); <add> c = new Config(props); <ide> _configs.put(packagePath, c); <ide> } <ide> return c;
JavaScript
mit
b5280ee9bc10b6362f56cf9f363d9cc1fcf6aae7
0
GreasyBacon/spotifytestapp,GreasyBacon/spotifytestapp
var createPlaylist = function(userId, accessToken, playlistName) { $.ajax({ url: 'https://api.spotify.com/v1/users/' + userId + '/playlists', method: 'POST', headers: { 'Authorization': 'Bearer ' + accessToken }, data: JSON.stringify({ 'name': playlistName, 'public': true}), contentType: "application/json; charset=utf-8", dataType: "json", success: function(response){ return response['id']; }, error: function(){ } }); }; var getPlaylistTracks = function(userId, accessToken, tracksURL) { var tracks = []; var initialOffset = 0; var apiCall = function(offset) { $.ajax({ url: tracksURL + '?offset=' + offset, method: 'GET', headers: { 'Authorization': 'Bearer ' + accessToken }, success: function(response){ if (response['items'].length){ response['items'].forEach(function(track){ tracks.push(track['track']['id']); }); if (response['next']){ initialOffset += 100; setTimeout(function(){apiCall(initialOffset);}, 2000); } else { console.log(tracks); return tracks; } } else { return tracks; } }, error: function(){ } }); }; apiCall(initialOffset); }; var addTracksToPlaylist = function(userId, accessToken, playlistId, trackIds) { };
public/js/merge.js
var createPlaylist = function(userId, accessToken, playlistName) { $.ajax({ url: 'https://api.spotify.com/v1/users/' + userId + '/playlists', method: 'POST', headers: { 'Authorization': 'Bearer ' + accessToken }, data: JSON.stringify({ 'name': playlistName, 'public': true}), contentType: "application/json; charset=utf-8", dataType: "json", success: function(response){ return response; }, error: function(){ } }); }; var getPlaylistTracks = function(userId, accessToken, playlistId) { }; var addTracksToPlaylist = function(userId, accessToken, playlistId, trackIds) { };
Implemented getPlaylistTracks function.
public/js/merge.js
Implemented getPlaylistTracks function.
<ide><path>ublic/js/merge.js <ide> contentType: "application/json; charset=utf-8", <ide> dataType: "json", <ide> success: function(response){ <del> return response; <add> return response['id']; <ide> }, <ide> error: function(){ <ide> <ide> <ide> }; <ide> <del>var getPlaylistTracks = function(userId, accessToken, playlistId) { <add>var getPlaylistTracks = function(userId, accessToken, tracksURL) { <add> <add> var tracks = []; <add> var initialOffset = 0; <add> <add> var apiCall = function(offset) { <add> $.ajax({ <add> url: tracksURL + '?offset=' + offset, <add> method: 'GET', <add> headers: { <add> 'Authorization': 'Bearer ' + accessToken <add> }, <add> success: function(response){ <add> <add> if (response['items'].length){ <add> <add> response['items'].forEach(function(track){ <add> tracks.push(track['track']['id']); <add> }); <add> <add> if (response['next']){ <add> <add> initialOffset += 100; <add> setTimeout(function(){apiCall(initialOffset);}, 2000); <add> <add> } else { <add> console.log(tracks); <add> return tracks; <add> } <add> <add> } else { <add> return tracks; <add> } <add> <add> }, <add> error: function(){ <add> <add> } <add> }); <add> }; <add> <add> apiCall(initialOffset); <ide> <ide> }; <ide>
JavaScript
apache-2.0
6a0acebd112d9a5a3b942bf2e83706e1a4789046
0
entrylabs/entryjs,entrylabs/entryjs,entrylabs/entryjs
/** * nt11576 Lee.Jaewon * commented area with "motion test" is for the motion detection testing canvas to test the cv, uncomment all codes labeled "motion test" */ import { GEHelper } from '../graphicEngine/GEHelper'; import VideoWorker from './workers/video.worker'; import clamp from 'lodash/clamp'; // webcam input resolution setting const VIDEO_WIDTH = 640; const VIDEO_HEIGHT = 360; // canvasVideo SETTING, used in all canvas' const CANVAS_WIDTH = 480; const CANVAS_HEIGHT = 270; // ** MOTION DETECTION // motion detection parameters const SAMPLE_SIZE = 15; const BOUNDARY_OFFSET = 4; const SAME_COORDINATE_COMPENSATION = 10; const worker = new VideoWorker(); class VideoUtils { constructor() { //with purpose of utilizing same value outside this.CANVAS_WIDTH = CANVAS_WIDTH; this.CANVAS_HEIGHT = CANVAS_HEIGHT; this.video = null; this.canvasVideo = null; this.flipStatus = { horizontal: false, vertical: false, }; // motion related this.motions = [...Array(CANVAS_HEIGHT / SAMPLE_SIZE)].map((e) => Array(CANVAS_WIDTH / SAMPLE_SIZE) ); this.motionPoint = { x: 0, y: 0 }; this.motionDirection = [...Array(CANVAS_HEIGHT / SAMPLE_SIZE)].map((e) => Array(CANVAS_WIDTH / SAMPLE_SIZE) ); this.totalMotions = 0; this.totalMotionDirection = { x: 0, y: 0 }; ///////////////////////////////// this.objects = null; this.initialized = false; this.poses = { predictions: [], adjacents: [] }; this.isInitialized = false; this.videoOnLoadHandler = this.videoOnLoadHandler.bind(this); //face models this.faces = []; //only for webGL this.subCanvas = null; this.indicatorStatus = { pose: false, face: false, object: false, }; } showIndicator(type) { this.indicatorStatus[type] = true; } removeIndicator(type) { this.indicatorStatus[type] = false; GEHelper.resetHandlers(); } reset() { this.indicatorStatus = { pose: false, face: false, object: false, }; this.disableAllModels(); GEHelper.resetHandlers(); this.turnOnWebcam(); if (!this.flipStatus.horizontal) { this.setOptions('hflip'); } if (this.flipStatus.vertical) { this.setOptions('vflip'); } GEHelper.resetCanvasBrightness(this.canvasVideo); GEHelper.setVideoAlpha(this.canvasVideo, 50); GEHelper.tickByEngine(); this.poses = { predictions: [], adjacents: [] }; this.faces = []; this.objects = []; } async initialize() { if (this.isInitialized) { return; } this.isInitialized = true; // this canvas is for motion calculation if (!this.inMemoryCanvas) { this.inMemoryCanvas = document.createElement('canvas'); this.inMemoryCanvas.width = CANVAS_WIDTH; this.inMemoryCanvas.height = CANVAS_HEIGHT; } // //motion test // this.tempCanvas = document.createElement('canvas'); // this.tempCanvas.width = CANVAS_WIDTH; // this.tempCanvas.height = CANVAS_HEIGHT; // const tempTarget = document.getElementsByClassName('uploadInput')[0]; // tempTarget.parentNode.insertBefore(this.tempCanvas, tempTarget); // //motion test navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; if (navigator.getUserMedia) { try { const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: { facingMode: 'user', width: VIDEO_WIDTH, height: VIDEO_HEIGHT, }, }); this.faceModelLoaded = true; this.stream = stream; const video = document.createElement('video'); video.srcObject = stream; video.width = CANVAS_WIDTH; video.height = CANVAS_HEIGHT; this.canvasVideo = GEHelper.getVideoElement(video); this.video = video; video.onloadedmetadata = this.videoOnLoadHandler; } catch (err) { console.log(err); this.isInitialized = false; } } else { console.log('getUserMedia not supported'); } } startDrawIndicators() { if (this.objects && this.indicatorStatus.object) { GEHelper.drawObjectBox(this.objects, this.flipStatus); } if (this.faces && this.indicatorStatus.face) { GEHelper.drawFaceBoxes(this.faces, this.flipStatus); } if (this.poses && this.indicatorStatus.pose) { GEHelper.drawHumanPoints(this.poses.predictions, this.flipStatus); GEHelper.drawHumanSkeletons(this.poses.adjacents, this.flipStatus); } requestAnimationFrame(this.startDrawIndicators.bind(this)); } videoOnLoadHandler() { Entry.addEventListener('beforeStop', this.reset.bind(this)); this.video.play(); this.startDrawIndicators(); this.turnOnWebcam(); if (this.initialized) { return; } const [track] = this.stream.getVideoTracks(); this.imageCapture = new ImageCapture(track); worker.onmessage = (e) => { const { type, message } = e.data; if (Entry.engine.state !== 'run' && type !== 'init') { return; } switch (type) { case 'init': this.initialized = true; break; case 'face': this.faces = message; break; case 'coco': this.objects = message; break; case 'pose': this.poses = message; break; } }; const offCanvas = new OffscreenCanvas(CANVAS_WIDTH, CANVAS_HEIGHT); worker.postMessage( { type: 'init', width: CANVAS_WIDTH, height: CANVAS_HEIGHT, offCanvas, }, [offCanvas] ); this.sendImageToWorker(); this.motionDetect(); } manageModel(target, mode) { worker.postMessage({ type: 'handle', target, mode, }); } disableAllModels() { worker.postMessage({ type: 'handleOff', }); } async sendImageToWorker() { const captured = await this.imageCapture.grabFrame(); worker.postMessage({ type: 'estimate', image: captured }, [captured]); // //motion test // const tempCtx = this.tempCanvas.getContext('2d'); // tempCtx.clearRect(0, 0, this.tempCanvas.width, this.tempCanvas.height); // this.motions.forEach((row, j) => { // row.forEach((col, i) => { // const { r, g, b, rDiff, gDiff, bDiff } = col; // tempCtx.fillStyle = `rgb(${rDiff},${gDiff},${bDiff})`; // tempCtx.fillRect(i * SAMPLE_SIZE, j * SAMPLE_SIZE, SAMPLE_SIZE, SAMPLE_SIZE); // }); // }); // //motion test setTimeout(() => { requestAnimationFrame(this.sendImageToWorker.bind(this)); }, 50); } // ** MOTION DETECTION motionDetect() { if (!this.inMemoryCanvas) { return; } /* let minX = CANVAS_WIDTH / 2 + x - (width * scaleX) / 2; let maxX = CANVAS_WIDTH / 2 + x + (width * scaleX) / 2; let minY = CANVAS_HEIGHT / 2 - y - (height * scaleY) / 2; let maxY = CANVAS_HEIGHT / 2 - y + (height * scaleY) / 2; */ const context = this.inMemoryCanvas.getContext('2d'); context.clearRect(0, 0, this.inMemoryCanvas.width, this.inMemoryCanvas.height); context.drawImage(this.video, 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); const imageData = context.getImageData(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); const data = imageData.data; this.totalMotions = 0; let totalMotionDirectionX = 0; let totalMotionDirectionY = 0; for (let y = 0; y < CANVAS_HEIGHT; y += SAMPLE_SIZE) { for (let x = 0; x < CANVAS_WIDTH; x += SAMPLE_SIZE) { const pos = (x + y * CANVAS_WIDTH) * 4; const r = data[pos]; const g = data[pos + 1]; const b = data[pos + 2]; // const a = data[pos + 3]; // diffScheme; const yIndex = y / SAMPLE_SIZE; const xIndex = x / SAMPLE_SIZE; const currentPos = this.motions[yIndex][xIndex] || { r: 0, g: 0, b: 0 }; const rDiff = Math.abs(currentPos.r - r); const gDiff = Math.abs(currentPos.g - g); const bDiff = Math.abs(currentPos.b - b); const areaMotionScore = rDiff + gDiff + bDiff / (SAMPLE_SIZE * SAMPLE_SIZE); const xLength = this.motions[0].length; const yLength = this.motions.length; const mostSimilar = { x: 0, y: 0, diff: 99999999 }; const minScanY = clamp(yIndex - BOUNDARY_OFFSET, 0, yLength - 1); const maxScanY = clamp(yIndex + BOUNDARY_OFFSET, 0, yLength - 1); const minScanX = clamp(xIndex - BOUNDARY_OFFSET, 0, xLength - 1); const maxScanX = clamp(xIndex + BOUNDARY_OFFSET, 0, xLength - 1); for (let scopeY = minScanY; scopeY <= maxScanY; scopeY++) { for (let scopeX = minScanX; scopeX <= maxScanX; scopeX++) { const valuesNearPos = this.motions[scopeY][scopeX] || { r: 0, g: 0, b: 0, }; const rDiffScope = Math.abs(valuesNearPos.r - r); const gDiffScope = Math.abs(valuesNearPos.g - g); const bDiffScope = Math.abs(valuesNearPos.b - b); let diff = rDiffScope + gDiffScope + bDiffScope; // compensation only if scope is looking for the same coordination in case of reducing noise when no movement has been detected. if (yIndex === scopeY && xIndex === scopeX) { diff = diff - SAME_COORDINATE_COMPENSATION; } if (diff < mostSimilar.diff) { mostSimilar.x = scopeX; mostSimilar.y = scopeY; mostSimilar.diff = diff; } } } this.totalMotions += areaMotionScore; //reduce noise of small motions if (mostSimilar.x > 1) { totalMotionDirectionX += mostSimilar.x - xIndex; } if (mostSimilar.y > 1) { totalMotionDirectionY += mostSimilar.y - yIndex; } this.motions[yIndex][xIndex] = { r, g, b, rDiff, gDiff, bDiff, }; this.motionDirection[yIndex][xIndex] = { x: mostSimilar.x - xIndex, y: mostSimilar.y - yIndex, }; } this.totalMotionDirection = { x: totalMotionDirectionX, y: totalMotionDirectionY, }; } setTimeout(this.motionDetect.bind(this), 200); } async checkUserCamAvailable() { try { await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); return true; } catch (err) { return false; } } // camera power cameraSwitch(value) { switch (value) { case 'on': this.turnOnWebcam(); break; default: this.turnOffWebcam(); break; } } turnOffWebcam() { GEHelper.turnOffWebcam(this.canvasVideo); } turnOnWebcam() { GEHelper.drawVideoElement(this.canvasVideo); if (!this.flipStatus.horizontal) { this.setOptions('hflip'); } } // option change setOptions(target, value) { if (!this.canvasVideo) { return; } switch (target) { case 'brightness': GEHelper.setVideoBrightness(this.canvasVideo, value); break; case 'transparency': GEHelper.setVideoAlpha(this.canvasVideo, value); break; case 'hflip': this.flipStatus.horizontal = !this.flipStatus.horizontal; worker.postMessage({ type: 'option', option: { flipStatus: this.flipStatus }, }); GEHelper.hFlipVideoElement(this.canvasVideo); break; case 'vflip': this.flipStatus.vertical = !this.flipStatus.vertical; GEHelper.vFlipVideoElement(this.canvasVideo); break; } } // videoUtils.destroy does not actually destroy singletonClass, but instead resets the whole stuff except models to be used destroy() { this.disableAllModels(); this.turnOffWebcam(); this.stream.getTracks().forEach((track) => { track.stop(); }); worker.terminate(); this.video = null; this.canvasVideo = null; this.inMemoryCanvas = null; this.flipStatus = { horizontal: false, vertical: false, }; this.poses = null; this.isInitialized = false; } } //Entry 네임스페이스에는 존재하지 않으므로 외부에서 사용할 수 없다. export default new VideoUtils();
src/util/videoUtils.js
/** * nt11576 Lee.Jaewon * commented area with "motion test" is for the motion detection testing canvas to test the cv, uncomment all codes labeled "motion test" */ import { GEHelper } from '../graphicEngine/GEHelper'; import VideoWorker from './workers/video.worker'; import clamp from 'lodash/clamp'; // webcam input resolution setting const VIDEO_WIDTH = 640; const VIDEO_HEIGHT = 360; // canvasVideo SETTING, used in all canvas' const CANVAS_WIDTH = 480; const CANVAS_HEIGHT = 270; // ** MOTION DETECTION // motion detection parameters const SAMPLE_SIZE = 15; const worker = new VideoWorker(); class VideoUtils { constructor() { //with purpose of utilizing same value outside this.CANVAS_WIDTH = CANVAS_WIDTH; this.CANVAS_HEIGHT = CANVAS_HEIGHT; this.video = null; this.canvasVideo = null; this.flipStatus = { horizontal: false, vertical: false, }; // motion related this.motions = [...Array(CANVAS_HEIGHT / SAMPLE_SIZE)].map((e) => Array(CANVAS_WIDTH / SAMPLE_SIZE) ); this.motionPoint = { x: 0, y: 0 }; this.motionDirection = [...Array(CANVAS_HEIGHT / SAMPLE_SIZE)].map((e) => Array(CANVAS_WIDTH / SAMPLE_SIZE) ); this.totalMotions = 0; this.totalMotionDirection = { x: 0, y: 0 }; ///////////////////////////////// this.objects = null; this.initialized = false; this.poses = { predictions: [], adjacents: [] }; this.isInitialized = false; this.videoOnLoadHandler = this.videoOnLoadHandler.bind(this); //face models this.faces = []; //only for webGL this.subCanvas = null; this.indicatorStatus = { pose: false, face: false, object: false, }; } showIndicator(type) { this.indicatorStatus[type] = true; } removeIndicator(type) { this.indicatorStatus[type] = false; GEHelper.resetHandlers(); } reset() { this.indicatorStatus = { pose: false, face: false, object: false, }; this.disableAllModels(); GEHelper.resetHandlers(); this.turnOnWebcam(); if (!this.flipStatus.horizontal) { this.setOptions('hflip'); } if (this.flipStatus.vertical) { this.setOptions('vflip'); } GEHelper.resetCanvasBrightness(this.canvasVideo); GEHelper.setVideoAlpha(this.canvasVideo, 50); GEHelper.tickByEngine(); this.poses = { predictions: [], adjacents: [] }; this.faces = []; this.objects = []; } async initialize() { if (this.isInitialized) { return; } this.isInitialized = true; // this canvas is for motion calculation if (!this.inMemoryCanvas) { this.inMemoryCanvas = document.createElement('canvas'); this.inMemoryCanvas.width = CANVAS_WIDTH; this.inMemoryCanvas.height = CANVAS_HEIGHT; } // //motion test // this.tempCanvas = document.createElement('canvas'); // this.tempCanvas.width = CANVAS_WIDTH; // this.tempCanvas.height = CANVAS_HEIGHT; // const tempTarget = document.getElementsByClassName('uploadInput')[0]; // tempTarget.parentNode.insertBefore(this.tempCanvas, tempTarget); // //motion test navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; if (navigator.getUserMedia) { try { const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: { facingMode: 'user', width: VIDEO_WIDTH, height: VIDEO_HEIGHT, }, }); this.faceModelLoaded = true; this.stream = stream; const video = document.createElement('video'); video.srcObject = stream; video.width = CANVAS_WIDTH; video.height = CANVAS_HEIGHT; this.canvasVideo = GEHelper.getVideoElement(video); this.video = video; video.onloadedmetadata = this.videoOnLoadHandler; } catch (err) { console.log(err); this.isInitialized = false; } } else { console.log('getUserMedia not supported'); } } startDrawIndicators() { if (this.objects && this.indicatorStatus.object) { GEHelper.drawObjectBox(this.objects, this.flipStatus); } if (this.faces && this.indicatorStatus.face) { GEHelper.drawFaceBoxes(this.faces, this.flipStatus); } if (this.poses && this.indicatorStatus.pose) { GEHelper.drawHumanPoints(this.poses.predictions, this.flipStatus); GEHelper.drawHumanSkeletons(this.poses.adjacents, this.flipStatus); } requestAnimationFrame(this.startDrawIndicators.bind(this)); } videoOnLoadHandler() { Entry.addEventListener('beforeStop', this.reset.bind(this)); this.video.play(); this.startDrawIndicators(); this.turnOnWebcam(); if (this.initialized) { return; } const [track] = this.stream.getVideoTracks(); this.imageCapture = new ImageCapture(track); worker.onmessage = (e) => { const { type, message } = e.data; if (Entry.engine.state !== 'run' && type !== 'init') { return; } switch (type) { case 'init': this.initialized = true; break; case 'face': this.faces = message; break; case 'coco': this.objects = message; break; case 'pose': this.poses = message; break; } }; const offCanvas = new OffscreenCanvas(CANVAS_WIDTH, CANVAS_HEIGHT); worker.postMessage( { type: 'init', width: CANVAS_WIDTH, height: CANVAS_HEIGHT, offCanvas, }, [offCanvas] ); this.sendImageToWorker(); this.motionDetect(); } manageModel(target, mode) { worker.postMessage({ type: 'handle', target, mode, }); } disableAllModels() { worker.postMessage({ type: 'handleOff', }); } async sendImageToWorker() { const captured = await this.imageCapture.grabFrame(); worker.postMessage({ type: 'estimate', image: captured }, [captured]); // //motion test // const tempCtx = this.tempCanvas.getContext('2d'); // tempCtx.clearRect(0, 0, this.tempCanvas.width, this.tempCanvas.height); // this.motions.forEach((row, j) => { // row.forEach((col, i) => { // const { r, g, b, rDiff, gDiff, bDiff } = col; // tempCtx.fillStyle = `rgb(${rDiff},${gDiff},${bDiff})`; // tempCtx.fillRect(i * SAMPLE_SIZE, j * SAMPLE_SIZE, SAMPLE_SIZE, SAMPLE_SIZE); // }); // }); // //motion test setTimeout(() => { requestAnimationFrame(this.sendImageToWorker.bind(this)); }, 50); } // ** MOTION DETECTION motionDetect() { if (!this.inMemoryCanvas) { return; } /* let minX = CANVAS_WIDTH / 2 + x - (width * scaleX) / 2; let maxX = CANVAS_WIDTH / 2 + x + (width * scaleX) / 2; let minY = CANVAS_HEIGHT / 2 - y - (height * scaleY) / 2; let maxY = CANVAS_HEIGHT / 2 - y + (height * scaleY) / 2; */ const context = this.inMemoryCanvas.getContext('2d'); context.clearRect(0, 0, this.inMemoryCanvas.width, this.inMemoryCanvas.height); context.drawImage(this.video, 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); const imageData = context.getImageData(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); const data = imageData.data; this.totalMotions = 0; let totalMotionDirectionX = 0; let totalMotionDirectionY = 0; for (let y = 0; y < CANVAS_HEIGHT; y += SAMPLE_SIZE) { for (let x = 0; x < CANVAS_WIDTH; x += SAMPLE_SIZE) { const pos = (x + y * CANVAS_WIDTH) * 4; const r = data[pos]; const g = data[pos + 1]; const b = data[pos + 2]; // const a = data[pos + 3]; // diffScheme; const yIndex = y / SAMPLE_SIZE; const xIndex = x / SAMPLE_SIZE; const currentPos = this.motions[yIndex][xIndex] || { r: 0, g: 0, b: 0 }; const rDiff = Math.abs(currentPos.r - r); const gDiff = Math.abs(currentPos.g - g); const bDiff = Math.abs(currentPos.b - b); const areaMotionScore = rDiff + gDiff + bDiff / (SAMPLE_SIZE * SAMPLE_SIZE); const xLength = this.motions[0].length; const yLength = this.motions.length; const mostSimilar = { x: 0, y: 0, diff: 99999999 }; for (let scopeY = yIndex - 2; scopeY <= yIndex + 2; scopeY++) { for (let scopeX = xIndex - 2; scopeX <= xIndex + 2; scopeX++) { // find min diff for the direction change const clampedX = clamp(scopeX, 0, xLength - 1); const clampedY = clamp(scopeY, 0, yLength - 1); const valuesNearPos = this.motions[clampedY][clampedX] || { r: 0, g: 0, b: 0, }; const rDiffScope = Math.abs(valuesNearPos.r - r); const gDiffScope = Math.abs(valuesNearPos.g - g); const bDiffScope = Math.abs(valuesNearPos.b - b); const diff = rDiffScope + gDiffScope + bDiffScope; if (diff < mostSimilar.diff) { mostSimilar.x = clampedX; mostSimilar.y = clampedY; mostSimilar.diff = diff; } } } // console.log('x : ', mostSimilar.x - xIndex, ' Y: ', mostSimilar.y - yIndex); this.totalMotions += areaMotionScore; totalMotionDirectionX += mostSimilar.x - xIndex; totalMotionDirectionY += mostSimilar.y - yIndex; this.motions[yIndex][xIndex] = { r, g, b, rDiff, gDiff, bDiff, }; this.motionDirection[yIndex][xIndex] = { x: mostSimilar.x - xIndex, y: mostSimilar.y - yIndex, }; } this.totalMotionDirection = { x: totalMotionDirectionX, y: totalMotionDirectionY, }; } setTimeout(this.motionDetect.bind(this), 80); } async checkUserCamAvailable() { try { await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); return true; } catch (err) { return false; } } // camera power cameraSwitch(value) { switch (value) { case 'on': this.turnOnWebcam(); break; default: this.turnOffWebcam(); break; } } turnOffWebcam() { GEHelper.turnOffWebcam(this.canvasVideo); } turnOnWebcam() { GEHelper.drawVideoElement(this.canvasVideo); if (!this.flipStatus.horizontal) { this.setOptions('hflip'); } } // option change setOptions(target, value) { if (!this.canvasVideo) { return; } switch (target) { case 'brightness': GEHelper.setVideoBrightness(this.canvasVideo, value); break; case 'transparency': GEHelper.setVideoAlpha(this.canvasVideo, value); break; case 'hflip': this.flipStatus.horizontal = !this.flipStatus.horizontal; worker.postMessage({ type: 'option', option: { flipStatus: this.flipStatus }, }); GEHelper.hFlipVideoElement(this.canvasVideo); break; case 'vflip': this.flipStatus.vertical = !this.flipStatus.vertical; GEHelper.vFlipVideoElement(this.canvasVideo); break; } } // videoUtils.destroy does not actually destroy singletonClass, but instead resets the whole stuff except models to be used destroy() { this.disableAllModels(); this.turnOffWebcam(); this.stream.getTracks().forEach((track) => { track.stop(); }); worker.terminate(); this.video = null; this.canvasVideo = null; this.inMemoryCanvas = null; this.flipStatus = { horizontal: false, vertical: false, }; this.poses = null; this.isInitialized = false; } } //Entry 네임스페이스에는 존재하지 않으므로 외부에서 사용할 수 없다. export default new VideoUtils();
화면 움직임 감지 개선
src/util/videoUtils.js
화면 움직임 감지 개선
<ide><path>rc/util/videoUtils.js <ide> // ** MOTION DETECTION <ide> // motion detection parameters <ide> const SAMPLE_SIZE = 15; <add>const BOUNDARY_OFFSET = 4; <add>const SAME_COORDINATE_COMPENSATION = 10; <ide> <ide> const worker = new VideoWorker(); <ide> <ide> const xLength = this.motions[0].length; <ide> const yLength = this.motions.length; <ide> const mostSimilar = { x: 0, y: 0, diff: 99999999 }; <del> for (let scopeY = yIndex - 2; scopeY <= yIndex + 2; scopeY++) { <del> for (let scopeX = xIndex - 2; scopeX <= xIndex + 2; scopeX++) { <del> // find min diff for the direction change <del> const clampedX = clamp(scopeX, 0, xLength - 1); <del> const clampedY = clamp(scopeY, 0, yLength - 1); <del> const valuesNearPos = this.motions[clampedY][clampedX] || { <add> <add> const minScanY = clamp(yIndex - BOUNDARY_OFFSET, 0, yLength - 1); <add> const maxScanY = clamp(yIndex + BOUNDARY_OFFSET, 0, yLength - 1); <add> const minScanX = clamp(xIndex - BOUNDARY_OFFSET, 0, xLength - 1); <add> const maxScanX = clamp(xIndex + BOUNDARY_OFFSET, 0, xLength - 1); <add> <add> for (let scopeY = minScanY; scopeY <= maxScanY; scopeY++) { <add> for (let scopeX = minScanX; scopeX <= maxScanX; scopeX++) { <add> const valuesNearPos = this.motions[scopeY][scopeX] || { <ide> r: 0, <ide> g: 0, <ide> b: 0, <ide> const rDiffScope = Math.abs(valuesNearPos.r - r); <ide> const gDiffScope = Math.abs(valuesNearPos.g - g); <ide> const bDiffScope = Math.abs(valuesNearPos.b - b); <del> const diff = rDiffScope + gDiffScope + bDiffScope; <add> let diff = rDiffScope + gDiffScope + bDiffScope; <add> // compensation only if scope is looking for the same coordination in case of reducing noise when no movement has been detected. <add> if (yIndex === scopeY && xIndex === scopeX) { <add> diff = diff - SAME_COORDINATE_COMPENSATION; <add> } <ide> if (diff < mostSimilar.diff) { <del> mostSimilar.x = clampedX; <del> mostSimilar.y = clampedY; <add> mostSimilar.x = scopeX; <add> mostSimilar.y = scopeY; <ide> mostSimilar.diff = diff; <ide> } <ide> } <ide> } <del> // console.log('x : ', mostSimilar.x - xIndex, ' Y: ', mostSimilar.y - yIndex); <ide> this.totalMotions += areaMotionScore; <del> totalMotionDirectionX += mostSimilar.x - xIndex; <del> totalMotionDirectionY += mostSimilar.y - yIndex; <add> <add> //reduce noise of small motions <add> if (mostSimilar.x > 1) { <add> totalMotionDirectionX += mostSimilar.x - xIndex; <add> } <add> if (mostSimilar.y > 1) { <add> totalMotionDirectionY += mostSimilar.y - yIndex; <add> } <ide> <ide> this.motions[yIndex][xIndex] = { <ide> r, <ide> }; <ide> } <ide> <del> setTimeout(this.motionDetect.bind(this), 80); <add> setTimeout(this.motionDetect.bind(this), 200); <ide> } <ide> <ide> async checkUserCamAvailable() {
Java
apache-2.0
752062c1a381f901f51c3e03ec63ead34ed2c636
0
debezium/debezium,debezium/debezium,debezium/debezium,debezium/debezium
/* * Copyright Debezium Authors. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package io.debezium.connector.mongodb; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; import com.mongodb.MongoClientSettings; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.MongoClient; import io.debezium.annotation.ThreadSafe; /** * A connection pool of MongoClient instances. This pool supports creating clients that communicate explicitly with a single * server, or clients that communicate with any members of a replica set or sharded cluster given a set of seed addresses. * * @author Randall Hauch */ @ThreadSafe public class MongoClients { /** * Obtain a builder that can be used to configure and {@link Builder#build() create} a connection pool. * * @return the new builder; never null */ public static Builder create() { return new Builder(); } /** * Configures and builds a ConnectionPool. */ public static class Builder { private final MongoClientSettings.Builder settingsBuilder = MongoClientSettings.builder(); /** * Add the given {@link MongoCredential} for use when creating clients. * * @param credential the credential; may be {@code null}, though this method does nothing if {@code null} * @return this builder object so methods can be chained; never null */ public Builder withCredential(MongoCredential credential) { if (credential != null) { settingsBuilder.credential(credential); } return this; } /** * Obtain the options builder for client connections. * * @return the option builder; never null */ public MongoClientSettings.Builder settings() { return settingsBuilder; } /** * Build the client pool that will use the credentials and options already configured on this builder. * * @return the new client pool; never null */ public MongoClients build() { return new MongoClients(settingsBuilder); } } protected static Supplier<MongoClientSettings.Builder> createSettingsSupplier(MongoClientSettings settings) { return () -> MongoClientSettings.builder(settings); } private final Map<ServerAddress, MongoClient> directConnections = new ConcurrentHashMap<>(); private final Map<List<ServerAddress>, MongoClient> connections = new ConcurrentHashMap<>(); private final Supplier<MongoClientSettings.Builder> settingsSupplier; private MongoClients(MongoClientSettings.Builder settings) { this.settingsSupplier = createSettingsSupplier(settings.build()); } /** * Creates fresh {@link MongoClientSettings.Builder} from {@link #settingsSupplier} * @return connection settings builder */ protected MongoClientSettings.Builder settings() { return settingsSupplier.get(); } /** * Clear out and close any open connections. */ public void clear() { directConnections.values().forEach(MongoClient::close); connections.values().forEach(MongoClient::close); directConnections.clear(); connections.clear(); } /** * Obtain a direct client connection to the specified server. This is typically used to connect to a standalone server, * but it also can be used to obtain a client that will only use this server, even if the server is a member of a replica * set or sharded cluster. * <p> * The format of the supplied string is one of the following: * * <pre> * host:port * host * </pre> * * where {@code host} contains the resolvable hostname or IP address of the server, and {@code port} is the integral port * number. If the port is not provided, the {@link ServerAddress#defaultPort() default port} is used. If neither the host * or port are provided (or {@code addressString} is {@code null}), then an address will use the * {@link ServerAddress#defaultHost() default host} and {@link ServerAddress#defaultPort() default port}. * * @param addressString the string that contains the host and port of the server * @return the MongoClient instance; never null */ public MongoClient clientFor(String addressString) { return clientFor(MongoUtil.parseAddress(addressString)); } /** * Obtain a direct client connection to the specified server. This is typically used to connect to a standalone server, * but it also can be used to obtain a client that will only use this server, even if the server is a member of a replica * set or sharded cluster. * * @param address the address of the server to use * @return the MongoClient instance; never null */ public MongoClient clientFor(ServerAddress address) { return directConnections.computeIfAbsent(address, this::directConnection); } /** * Obtain a client connection to the replica set or cluster. The supplied addresses are used as seeds, and once a connection * is established it will discover all of the members. * <p> * The format of the supplied string is one of the following: * * <pre> * replicaSetName/host:port * replicaSetName/host:port,host2:port2 * replicaSetName/host:port,host2:port2,host3:port3 * host:port * host:port,host2:port2 * host:port,host2:port2,host3:port3 * </pre> * * where {@code replicaSetName} is the name of the replica set, {@code host} contains the resolvable hostname or IP address of * the server, and {@code port} is the integral port number. If the port is not provided, the * {@link ServerAddress#defaultPort() default port} is used. If neither the host or port are provided (or * {@code addressString} is {@code null}), then an address will use the {@link ServerAddress#defaultHost() default host} and * {@link ServerAddress#defaultPort() default port}. * <p> * This method does not use the replica set name. * * @param addressList the string containing a comma-separated list of host and port pairs, optionally preceded by a * replica set name * @return the MongoClient instance; never null */ public MongoClient clientForMembers(String addressList) { return clientForMembers(MongoUtil.parseAddresses(addressList)); } /** * Obtain a client connection to the replica set or cluster. The supplied addresses are used as seeds, and once a connection * is established it will discover all of the members. * * @param seedAddresses the seed addresses * @return the MongoClient instance; never null */ public MongoClient clientForMembers(List<ServerAddress> seedAddresses) { return connections.computeIfAbsent(seedAddresses, this::connection); } protected MongoClient directConnection(ServerAddress address) { MongoClientSettings.Builder settings = settings().applyToClusterSettings(builder -> builder.hosts(Collections.singletonList(address))); return com.mongodb.client.MongoClients.create(settings.build()); } protected MongoClient connection(List<ServerAddress> addresses) { MongoClientSettings.Builder settings = settings().applyToClusterSettings(builder -> builder.hosts(addresses)); return com.mongodb.client.MongoClients.create(settings.build()); } }
debezium-connector-mongodb/src/main/java/io/debezium/connector/mongodb/MongoClients.java
/* * Copyright Debezium Authors. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package io.debezium.connector.mongodb; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.mongodb.MongoClientSettings; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.MongoClient; import io.debezium.annotation.ThreadSafe; /** * A connection pool of MongoClient instances. This pool supports creating clients that communicate explicitly with a single * server, or clients that communicate with any members of a replica set or sharded cluster given a set of seed addresses. * * @author Randall Hauch */ @ThreadSafe public class MongoClients { /** * Obtain a builder that can be used to configure and {@link Builder#build() create} a connection pool. * * @return the new builder; never null */ public static Builder create() { return new Builder(); } /** * Configures and builds a ConnectionPool. */ public static class Builder { private final MongoClientSettings.Builder settingsBuilder = MongoClientSettings.builder(); /** * Add the given {@link MongoCredential} for use when creating clients. * * @param credential the credential; may be {@code null}, though this method does nothing if {@code null} * @return this builder object so methods can be chained; never null */ public Builder withCredential(MongoCredential credential) { if (credential != null) { settingsBuilder.credential(credential); } return this; } /** * Obtain the options builder for client connections. * * @return the option builder; never null */ public MongoClientSettings.Builder settings() { return settingsBuilder; } /** * Build the client pool that will use the credentials and options already configured on this builder. * * @return the new client pool; never null */ public MongoClients build() { return new MongoClients(settingsBuilder); } } private final Map<ServerAddress, MongoClient> directConnections = new ConcurrentHashMap<>(); private final Map<List<ServerAddress>, MongoClient> connections = new ConcurrentHashMap<>(); private final MongoClientSettings.Builder settings; private MongoClients(MongoClientSettings.Builder settings) { this.settings = settings; } /** * Clear out and close any open connections. */ public void clear() { directConnections.values().forEach(MongoClient::close); connections.values().forEach(MongoClient::close); directConnections.clear(); connections.clear(); } /** * Obtain a direct client connection to the specified server. This is typically used to connect to a standalone server, * but it also can be used to obtain a client that will only use this server, even if the server is a member of a replica * set or sharded cluster. * <p> * The format of the supplied string is one of the following: * * <pre> * host:port * host * </pre> * * where {@code host} contains the resolvable hostname or IP address of the server, and {@code port} is the integral port * number. If the port is not provided, the {@link ServerAddress#defaultPort() default port} is used. If neither the host * or port are provided (or {@code addressString} is {@code null}), then an address will use the * {@link ServerAddress#defaultHost() default host} and {@link ServerAddress#defaultPort() default port}. * * @param addressString the string that contains the host and port of the server * @return the MongoClient instance; never null */ public MongoClient clientFor(String addressString) { return clientFor(MongoUtil.parseAddress(addressString)); } /** * Obtain a direct client connection to the specified server. This is typically used to connect to a standalone server, * but it also can be used to obtain a client that will only use this server, even if the server is a member of a replica * set or sharded cluster. * * @param address the address of the server to use * @return the MongoClient instance; never null */ public MongoClient clientFor(ServerAddress address) { return directConnections.computeIfAbsent(address, this::directConnection); } /** * Obtain a client connection to the replica set or cluster. The supplied addresses are used as seeds, and once a connection * is established it will discover all of the members. * <p> * The format of the supplied string is one of the following: * * <pre> * replicaSetName/host:port * replicaSetName/host:port,host2:port2 * replicaSetName/host:port,host2:port2,host3:port3 * host:port * host:port,host2:port2 * host:port,host2:port2,host3:port3 * </pre> * * where {@code replicaSetName} is the name of the replica set, {@code host} contains the resolvable hostname or IP address of * the server, and {@code port} is the integral port number. If the port is not provided, the * {@link ServerAddress#defaultPort() default port} is used. If neither the host or port are provided (or * {@code addressString} is {@code null}), then an address will use the {@link ServerAddress#defaultHost() default host} and * {@link ServerAddress#defaultPort() default port}. * <p> * This method does not use the replica set name. * * @param addressList the string containing a comma-separated list of host and port pairs, optionally preceded by a * replica set name * @return the MongoClient instance; never null */ public MongoClient clientForMembers(String addressList) { return clientForMembers(MongoUtil.parseAddresses(addressList)); } /** * Obtain a client connection to the replica set or cluster. The supplied addresses are used as seeds, and once a connection * is established it will discover all of the members. * * @param seedAddresses the seed addresses * @return the MongoClient instance; never null */ public MongoClient clientForMembers(List<ServerAddress> seedAddresses) { return connections.computeIfAbsent(seedAddresses, this::connection); } protected MongoClient directConnection(ServerAddress address) { settings.applyToClusterSettings(builder -> builder.hosts(Collections.singletonList(address))); return com.mongodb.client.MongoClients.create(settings.build()); } protected MongoClient connection(List<ServerAddress> addresses) { settings.applyToClusterSettings(builder -> builder.hosts(addresses)); return com.mongodb.client.MongoClients.create(settings.build()); } }
DBZ-4733 Fixed thread safety of MongoClients
debezium-connector-mongodb/src/main/java/io/debezium/connector/mongodb/MongoClients.java
DBZ-4733 Fixed thread safety of MongoClients
<ide><path>ebezium-connector-mongodb/src/main/java/io/debezium/connector/mongodb/MongoClients.java <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.concurrent.ConcurrentHashMap; <add>import java.util.function.Supplier; <ide> <ide> import com.mongodb.MongoClientSettings; <ide> import com.mongodb.MongoCredential; <ide> } <ide> } <ide> <add> protected static Supplier<MongoClientSettings.Builder> createSettingsSupplier(MongoClientSettings settings) { <add> return () -> MongoClientSettings.builder(settings); <add> } <add> <ide> private final Map<ServerAddress, MongoClient> directConnections = new ConcurrentHashMap<>(); <ide> private final Map<List<ServerAddress>, MongoClient> connections = new ConcurrentHashMap<>(); <del> private final MongoClientSettings.Builder settings; <add> private final Supplier<MongoClientSettings.Builder> settingsSupplier; <ide> <ide> private MongoClients(MongoClientSettings.Builder settings) { <del> this.settings = settings; <add> this.settingsSupplier = createSettingsSupplier(settings.build()); <add> } <add> <add> /** <add> * Creates fresh {@link MongoClientSettings.Builder} from {@link #settingsSupplier} <add> * @return connection settings builder <add> */ <add> protected MongoClientSettings.Builder settings() { <add> return settingsSupplier.get(); <ide> } <ide> <ide> /** <ide> } <ide> <ide> protected MongoClient directConnection(ServerAddress address) { <del> settings.applyToClusterSettings(builder -> builder.hosts(Collections.singletonList(address))); <add> MongoClientSettings.Builder settings = settings().applyToClusterSettings(builder -> builder.hosts(Collections.singletonList(address))); <ide> return com.mongodb.client.MongoClients.create(settings.build()); <ide> } <ide> <ide> protected MongoClient connection(List<ServerAddress> addresses) { <del> settings.applyToClusterSettings(builder -> builder.hosts(addresses)); <add> MongoClientSettings.Builder settings = settings().applyToClusterSettings(builder -> builder.hosts(addresses)); <ide> return com.mongodb.client.MongoClients.create(settings.build()); <ide> } <ide> }
Java
bsd-2-clause
386049012e21e82619bf13fdd56f780ab60a2445
0
highsource/maven-jaxb2-plugin,highsource/maven-jaxb2-plugin
package org.jvnet.jaxb2.maven2; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.jvnet.jaxb2.maven2.util.IOUtils; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver; public class OptionsConfiguration { private final String encoding; private final String schemaLanguage; private final List<URI> schemas; private final List<URI> bindings; private final List<URI> catalogs; private final CatalogResolver catalogResolver; private final String generatePackage; private final File generateDirectory; private final boolean readOnly; private final boolean packageLevelAnnotations; private final boolean noFileHeader; private final boolean enableIntrospection; private final boolean disableXmlSecurity; private final String accessExternalSchema; private final String accessExternalDTD; private final boolean contentForWildcard; private final boolean extension; private final boolean strict; private final boolean verbose; private final boolean debugMode; private final List<String> arguments; private final List<URL> plugins; private final String specVersion; public OptionsConfiguration(String encoding, String schemaLanguage, List<URI> schemas, List<URI> bindings, List<URI> catalogs, CatalogResolver catalogResolver, String generatePackage, File generateDirectory, boolean readOnly, boolean packageLevelAnnotations, boolean noFileHeader, boolean enableIntrospection, boolean disableXmlSecurity, String accessExternalSchema, String accessExternalDTD, boolean contentForWildcard, boolean extension, boolean strict, boolean verbose, boolean debugMode, List<String> arguments, List<URL> plugins, String specVersion) { super(); this.encoding = encoding; this.schemaLanguage = schemaLanguage; this.schemas = schemas; this.bindings = bindings; this.catalogs = catalogs; this.catalogResolver = catalogResolver; this.generatePackage = generatePackage; this.generateDirectory = generateDirectory; this.readOnly = readOnly; this.packageLevelAnnotations = packageLevelAnnotations; this.noFileHeader = noFileHeader; this.enableIntrospection = enableIntrospection; this.disableXmlSecurity = disableXmlSecurity; this.accessExternalSchema = accessExternalSchema; this.accessExternalDTD = accessExternalDTD; this.contentForWildcard = contentForWildcard; this.extension = extension; this.strict = strict; this.verbose = verbose; this.debugMode = debugMode; this.arguments = arguments; this.plugins = plugins; this.specVersion = specVersion; } public String getEncoding() { return encoding; } public String getSchemaLanguage() { return schemaLanguage; } public List<URI> getSchemas() { return schemas; } public List<InputSource> getGrammars(EntityResolver resolver) throws IOException, SAXException { final List<URI> schemas = getSchemas(); return getInputSources(schemas, resolver); } public List<URI> getBindings() { return bindings; } public List<InputSource> getBindFiles(EntityResolver resolver) throws IOException, SAXException { final List<URI> bindings = getBindings(); return getInputSources(bindings, resolver); } private List<InputSource> getInputSources(final List<URI> uris, EntityResolver resolver) throws IOException, SAXException { final List<InputSource> inputSources = new ArrayList<InputSource>( uris.size()); for (final URI uri : uris) { InputSource inputSource = IOUtils.getInputSource(uri); if (resolver != null) { final InputSource resolvedInputSource = resolver.resolveEntity( inputSource.getPublicId(), inputSource.getSystemId()); if (resolvedInputSource != null) { inputSource = resolvedInputSource; } } inputSources.add(inputSource); } return inputSources; } public boolean hasCatalogs() { return !this.catalogs.isEmpty(); } public List<URI> getCatalogs() { final CatalogResolver resolver = getCatalogResolver(); if (resolver == null) { return this.catalogs; } else { final List<URI> uris = new ArrayList<URI>(this.catalogs.size()); for (URI uri : catalogs) { final String resolvedUri = resolver.getResolvedEntity(null, uri.toString()); if (resolvedUri != null) { try { uri = new URI(resolvedUri); } catch (URISyntaxException ignored) { } } uris.add(uri); } return uris; } } public CatalogResolver getCatalogResolver() { return catalogResolver; } public String getGeneratePackage() { return generatePackage; } public File getGenerateDirectory() { return generateDirectory; } public boolean isReadOnly() { return readOnly; } public boolean isPackageLevelAnnotations() { return packageLevelAnnotations; } public boolean isNoFileHeader() { return noFileHeader; } public boolean isEnableIntrospection() { return enableIntrospection; } public boolean isDisableXmlSecurity() { return disableXmlSecurity; } public String getAccessExternalSchema() { return accessExternalSchema; } public String getAccessExternalDTD() { return accessExternalDTD; } public boolean isContentForWildcard() { return contentForWildcard; } public boolean isExtension() { return extension; } public boolean isStrict() { return strict; } public boolean isVerbose() { return verbose; } public boolean isDebugMode() { return debugMode; } public List<String> getArguments() { return arguments; } public String getSpecVersion() { return specVersion; } public List<URL> getPlugins() { return plugins; } @Override public String toString() { return MessageFormat.format("OptionsConfiguration [" + // "specVersion={0}\n " + // "generateDirectory={1}\n " + // "generatePackage={2}\n " + // "schemaLanguage={3}\n " + // "schemas={4}\n " + // "bindings={5}\n " + // "plugins={6}\n " + // "catalogs={7}\n " + // "catalogResolver={8}\n " + // "readOnly={9}\n " + // "packageLevelAnnotations={10}\n " + // "noFileHeader={11}\n " + // "enableIntrospection={12}\n " + // "disableXmlSecurity={13}\n " + // "accessExternalSchema={14}\n " + // "accessExternalDTD={15}\n " + // "contentForWildcard={16}\n " + // "extension={17}\n " + // "strict={18}\n " + // "verbose={19}\n " + // "debugMode={20}\n " + // "arguments={19}" + // "]", specVersion, generateDirectory, generatePackage, schemaLanguage, schemas, bindings, plugins, catalogs, catalogResolver, readOnly, packageLevelAnnotations, noFileHeader, enableIntrospection, disableXmlSecurity, accessExternalSchema, accessExternalDTD, contentForWildcard, extension, strict, verbose, debugMode, arguments); } }
plugin-core/src/main/java/org/jvnet/jaxb2/maven2/OptionsConfiguration.java
package org.jvnet.jaxb2.maven2; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.jvnet.jaxb2.maven2.util.IOUtils; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver; public class OptionsConfiguration { private final String encoding; private final String schemaLanguage; private final List<URI> schemas; private final List<URI> bindings; private final List<URI> catalogs; private final CatalogResolver catalogResolver; private final String generatePackage; private final File generateDirectory; private final boolean readOnly; private final boolean packageLevelAnnotations; private final boolean noFileHeader; private final boolean enableIntrospection; private final boolean disableXmlSecurity; private final String accessExternalSchema; private final String accessExternalDTD; private final boolean contentForWildcard; private final boolean extension; private final boolean strict; private final boolean verbose; private final boolean debugMode; private final List<String> arguments; private final List<URL> plugins; private final String specVersion; public OptionsConfiguration(String encoding, String schemaLanguage, List<URI> schemas, List<URI> bindings, List<URI> catalogs, CatalogResolver catalogResolver, String generatePackage, File generateDirectory, boolean readOnly, boolean packageLevelAnnotations, boolean noFileHeader, boolean enableIntrospection, boolean disableXmlSecurity, String accessExternalSchema, String accessExternalDTD, boolean contentForWildcard, boolean extension, boolean strict, boolean verbose, boolean debugMode, List<String> arguments, List<URL> plugins, String specVersion) { super(); this.encoding = encoding; this.schemaLanguage = schemaLanguage; this.schemas = schemas; this.bindings = bindings; this.catalogs = catalogs; this.catalogResolver = catalogResolver; this.generatePackage = generatePackage; this.generateDirectory = generateDirectory; this.readOnly = readOnly; this.packageLevelAnnotations = packageLevelAnnotations; this.noFileHeader = noFileHeader; this.enableIntrospection = enableIntrospection; this.disableXmlSecurity = disableXmlSecurity; this.accessExternalSchema = accessExternalSchema; this.accessExternalDTD = accessExternalDTD; this.contentForWildcard = contentForWildcard; this.extension = extension; this.strict = strict; this.verbose = verbose; this.debugMode = debugMode; this.arguments = arguments; this.plugins = plugins; this.specVersion = specVersion; } public String getEncoding() { return encoding; } public String getSchemaLanguage() { return schemaLanguage; } public List<URI> getSchemas() { return schemas; } public List<InputSource> getGrammars(EntityResolver resolver) throws IOException, SAXException { final List<URI> schemas = getSchemas(); return getInputSources(schemas, resolver); } public List<URI> getBindings() { return bindings; } public List<InputSource> getBindFiles(EntityResolver resolver) throws IOException, SAXException { final List<URI> bindings = getBindings(); return getInputSources(bindings, resolver); } private List<InputSource> getInputSources(final List<URI> uris, EntityResolver resolver) throws IOException, SAXException { final List<InputSource> inputSources = new ArrayList<InputSource>( uris.size()); for (final URI uri : uris) { InputSource inputSource = IOUtils.getInputSource(uri); if (resolver != null) { final InputSource resolvedInputSource = resolver.resolveEntity( inputSource.getPublicId(), inputSource.getSystemId()); if (resolvedInputSource != null) { inputSource = resolvedInputSource; } } inputSources.add(inputSource); } return inputSources; } public List<URI> getCatalogs() { final CatalogResolver resolver = getCatalogResolver(); if (resolver == null) { return this.catalogs; } else { final List<URI> uris = new ArrayList<URI>(this.catalogs.size()); for (URI uri : catalogs) { final String resolvedUri = resolver.getResolvedEntity(null, uri.toString()); if (resolvedUri != null) { try { uri = new URI(resolvedUri); } catch (URISyntaxException ignored) { } } uris.add(uri); } return uris; } } public CatalogResolver getCatalogResolver() { return catalogResolver; } public String getGeneratePackage() { return generatePackage; } public File getGenerateDirectory() { return generateDirectory; } public boolean isReadOnly() { return readOnly; } public boolean isPackageLevelAnnotations() { return packageLevelAnnotations; } public boolean isNoFileHeader() { return noFileHeader; } public boolean isEnableIntrospection() { return enableIntrospection; } public boolean isDisableXmlSecurity() { return disableXmlSecurity; } public String getAccessExternalSchema() { return accessExternalSchema; } public String getAccessExternalDTD() { return accessExternalDTD; } public boolean isContentForWildcard() { return contentForWildcard; } public boolean isExtension() { return extension; } public boolean isStrict() { return strict; } public boolean isVerbose() { return verbose; } public boolean isDebugMode() { return debugMode; } public List<String> getArguments() { return arguments; } public String getSpecVersion() { return specVersion; } public List<URL> getPlugins() { return plugins; } @Override public String toString() { return MessageFormat.format("OptionsConfiguration [" + // "specVersion={0}\n " + // "generateDirectory={1}\n " + // "generatePackage={2}\n " + // "schemaLanguage={3}\n " + // "schemas={4}\n " + // "bindings={5}\n " + // "plugins={6}\n " + // "catalogs={7}\n " + // "catalogResolver={8}\n " + // "readOnly={9}\n " + // "packageLevelAnnotations={10}\n " + // "noFileHeader={11}\n " + // "enableIntrospection={12}\n " + // "disableXmlSecurity={13}\n " + // "accessExternalSchema={14}\n " + // "accessExternalDTD={15}\n " + // "contentForWildcard={16}\n " + // "extension={17}\n " + // "strict={18}\n " + // "verbose={19}\n " + // "debugMode={20}\n " + // "arguments={19}" + // "]", specVersion, generateDirectory, generatePackage, schemaLanguage, schemas, bindings, plugins, catalogs, catalogResolver, readOnly, packageLevelAnnotations, noFileHeader, enableIntrospection, disableXmlSecurity, accessExternalSchema, accessExternalDTD, contentForWildcard, extension, strict, verbose, debugMode, arguments); } }
Issue #23. Added hasCatalogs() method to check if catalogs are set.
plugin-core/src/main/java/org/jvnet/jaxb2/maven2/OptionsConfiguration.java
Issue #23. Added hasCatalogs() method to check if catalogs are set.
<ide><path>lugin-core/src/main/java/org/jvnet/jaxb2/maven2/OptionsConfiguration.java <ide> } <ide> return inputSources; <ide> } <add> <add> public boolean hasCatalogs() <add> { <add> return !this.catalogs.isEmpty(); <add> } <ide> <ide> public List<URI> getCatalogs() { <ide> final CatalogResolver resolver = getCatalogResolver();
Java
mit
cf75e0581d15c1d33f8625a637ea1df77f6004bc
0
dlcs/elucidate-server
package com.digirati.elucidate.infrastructure.security.impl; import com.digirati.elucidate.infrastructure.security.UserSecurityDetails; import com.digirati.elucidate.infrastructure.security.UserSecurityDetailsLoader; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter; public final class JwtUserAuthenticationConverter extends DefaultUserAuthenticationConverter { private List<String> uidProperties; private UserSecurityDetailsLoader securityDetailsLoader; public JwtUserAuthenticationConverter(List<String> uidProperties, UserSecurityDetailsLoader securityDetailsLoader) { this.uidProperties = uidProperties; this.securityDetailsLoader = securityDetailsLoader; } @Override public Authentication extractAuthentication(Map<String, ?> details) { return uidProperties.stream() .filter(details::containsKey) .map(prop -> (String) details.get(prop)) .findFirst() .map(uid -> { UserSecurityDetails securityDetails = securityDetailsLoader.findOrCreateUserDetails(uid); Collection<String> roles = (Collection<String>) details.get(AUTHORITIES); if (roles == null) { roles = Collections.emptyList(); } List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roles.toArray(new String[0])); Authentication auth = new UsernamePasswordAuthenticationToken( securityDetails, "N/A", authorities ); return auth; }) .orElse(null); } }
elucidate-server/src/main/java/com/digirati/elucidate/infrastructure/security/impl/JwtUserAuthenticationConverter.java
package com.digirati.elucidate.infrastructure.security.impl; import com.digirati.elucidate.infrastructure.security.UserSecurityDetails; import com.digirati.elucidate.infrastructure.security.UserSecurityDetailsLoader; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter; import java.util.Collections; import java.util.List; import java.util.Map; public final class JwtUserAuthenticationConverter extends DefaultUserAuthenticationConverter { private List<String> uidProperties; private UserSecurityDetailsLoader securityDetailsLoader; public JwtUserAuthenticationConverter(List<String> uidProperties, UserSecurityDetailsLoader securityDetailsLoader) { this.uidProperties = uidProperties; this.securityDetailsLoader = securityDetailsLoader; } @Override public Authentication extractAuthentication(Map<String, ?> details) { return uidProperties.stream() .filter(details::containsKey) .map(prop -> (String) details.get(prop)) .findFirst() .map(uid -> { UserSecurityDetails securityDetails = securityDetailsLoader.findOrCreateUserDetails(uid); Authentication auth = new UsernamePasswordAuthenticationToken( securityDetails, "N/A", Collections.emptySet() ); return auth; }) .orElse(null); } }
Fix decoding of admin authorities from access tokens
elucidate-server/src/main/java/com/digirati/elucidate/infrastructure/security/impl/JwtUserAuthenticationConverter.java
Fix decoding of admin authorities from access tokens
<ide><path>lucidate-server/src/main/java/com/digirati/elucidate/infrastructure/security/impl/JwtUserAuthenticationConverter.java <ide> <ide> import com.digirati.elucidate.infrastructure.security.UserSecurityDetails; <ide> import com.digirati.elucidate.infrastructure.security.UserSecurityDetailsLoader; <del>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; <del>import org.springframework.security.core.Authentication; <del>import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter; <del> <add>import java.util.Collection; <ide> import java.util.Collections; <ide> import java.util.List; <ide> import java.util.Map; <add>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; <add>import org.springframework.security.core.Authentication; <add>import org.springframework.security.core.GrantedAuthority; <add>import org.springframework.security.core.authority.AuthorityUtils; <add>import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter; <ide> <ide> public final class JwtUserAuthenticationConverter extends DefaultUserAuthenticationConverter { <ide> <ide> .findFirst() <ide> .map(uid -> { <ide> UserSecurityDetails securityDetails = securityDetailsLoader.findOrCreateUserDetails(uid); <add> Collection<String> roles = (Collection<String>) details.get(AUTHORITIES); <add> <add> if (roles == null) { <add> roles = Collections.emptyList(); <add> } <add> <add> List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roles.toArray(new String[0])); <ide> Authentication auth = new UsernamePasswordAuthenticationToken( <ide> securityDetails, <ide> "N/A", <del> Collections.emptySet() <add> authorities <ide> ); <ide> <ide> return auth;
Java
apache-2.0
db5665e3f6b179f94ddc2e6dcbc34d2efb422941
0
jagguli/intellij-community,caot/intellij-community,ol-loginov/intellij-community,caot/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,holmes/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,caot/intellij-community,semonte/intellij-community,FHannes/intellij-community,izonder/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,allotria/intellij-community,jagguli/intellij-community,blademainer/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,kool79/intellij-community,blademainer/intellij-community,clumsy/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,ernestp/consulo,ivan-fedorov/intellij-community,slisson/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,kool79/intellij-community,ryano144/intellij-community,fitermay/intellij-community,asedunov/intellij-community,kool79/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,da1z/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,ernestp/consulo,kool79/intellij-community,retomerz/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,FHannes/intellij-community,dslomov/intellij-community,samthor/intellij-community,slisson/intellij-community,adedayo/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,slisson/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,clumsy/intellij-community,supersven/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,clumsy/intellij-community,diorcety/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,slisson/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,consulo/consulo,slisson/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,semonte/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,kool79/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,FHannes/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,semonte/intellij-community,allotria/intellij-community,samthor/intellij-community,supersven/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,signed/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,xfournet/intellij-community,asedunov/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,signed/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,signed/intellij-community,fitermay/intellij-community,consulo/consulo,izonder/intellij-community,asedunov/intellij-community,blademainer/intellij-community,petteyg/intellij-community,vladmm/intellij-community,semonte/intellij-community,jagguli/intellij-community,robovm/robovm-studio,retomerz/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,gnuhub/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,signed/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,xfournet/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,da1z/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,clumsy/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,amith01994/intellij-community,izonder/intellij-community,samthor/intellij-community,Lekanich/intellij-community,kool79/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,semonte/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,ibinti/intellij-community,signed/intellij-community,consulo/consulo,MER-GROUP/intellij-community,adedayo/intellij-community,FHannes/intellij-community,holmes/intellij-community,retomerz/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ryano144/intellij-community,clumsy/intellij-community,kool79/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,samthor/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,FHannes/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,retomerz/intellij-community,izonder/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,petteyg/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,ernestp/consulo,ibinti/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,xfournet/intellij-community,youdonghai/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,signed/intellij-community,clumsy/intellij-community,vladmm/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,consulo/consulo,izonder/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,ibinti/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,samthor/intellij-community,signed/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,samthor/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,vladmm/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,fitermay/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,semonte/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,fitermay/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,FHannes/intellij-community,asedunov/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,ibinti/intellij-community,apixandru/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,consulo/consulo,blademainer/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,signed/intellij-community,caot/intellij-community,fnouama/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,semonte/intellij-community,apixandru/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,fnouama/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,dslomov/intellij-community,ibinti/intellij-community,slisson/intellij-community,kdwink/intellij-community,allotria/intellij-community,hurricup/intellij-community,adedayo/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,vladmm/intellij-community,allotria/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,fnouama/intellij-community,samthor/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,wreckJ/intellij-community,signed/intellij-community,da1z/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,clumsy/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,ryano144/intellij-community,slisson/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,da1z/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,hurricup/intellij-community,holmes/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,diorcety/intellij-community,signed/intellij-community,allotria/intellij-community,hurricup/intellij-community,fnouama/intellij-community,ryano144/intellij-community,retomerz/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,fitermay/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,samthor/intellij-community,izonder/intellij-community,petteyg/intellij-community,da1z/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,supersven/intellij-community,fitermay/intellij-community,ryano144/intellij-community,signed/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,FHannes/intellij-community,diorcety/intellij-community,jagguli/intellij-community,robovm/robovm-studio,semonte/intellij-community,apixandru/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,petteyg/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,apixandru/intellij-community,vladmm/intellij-community,supersven/intellij-community,orekyuu/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,da1z/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,caot/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,xfournet/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,da1z/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,dslomov/intellij-community,amith01994/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community
/* * Copyright 2000-2011 JetBrains s.r.o. * * 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.intellij.ide.util; import com.intellij.ide.IdeBundle; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import javax.swing.*; import java.awt.*; public class GotoLineNumberDialog extends DialogWrapper { private JTextField myField; private JTextField myOffsetField; private final Editor myEditor; public GotoLineNumberDialog(Project project, Editor editor){ super(project, true); myEditor = editor; setTitle(IdeBundle.message("title.go.to.line")); init(); } protected void doOKAction(){ final LogicalPosition currentPosition = myEditor.getCaretModel().getLogicalPosition(); int lineNumber = getLineNumber(currentPosition.line + 1); if (isInternal() && myOffsetField.getText().length() > 0) { try { final int offset = Integer.parseInt(myOffsetField.getText()); if (offset < myEditor.getDocument().getTextLength()) { myEditor.getCaretModel().moveToOffset(offset); myEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER); myEditor.getSelectionModel().removeSelection(); super.doOKAction(); } return; } catch (NumberFormatException e) { return; } } if (lineNumber <= 0) return; int columnNumber = getColumnNumber(currentPosition.column); myEditor.getCaretModel().moveToLogicalPosition(new LogicalPosition(lineNumber - 1, Math.max(0, columnNumber - 1))); myEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER); myEditor.getSelectionModel().removeSelection(); super.doOKAction(); } private int getColumnNumber(int defaultValue) { String text = getText(); int columnIndex = columnSeparatorIndex(text); if (columnIndex == -1) return defaultValue; try { return Integer.parseInt(text.substring(columnIndex + 1)); } catch (NumberFormatException e) { return defaultValue; } } private static int columnSeparatorIndex(final String text) { final int colonIndex = text.indexOf(':'); return colonIndex >= 0 ? colonIndex : text.indexOf(','); } private int getLineNumber(int defaultLine) { try { String text = getText(); int columnIndex = columnSeparatorIndex(text); text = columnIndex == -1 ? text : text.substring(0, columnIndex); if (text.trim().length() == 0) return defaultLine; return Integer.parseInt(text); } catch (NumberFormatException e) { return -1; } } private static boolean isInternal() { return ApplicationManagerEx.getApplicationEx().isInternal(); } public JComponent getPreferredFocusedComponent() { return myField; } protected JComponent createCenterPanel() { return null; } private String getText() { return myField.getText(); } protected JComponent createNorthPanel() { class MyTextField extends JTextField { public MyTextField() { super(""); } public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); return new Dimension(200, d.height); } } JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.insets = new Insets(4, 0, 8, 8); gbConstraints.fill = GridBagConstraints.VERTICAL; gbConstraints.weightx = 0; gbConstraints.weighty = 1; gbConstraints.anchor = GridBagConstraints.EAST; JLabel label = new JLabel(IdeBundle.message("editbox.line.number")); panel.add(label, gbConstraints); gbConstraints.fill = GridBagConstraints.BOTH; gbConstraints.weightx = 1; myField = new MyTextField(); panel.add(myField, gbConstraints); myField.setToolTipText(IdeBundle.message("tooltip.syntax.linenumber.columnnumber")); LogicalPosition position = myEditor.getCaretModel().getLogicalPosition(); myField.setText(String.format("%d:%d", position.line + 1, position.column + 1)); if (isInternal()) { gbConstraints.gridy = 1; gbConstraints.weightx = 0; gbConstraints.weighty = 1; gbConstraints.anchor = GridBagConstraints.EAST; final JLabel offsetLabel = new JLabel("Offset:"); panel.add(offsetLabel, gbConstraints); gbConstraints.fill = GridBagConstraints.BOTH; gbConstraints.weightx = 1; myOffsetField = new MyTextField(); panel.add(myOffsetField, gbConstraints); } return panel; } }
platform/platform-impl/src/com/intellij/ide/util/GotoLineNumberDialog.java
/* * Copyright 2000-2011 JetBrains s.r.o. * * 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.intellij.ide.util; import com.intellij.ide.IdeBundle; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import javax.swing.*; import java.awt.*; public class GotoLineNumberDialog extends DialogWrapper { private JTextField myField; private JTextField myOffsetField; private final Editor myEditor; public GotoLineNumberDialog(Project project, Editor editor){ super(project, true); myEditor = editor; setTitle(IdeBundle.message("title.go.to.line")); init(); } protected void doOKAction(){ final LogicalPosition currentPosition = myEditor.getCaretModel().getLogicalPosition(); int lineNumber = getLineNumber(currentPosition.line + 1); if (isInternal() && myOffsetField.getText().length() > 0) { try { final int offset = Integer.parseInt(myOffsetField.getText()); if (offset < myEditor.getDocument().getTextLength()) { myEditor.getCaretModel().moveToOffset(offset); myEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER); myEditor.getSelectionModel().removeSelection(); super.doOKAction(); } return; } catch (NumberFormatException e) { return; } } if (lineNumber <= 0) return; int columnNumber = getColumnNumber(currentPosition.column); myEditor.getCaretModel().moveToLogicalPosition(new LogicalPosition(lineNumber - 1, Math.max(0, columnNumber - 1))); myEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER); myEditor.getSelectionModel().removeSelection(); super.doOKAction(); } private int getColumnNumber(int defaultValue) { String text = getText(); int columnIndex = columnSeparatorIndex(text); if (columnIndex == -1) return defaultValue; try { return Integer.parseInt(text.substring(columnIndex + 1)); } catch (NumberFormatException e) { return defaultValue; } } private static int columnSeparatorIndex(final String text) { final int colonIndex = text.indexOf(':'); return colonIndex >= 0 ? colonIndex : text.indexOf(','); } private int getLineNumber(int defaultLine) { try { String text = getText(); int columnIndex = columnSeparatorIndex(text); text = columnIndex == -1 ? text : text.substring(0, columnIndex); if (text.trim().length() == 0) return defaultLine; return Integer.parseInt(text); } catch (NumberFormatException e) { return -1; } } private static boolean isInternal() { return ApplicationManagerEx.getApplicationEx().isInternal(); } public JComponent getPreferredFocusedComponent() { return myField; } protected JComponent createCenterPanel() { return null; } private String getText() { return myField.getText(); } protected JComponent createNorthPanel() { class MyTextField extends JTextField { public MyTextField() { super(""); } public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); return new Dimension(200, d.height); } } JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.insets = new Insets(4, 0, 8, 8); gbConstraints.fill = GridBagConstraints.VERTICAL; gbConstraints.weightx = 0; gbConstraints.weighty = 1; gbConstraints.anchor = GridBagConstraints.EAST; JLabel label = new JLabel(IdeBundle.message("editbox.line.number")); panel.add(label, gbConstraints); gbConstraints.fill = GridBagConstraints.BOTH; gbConstraints.weightx = 1; myField = new MyTextField(); panel.add(myField, gbConstraints); myField.setToolTipText(IdeBundle.message("tooltip.syntax.linenumber.columnnumber")); if (isInternal()) { gbConstraints.gridy = 1; gbConstraints.weightx = 0; gbConstraints.weighty = 1; gbConstraints.anchor = GridBagConstraints.EAST; final JLabel offsetLabel = new JLabel("Offset:"); panel.add(offsetLabel, gbConstraints); gbConstraints.fill = GridBagConstraints.BOTH; gbConstraints.weightx = 1; myOffsetField = new MyTextField(); panel.add(myOffsetField, gbConstraints); } return panel; } }
IDEA-90323 Navigate/Line command (Go To Line) dialog should show the current line
platform/platform-impl/src/com/intellij/ide/util/GotoLineNumberDialog.java
IDEA-90323 Navigate/Line command (Go To Line) dialog should show the current line
<ide><path>latform/platform-impl/src/com/intellij/ide/util/GotoLineNumberDialog.java <ide> myField = new MyTextField(); <ide> panel.add(myField, gbConstraints); <ide> myField.setToolTipText(IdeBundle.message("tooltip.syntax.linenumber.columnnumber")); <add> LogicalPosition position = myEditor.getCaretModel().getLogicalPosition(); <add> myField.setText(String.format("%d:%d", position.line + 1, position.column + 1)); <ide> <ide> if (isInternal()) { <ide> gbConstraints.gridy = 1;
Java
apache-2.0
fc0d7696859ae91d921b9cb23b1c5fbbed4ecff8
0
vbekiaris/liquibase,fossamagna/liquibase,dprguard2000/liquibase,lazaronixon/liquibase,EVODelavega/liquibase,mortegac/liquibase,dyk/liquibase,C0mmi3/liquibase,liquibase/liquibase,dyk/liquibase,Datical/liquibase,lazaronixon/liquibase,OpenCST/liquibase,pellcorp/liquibase,pellcorp/liquibase,FreshGrade/liquibase,syncron/liquibase,dprguard2000/liquibase,Willem1987/liquibase,vfpfafrf/liquibase,FreshGrade/liquibase,vfpfafrf/liquibase,evigeant/liquibase,syncron/liquibase,NSIT/liquibase,CoderPaulK/liquibase,liquibase/liquibase,mbreslow/liquibase,NSIT/liquibase,evigeant/liquibase,mattbertolini/liquibase,klopfdreh/liquibase,instantdelay/liquibase,iherasymenko/liquibase,mattbertolini/liquibase,vast-engineering/liquibase,NSIT/liquibase,mbreslow/liquibase,dyk/liquibase,vast-engineering/liquibase,hbogaards/liquibase,lazaronixon/liquibase,maberle/liquibase,klopfdreh/liquibase,balazs-zsoldos/liquibase,mattbertolini/liquibase,fossamagna/liquibase,balazs-zsoldos/liquibase,OpenCST/liquibase,CoderPaulK/liquibase,dprguard2000/liquibase,jimmycd/liquibase,Datical/liquibase,hbogaards/liquibase,C0mmi3/liquibase,instantdelay/liquibase,jimmycd/liquibase,talklittle/liquibase,cleiter/liquibase,cleiter/liquibase,balazs-zsoldos/liquibase,vast-engineering/liquibase,Willem1987/liquibase,vast-engineering/liquibase,russ-p/liquibase,mbreslow/liquibase,mattbertolini/liquibase,mwaylabs/liquibase,fbiville/liquibase,danielkec/liquibase,dbmanul/dbmanul,dbmanul/dbmanul,vfpfafrf/liquibase,instantdelay/liquibase,pellcorp/liquibase,hbogaards/liquibase,EVODelavega/liquibase,danielkec/liquibase,evigeant/liquibase,danielkec/liquibase,talklittle/liquibase,ivaylo5ev/liquibase,cleiter/liquibase,mwaylabs/liquibase,iherasymenko/liquibase,vfpfafrf/liquibase,mortegac/liquibase,mwaylabs/liquibase,fbiville/liquibase,C0mmi3/liquibase,mwaylabs/liquibase,syncron/liquibase,iherasymenko/liquibase,dyk/liquibase,OpenCST/liquibase,vbekiaris/liquibase,jimmycd/liquibase,NSIT/liquibase,EVODelavega/liquibase,OpenCST/liquibase,Datical/liquibase,fbiville/liquibase,russ-p/liquibase,maberle/liquibase,mortegac/liquibase,evigeant/liquibase,fossamagna/liquibase,hbogaards/liquibase,Willem1987/liquibase,lazaronixon/liquibase,C0mmi3/liquibase,liquibase/liquibase,vbekiaris/liquibase,cleiter/liquibase,FreshGrade/liquibase,vbekiaris/liquibase,talklittle/liquibase,pellcorp/liquibase,klopfdreh/liquibase,EVODelavega/liquibase,FreshGrade/liquibase,dbmanul/dbmanul,Willem1987/liquibase,mortegac/liquibase,fbiville/liquibase,maberle/liquibase,klopfdreh/liquibase,iherasymenko/liquibase,dprguard2000/liquibase,talklittle/liquibase,balazs-zsoldos/liquibase,ivaylo5ev/liquibase,CoderPaulK/liquibase,instantdelay/liquibase,mbreslow/liquibase,dbmanul/dbmanul,russ-p/liquibase,maberle/liquibase,Datical/liquibase,jimmycd/liquibase,russ-p/liquibase,danielkec/liquibase,CoderPaulK/liquibase,syncron/liquibase
package liquibase.datatype.core; import liquibase.configuration.GlobalConfiguration; import liquibase.configuration.LiquibaseConfiguration; import liquibase.database.Database; import liquibase.database.core.MSSQLDatabase; import liquibase.database.core.MySQLDatabase; import liquibase.datatype.DataTypeInfo; import liquibase.datatype.DatabaseDataType; import liquibase.datatype.LiquibaseDataType; import liquibase.util.StringUtils; @DataTypeInfo(name = "timestamp", aliases = {"java.sql.Types.TIMESTAMP", "java.sql.Timestamp", "timestamptz"}, minParameters = 0, maxParameters = 1, priority = LiquibaseDataType.PRIORITY_DEFAULT) public class TimestampType extends DateTimeType { @Override public DatabaseDataType toDatabaseDataType(Database database) { String originalDefinition = StringUtils.trimToEmpty(getRawDefinition()); if (database instanceof MySQLDatabase) { if (getRawDefinition().contains(" ") || getRawDefinition().contains("(")) { return new DatabaseDataType(getRawDefinition()); } return super.toDatabaseDataType(database); } if (database instanceof MSSQLDatabase) { if (!LiquibaseConfiguration.getInstance().getProperty(GlobalConfiguration.class, GlobalConfiguration.CONVERT_DATA_TYPES).getValue(Boolean.class) && originalDefinition.toLowerCase().startsWith("timestamp")) { return new DatabaseDataType(database.escapeDataTypeName("TIMESTAMP")); } return new DatabaseDataType(database.escapeDataTypeName("DATETIME")); } return super.toDatabaseDataType(database); } }
liquibase-core/src/main/java/liquibase/datatype/core/TimestampType.java
package liquibase.datatype.core; import liquibase.configuration.GlobalConfiguration; import liquibase.configuration.LiquibaseConfiguration; import liquibase.database.Database; import liquibase.database.core.MSSQLDatabase; import liquibase.database.core.MySQLDatabase; import liquibase.datatype.DataTypeInfo; import liquibase.datatype.DatabaseDataType; import liquibase.datatype.LiquibaseDataType; @DataTypeInfo(name = "timestamp", aliases = {"java.sql.Types.TIMESTAMP", "java.sql.Timestamp", "timestamptz"}, minParameters = 0, maxParameters = 1, priority = LiquibaseDataType.PRIORITY_DEFAULT) public class TimestampType extends DateTimeType { @Override public DatabaseDataType toDatabaseDataType(Database database) { if (database instanceof MySQLDatabase) { if (getRawDefinition().contains(" ")) { return new DatabaseDataType(getRawDefinition()); } return new DatabaseDataType("TIMESTAMP"); } if (database instanceof MSSQLDatabase) { if (!LiquibaseConfiguration.getInstance().getProperty(GlobalConfiguration.class, GlobalConfiguration.CONVERT_DATA_TYPES).getValue(Boolean.class) && originalDefinition.toLowerCase().startsWith("timestamp")) { return new DatabaseDataType(database.escapeDataTypeName("TIMESTAMP")); } return new DatabaseDataType(database.escapeDataTypeName("DATETIME")); } return super.toDatabaseDataType(database); } }
CORE-2401 MSSQL handling timestamp according to sql standard, not sqlserver usage (cherry picked from commit b7d1f44)
liquibase-core/src/main/java/liquibase/datatype/core/TimestampType.java
CORE-2401 MSSQL handling timestamp according to sql standard, not sqlserver usage (cherry picked from commit b7d1f44)
<ide><path>iquibase-core/src/main/java/liquibase/datatype/core/TimestampType.java <ide> import liquibase.datatype.DataTypeInfo; <ide> import liquibase.datatype.DatabaseDataType; <ide> import liquibase.datatype.LiquibaseDataType; <add>import liquibase.util.StringUtils; <ide> <ide> @DataTypeInfo(name = "timestamp", aliases = {"java.sql.Types.TIMESTAMP", "java.sql.Timestamp", "timestamptz"}, minParameters = 0, maxParameters = 1, priority = LiquibaseDataType.PRIORITY_DEFAULT) <ide> public class TimestampType extends DateTimeType { <ide> <ide> @Override <ide> public DatabaseDataType toDatabaseDataType(Database database) { <add> String originalDefinition = StringUtils.trimToEmpty(getRawDefinition()); <ide> if (database instanceof MySQLDatabase) { <del> if (getRawDefinition().contains(" ")) { <add> if (getRawDefinition().contains(" ") || getRawDefinition().contains("(")) { <ide> return new DatabaseDataType(getRawDefinition()); <ide> } <del> return new DatabaseDataType("TIMESTAMP"); <add> return super.toDatabaseDataType(database); <ide> } <ide> if (database instanceof MSSQLDatabase) { <ide> if (!LiquibaseConfiguration.getInstance().getProperty(GlobalConfiguration.class, GlobalConfiguration.CONVERT_DATA_TYPES).getValue(Boolean.class) && originalDefinition.toLowerCase().startsWith("timestamp")) {
Java
mit
error: pathspec 'Jenga/Jenga.java' did not match any file(s) known to git
303238ea0fc61d8a18e2ce959865b5b88fb798a6
1
MarsCapone/game-data-structures,MarsCapone/game-data-structures
import java.util.ArrayList; import java.util.Random; public class Jenga<E> { int stability = 100; ArrayList<Layer<E>> layers = new ArrayList<Layer<E>>(); int layerCount = 0; int removedBlocks = 0; public Jenga() { } public boolean add(E e) { return true; } public boolean remove(int layer, int index) throws TowerCollapseError, HandOfGodError, CheatingAttemptException { return true; } public int prod(int layer, int index) { return -1; } public void destroy() throws HandOfGodError { layers.clear(); throw new HandOfGodError(); } private boolean collapseCheck() { return CollapseChecker.checkCollapse(stability); } } class Block<E> { public final E data; public final int friction; public Block(E data) { this.data = data; this.friction = new Random().nextInt(10 + 1); } } class Layer<E> { Block[] blocks = new Block[3]; Layer() { for (int i = 0; i < 3; i++) { blocks[i] = null; } } public boolean add(E e, int i) { if (blocks[i] == null) { blocks[i] = new Block(e); return true; } return false; } public int friction(int i) throws NonExistentBlockException { if (blocks[i] == null) { throw new NonExistentBlockException(); } return blocks[i].friction; } public E prod(int i) throws NonExistentBlockException { if (blocks[i] == null) { throw new NonExistentBlockException(); } return (E) blocks[i].data; } public E remove(int i) throws NonExistentBlockException { if (blocks[i] == null) { throw new NonExistentBlockException(); } Block block = blocks[i]; blocks[i] = null; return (E) block.data; } public boolean full() { for (int i=0; i<3; i++) { if (blocks[i] == null) { return false; } } return true; } } class TowerCollapseError extends Error { public TowerCollapseError() { super("The tower has become too unstable. Tower collapsed and all data destroyed."); } } class CheatingAttemptException extends Exception { public CheatingAttemptException() { super("You have been caught cheating. No removing from the top 3 layers."); } } class HandOfGodError extends Error { public HandOfGodError() { super("You have knocked over the tower, all data is lost."); } } class NonExistentBlockException extends Exception { public NonExistentBlockException() { super("There is no block there, so you cannot do anything with it."); } } class CollapseChecker { public static boolean checkCollapse(int stability) { return randomNumberPicker() == stability + 1; } private static int randomNumberPicker(int min, int max) { Random r = new Random(); return r.nextInt(max - min + 1) + min; } private static int randomNumberPicker() { return randomNumberPicker(0, 100); } }
Jenga/Jenga.java
add layers and blocks and errors to the java jenga structure
Jenga/Jenga.java
add layers and blocks and errors to the java jenga structure
<ide><path>enga/Jenga.java <add>import java.util.ArrayList; <add>import java.util.Random; <add> <add>public class Jenga<E> { <add> <add> int stability = 100; <add> ArrayList<Layer<E>> layers = new ArrayList<Layer<E>>(); <add> int layerCount = 0; <add> int removedBlocks = 0; <add> <add> public Jenga() { <add> <add> } <add> <add> public boolean add(E e) { <add> return true; <add> } <add> <add> public boolean remove(int layer, int index) throws TowerCollapseError, HandOfGodError, CheatingAttemptException { <add> return true; <add> } <add> <add> public int prod(int layer, int index) { <add> return -1; <add> } <add> <add> public void destroy() throws HandOfGodError { <add> layers.clear(); <add> throw new HandOfGodError(); <add> } <add> <add> private boolean collapseCheck() { <add> return CollapseChecker.checkCollapse(stability); <add> } <add> <add>} <add> <add>class Block<E> { <add> public final E data; <add> public final int friction; <add> <add> public Block(E data) { <add> this.data = data; <add> this.friction = new Random().nextInt(10 + 1); <add> } <add>} <add> <add>class Layer<E> { <add> <add> Block[] blocks = new Block[3]; <add> <add> Layer() { <add> for (int i = 0; i < 3; i++) { <add> blocks[i] = null; <add> } <add> } <add> <add> public boolean add(E e, int i) { <add> if (blocks[i] == null) { <add> blocks[i] = new Block(e); <add> return true; <add> } <add> return false; <add> } <add> <add> public int friction(int i) throws NonExistentBlockException { <add> if (blocks[i] == null) { <add> throw new NonExistentBlockException(); <add> } <add> return blocks[i].friction; <add> } <add> <add> public E prod(int i) throws NonExistentBlockException { <add> if (blocks[i] == null) { <add> throw new NonExistentBlockException(); <add> } <add> return (E) blocks[i].data; <add> } <add> <add> public E remove(int i) throws NonExistentBlockException { <add> if (blocks[i] == null) { <add> throw new NonExistentBlockException(); <add> } <add> Block block = blocks[i]; <add> blocks[i] = null; <add> return (E) block.data; <add> } <add> <add> public boolean full() { <add> for (int i=0; i<3; i++) { <add> if (blocks[i] == null) { <add> return false; <add> } <add> } <add> return true; <add> } <add>} <add> <add>class TowerCollapseError extends Error { <add> public TowerCollapseError() { <add> super("The tower has become too unstable. Tower collapsed and all data destroyed."); <add> } <add>} <add> <add>class CheatingAttemptException extends Exception { <add> public CheatingAttemptException() { <add> super("You have been caught cheating. No removing from the top 3 layers."); <add> } <add>} <add> <add>class HandOfGodError extends Error { <add> public HandOfGodError() { <add> super("You have knocked over the tower, all data is lost."); <add> } <add>} <add> <add>class NonExistentBlockException extends Exception { <add> public NonExistentBlockException() { <add> super("There is no block there, so you cannot do anything with it."); <add> } <add>} <add> <add>class CollapseChecker { <add> public static boolean checkCollapse(int stability) { <add> return randomNumberPicker() == stability + 1; <add> } <add> <add> private static int randomNumberPicker(int min, int max) { <add> Random r = new Random(); <add> return r.nextInt(max - min + 1) + min; <add> } <add> <add> private static int randomNumberPicker() { <add> return randomNumberPicker(0, 100); <add> } <add>}
Java
apache-2.0
634fdd8629045c4767a391c205bf233350aa76c1
0
msgpack/msgpack-java,msgpack/msgpack-java,xuwei-k/msgpack-java,xuwei-k/msgpack-java
// // MessagePack for Java // // 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.msgpack.core; import org.msgpack.core.MessagePack.Code; import org.msgpack.core.buffer.MessageBuffer; import org.msgpack.core.buffer.MessageBufferInput; import org.msgpack.value.ImmutableValue; import org.msgpack.value.Value; import org.msgpack.value.ValueFactory; import org.msgpack.value.Variable; import java.io.Closeable; import java.io.EOFException; import java.io.IOException; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.nio.charset.MalformedInputException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.msgpack.core.Preconditions.checkArgument; import static org.msgpack.core.Preconditions.checkNotNull; /** * MessageUnpacker lets an application read message-packed values from a data stream. * The application needs to call {@link #getNextFormat()} followed by an appropriate unpackXXX method according to the the returned format type. * <p/> * <pre> * <code> * MessageUnpacker unpacker = MessagePackFactory.DEFAULT.newUnpacker(...); * while(unpacker.hasNext()) { * MessageFormat f = unpacker.getNextFormat(); * switch(f) { * case MessageFormat.POSFIXINT: * case MessageFormat.INT8: * case MessageFormat.UINT8: { * int v = unpacker.unpackInt(); * break; * } * case MessageFormat.STRING: { * String v = unpacker.unpackString(); * break; * } * // ... * } * } * * </code> * </pre> */ public class MessageUnpacker implements Closeable { private static final MessageBuffer EMPTY_BUFFER = MessageBuffer.wrap(new byte[0]); private static final byte HEAD_BYTE_REQUIRED = (byte) 0xc1; private final MessagePack.Config config; private MessageBufferInput in; private byte headByte = HEAD_BYTE_REQUIRED; /** * Points to the current buffer to read */ private MessageBuffer buffer = EMPTY_BUFFER; /** * Cursor position in the current buffer */ private int position; /** * Total read byte size */ private long totalReadBytes; /** * Extra buffer for fixed-length data at the buffer boundary. At most 17-byte buffer (for FIXEXT16) is required. */ private final MessageBuffer castBuffer = MessageBuffer.newBuffer(24); /** * Variable by ensureHeader method. Caller of the method should use this variable to read from returned MessageBuffer. */ private int readCastBufferPosition; /** * For decoding String in unpackString. */ private StringBuilder decodeStringBuffer; /** * For decoding String in unpackString. */ private int readingRawRemaining = 0; /** * For decoding String in unpackString. */ private CharsetDecoder decoder; /** * Buffer for decoding strings */ private CharBuffer decodeBuffer; /** * Create an MessageUnpacker that reads data from the given MessageBufferInput * * @param in */ public MessageUnpacker(MessageBufferInput in) { this(in, MessagePack.DEFAULT_CONFIG); } /** * Create an MessageUnpacker * * @param in * @param config configuration */ public MessageUnpacker(MessageBufferInput in, MessagePack.Config config) { // Root constructor. All of the constructors must call this constructor. this.in = checkNotNull(in, "MessageBufferInput is null"); this.config = checkNotNull(config, "Config"); } /** * Reset input. This method doesn't close the old resource. * * @param in new input * @return the old resource */ public MessageBufferInput reset(MessageBufferInput in) throws IOException { MessageBufferInput newIn = checkNotNull(in, "MessageBufferInput is null"); // Reset the internal states MessageBufferInput old = this.in; this.in = newIn; this.buffer = EMPTY_BUFFER; this.position = 0; this.totalReadBytes = 0; this.readingRawRemaining = 0; // No need to initialize the already allocated string decoder here since we can reuse it. return old; } public long getTotalReadBytes() { return totalReadBytes + position; } private byte getHeadByte() throws IOException { byte b = headByte; if (b == HEAD_BYTE_REQUIRED) { b = headByte = readByte(); if (b == HEAD_BYTE_REQUIRED) { throw new MessageNeverUsedFormatException("Encountered 0xC1 \"NEVER_USED\" byte"); } } return b; } private void resetHeadByte() { headByte = HEAD_BYTE_REQUIRED; } private void nextBuffer() throws IOException { MessageBuffer next = in.next(); if (next == null) { throw new MessageInsufficientBufferException(); } totalReadBytes += buffer.size(); buffer = next; position = 0; } private MessageBuffer readCastBuffer(int length) throws IOException { int remaining = buffer.size() - position; if (remaining >= length) { readCastBufferPosition = position; position += length; // here assumes following buffer.getXxx never throws exception return buffer; } else { // TODO loop this method until castBuffer is filled MessageBuffer next = in.next(); if (next == null) { throw new MessageInsufficientBufferException(); } // TODO this doesn't work if MessageBuffer is allocated by newDirectBuffer. // add copy method to MessageBuffer to solve this issue. castBuffer.putBytes(0, buffer.getArray(), buffer.offset() + position, remaining); castBuffer.putBytes(remaining, next.getArray(), next.offset(), length - remaining); totalReadBytes += buffer.size(); buffer = next; position = length - remaining; readCastBufferPosition = 0; return castBuffer; } } private static int utf8MultibyteCharacterSize(byte firstByte) { return Integer.numberOfLeadingZeros(~(firstByte & 0xff) << 24); } /** * Returns true true if this unpacker has more elements. * When this returns true, subsequent call to {@link #getNextFormat()} returns an * MessageFormat instance. If false, next {@link #getNextFormat()} call will throw an MessageInsufficientBufferException. * * @return true if this unpacker has more elements to read */ public boolean hasNext() throws IOException { if (buffer.size() <= position) { MessageBuffer next = in.next(); if (next == null) { return false; } totalReadBytes += buffer.size(); buffer = next; position = 0; } return true; } /** * Returns the next MessageFormat type. This method should be called after {@link #hasNext()} returns true. * If {@link #hasNext()} returns false, calling this method throws {@link MessageInsufficientBufferException}. * <p/> * This method does not proceed the internal cursor. * * @return the next MessageFormat * @throws IOException when failed to read the input data. * @throws MessageInsufficientBufferException when the end of file reached, i.e. {@link #hasNext()} == false. */ public MessageFormat getNextFormat() throws IOException { try { byte b = getHeadByte(); return MessageFormat.valueOf(b); } catch (MessageNeverUsedFormatException ex) { return MessageFormat.NEVER_USED; } } /** * Read a byte value at the cursor and proceed the cursor. * * @return * @throws IOException */ private byte readByte() throws IOException { if (buffer.size() > position) { byte b = buffer.getByte(position); position++; return b; } else { nextBuffer(); if (buffer.size() > 0) { byte b = buffer.getByte(0); position = 1; return b; } return readByte(); } } private short readShort() throws IOException { MessageBuffer castBuffer = readCastBuffer(2); return castBuffer.getShort(readCastBufferPosition); } private int readInt() throws IOException { MessageBuffer castBuffer = readCastBuffer(4); return castBuffer.getInt(readCastBufferPosition); } private long readLong() throws IOException { MessageBuffer castBuffer = readCastBuffer(8); return castBuffer.getLong(readCastBufferPosition); } private float readFloat() throws IOException { MessageBuffer castBuffer = readCastBuffer(4); return castBuffer.getFloat(readCastBufferPosition); } private double readDouble() throws IOException { MessageBuffer castBuffer = readCastBuffer(8); return castBuffer.getDouble(readCastBufferPosition); } /** * Skip the next value, then move the cursor at the end of the value * * @throws IOException */ public void skipValue() throws IOException { int remainingValues = 1; while (remainingValues > 0) { byte b = getHeadByte(); MessageFormat f = MessageFormat.valueOf(b); resetHeadByte(); switch (f) { case POSFIXINT: case NEGFIXINT: case BOOLEAN: case NIL: break; case FIXMAP: { int mapLen = b & 0x0f; remainingValues += mapLen * 2; break; } case FIXARRAY: { int arrayLen = b & 0x0f; remainingValues += arrayLen; break; } case FIXSTR: { int strLen = b & 0x1f; skipPayload(strLen); break; } case INT8: case UINT8: skipPayload(1); break; case INT16: case UINT16: skipPayload(2); break; case INT32: case UINT32: case FLOAT32: skipPayload(4); break; case INT64: case UINT64: case FLOAT64: skipPayload(8); break; case BIN8: case STR8: skipPayload(readNextLength8()); break; case BIN16: case STR16: skipPayload(readNextLength16()); break; case BIN32: case STR32: skipPayload(readNextLength32()); break; case FIXEXT1: skipPayload(2); break; case FIXEXT2: skipPayload(3); break; case FIXEXT4: skipPayload(5); break; case FIXEXT8: skipPayload(9); break; case FIXEXT16: skipPayload(17); break; case EXT8: skipPayload(readNextLength8() + 1); break; case EXT16: skipPayload(readNextLength16() + 1); break; case EXT32: skipPayload(readNextLength32() + 1); break; case ARRAY16: remainingValues += readNextLength16(); break; case ARRAY32: remainingValues += readNextLength32(); break; case MAP16: remainingValues += readNextLength16() * 2; break; case MAP32: remainingValues += readNextLength32() * 2; // TODO check int overflow break; case NEVER_USED: throw new MessageNeverUsedFormatException("Encountered 0xC1 \"NEVER_USED\" byte"); } remainingValues--; } } /** * Create an exception for the case when an unexpected byte value is read * * @param expected * @param b * @return * @throws MessageFormatException */ private static MessagePackException unexpected(String expected, byte b) { MessageFormat format = MessageFormat.valueOf(b); if (format == MessageFormat.NEVER_USED) { return new MessageNeverUsedFormatException(String.format("Expected %s, but encountered 0xC1 \"NEVER_USED\" byte", expected)); } else { String name = format.getValueType().name(); String typeName = name.substring(0, 1) + name.substring(1).toLowerCase(); return new MessageTypeException(String.format("Expected %s, but got %s (%02x)", expected, typeName, b)); } } public ImmutableValue unpackValue() throws IOException { MessageFormat mf = getNextFormat(); switch (mf.getValueType()) { case NIL: readByte(); return ValueFactory.newNil(); case BOOLEAN: return ValueFactory.newBoolean(unpackBoolean()); case INTEGER: switch (mf) { case UINT64: return ValueFactory.newInteger(unpackBigInteger()); default: return ValueFactory.newInteger(unpackLong()); } case FLOAT: return ValueFactory.newFloat(unpackDouble()); case STRING: { int length = unpackRawStringHeader(); return ValueFactory.newString(readPayload(length)); } case BINARY: { int length = unpackBinaryHeader(); return ValueFactory.newBinary(readPayload(length)); } case ARRAY: { int size = unpackArrayHeader(); Value[] array = new Value[size]; for (int i = 0; i < size; i++) { array[i] = unpackValue(); } return ValueFactory.newArray(array); } case MAP: { int size = unpackMapHeader(); Value[] kvs = new Value[size * 2]; for (int i = 0; i < size * 2; ) { kvs[i] = unpackValue(); i++; kvs[i] = unpackValue(); i++; } return ValueFactory.newMap(kvs); } case EXTENSION: { ExtensionTypeHeader extHeader = unpackExtensionTypeHeader(); return ValueFactory.newExtension(extHeader.getType(), readPayload(extHeader.getLength())); } default: throw new MessageNeverUsedFormatException("Unknown value type"); } } public Variable unpackValue(Variable var) throws IOException { MessageFormat mf = getNextFormat(); switch (mf.getValueType()) { case NIL: unpackNil(); var.setNilValue(); return var; case BOOLEAN: var.setBooleanValue(unpackBoolean()); return var; case INTEGER: switch (mf) { case UINT64: var.setIntegerValue(unpackBigInteger()); return var; default: var.setIntegerValue(unpackLong()); return var; } case FLOAT: var.setFloatValue(unpackDouble()); return var; case STRING: { int length = unpackRawStringHeader(); var.setStringValue(readPayload(length)); return var; } case BINARY: { int length = unpackBinaryHeader(); var.setBinaryValue(readPayload(length)); return var; } case ARRAY: { int size = unpackArrayHeader(); List<Value> list = new ArrayList<Value>(size); for (int i = 0; i < size; i++) { //Variable e = new Variable(); //unpackValue(e); //list.add(e); list.add(unpackValue()); } var.setArrayValue(list); return var; } case MAP: { int size = unpackMapHeader(); Map<Value, Value> map = new HashMap<Value, Value>(); for (int i = 0; i < size; i++) { //Variable k = new Variable(); //unpackValue(k); //Variable v = new Variable(); //unpackValue(v); Value k = unpackValue(); Value v = unpackValue(); map.put(k, v); } var.setMapValue(map); return var; } case EXTENSION: { ExtensionTypeHeader extHeader = unpackExtensionTypeHeader(); var.setExtensionValue(extHeader.getType(), readPayload(extHeader.getLength())); return var; } default: throw new MessageFormatException("Unknown value type"); } } public void unpackNil() throws IOException { byte b = getHeadByte(); if (b == Code.NIL) { resetHeadByte(); return; } throw unexpected("Nil", b); } public boolean unpackBoolean() throws IOException { byte b = getHeadByte(); if (b == Code.FALSE) { resetHeadByte(); return false; } else if (b == Code.TRUE) { resetHeadByte(); return true; } throw unexpected("boolean", b); } public byte unpackByte() throws IOException { byte b = getHeadByte(); if (Code.isFixInt(b)) { resetHeadByte(); return b; } switch (b) { case Code.UINT8: // unsigned int 8 byte u8 = readByte(); resetHeadByte(); if (u8 < (byte) 0) { throw overflowU8(u8); } return u8; case Code.UINT16: // unsigned int 16 short u16 = readShort(); resetHeadByte(); if (u16 < 0 || u16 > Byte.MAX_VALUE) { throw overflowU16(u16); } return (byte) u16; case Code.UINT32: // unsigned int 32 int u32 = readInt(); resetHeadByte(); if (u32 < 0 || u32 > Byte.MAX_VALUE) { throw overflowU32(u32); } return (byte) u32; case Code.UINT64: // unsigned int 64 long u64 = readLong(); resetHeadByte(); if (u64 < 0L || u64 > Byte.MAX_VALUE) { throw overflowU64(u64); } return (byte) u64; case Code.INT8: // signed int 8 byte i8 = readByte(); resetHeadByte(); return i8; case Code.INT16: // signed int 16 short i16 = readShort(); resetHeadByte(); if (i16 < Byte.MIN_VALUE || i16 > Byte.MAX_VALUE) { throw overflowI16(i16); } return (byte) i16; case Code.INT32: // signed int 32 int i32 = readInt(); resetHeadByte(); if (i32 < Byte.MIN_VALUE || i32 > Byte.MAX_VALUE) { throw overflowI32(i32); } return (byte) i32; case Code.INT64: // signed int 64 long i64 = readLong(); resetHeadByte(); if (i64 < Byte.MIN_VALUE || i64 > Byte.MAX_VALUE) { throw overflowI64(i64); } return (byte) i64; } throw unexpected("Integer", b); } public short unpackShort() throws IOException { byte b = getHeadByte(); if (Code.isFixInt(b)) { resetHeadByte(); return (short) b; } switch (b) { case Code.UINT8: // unsigned int 8 byte u8 = readByte(); resetHeadByte(); return (short) (u8 & 0xff); case Code.UINT16: // unsigned int 16 short u16 = readShort(); resetHeadByte(); if (u16 < (short) 0) { throw overflowU16(u16); } return u16; case Code.UINT32: // unsigned int 32 int u32 = readInt(); resetHeadByte(); if (u32 < 0 || u32 > Short.MAX_VALUE) { throw overflowU32(u32); } return (short) u32; case Code.UINT64: // unsigned int 64 resetHeadByte(); long u64 = readLong(); if (u64 < 0L || u64 > Short.MAX_VALUE) { throw overflowU64(u64); } return (short) u64; case Code.INT8: // signed int 8 byte i8 = readByte(); resetHeadByte(); return (short) i8; case Code.INT16: // signed int 16 short i16 = readShort(); resetHeadByte(); return i16; case Code.INT32: // signed int 32 int i32 = readInt(); resetHeadByte(); if (i32 < Short.MIN_VALUE || i32 > Short.MAX_VALUE) { throw overflowI32(i32); } return (short) i32; case Code.INT64: // signed int 64 long i64 = readLong(); resetHeadByte(); if (i64 < Short.MIN_VALUE || i64 > Short.MAX_VALUE) { throw overflowI64(i64); } return (short) i64; } throw unexpected("Integer", b); } public int unpackInt() throws IOException { byte b = getHeadByte(); if (Code.isFixInt(b)) { resetHeadByte(); return (int) b; } switch (b) { case Code.UINT8: // unsigned int 8 byte u8 = readByte(); resetHeadByte(); return u8 & 0xff; case Code.UINT16: // unsigned int 16 short u16 = readShort(); resetHeadByte(); return u16 & 0xffff; case Code.UINT32: // unsigned int 32 int u32 = readInt(); if (u32 < 0) { throw overflowU32(u32); } resetHeadByte(); return u32; case Code.UINT64: // unsigned int 64 long u64 = readLong(); resetHeadByte(); if (u64 < 0L || u64 > (long) Integer.MAX_VALUE) { throw overflowU64(u64); } return (int) u64; case Code.INT8: // signed int 8 byte i8 = readByte(); resetHeadByte(); return i8; case Code.INT16: // signed int 16 short i16 = readShort(); resetHeadByte(); return i16; case Code.INT32: // signed int 32 int i32 = readInt(); resetHeadByte(); return i32; case Code.INT64: // signed int 64 long i64 = readLong(); resetHeadByte(); if (i64 < (long) Integer.MIN_VALUE || i64 > (long) Integer.MAX_VALUE) { throw overflowI64(i64); } return (int) i64; } throw unexpected("Integer", b); } public long unpackLong() throws IOException { byte b = getHeadByte(); if (Code.isFixInt(b)) { resetHeadByte(); return (long) b; } switch (b) { case Code.UINT8: // unsigned int 8 byte u8 = readByte(); resetHeadByte(); return (long) (u8 & 0xff); case Code.UINT16: // unsigned int 16 short u16 = readShort(); resetHeadByte(); return (long) (u16 & 0xffff); case Code.UINT32: // unsigned int 32 int u32 = readInt(); resetHeadByte(); if (u32 < 0) { return (long) (u32 & 0x7fffffff) + 0x80000000L; } else { return (long) u32; } case Code.UINT64: // unsigned int 64 long u64 = readLong(); resetHeadByte(); if (u64 < 0L) { throw overflowU64(u64); } return u64; case Code.INT8: // signed int 8 byte i8 = readByte(); resetHeadByte(); return (long) i8; case Code.INT16: // signed int 16 short i16 = readShort(); resetHeadByte(); return (long) i16; case Code.INT32: // signed int 32 int i32 = readInt(); resetHeadByte(); return (long) i32; case Code.INT64: // signed int 64 long i64 = readLong(); resetHeadByte(); return i64; } throw unexpected("Integer", b); } public BigInteger unpackBigInteger() throws IOException { byte b = getHeadByte(); if (Code.isFixInt(b)) { resetHeadByte(); return BigInteger.valueOf((long) b); } switch (b) { case Code.UINT8: // unsigned int 8 byte u8 = readByte(); resetHeadByte(); return BigInteger.valueOf((long) (u8 & 0xff)); case Code.UINT16: // unsigned int 16 short u16 = readShort(); resetHeadByte(); return BigInteger.valueOf((long) (u16 & 0xffff)); case Code.UINT32: // unsigned int 32 int u32 = readInt(); resetHeadByte(); if (u32 < 0) { return BigInteger.valueOf((long) (u32 & 0x7fffffff) + 0x80000000L); } else { return BigInteger.valueOf((long) u32); } case Code.UINT64: // unsigned int 64 long u64 = readLong(); resetHeadByte(); if (u64 < 0L) { BigInteger bi = BigInteger.valueOf(u64 + Long.MAX_VALUE + 1L).setBit(63); return bi; } else { return BigInteger.valueOf(u64); } case Code.INT8: // signed int 8 byte i8 = readByte(); resetHeadByte(); return BigInteger.valueOf((long) i8); case Code.INT16: // signed int 16 short i16 = readShort(); resetHeadByte(); return BigInteger.valueOf((long) i16); case Code.INT32: // signed int 32 int i32 = readInt(); resetHeadByte(); return BigInteger.valueOf((long) i32); case Code.INT64: // signed int 64 long i64 = readLong(); resetHeadByte(); return BigInteger.valueOf(i64); } throw unexpected("Integer", b); } public float unpackFloat() throws IOException { byte b = getHeadByte(); switch (b) { case Code.FLOAT32: // float float fv = readFloat(); resetHeadByte(); return fv; case Code.FLOAT64: // double double dv = readDouble(); resetHeadByte(); return (float) dv; } throw unexpected("Float", b); } public double unpackDouble() throws IOException { byte b = getHeadByte(); switch (b) { case Code.FLOAT32: // float float fv = readFloat(); resetHeadByte(); return (double) fv; case Code.FLOAT64: // double double dv = readDouble(); resetHeadByte(); return dv; } throw unexpected("Float", b); } private static final String EMPTY_STRING = ""; private void resetDecoder() { if (decoder == null) { decodeBuffer = CharBuffer.allocate(config.stringDecoderBufferSize); decoder = MessagePack.UTF8.newDecoder() .onMalformedInput(config.actionOnMalFormedInput) .onUnmappableCharacter(config.actionOnUnmappableCharacter); } else { decoder.reset(); } decodeStringBuffer = new StringBuilder(); } /** * This method is not repeatable. */ public String unpackString() throws IOException { if (readingRawRemaining == 0) { int len = unpackRawStringHeader(); if (len == 0) { return EMPTY_STRING; } if (len > config.maxUnpackStringSize) { throw new MessageSizeException(String.format("cannot unpack a String of size larger than %,d: %,d", config.maxUnpackStringSize, len), len); } if (buffer.size() - position >= len) { return decodeStringFastPath(len); } readingRawRemaining = len; resetDecoder(); } assert (decoder != null); try { while (readingRawRemaining > 0) { int bufferRemaining = buffer.size() - position; if (bufferRemaining >= readingRawRemaining) { decodeStringBuffer.append(decodeStringFastPath(readingRawRemaining)); readingRawRemaining = 0; break; } else if (bufferRemaining == 0) { nextBuffer(); } else { ByteBuffer bb = buffer.toByteBuffer(position, bufferRemaining); int bbStartPosition = bb.position(); decodeBuffer.clear(); CoderResult cr = decoder.decode(bb, decodeBuffer, false); int readLen = bb.position() - bbStartPosition; position += readLen; readingRawRemaining -= readLen; decodeStringBuffer.append(decodeBuffer.flip()); if (cr.isError()) { handleCoderError(cr); } if (cr.isUnderflow() && readLen < bufferRemaining) { // handle incomplete multibyte character int incompleteMultiBytes = utf8MultibyteCharacterSize(buffer.getByte(position)); ByteBuffer multiByteBuffer = ByteBuffer.allocate(incompleteMultiBytes); buffer.getBytes(position, buffer.size() - position, multiByteBuffer); // read until multiByteBuffer is filled while (true) { nextBuffer(); int more = multiByteBuffer.remaining(); if (buffer.size() >= more) { buffer.getBytes(0, more, multiByteBuffer); position = more; break; } else { buffer.getBytes(0, buffer.size(), multiByteBuffer); position = buffer.size(); } } multiByteBuffer.position(0); decodeBuffer.clear(); cr = decoder.decode(multiByteBuffer, decodeBuffer, false); if (cr.isError()) { handleCoderError(cr); } if (cr.isOverflow() || (cr.isUnderflow() && multiByteBuffer.position() < multiByteBuffer.limit())) { // isOverflow or isOverflow must not happen. if happened, throw exception try { cr.throwException(); throw new MessageFormatException("Unexpected UTF-8 multibyte sequence"); } catch (Exception ex) { throw new MessageFormatException("Unexpected UTF-8 multibyte sequence", ex); } } readingRawRemaining -= multiByteBuffer.limit(); decodeStringBuffer.append(decodeBuffer.flip()); } } } return decodeStringBuffer.toString(); } catch (CharacterCodingException e) { throw new MessageStringCodingException(e); } } private void handleCoderError(CoderResult cr) throws CharacterCodingException { if ((cr.isMalformed() && config.actionOnMalFormedInput == CodingErrorAction.REPORT) || (cr.isUnmappable() && config.actionOnUnmappableCharacter == CodingErrorAction.REPORT)) { cr.throwException(); } } private String decodeStringFastPath(int length) { if (config.actionOnMalFormedInput == CodingErrorAction.REPLACE && config.actionOnUnmappableCharacter == CodingErrorAction.REPLACE && buffer.hasArray()) { String s = new String(buffer.getArray(), buffer.offset() + position, length, MessagePack.UTF8); position += length; return s; } else { resetDecoder(); ByteBuffer bb = buffer.toByteBuffer(); bb.limit(position + length); bb.position(position); CharBuffer cb; try { cb = decoder.decode(bb); } catch (CharacterCodingException e) { throw new MessageStringCodingException(e); } position += length; return cb.toString(); } } public int unpackArrayHeader() throws IOException { byte b = getHeadByte(); if (Code.isFixedArray(b)) { // fixarray resetHeadByte(); return b & 0x0f; } switch (b) { case Code.ARRAY16: { // array 16 int len = readNextLength16(); resetHeadByte(); return len; } case Code.ARRAY32: { // array 32 int len = readNextLength32(); resetHeadByte(); return len; } } throw unexpected("Array", b); } public int unpackMapHeader() throws IOException { byte b = getHeadByte(); if (Code.isFixedMap(b)) { // fixmap resetHeadByte(); return b & 0x0f; } switch (b) { case Code.MAP16: { // map 16 int len = readNextLength16(); resetHeadByte(); return len; } case Code.MAP32: { // map 32 int len = readNextLength32(); resetHeadByte(); return len; } } throw unexpected("Map", b); } public ExtensionTypeHeader unpackExtensionTypeHeader() throws IOException { byte b = getHeadByte(); switch (b) { case Code.FIXEXT1: { byte type = readByte(); resetHeadByte(); return new ExtensionTypeHeader(type, 1); } case Code.FIXEXT2: { byte type = readByte(); resetHeadByte(); return new ExtensionTypeHeader(type, 2); } case Code.FIXEXT4: { byte type = readByte(); resetHeadByte(); return new ExtensionTypeHeader(type, 4); } case Code.FIXEXT8: { byte type = readByte(); resetHeadByte(); return new ExtensionTypeHeader(type, 8); } case Code.FIXEXT16: { byte type = readByte(); resetHeadByte(); return new ExtensionTypeHeader(type, 16); } case Code.EXT8: { MessageBuffer castBuffer = readCastBuffer(2); resetHeadByte(); int u8 = castBuffer.getByte(readCastBufferPosition); int length = u8 & 0xff; byte type = castBuffer.getByte(readCastBufferPosition + 1); return new ExtensionTypeHeader(type, length); } case Code.EXT16: { MessageBuffer castBuffer = readCastBuffer(3); resetHeadByte(); int u16 = castBuffer.getShort(readCastBufferPosition); int length = u16 & 0xffff; byte type = castBuffer.getByte(readCastBufferPosition + 2); return new ExtensionTypeHeader(type, length); } case Code.EXT32: { MessageBuffer castBuffer = readCastBuffer(5); resetHeadByte(); int u32 = castBuffer.getInt(readCastBufferPosition); if (u32 < 0) { throw overflowU32Size(u32); } int length = u32; byte type = castBuffer.getByte(readCastBufferPosition + 4); return new ExtensionTypeHeader(type, length); } } throw unexpected("Ext", b); } private int tryReadStringHeader(byte b) throws IOException { switch (b) { case Code.STR8: // str 8 return readNextLength8(); case Code.STR16: // str 16 return readNextLength16(); case Code.STR32: // str 32 return readNextLength32(); default: return -1; } } private int tryReadBinaryHeader(byte b) throws IOException { switch (b) { case Code.BIN8: // bin 8 return readNextLength8(); case Code.BIN16: // bin 16 return readNextLength16(); case Code.BIN32: // bin 32 return readNextLength32(); default: return -1; } } public int unpackRawStringHeader() throws IOException { byte b = getHeadByte(); if (Code.isFixedRaw(b)) { // FixRaw resetHeadByte(); return b & 0x1f; } int len = tryReadStringHeader(b); if (len >= 0) { resetHeadByte(); return len; } if (config.readBinaryAsString) { len = tryReadBinaryHeader(b); if (len >= 0) { resetHeadByte(); return len; } } throw unexpected("String", b); } public int unpackBinaryHeader() throws IOException { byte b = getHeadByte(); if (Code.isFixedRaw(b)) { // FixRaw resetHeadByte(); return b & 0x1f; } int len = tryReadBinaryHeader(b); if (len >= 0) { resetHeadByte(); return len; } if (config.readStringAsBinary) { len = tryReadStringHeader(b); if (len >= 0) { resetHeadByte(); return len; } } throw unexpected("Binary", b); } /** * Skip reading the specified number of bytes. Use this method only if you know skipping data is safe. * For simply skipping the next value, use {@link #skipValue()}. * * @param numBytes * @throws IOException */ private void skipPayload(int numBytes) throws IOException { while (true) { int bufferRemaining = buffer.size() - position; if (bufferRemaining >= numBytes) { position += numBytes; return; } else { position += bufferRemaining; numBytes -= bufferRemaining; } nextBuffer(); } } public void readPayload(ByteBuffer dst) throws IOException { while (true) { int dstRemaining = dst.remaining(); int bufferRemaining = buffer.size() - position; if (bufferRemaining >= dstRemaining) { buffer.getBytes(position, dstRemaining, dst); position += dstRemaining; return; } buffer.getBytes(position, bufferRemaining, dst); position += bufferRemaining; nextBuffer(); } } public void readPayload(byte[] dst) throws IOException { readPayload(dst, 0, dst.length); } public byte[] readPayload(int length) throws IOException { byte[] newArray = new byte[length]; readPayload(newArray); return newArray; } /** * Read up to len bytes of data into the destination array * * @param dst the buffer into which the data is read * @param off the offset in the dst array * @param len the number of bytes to read * @throws IOException */ public void readPayload(byte[] dst, int off, int len) throws IOException { // TODO optimize readPayload(ByteBuffer.wrap(dst, off, len)); } public MessageBuffer readPayloadAsReference(int length) throws IOException { int bufferRemaining = buffer.size() - position; if (bufferRemaining >= length) { MessageBuffer slice = buffer.slice(position, length); position += length; return slice; } MessageBuffer dst = MessageBuffer.newBuffer(length); readPayload(dst.getReference()); return dst; } private int readNextLength8() throws IOException { byte u8 = readByte(); return u8 & 0xff; } private int readNextLength16() throws IOException { short u16 = readShort(); return u16 & 0xffff; } private int readNextLength32() throws IOException { int u32 = readInt(); if (u32 < 0) { throw overflowU32Size(u32); } return u32; } @Override public void close() throws IOException { buffer = EMPTY_BUFFER; position = 0; in.close(); } private static MessageIntegerOverflowException overflowU8(byte u8) { BigInteger bi = BigInteger.valueOf((long) (u8 & 0xff)); return new MessageIntegerOverflowException(bi); } private static MessageIntegerOverflowException overflowU16(short u16) { BigInteger bi = BigInteger.valueOf((long) (u16 & 0xffff)); return new MessageIntegerOverflowException(bi); } private static MessageIntegerOverflowException overflowU32(int u32) { BigInteger bi = BigInteger.valueOf((long) (u32 & 0x7fffffff) + 0x80000000L); return new MessageIntegerOverflowException(bi); } private static MessageIntegerOverflowException overflowU64(long u64) { BigInteger bi = BigInteger.valueOf(u64 + Long.MAX_VALUE + 1L).setBit(63); return new MessageIntegerOverflowException(bi); } private static MessageIntegerOverflowException overflowI16(short i16) { BigInteger bi = BigInteger.valueOf((long) i16); return new MessageIntegerOverflowException(bi); } private static MessageIntegerOverflowException overflowI32(int i32) { BigInteger bi = BigInteger.valueOf((long) i32); return new MessageIntegerOverflowException(bi); } private static MessageIntegerOverflowException overflowI64(long i64) { BigInteger bi = BigInteger.valueOf(i64); return new MessageIntegerOverflowException(bi); } private static MessageSizeException overflowU32Size(int u32) { long lv = (long) (u32 & 0x7fffffff) + 0x80000000L; return new MessageSizeException(lv); } }
msgpack-core/src/main/java/org/msgpack/core/MessageUnpacker.java
// // MessagePack for Java // // 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.msgpack.core; import org.msgpack.core.MessagePack.Code; import org.msgpack.core.buffer.MessageBuffer; import org.msgpack.core.buffer.MessageBufferInput; import org.msgpack.value.ImmutableValue; import org.msgpack.value.Value; import org.msgpack.value.ValueFactory; import org.msgpack.value.Variable; import java.io.Closeable; import java.io.EOFException; import java.io.IOException; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.nio.charset.MalformedInputException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.msgpack.core.Preconditions.checkArgument; import static org.msgpack.core.Preconditions.checkNotNull; /** * MessageUnpacker lets an application read message-packed values from a data stream. * The application needs to call {@link #getNextFormat()} followed by an appropriate unpackXXX method according to the the returned format type. * <p/> * <pre> * <code> * MessageUnpacker unpacker = MessagePackFactory.DEFAULT.newUnpacker(...); * while(unpacker.hasNext()) { * MessageFormat f = unpacker.getNextFormat(); * switch(f) { * case MessageFormat.POSFIXINT: * case MessageFormat.INT8: * case MessageFormat.UINT8: { * int v = unpacker.unpackInt(); * break; * } * case MessageFormat.STRING: { * String v = unpacker.unpackString(); * break; * } * // ... * } * } * * </code> * </pre> */ public class MessageUnpacker implements Closeable { private static final MessageBuffer EMPTY_BUFFER = MessageBuffer.wrap(new byte[0]); private static final byte HEAD_BYTE_REQUIRED = (byte) 0xc1; private final MessagePack.Config config; private MessageBufferInput in; private byte headByte = HEAD_BYTE_REQUIRED; /** * Points to the current buffer to read */ private MessageBuffer buffer = EMPTY_BUFFER; /** * Cursor position in the current buffer */ private int position; /** * Total read byte size */ private long totalReadBytes; /** * Extra buffer for fixed-length data at the buffer boundary. At most 17-byte buffer (for FIXEXT16) is required. */ private final MessageBuffer castBuffer = MessageBuffer.newBuffer(24); /** * Variable by ensureHeader method. Caller of the method should use this variable to read from returned MessageBuffer. */ private int readCastBufferPosition; /** * For decoding String in unpackString. */ private StringBuilder decodeStringBuffer; /** * For decoding String in unpackString. */ private int readingRawRemaining = 0; /** * For decoding String in unpackString. */ private CharsetDecoder decoder; /** * Buffer for decoding strings */ private CharBuffer decodeBuffer; /** * Create an MessageUnpacker that reads data from the given MessageBufferInput * * @param in */ public MessageUnpacker(MessageBufferInput in) { this(in, MessagePack.DEFAULT_CONFIG); } /** * Create an MessageUnpacker * * @param in * @param config configuration */ public MessageUnpacker(MessageBufferInput in, MessagePack.Config config) { // Root constructor. All of the constructors must call this constructor. this.in = checkNotNull(in, "MessageBufferInput is null"); this.config = checkNotNull(config, "Config"); } /** * Reset input. This method doesn't close the old resource. * * @param in new input * @return the old resource */ public MessageBufferInput reset(MessageBufferInput in) throws IOException { MessageBufferInput newIn = checkNotNull(in, "MessageBufferInput is null"); // Reset the internal states MessageBufferInput old = this.in; this.in = newIn; this.buffer = EMPTY_BUFFER; this.position = 0; this.totalReadBytes = 0; this.readingRawRemaining = 0; // No need to initialize the already allocated string decoder here since we can reuse it. return old; } public long getTotalReadBytes() { return totalReadBytes + position; } private byte getHeadByte() throws IOException { byte b = headByte; if (b == HEAD_BYTE_REQUIRED) { b = headByte = readByte(); if (b == HEAD_BYTE_REQUIRED) { throw new MessageNeverUsedFormatException("Encountered 0xC1 \"NEVER_USED\" byte"); } } return b; } private void resetHeadByte() { headByte = HEAD_BYTE_REQUIRED; } private void nextBuffer() throws IOException { MessageBuffer next = in.next(); if (next == null) { throw new MessageInsufficientBufferException(); } totalReadBytes += buffer.size(); buffer = next; position = 0; } private MessageBuffer readCastBuffer(int length) throws IOException { int remaining = buffer.size() - position; if (remaining >= length) { readCastBufferPosition = position; position += length; // here assumes following buffer.getXxx never throws exception return buffer; } else { // TODO loop this method until castBuffer is filled MessageBuffer next = in.next(); if (next == null) { throw new MessageInsufficientBufferException(); } // TODO this doesn't work if MessageBuffer is allocated by newDirectBuffer. // add copy method to MessageBuffer to solve this issue. castBuffer.putBytes(0, buffer.getArray(), buffer.offset() + position, remaining); castBuffer.putBytes(remaining, next.getArray(), next.offset(), length - remaining); totalReadBytes += buffer.size(); buffer = next; position = length - remaining; readCastBufferPosition = 0; return castBuffer; } } private static int utf8MultibyteCharacterSize(byte firstByte) { return Integer.numberOfLeadingZeros(~(firstByte & 0xff) << 24); } /** * Returns true true if this unpacker has more elements. * When this returns true, subsequent call to {@link #getNextFormat()} returns an * MessageFormat instance. If false, next {@link #getNextFormat()} call will throw an MessageInsufficientBufferException. * * @return true if this unpacker has more elements to read */ public boolean hasNext() throws IOException { if (buffer.size() <= position) { MessageBuffer next = in.next(); if (next == null) { return false; } totalReadBytes += buffer.size(); buffer = next; position = 0; } return true; } /** * Returns the next MessageFormat type. This method should be called after {@link #hasNext()} returns true. * If {@link #hasNext()} returns false, calling this method throws {@link MessageInsufficientBufferException}. * <p/> * This method does not proceed the internal cursor. * * @return the next MessageFormat * @throws IOException when failed to read the input data. * @throws MessageInsufficientBufferException when the end of file reached, i.e. {@link #hasNext()} == false. */ public MessageFormat getNextFormat() throws IOException { try { byte b = getHeadByte(); return MessageFormat.valueOf(b); } catch (MessageNeverUsedFormatException ex) { return MessageFormat.NEVER_USED; } } /** * Read a byte value at the cursor and proceed the cursor. * * @return * @throws IOException */ private byte readByte() throws IOException { if (buffer.size() > position) { byte b = buffer.getByte(position); position++; return b; } else { nextBuffer(); if (buffer.size() > 0) { byte b = buffer.getByte(0); position = 1; return b; } return readByte(); } } private short readShort() throws IOException { MessageBuffer castBuffer = readCastBuffer(2); return castBuffer.getShort(readCastBufferPosition); } private int readInt() throws IOException { MessageBuffer castBuffer = readCastBuffer(4); return castBuffer.getInt(readCastBufferPosition); } private long readLong() throws IOException { MessageBuffer castBuffer = readCastBuffer(8); return castBuffer.getLong(readCastBufferPosition); } private float readFloat() throws IOException { MessageBuffer castBuffer = readCastBuffer(4); return castBuffer.getFloat(readCastBufferPosition); } private double readDouble() throws IOException { MessageBuffer castBuffer = readCastBuffer(8); return castBuffer.getDouble(readCastBufferPosition); } /** * Skip the next value, then move the cursor at the end of the value * * @throws IOException */ public void skipValue() throws IOException { int remainingValues = 1; while (remainingValues > 0) { byte b = getHeadByte(); MessageFormat f = MessageFormat.valueOf(b); resetHeadByte(); switch (f) { case POSFIXINT: case NEGFIXINT: case BOOLEAN: case NIL: break; case FIXMAP: { int mapLen = b & 0x0f; remainingValues += mapLen * 2; break; } case FIXARRAY: { int arrayLen = b & 0x0f; remainingValues += arrayLen; break; } case FIXSTR: { int strLen = b & 0x1f; skipPayload(strLen); break; } case INT8: case UINT8: skipPayload(1); break; case INT16: case UINT16: skipPayload(2); break; case INT32: case UINT32: case FLOAT32: skipPayload(4); break; case INT64: case UINT64: case FLOAT64: skipPayload(8); break; case BIN8: case STR8: skipPayload(readNextLength8()); break; case BIN16: case STR16: skipPayload(readNextLength16()); break; case BIN32: case STR32: skipPayload(readNextLength32()); break; case FIXEXT1: skipPayload(2); break; case FIXEXT2: skipPayload(3); break; case FIXEXT4: skipPayload(5); break; case FIXEXT8: skipPayload(9); break; case FIXEXT16: skipPayload(17); break; case EXT8: skipPayload(readNextLength8() + 1); break; case EXT16: skipPayload(readNextLength16() + 1); break; case EXT32: skipPayload(readNextLength32() + 1); break; case ARRAY16: remainingValues += readNextLength16(); break; case ARRAY32: remainingValues += readNextLength32(); break; case MAP16: remainingValues += readNextLength16() * 2; break; case MAP32: remainingValues += readNextLength32() * 2; // TODO check int overflow break; case NEVER_USED: throw new MessageFormatException(String.format("unknown code: %02x is found", b)); } remainingValues--; } } /** * Create an exception for the case when an unexpected byte value is read * * @param expected * @param b * @return * @throws MessageFormatException */ private static MessageTypeException unexpected(String expected, byte b) throws MessageTypeException { MessageFormat format = MessageFormat.valueOf(b); String typeName; if (format == MessageFormat.NEVER_USED) { typeName = "NeverUsed"; } else { String name = format.getValueType().name(); typeName = name.substring(0, 1) + name.substring(1).toLowerCase(); } return new MessageTypeException(String.format("Expected %s, but got %s (%02x)", expected, typeName, b)); } public ImmutableValue unpackValue() throws IOException { MessageFormat mf = getNextFormat(); switch (mf.getValueType()) { case NIL: readByte(); return ValueFactory.newNil(); case BOOLEAN: return ValueFactory.newBoolean(unpackBoolean()); case INTEGER: switch (mf) { case UINT64: return ValueFactory.newInteger(unpackBigInteger()); default: return ValueFactory.newInteger(unpackLong()); } case FLOAT: return ValueFactory.newFloat(unpackDouble()); case STRING: { int length = unpackRawStringHeader(); return ValueFactory.newString(readPayload(length)); } case BINARY: { int length = unpackBinaryHeader(); return ValueFactory.newBinary(readPayload(length)); } case ARRAY: { int size = unpackArrayHeader(); Value[] array = new Value[size]; for (int i = 0; i < size; i++) { array[i] = unpackValue(); } return ValueFactory.newArray(array); } case MAP: { int size = unpackMapHeader(); Value[] kvs = new Value[size * 2]; for (int i = 0; i < size * 2; ) { kvs[i] = unpackValue(); i++; kvs[i] = unpackValue(); i++; } return ValueFactory.newMap(kvs); } case EXTENSION: { ExtensionTypeHeader extHeader = unpackExtensionTypeHeader(); return ValueFactory.newExtension(extHeader.getType(), readPayload(extHeader.getLength())); } default: throw new MessageFormatException("Unknown value type"); } } public Variable unpackValue(Variable var) throws IOException { MessageFormat mf = getNextFormat(); switch (mf.getValueType()) { case NIL: unpackNil(); var.setNilValue(); return var; case BOOLEAN: var.setBooleanValue(unpackBoolean()); return var; case INTEGER: switch (mf) { case UINT64: var.setIntegerValue(unpackBigInteger()); return var; default: var.setIntegerValue(unpackLong()); return var; } case FLOAT: var.setFloatValue(unpackDouble()); return var; case STRING: { int length = unpackRawStringHeader(); var.setStringValue(readPayload(length)); return var; } case BINARY: { int length = unpackBinaryHeader(); var.setBinaryValue(readPayload(length)); return var; } case ARRAY: { int size = unpackArrayHeader(); List<Value> list = new ArrayList<Value>(size); for (int i = 0; i < size; i++) { //Variable e = new Variable(); //unpackValue(e); //list.add(e); list.add(unpackValue()); } var.setArrayValue(list); return var; } case MAP: { int size = unpackMapHeader(); Map<Value, Value> map = new HashMap<Value, Value>(); for (int i = 0; i < size; i++) { //Variable k = new Variable(); //unpackValue(k); //Variable v = new Variable(); //unpackValue(v); Value k = unpackValue(); Value v = unpackValue(); map.put(k, v); } var.setMapValue(map); return var; } case EXTENSION: { ExtensionTypeHeader extHeader = unpackExtensionTypeHeader(); var.setExtensionValue(extHeader.getType(), readPayload(extHeader.getLength())); return var; } default: throw new MessageFormatException("Unknown value type"); } } public void unpackNil() throws IOException { byte b = getHeadByte(); if (b == Code.NIL) { resetHeadByte(); return; } throw unexpected("Nil", b); } public boolean unpackBoolean() throws IOException { byte b = getHeadByte(); if (b == Code.FALSE) { resetHeadByte(); return false; } else if (b == Code.TRUE) { resetHeadByte(); return true; } throw unexpected("boolean", b); } public byte unpackByte() throws IOException { byte b = getHeadByte(); if (Code.isFixInt(b)) { resetHeadByte(); return b; } switch (b) { case Code.UINT8: // unsigned int 8 byte u8 = readByte(); resetHeadByte(); if (u8 < (byte) 0) { throw overflowU8(u8); } return u8; case Code.UINT16: // unsigned int 16 short u16 = readShort(); resetHeadByte(); if (u16 < 0 || u16 > Byte.MAX_VALUE) { throw overflowU16(u16); } return (byte) u16; case Code.UINT32: // unsigned int 32 int u32 = readInt(); resetHeadByte(); if (u32 < 0 || u32 > Byte.MAX_VALUE) { throw overflowU32(u32); } return (byte) u32; case Code.UINT64: // unsigned int 64 long u64 = readLong(); resetHeadByte(); if (u64 < 0L || u64 > Byte.MAX_VALUE) { throw overflowU64(u64); } return (byte) u64; case Code.INT8: // signed int 8 byte i8 = readByte(); resetHeadByte(); return i8; case Code.INT16: // signed int 16 short i16 = readShort(); resetHeadByte(); if (i16 < Byte.MIN_VALUE || i16 > Byte.MAX_VALUE) { throw overflowI16(i16); } return (byte) i16; case Code.INT32: // signed int 32 int i32 = readInt(); resetHeadByte(); if (i32 < Byte.MIN_VALUE || i32 > Byte.MAX_VALUE) { throw overflowI32(i32); } return (byte) i32; case Code.INT64: // signed int 64 long i64 = readLong(); resetHeadByte(); if (i64 < Byte.MIN_VALUE || i64 > Byte.MAX_VALUE) { throw overflowI64(i64); } return (byte) i64; } throw unexpected("Integer", b); } public short unpackShort() throws IOException { byte b = getHeadByte(); if (Code.isFixInt(b)) { resetHeadByte(); return (short) b; } switch (b) { case Code.UINT8: // unsigned int 8 byte u8 = readByte(); resetHeadByte(); return (short) (u8 & 0xff); case Code.UINT16: // unsigned int 16 short u16 = readShort(); resetHeadByte(); if (u16 < (short) 0) { throw overflowU16(u16); } return u16; case Code.UINT32: // unsigned int 32 int u32 = readInt(); resetHeadByte(); if (u32 < 0 || u32 > Short.MAX_VALUE) { throw overflowU32(u32); } return (short) u32; case Code.UINT64: // unsigned int 64 resetHeadByte(); long u64 = readLong(); if (u64 < 0L || u64 > Short.MAX_VALUE) { throw overflowU64(u64); } return (short) u64; case Code.INT8: // signed int 8 byte i8 = readByte(); resetHeadByte(); return (short) i8; case Code.INT16: // signed int 16 short i16 = readShort(); resetHeadByte(); return i16; case Code.INT32: // signed int 32 int i32 = readInt(); resetHeadByte(); if (i32 < Short.MIN_VALUE || i32 > Short.MAX_VALUE) { throw overflowI32(i32); } return (short) i32; case Code.INT64: // signed int 64 long i64 = readLong(); resetHeadByte(); if (i64 < Short.MIN_VALUE || i64 > Short.MAX_VALUE) { throw overflowI64(i64); } return (short) i64; } throw unexpected("Integer", b); } public int unpackInt() throws IOException { byte b = getHeadByte(); if (Code.isFixInt(b)) { resetHeadByte(); return (int) b; } switch (b) { case Code.UINT8: // unsigned int 8 byte u8 = readByte(); resetHeadByte(); return u8 & 0xff; case Code.UINT16: // unsigned int 16 short u16 = readShort(); resetHeadByte(); return u16 & 0xffff; case Code.UINT32: // unsigned int 32 int u32 = readInt(); if (u32 < 0) { throw overflowU32(u32); } resetHeadByte(); return u32; case Code.UINT64: // unsigned int 64 long u64 = readLong(); resetHeadByte(); if (u64 < 0L || u64 > (long) Integer.MAX_VALUE) { throw overflowU64(u64); } return (int) u64; case Code.INT8: // signed int 8 byte i8 = readByte(); resetHeadByte(); return i8; case Code.INT16: // signed int 16 short i16 = readShort(); resetHeadByte(); return i16; case Code.INT32: // signed int 32 int i32 = readInt(); resetHeadByte(); return i32; case Code.INT64: // signed int 64 long i64 = readLong(); resetHeadByte(); if (i64 < (long) Integer.MIN_VALUE || i64 > (long) Integer.MAX_VALUE) { throw overflowI64(i64); } return (int) i64; } throw unexpected("Integer", b); } public long unpackLong() throws IOException { byte b = getHeadByte(); if (Code.isFixInt(b)) { resetHeadByte(); return (long) b; } switch (b) { case Code.UINT8: // unsigned int 8 byte u8 = readByte(); resetHeadByte(); return (long) (u8 & 0xff); case Code.UINT16: // unsigned int 16 short u16 = readShort(); resetHeadByte(); return (long) (u16 & 0xffff); case Code.UINT32: // unsigned int 32 int u32 = readInt(); resetHeadByte(); if (u32 < 0) { return (long) (u32 & 0x7fffffff) + 0x80000000L; } else { return (long) u32; } case Code.UINT64: // unsigned int 64 long u64 = readLong(); resetHeadByte(); if (u64 < 0L) { throw overflowU64(u64); } return u64; case Code.INT8: // signed int 8 byte i8 = readByte(); resetHeadByte(); return (long) i8; case Code.INT16: // signed int 16 short i16 = readShort(); resetHeadByte(); return (long) i16; case Code.INT32: // signed int 32 int i32 = readInt(); resetHeadByte(); return (long) i32; case Code.INT64: // signed int 64 long i64 = readLong(); resetHeadByte(); return i64; } throw unexpected("Integer", b); } public BigInteger unpackBigInteger() throws IOException { byte b = getHeadByte(); if (Code.isFixInt(b)) { resetHeadByte(); return BigInteger.valueOf((long) b); } switch (b) { case Code.UINT8: // unsigned int 8 byte u8 = readByte(); resetHeadByte(); return BigInteger.valueOf((long) (u8 & 0xff)); case Code.UINT16: // unsigned int 16 short u16 = readShort(); resetHeadByte(); return BigInteger.valueOf((long) (u16 & 0xffff)); case Code.UINT32: // unsigned int 32 int u32 = readInt(); resetHeadByte(); if (u32 < 0) { return BigInteger.valueOf((long) (u32 & 0x7fffffff) + 0x80000000L); } else { return BigInteger.valueOf((long) u32); } case Code.UINT64: // unsigned int 64 long u64 = readLong(); resetHeadByte(); if (u64 < 0L) { BigInteger bi = BigInteger.valueOf(u64 + Long.MAX_VALUE + 1L).setBit(63); return bi; } else { return BigInteger.valueOf(u64); } case Code.INT8: // signed int 8 byte i8 = readByte(); resetHeadByte(); return BigInteger.valueOf((long) i8); case Code.INT16: // signed int 16 short i16 = readShort(); resetHeadByte(); return BigInteger.valueOf((long) i16); case Code.INT32: // signed int 32 int i32 = readInt(); resetHeadByte(); return BigInteger.valueOf((long) i32); case Code.INT64: // signed int 64 long i64 = readLong(); resetHeadByte(); return BigInteger.valueOf(i64); } throw unexpected("Integer", b); } public float unpackFloat() throws IOException { byte b = getHeadByte(); switch (b) { case Code.FLOAT32: // float float fv = readFloat(); resetHeadByte(); return fv; case Code.FLOAT64: // double double dv = readDouble(); resetHeadByte(); return (float) dv; } throw unexpected("Float", b); } public double unpackDouble() throws IOException { byte b = getHeadByte(); switch (b) { case Code.FLOAT32: // float float fv = readFloat(); resetHeadByte(); return (double) fv; case Code.FLOAT64: // double double dv = readDouble(); resetHeadByte(); return dv; } throw unexpected("Float", b); } private static final String EMPTY_STRING = ""; private void resetDecoder() { if (decoder == null) { decodeBuffer = CharBuffer.allocate(config.stringDecoderBufferSize); decoder = MessagePack.UTF8.newDecoder() .onMalformedInput(config.actionOnMalFormedInput) .onUnmappableCharacter(config.actionOnUnmappableCharacter); } else { decoder.reset(); } decodeStringBuffer = new StringBuilder(); } /** * This method is not repeatable. */ public String unpackString() throws IOException { if (readingRawRemaining == 0) { int len = unpackRawStringHeader(); if (len == 0) { return EMPTY_STRING; } if (len > config.maxUnpackStringSize) { throw new MessageSizeException(String.format("cannot unpack a String of size larger than %,d: %,d", config.maxUnpackStringSize, len), len); } if (buffer.size() - position >= len) { return decodeStringFastPath(len); } readingRawRemaining = len; resetDecoder(); } assert (decoder != null); try { while (readingRawRemaining > 0) { int bufferRemaining = buffer.size() - position; if (bufferRemaining >= readingRawRemaining) { decodeStringBuffer.append(decodeStringFastPath(readingRawRemaining)); readingRawRemaining = 0; break; } else if (bufferRemaining == 0) { nextBuffer(); } else { ByteBuffer bb = buffer.toByteBuffer(position, bufferRemaining); int bbStartPosition = bb.position(); decodeBuffer.clear(); CoderResult cr = decoder.decode(bb, decodeBuffer, false); int readLen = bb.position() - bbStartPosition; position += readLen; readingRawRemaining -= readLen; decodeStringBuffer.append(decodeBuffer.flip()); if (cr.isError()) { handleCoderError(cr); } if (cr.isUnderflow() && readLen < bufferRemaining) { // handle incomplete multibyte character int incompleteMultiBytes = utf8MultibyteCharacterSize(buffer.getByte(position)); ByteBuffer multiByteBuffer = ByteBuffer.allocate(incompleteMultiBytes); buffer.getBytes(position, buffer.size() - position, multiByteBuffer); // read until multiByteBuffer is filled while (true) { nextBuffer(); int more = multiByteBuffer.remaining(); if (buffer.size() >= more) { buffer.getBytes(0, more, multiByteBuffer); position = more; break; } else { buffer.getBytes(0, buffer.size(), multiByteBuffer); position = buffer.size(); } } multiByteBuffer.position(0); decodeBuffer.clear(); cr = decoder.decode(multiByteBuffer, decodeBuffer, false); if (cr.isError()) { handleCoderError(cr); } if (cr.isOverflow() || (cr.isUnderflow() && multiByteBuffer.position() < multiByteBuffer.limit())) { // isOverflow or isOverflow must not happen. if happened, throw exception try { cr.throwException(); throw new MessageFormatException("Unexpected UTF-8 multibyte sequence"); } catch (Exception ex) { throw new MessageFormatException("Unexpected UTF-8 multibyte sequence", ex); } } readingRawRemaining -= multiByteBuffer.limit(); decodeStringBuffer.append(decodeBuffer.flip()); } } } return decodeStringBuffer.toString(); } catch (CharacterCodingException e) { throw new MessageStringCodingException(e); } } private void handleCoderError(CoderResult cr) throws CharacterCodingException { if ((cr.isMalformed() && config.actionOnMalFormedInput == CodingErrorAction.REPORT) || (cr.isUnmappable() && config.actionOnUnmappableCharacter == CodingErrorAction.REPORT)) { cr.throwException(); } } private String decodeStringFastPath(int length) { if (config.actionOnMalFormedInput == CodingErrorAction.REPLACE && config.actionOnUnmappableCharacter == CodingErrorAction.REPLACE && buffer.hasArray()) { String s = new String(buffer.getArray(), buffer.offset() + position, length, MessagePack.UTF8); position += length; return s; } else { resetDecoder(); ByteBuffer bb = buffer.toByteBuffer(); bb.limit(position + length); bb.position(position); CharBuffer cb; try { cb = decoder.decode(bb); } catch (CharacterCodingException e) { throw new MessageStringCodingException(e); } position += length; return cb.toString(); } } public int unpackArrayHeader() throws IOException { byte b = getHeadByte(); if (Code.isFixedArray(b)) { // fixarray resetHeadByte(); return b & 0x0f; } switch (b) { case Code.ARRAY16: { // array 16 int len = readNextLength16(); resetHeadByte(); return len; } case Code.ARRAY32: { // array 32 int len = readNextLength32(); resetHeadByte(); return len; } } throw unexpected("Array", b); } public int unpackMapHeader() throws IOException { byte b = getHeadByte(); if (Code.isFixedMap(b)) { // fixmap resetHeadByte(); return b & 0x0f; } switch (b) { case Code.MAP16: { // map 16 int len = readNextLength16(); resetHeadByte(); return len; } case Code.MAP32: { // map 32 int len = readNextLength32(); resetHeadByte(); return len; } } throw unexpected("Map", b); } public ExtensionTypeHeader unpackExtensionTypeHeader() throws IOException { byte b = getHeadByte(); switch (b) { case Code.FIXEXT1: { byte type = readByte(); resetHeadByte(); return new ExtensionTypeHeader(type, 1); } case Code.FIXEXT2: { byte type = readByte(); resetHeadByte(); return new ExtensionTypeHeader(type, 2); } case Code.FIXEXT4: { byte type = readByte(); resetHeadByte(); return new ExtensionTypeHeader(type, 4); } case Code.FIXEXT8: { byte type = readByte(); resetHeadByte(); return new ExtensionTypeHeader(type, 8); } case Code.FIXEXT16: { byte type = readByte(); resetHeadByte(); return new ExtensionTypeHeader(type, 16); } case Code.EXT8: { MessageBuffer castBuffer = readCastBuffer(2); resetHeadByte(); int u8 = castBuffer.getByte(readCastBufferPosition); int length = u8 & 0xff; byte type = castBuffer.getByte(readCastBufferPosition + 1); return new ExtensionTypeHeader(type, length); } case Code.EXT16: { MessageBuffer castBuffer = readCastBuffer(3); resetHeadByte(); int u16 = castBuffer.getShort(readCastBufferPosition); int length = u16 & 0xffff; byte type = castBuffer.getByte(readCastBufferPosition + 2); return new ExtensionTypeHeader(type, length); } case Code.EXT32: { MessageBuffer castBuffer = readCastBuffer(5); resetHeadByte(); int u32 = castBuffer.getInt(readCastBufferPosition); if (u32 < 0) { throw overflowU32Size(u32); } int length = u32; byte type = castBuffer.getByte(readCastBufferPosition + 4); return new ExtensionTypeHeader(type, length); } } throw unexpected("Ext", b); } private int tryReadStringHeader(byte b) throws IOException { switch (b) { case Code.STR8: // str 8 return readNextLength8(); case Code.STR16: // str 16 return readNextLength16(); case Code.STR32: // str 32 return readNextLength32(); default: return -1; } } private int tryReadBinaryHeader(byte b) throws IOException { switch (b) { case Code.BIN8: // bin 8 return readNextLength8(); case Code.BIN16: // bin 16 return readNextLength16(); case Code.BIN32: // bin 32 return readNextLength32(); default: return -1; } } public int unpackRawStringHeader() throws IOException { byte b = getHeadByte(); if (Code.isFixedRaw(b)) { // FixRaw resetHeadByte(); return b & 0x1f; } int len = tryReadStringHeader(b); if (len >= 0) { resetHeadByte(); return len; } if (config.readBinaryAsString) { len = tryReadBinaryHeader(b); if (len >= 0) { resetHeadByte(); return len; } } throw unexpected("String", b); } public int unpackBinaryHeader() throws IOException { byte b = getHeadByte(); if (Code.isFixedRaw(b)) { // FixRaw resetHeadByte(); return b & 0x1f; } int len = tryReadBinaryHeader(b); if (len >= 0) { resetHeadByte(); return len; } if (config.readStringAsBinary) { len = tryReadStringHeader(b); if (len >= 0) { resetHeadByte(); return len; } } throw unexpected("Binary", b); } /** * Skip reading the specified number of bytes. Use this method only if you know skipping data is safe. * For simply skipping the next value, use {@link #skipValue()}. * * @param numBytes * @throws IOException */ private void skipPayload(int numBytes) throws IOException { while (true) { int bufferRemaining = buffer.size() - position; if (bufferRemaining >= numBytes) { position += numBytes; return; } else { position += bufferRemaining; numBytes -= bufferRemaining; } nextBuffer(); } } public void readPayload(ByteBuffer dst) throws IOException { while (true) { int dstRemaining = dst.remaining(); int bufferRemaining = buffer.size() - position; if (bufferRemaining >= dstRemaining) { buffer.getBytes(position, dstRemaining, dst); position += dstRemaining; return; } buffer.getBytes(position, bufferRemaining, dst); position += bufferRemaining; nextBuffer(); } } public void readPayload(byte[] dst) throws IOException { readPayload(dst, 0, dst.length); } public byte[] readPayload(int length) throws IOException { byte[] newArray = new byte[length]; readPayload(newArray); return newArray; } /** * Read up to len bytes of data into the destination array * * @param dst the buffer into which the data is read * @param off the offset in the dst array * @param len the number of bytes to read * @throws IOException */ public void readPayload(byte[] dst, int off, int len) throws IOException { // TODO optimize readPayload(ByteBuffer.wrap(dst, off, len)); } public MessageBuffer readPayloadAsReference(int length) throws IOException { int bufferRemaining = buffer.size() - position; if (bufferRemaining >= length) { MessageBuffer slice = buffer.slice(position, length); position += length; return slice; } MessageBuffer dst = MessageBuffer.newBuffer(length); readPayload(dst.getReference()); return dst; } private int readNextLength8() throws IOException { byte u8 = readByte(); return u8 & 0xff; } private int readNextLength16() throws IOException { short u16 = readShort(); return u16 & 0xffff; } private int readNextLength32() throws IOException { int u32 = readInt(); if (u32 < 0) { throw overflowU32Size(u32); } return u32; } @Override public void close() throws IOException { buffer = EMPTY_BUFFER; position = 0; in.close(); } private static MessageIntegerOverflowException overflowU8(byte u8) { BigInteger bi = BigInteger.valueOf((long) (u8 & 0xff)); return new MessageIntegerOverflowException(bi); } private static MessageIntegerOverflowException overflowU16(short u16) { BigInteger bi = BigInteger.valueOf((long) (u16 & 0xffff)); return new MessageIntegerOverflowException(bi); } private static MessageIntegerOverflowException overflowU32(int u32) { BigInteger bi = BigInteger.valueOf((long) (u32 & 0x7fffffff) + 0x80000000L); return new MessageIntegerOverflowException(bi); } private static MessageIntegerOverflowException overflowU64(long u64) { BigInteger bi = BigInteger.valueOf(u64 + Long.MAX_VALUE + 1L).setBit(63); return new MessageIntegerOverflowException(bi); } private static MessageIntegerOverflowException overflowI16(short i16) { BigInteger bi = BigInteger.valueOf((long) i16); return new MessageIntegerOverflowException(bi); } private static MessageIntegerOverflowException overflowI32(int i32) { BigInteger bi = BigInteger.valueOf((long) i32); return new MessageIntegerOverflowException(bi); } private static MessageIntegerOverflowException overflowI64(long i64) { BigInteger bi = BigInteger.valueOf(i64); return new MessageIntegerOverflowException(bi); } private static MessageSizeException overflowU32Size(int u32) { long lv = (long) (u32 & 0x7fffffff) + 0x80000000L; return new MessageSizeException(lv); } }
0xC1 NEVER_USED always throws MessageNeverUsedFormatException regardless of context rather than MessageTypeException or MessageFormatException depending on context
msgpack-core/src/main/java/org/msgpack/core/MessageUnpacker.java
0xC1 NEVER_USED always throws MessageNeverUsedFormatException regardless of context rather than MessageTypeException or MessageFormatException depending on context
<ide><path>sgpack-core/src/main/java/org/msgpack/core/MessageUnpacker.java <ide> remainingValues += readNextLength32() * 2; // TODO check int overflow <ide> break; <ide> case NEVER_USED: <del> throw new MessageFormatException(String.format("unknown code: %02x is found", b)); <add> throw new MessageNeverUsedFormatException("Encountered 0xC1 \"NEVER_USED\" byte"); <ide> } <ide> <ide> remainingValues--; <ide> * @return <ide> * @throws MessageFormatException <ide> */ <del> private static MessageTypeException unexpected(String expected, byte b) <del> throws MessageTypeException <add> private static MessagePackException unexpected(String expected, byte b) <ide> { <ide> MessageFormat format = MessageFormat.valueOf(b); <del> String typeName; <ide> if (format == MessageFormat.NEVER_USED) { <del> typeName = "NeverUsed"; <add> return new MessageNeverUsedFormatException(String.format("Expected %s, but encountered 0xC1 \"NEVER_USED\" byte", expected)); <ide> } <ide> else { <ide> String name = format.getValueType().name(); <del> typeName = name.substring(0, 1) + name.substring(1).toLowerCase(); <del> } <del> return new MessageTypeException(String.format("Expected %s, but got %s (%02x)", expected, typeName, b)); <add> String typeName = name.substring(0, 1) + name.substring(1).toLowerCase(); <add> return new MessageTypeException(String.format("Expected %s, but got %s (%02x)", expected, typeName, b)); <add> } <ide> } <ide> <ide> public ImmutableValue unpackValue() <ide> return ValueFactory.newExtension(extHeader.getType(), readPayload(extHeader.getLength())); <ide> } <ide> default: <del> throw new MessageFormatException("Unknown value type"); <add> throw new MessageNeverUsedFormatException("Unknown value type"); <ide> } <ide> } <ide>
Java
apache-2.0
87f43c63c35507d52debfe0e142b30bb988dde35
0
OpenNTF/XPagesToolkit,OpenNTF/XPagesToolkit,OpenNTF/XPagesToolkit
/** * Copyright 2013, WebGate Consulting AG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.openntf.xpt.core.dss.binding.embedded; import java.lang.reflect.Method; import java.util.Vector; import lotus.domino.Document; import org.openntf.xpt.core.dss.DSSException; import org.openntf.xpt.core.dss.binding.Definition; import org.openntf.xpt.core.dss.binding.Domino2JavaBinder; import org.openntf.xpt.core.dss.binding.IBinder; import org.openntf.xpt.core.dss.binding.Java2DominoBinder; import org.openntf.xpt.core.utils.logging.LoggerFactory; import com.ibm.commons.util.StringUtil; public class EmbeddedObjectBinder implements IBinder<Object> { private static final EmbeddedObjectBinder m_Binder = new EmbeddedObjectBinder(); private EmbeddedObjectBinder() { } public static EmbeddedObjectBinder getInstance() { return m_Binder; } @Override public void processDomino2Java(Document docCurrent, Object objCurrent, Vector<?> vecValues, Definition def) { try { String strClassStore = docCurrent.getItemValueString(def.getNotesField()); if (StringUtil.isEmpty(strClassStore)) { LoggerFactory.logWarning(getClass(), "No Class Defined. Using Class: " + def.getInnerClass().getCanonicalName(), null); } else { if (!strClassStore.equals(def.getInnerClass().getCanonicalName())) { LoggerFactory.logWarning(getClass(), strClassStore + " expected. Effective Class: " + def.getInnerClass().getCanonicalName(), null); } } Method mt = objCurrent.getClass().getMethod("set" + def.getJavaField(), (Class<?>) def.getInnerClass()); mt.invoke(objCurrent, getValueFromStore(docCurrent, null, def)); } catch (Exception ex) { ex.printStackTrace(); } } @Override public Object[] processJava2Domino(Document docCurrent, Object objCurrent, Definition def) { Object[] objRC = new Object[2]; try { objRC[0] = getValueFromStore(docCurrent, null, def); objRC[1] = getValue(objCurrent, def.getJavaField()); Java2DominoBinder j2d = def.getContainer().getSaver(def.getInnerClass()); if (objRC[1] == null) { j2d.cleanFields(docCurrent); docCurrent.removeItem(def.getNotesField()); } else { j2d.processDocument(docCurrent, objRC[1], null); docCurrent.replaceItemValue(def.getNotesField(), objRC[1].getClass().getCanonicalName()); } } catch (Exception e) { e.printStackTrace(); } return objRC; } @Override public Object getValue(Object objCurrent, String strJavaField) { try { Method mt = objCurrent.getClass().getMethod("get" + strJavaField); return mt.invoke(objCurrent); } catch (Exception ex) { ex.printStackTrace(); } return null; } @Override public Object getValueFromStore(Document docCurrent, Vector<?> vecValues, Definition def) throws DSSException { Object objSet = null; try { objSet = def.getInnerClass().newInstance(); Domino2JavaBinder d2j = def.getContainer().getLoader(objSet.getClass()); d2j.processDocument(docCurrent, objSet); } catch (Exception e) { // TODO: Handling exception } return objSet; } }
org.openntf.xpt.core/src/org/openntf/xpt/core/dss/binding/embedded/EmbeddedObjectBinder.java
/** * Copyright 2013, WebGate Consulting AG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.openntf.xpt.core.dss.binding.embedded; import java.lang.reflect.Method; import java.util.Vector; import lotus.domino.Document; import org.openntf.xpt.core.dss.DSSException; import org.openntf.xpt.core.dss.binding.Definition; import org.openntf.xpt.core.dss.binding.Domino2JavaBinder; import org.openntf.xpt.core.dss.binding.IBinder; import org.openntf.xpt.core.dss.binding.Java2DominoBinder; import org.openntf.xpt.core.utils.logging.LoggerFactory; import com.ibm.commons.util.StringUtil; public class EmbeddedObjectBinder implements IBinder<Object> { private final static EmbeddedObjectBinder m_Binder = new EmbeddedObjectBinder(); public static EmbeddedObjectBinder getInstance() { return m_Binder; } private EmbeddedObjectBinder() { } @Override public void processDomino2Java(Document docCurrent, Object objCurrent, Vector<?> vecValues, Definition def) { try { String strClassStore = docCurrent.getItemValueString(def.getNotesField()); if (StringUtil.isEmpty(strClassStore)) { return; } if (!strClassStore.equals(def.getInnerClass().getCanonicalName())) { LoggerFactory.logWarning(getClass(), strClassStore + " expected. Effective Class: " + def.getInnerClass().getCanonicalName(), null); } Method mt = objCurrent.getClass().getMethod("set" + def.getJavaField(), (Class<?>) def.getInnerClass()); mt.invoke(objCurrent, getValueFromStore(docCurrent, null, def)); } catch (Exception ex) { } } @Override public Object[] processJava2Domino(Document docCurrent, Object objCurrent, Definition def) { Object[] objRC = new Object[2]; try { objRC[0] = getValueFromStore(docCurrent, null, def); objRC[1] = getValue(objCurrent, def.getJavaField()); Java2DominoBinder j2d = def.getContainer().getSaver(def.getInnerClass()); if (objRC[1] == null) { j2d.cleanFields(docCurrent); docCurrent.removeItem(def.getNotesField()); } else { j2d.processDocument(docCurrent, objRC[1], null); docCurrent.replaceItemValue(def.getNotesField(), objRC[1].getClass().getCanonicalName()); } } catch (Exception e) { e.printStackTrace(); } return objRC; } @Override public Object getValue(Object objCurrent, String strJavaField) { try { Method mt = objCurrent.getClass().getMethod("get" + strJavaField); return mt.invoke(objCurrent); } catch (Exception ex) { ex.printStackTrace(); } return null; } @Override public Object getValueFromStore(Document docCurrent, Vector<?> vecValues, Definition def) throws DSSException { Object objSet = null; try { objSet = def.getInnerClass().newInstance(); Domino2JavaBinder d2j = def.getContainer().getLoader(objSet.getClass()); d2j.processDocument(docCurrent, objSet); } catch (Exception e) { // TODO: Handling exception } return objSet; } }
Making Embedded Loading better
org.openntf.xpt.core/src/org/openntf/xpt/core/dss/binding/embedded/EmbeddedObjectBinder.java
Making Embedded Loading better
<ide><path>rg.openntf.xpt.core/src/org/openntf/xpt/core/dss/binding/embedded/EmbeddedObjectBinder.java <ide> <ide> public class EmbeddedObjectBinder implements IBinder<Object> { <ide> <del> private final static EmbeddedObjectBinder m_Binder = new EmbeddedObjectBinder(); <add> private static final EmbeddedObjectBinder m_Binder = new EmbeddedObjectBinder(); <add> <add> private EmbeddedObjectBinder() { <add> } <ide> <ide> public static EmbeddedObjectBinder getInstance() { <ide> return m_Binder; <del> } <del> <del> private EmbeddedObjectBinder() { <ide> } <ide> <ide> @Override <ide> try { <ide> String strClassStore = docCurrent.getItemValueString(def.getNotesField()); <ide> if (StringUtil.isEmpty(strClassStore)) { <del> return; <del> } <del> if (!strClassStore.equals(def.getInnerClass().getCanonicalName())) { <del> LoggerFactory.logWarning(getClass(), strClassStore + " expected. Effective Class: " + def.getInnerClass().getCanonicalName(), null); <add> LoggerFactory.logWarning(getClass(), "No Class Defined. Using Class: " + def.getInnerClass().getCanonicalName(), null); <add> } else { <add> if (!strClassStore.equals(def.getInnerClass().getCanonicalName())) { <add> LoggerFactory.logWarning(getClass(), strClassStore + " expected. Effective Class: " + def.getInnerClass().getCanonicalName(), null); <add> } <ide> } <ide> Method mt = objCurrent.getClass().getMethod("set" + def.getJavaField(), (Class<?>) def.getInnerClass()); <ide> mt.invoke(objCurrent, getValueFromStore(docCurrent, null, def)); <ide> } catch (Exception ex) { <del> <add> ex.printStackTrace(); <ide> } <ide> } <ide>
Java
apache-2.0
7d097ab7cad033c37a50092227d5e8317e022d51
0
palantir/eclipse-typescript,BlacKCaT27/eclipse-typescript,palantir/eclipse-typescript,lgrignon/eclipse-typescript,BlacKCaT27/eclipse-typescript,amergey/eclipse-typescript,lgrignon/eclipse-typescript,lgrignon/eclipse-typescript,amergey/eclipse-typescript,BlacKCaT27/eclipse-typescript,palantir/eclipse-typescript,BlacKCaT27/eclipse-typescript,lgrignon/eclipse-typescript,palantir/eclipse-typescript,amergey/eclipse-typescript,amergey/eclipse-typescript
/* * Copyright 2013 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.typescript; import java.io.File; import java.util.List; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; import org.osgi.framework.BundleContext; import com.google.common.base.Splitter; import com.google.common.base.StandardSystemProperty; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.palantir.typescript.services.classifier.Classifier; import com.palantir.typescript.services.language.FileDelta; import com.palantir.typescript.services.language.LanguageEndpoint; import com.palantir.typescript.services.language.LanguageVersion; import com.palantir.typescript.services.language.ModuleGenTarget; /** * The TypeScript plug-in for the Eclipse platform. * * @author tyleradams */ public final class TypeScriptPlugin extends AbstractUIPlugin { public static final String ID = "com.palantir.typescript"; private static final String OS_NAME = StandardSystemProperty.OS_NAME.value(); private static final Splitter PATH_SPLITTER = Splitter.on(File.pathSeparatorChar); private static TypeScriptPlugin PLUGIN; private LanguageEndpoint builderLanguageEndpoint; private Classifier classifier; private LanguageEndpoint editorLanguageEndpoint; private LanguageEndpoint reconcilerLanguageEndpoint; private MyResourceChangeListener resourceChangeListener; @Override public void start(BundleContext context) throws Exception { super.start(context); PLUGIN = this; this.resourceChangeListener = new MyResourceChangeListener(); ResourcesPlugin.getWorkspace().addResourceChangeListener(this.resourceChangeListener, IResourceChangeEvent.POST_CHANGE); } @Override public void stop(BundleContext context) throws Exception { ResourcesPlugin.getWorkspace().removeResourceChangeListener(this.resourceChangeListener); if (this.builderLanguageEndpoint != null) { this.builderLanguageEndpoint.dispose(); } if (this.classifier != null) { this.classifier.dispose(); } if (this.editorLanguageEndpoint != null) { this.editorLanguageEndpoint.dispose(); } if (this.reconcilerLanguageEndpoint != null) { this.reconcilerLanguageEndpoint.dispose(); } PLUGIN = null; super.stop(context); } /** * Returns the shared instance. */ public static TypeScriptPlugin getDefault() { return PLUGIN; } /** * Returns an image descriptor for the image file at the given plug-in relative path. */ public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(TypeScriptPlugin.ID, path); } public synchronized LanguageEndpoint getBuilderLanguageEndpoint() { if (this.builderLanguageEndpoint == null) { this.builderLanguageEndpoint = new LanguageEndpoint(); } return this.builderLanguageEndpoint; } public synchronized Classifier getClassifier() { if (this.classifier == null) { this.classifier = new Classifier(); } return this.classifier; } public synchronized LanguageEndpoint getEditorLanguageEndpoint() { if (this.editorLanguageEndpoint == null) { this.editorLanguageEndpoint = new LanguageEndpoint(); } return this.editorLanguageEndpoint; } public synchronized LanguageEndpoint getReconcilerLanguageEndpoint() { if (this.reconcilerLanguageEndpoint == null) { this.reconcilerLanguageEndpoint = new LanguageEndpoint(); } return this.reconcilerLanguageEndpoint; } @Override protected void initializeDefaultPluginPreferences() { IPreferenceStore store = TypeScriptPlugin.getDefault().getPreferenceStore(); store.setDefault(IPreferenceConstants.COMPILER_CODE_GEN_TARGET, LanguageVersion.ECMASCRIPT3.toString()); store.setDefault(IPreferenceConstants.COMPILER_COMPILE_ON_SAVE, false); store.setDefault(IPreferenceConstants.COMPILER_GENERATE_DECLARATION_FILES, false); store.setDefault(IPreferenceConstants.COMPILER_MAP_SOURCE_FILES, false); store.setDefault(IPreferenceConstants.COMPILER_MODULE_GEN_TARGET, ModuleGenTarget.UNSPECIFIED.toString()); store.setDefault(IPreferenceConstants.COMPILER_NO_IMPLICIT_ANY, false); store.setDefault(IPreferenceConstants.COMPILER_NO_LIB, false); store.setDefault(IPreferenceConstants.COMPILER_REMOVE_COMMENTS, false); store.setDefault(IPreferenceConstants.CONTENT_ASSIST_AUTO_ACTIVATION_DELAY, 200); store.setDefault(IPreferenceConstants.CONTENT_ASSIST_AUTO_ACTIVATION_ENABLED, true); store.setDefault(IPreferenceConstants.CONTENT_ASSIST_AUTO_ACTIVATION_TRIGGERS, "."); store.setDefault(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SPACES_FOR_TABS, true); store.setDefault(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH, 4); store.setDefault(IPreferenceConstants.EDITOR_CLOSE_BRACES, false); store.setDefault(IPreferenceConstants.EDITOR_CLOSE_JSDOCS, true); store.setDefault(IPreferenceConstants.EDITOR_INDENT_SIZE, 4); store.setDefault(IPreferenceConstants.EDITOR_MATCHING_BRACKETS, true); store.setDefault(IPreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, "128,128,128"); store.setDefault(IPreferenceConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_DELIMITER, true); store.setDefault(IPreferenceConstants.FORMATTER_INSERT_SPACE_AFTER_FUNCTION_KEYWORD_FOR_ANONYMOUS_FUNCTIONS, false); store.setDefault(IPreferenceConstants.FORMATTER_INSERT_SPACE_AFTER_KEYWORDS_IN_CONTROL_FLOW_STATEMENTS, true); store.setDefault(IPreferenceConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_AND_BEFORE_CLOSING_NONEMPTY_PARENTHESIS, false); store.setDefault(IPreferenceConstants.FORMATTER_INSERT_SPACE_AFTER_SEMICOLON_IN_FOR_STATEMENTS, true); store.setDefault(IPreferenceConstants.FORMATTER_INSERT_SPACE_BEFORE_AND_AFTER_BINARY_OPERATORS, true); store.setDefault(IPreferenceConstants.FORMATTER_PLACE_OPEN_BRACE_ON_NEW_LINE_FOR_CONTROL_BLOCKS, false); store.setDefault(IPreferenceConstants.FORMATTER_PLACE_OPEN_BRACE_ON_NEW_LINE_FOR_FUNCTIONS, false); store.setDefault(IPreferenceConstants.GENERAL_NODE_PATH, findNodejs()); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_COMMENT_COLOR, "63,127,95"); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_IDENTIFIER_COLOR, "0,0,0"); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_KEYWORD_COLOR, "127,0,85"); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_NUMBER_LITERAL_COLOR, "0,0,0"); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_OPERATOR_COLOR, "0,0,0"); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_PUNCTUATION_COLOR, "0,0,0"); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_REG_EXP_LITERAL_COLOR, "219,0,0"); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_STRING_LITERAL_COLOR, "42,0,255"); } private static String findNodejs() { String nodeFileName = getNodeFileName(); String path = System.getenv("PATH"); List<String> directories = Lists.newArrayList(PATH_SPLITTER.split(path)); // ensure /usr/local/bin is included for OS X if (OS_NAME.startsWith("Mac OS X")) { directories.add("/usr/local/bin"); } // search for Node.js in the PATH directories for (String directory : directories) { File nodeFile = new File(directory, nodeFileName); if (nodeFile.exists()) { return nodeFile.getAbsolutePath(); } } return ""; } private static String getNodeFileName() { if (OS_NAME.startsWith("Windows")) { return "node.exe"; } return "node"; } private final class MyResourceChangeListener implements IResourceChangeListener { @Override public void resourceChanged(IResourceChangeEvent event) { IResourceDelta delta = event.getDelta(); final ImmutableList<FileDelta> fileDeltas = EclipseResources.getTypeScriptFileDeltas(delta); if (TypeScriptPlugin.this.editorLanguageEndpoint != null) { TypeScriptPlugin.this.editorLanguageEndpoint.updateFiles(fileDeltas); } if (TypeScriptPlugin.this.reconcilerLanguageEndpoint != null) { TypeScriptPlugin.this.reconcilerLanguageEndpoint.updateFiles(fileDeltas); } } } }
com.palantir.typescript/src/com/palantir/typescript/TypeScriptPlugin.java
/* * Copyright 2013 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.typescript; import java.io.File; import java.util.List; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; import org.osgi.framework.BundleContext; import com.google.common.base.Splitter; import com.google.common.base.StandardSystemProperty; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.palantir.typescript.services.classifier.Classifier; import com.palantir.typescript.services.language.FileDelta; import com.palantir.typescript.services.language.LanguageEndpoint; import com.palantir.typescript.services.language.LanguageVersion; import com.palantir.typescript.services.language.ModuleGenTarget; /** * The TypeScript plug-in for the Eclipse platform. * * @author tyleradams */ public final class TypeScriptPlugin extends AbstractUIPlugin { public static final String ID = "com.palantir.typescript"; private static final String OS_NAME = StandardSystemProperty.OS_NAME.value(); private static final Splitter PATH_SPLITTER = Splitter.on(File.pathSeparatorChar); private static TypeScriptPlugin PLUGIN; private LanguageEndpoint builderLanguageEndpoint; private Classifier classifier; private LanguageEndpoint editorLanguageEndpoint; private LanguageEndpoint reconcilerLanguageEndpoint; private MyResourceChangeListener resourceChangeListener; @Override public void start(BundleContext context) throws Exception { super.start(context); PLUGIN = this; this.builderLanguageEndpoint = new LanguageEndpoint(); this.classifier = new Classifier(); this.editorLanguageEndpoint = new LanguageEndpoint(); this.reconcilerLanguageEndpoint = new LanguageEndpoint(); this.resourceChangeListener = new MyResourceChangeListener(); ResourcesPlugin.getWorkspace().addResourceChangeListener(this.resourceChangeListener, IResourceChangeEvent.POST_CHANGE); } @Override public void stop(BundleContext context) throws Exception { ResourcesPlugin.getWorkspace().removeResourceChangeListener(this.resourceChangeListener); this.builderLanguageEndpoint.dispose(); this.classifier.dispose(); this.editorLanguageEndpoint.dispose(); this.reconcilerLanguageEndpoint.dispose(); PLUGIN = null; super.stop(context); } /** * Returns the shared instance. */ public static TypeScriptPlugin getDefault() { return PLUGIN; } /** * Returns an image descriptor for the image file at the given plug-in relative path. */ public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(TypeScriptPlugin.ID, path); } public LanguageEndpoint getBuilderLanguageEndpoint() { return this.builderLanguageEndpoint; } public Classifier getClassifier() { return this.classifier; } public LanguageEndpoint getEditorLanguageEndpoint() { return this.editorLanguageEndpoint; } public LanguageEndpoint getReconcilerLanguageEndpoint() { return this.reconcilerLanguageEndpoint; } @Override protected void initializeDefaultPluginPreferences() { IPreferenceStore store = TypeScriptPlugin.getDefault().getPreferenceStore(); store.setDefault(IPreferenceConstants.COMPILER_CODE_GEN_TARGET, LanguageVersion.ECMASCRIPT3.toString()); store.setDefault(IPreferenceConstants.COMPILER_COMPILE_ON_SAVE, false); store.setDefault(IPreferenceConstants.COMPILER_GENERATE_DECLARATION_FILES, false); store.setDefault(IPreferenceConstants.COMPILER_MAP_SOURCE_FILES, false); store.setDefault(IPreferenceConstants.COMPILER_MODULE_GEN_TARGET, ModuleGenTarget.UNSPECIFIED.toString()); store.setDefault(IPreferenceConstants.COMPILER_NO_IMPLICIT_ANY, false); store.setDefault(IPreferenceConstants.COMPILER_NO_LIB, false); store.setDefault(IPreferenceConstants.COMPILER_REMOVE_COMMENTS, false); store.setDefault(IPreferenceConstants.CONTENT_ASSIST_AUTO_ACTIVATION_DELAY, 200); store.setDefault(IPreferenceConstants.CONTENT_ASSIST_AUTO_ACTIVATION_ENABLED, true); store.setDefault(IPreferenceConstants.CONTENT_ASSIST_AUTO_ACTIVATION_TRIGGERS, "."); store.setDefault(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SPACES_FOR_TABS, true); store.setDefault(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH, 4); store.setDefault(IPreferenceConstants.EDITOR_CLOSE_BRACES, false); store.setDefault(IPreferenceConstants.EDITOR_CLOSE_JSDOCS, true); store.setDefault(IPreferenceConstants.EDITOR_INDENT_SIZE, 4); store.setDefault(IPreferenceConstants.EDITOR_MATCHING_BRACKETS, true); store.setDefault(IPreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, "128,128,128"); store.setDefault(IPreferenceConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_DELIMITER, true); store.setDefault(IPreferenceConstants.FORMATTER_INSERT_SPACE_AFTER_FUNCTION_KEYWORD_FOR_ANONYMOUS_FUNCTIONS, false); store.setDefault(IPreferenceConstants.FORMATTER_INSERT_SPACE_AFTER_KEYWORDS_IN_CONTROL_FLOW_STATEMENTS, true); store.setDefault(IPreferenceConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_AND_BEFORE_CLOSING_NONEMPTY_PARENTHESIS, false); store.setDefault(IPreferenceConstants.FORMATTER_INSERT_SPACE_AFTER_SEMICOLON_IN_FOR_STATEMENTS, true); store.setDefault(IPreferenceConstants.FORMATTER_INSERT_SPACE_BEFORE_AND_AFTER_BINARY_OPERATORS, true); store.setDefault(IPreferenceConstants.FORMATTER_PLACE_OPEN_BRACE_ON_NEW_LINE_FOR_CONTROL_BLOCKS, false); store.setDefault(IPreferenceConstants.FORMATTER_PLACE_OPEN_BRACE_ON_NEW_LINE_FOR_FUNCTIONS, false); store.setDefault(IPreferenceConstants.GENERAL_NODE_PATH, findNodejs()); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_COMMENT_COLOR, "63,127,95"); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_IDENTIFIER_COLOR, "0,0,0"); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_KEYWORD_COLOR, "127,0,85"); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_NUMBER_LITERAL_COLOR, "0,0,0"); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_OPERATOR_COLOR, "0,0,0"); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_PUNCTUATION_COLOR, "0,0,0"); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_REG_EXP_LITERAL_COLOR, "219,0,0"); store.setDefault(IPreferenceConstants.SYNTAX_COLORING_STRING_LITERAL_COLOR, "42,0,255"); } private static String findNodejs() { String nodeFileName = getNodeFileName(); String path = System.getenv("PATH"); List<String> directories = Lists.newArrayList(PATH_SPLITTER.split(path)); // ensure /usr/local/bin is included for OS X if (OS_NAME.startsWith("Mac OS X")) { directories.add("/usr/local/bin"); } // search for Node.js in the PATH directories for (String directory : directories) { File nodeFile = new File(directory, nodeFileName); if (nodeFile.exists()) { return nodeFile.getAbsolutePath(); } } return ""; } private static String getNodeFileName() { if (OS_NAME.startsWith("Windows")) { return "node.exe"; } return "node"; } private final class MyResourceChangeListener implements IResourceChangeListener { @Override public void resourceChanged(IResourceChangeEvent event) { IResourceDelta delta = event.getDelta(); final ImmutableList<FileDelta> fileDeltas = EclipseResources.getTypeScriptFileDeltas(delta); TypeScriptPlugin.this.editorLanguageEndpoint.updateFiles(fileDeltas); TypeScriptPlugin.this.reconcilerLanguageEndpoint.updateFiles(fileDeltas); } } }
Fixes #154 Lazily start NodeJS processes * besides being more efficient, this allows access to the workspace properties when the NodeJS path is incorrect
com.palantir.typescript/src/com/palantir/typescript/TypeScriptPlugin.java
Fixes #154 Lazily start NodeJS processes
<ide><path>om.palantir.typescript/src/com/palantir/typescript/TypeScriptPlugin.java <ide> <ide> PLUGIN = this; <ide> <del> this.builderLanguageEndpoint = new LanguageEndpoint(); <del> this.classifier = new Classifier(); <del> this.editorLanguageEndpoint = new LanguageEndpoint(); <del> this.reconcilerLanguageEndpoint = new LanguageEndpoint(); <ide> this.resourceChangeListener = new MyResourceChangeListener(); <ide> <ide> ResourcesPlugin.getWorkspace().addResourceChangeListener(this.resourceChangeListener, IResourceChangeEvent.POST_CHANGE); <ide> public void stop(BundleContext context) throws Exception { <ide> ResourcesPlugin.getWorkspace().removeResourceChangeListener(this.resourceChangeListener); <ide> <del> this.builderLanguageEndpoint.dispose(); <del> this.classifier.dispose(); <del> this.editorLanguageEndpoint.dispose(); <del> this.reconcilerLanguageEndpoint.dispose(); <add> if (this.builderLanguageEndpoint != null) { <add> this.builderLanguageEndpoint.dispose(); <add> } <add> <add> if (this.classifier != null) { <add> this.classifier.dispose(); <add> } <add> <add> if (this.editorLanguageEndpoint != null) { <add> this.editorLanguageEndpoint.dispose(); <add> } <add> <add> if (this.reconcilerLanguageEndpoint != null) { <add> this.reconcilerLanguageEndpoint.dispose(); <add> } <ide> <ide> PLUGIN = null; <ide> <ide> return imageDescriptorFromPlugin(TypeScriptPlugin.ID, path); <ide> } <ide> <del> public LanguageEndpoint getBuilderLanguageEndpoint() { <add> public synchronized LanguageEndpoint getBuilderLanguageEndpoint() { <add> if (this.builderLanguageEndpoint == null) { <add> this.builderLanguageEndpoint = new LanguageEndpoint(); <add> } <add> <ide> return this.builderLanguageEndpoint; <ide> } <ide> <del> public Classifier getClassifier() { <add> public synchronized Classifier getClassifier() { <add> if (this.classifier == null) { <add> this.classifier = new Classifier(); <add> } <add> <ide> return this.classifier; <ide> } <ide> <del> public LanguageEndpoint getEditorLanguageEndpoint() { <add> public synchronized LanguageEndpoint getEditorLanguageEndpoint() { <add> if (this.editorLanguageEndpoint == null) { <add> this.editorLanguageEndpoint = new LanguageEndpoint(); <add> } <add> <ide> return this.editorLanguageEndpoint; <ide> } <ide> <del> public LanguageEndpoint getReconcilerLanguageEndpoint() { <add> public synchronized LanguageEndpoint getReconcilerLanguageEndpoint() { <add> if (this.reconcilerLanguageEndpoint == null) { <add> this.reconcilerLanguageEndpoint = new LanguageEndpoint(); <add> } <add> <ide> return this.reconcilerLanguageEndpoint; <ide> } <ide> <ide> IResourceDelta delta = event.getDelta(); <ide> final ImmutableList<FileDelta> fileDeltas = EclipseResources.getTypeScriptFileDeltas(delta); <ide> <del> TypeScriptPlugin.this.editorLanguageEndpoint.updateFiles(fileDeltas); <del> TypeScriptPlugin.this.reconcilerLanguageEndpoint.updateFiles(fileDeltas); <add> if (TypeScriptPlugin.this.editorLanguageEndpoint != null) { <add> TypeScriptPlugin.this.editorLanguageEndpoint.updateFiles(fileDeltas); <add> } <add> <add> if (TypeScriptPlugin.this.reconcilerLanguageEndpoint != null) { <add> TypeScriptPlugin.this.reconcilerLanguageEndpoint.updateFiles(fileDeltas); <add> } <ide> } <ide> } <ide> }
JavaScript
lgpl-2.1
36320e55b18e1170fa5ff50b6333971ca0078524
0
tikiorg/tiki,changi67/tiki,tikiorg/tiki,tikiorg/tiki,oregional/tiki,oregional/tiki,tikiorg/tiki,oregional/tiki,changi67/tiki,oregional/tiki,changi67/tiki,changi67/tiki,changi67/tiki
(function ($) { /** * One executor is created for each object containing inline fields. * When the field is modified, the executor is triggered. * * As a delayed executor, a period of grace is given for the field to * be corrected or other fields to be modified. Each modification resets * the counter. * * When modifications stop happening, the entire object is stored in a * single AJAX request. */ var executors = {}, obtainExecutor; obtainExecutor = function (container) { var url = $(container).data('object-store-url'); if (executors[url]) { return executors[url]; } return executors[url] = delayedExecutor(5000, function () { var parts = []; var containers = []; $('.editable-inline :input').each(function () { var container = $(this).closest('.editable-inline')[0]; var ownership = $(container).data('object-store-url'); if (ownership === url) { containers.push(container); parts.push($(this).serialize()); } }); $.post(url, parts.join('&'), 'json') .success(function () { $(containers). removeClass('modified'). removeClass('unsaved'). each( function () { var $input = $("input:first, select:first option:selected", this), newVal; if ($input.length) { var html = $(this).data("saved_html"); var oldVal = $(this).data("saved_text"); if ($input.is("input[type=checkbox]")) { if ($input.prop("checked")) { newVal = tr("Yes"); } else { newVal = tr("No"); } } else if ($input.is("option")) { newVal = $input.text(); } else { newVal = $input.val(); } var newHtml = html.replace(new RegExp(oldVal.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")), $.trim(newVal)); $(this).removeClass("loaded").html(newHtml); } }); }) .error(function () { $(containers).filter('.modified').addClass('unsaved'); $.getJSON($.service('object', 'report_error')); }) ; }); }; $(document).on('click', '.editable-inline:not(.loaded)', function () { var container = this , url = $(this).data('field-fetch-url') ; $(container). addClass('loaded'). data("saved_html", $(container).html()). data("saved_text", $(container).text()); if (url) { $.get(url) .success(function (data) { $(container).html(data); }) .error(function () { $(container).addClass('failure'); }) ; } }); $(document).on('change', '.editable-inline.loaded :input', function () { var container, executor; container = $(this).closest('.editable-inline')[0]; executor = obtainExecutor(container); $(container).addClass('modified'); executor(); }); })(jQuery);
lib/jquery_tiki/inline_edit.js
(function ($) { /** * One executor is created for each object containing inline fields. * When the field is modified, the executor is triggered. * * As a delayed executor, a period of grace is given for the field to * be corrected or other fields to be modified. Each modification resets * the counter. * * When modifications stop happening, the entire object is stored in a * single AJAX request. */ var executors = {}, obtainExecutor; obtainExecutor = function (container) { var url = $(container).data('object-store-url'); if (executors[url]) { return executors[url]; } return executors[url] = delayedExecutor(5000, function () { var parts = []; var containers = []; $('.editable-inline :input').each(function () { var container = $(this).closest('.editable-inline')[0]; var ownership = $(container).data('object-store-url'); if (ownership === url) { containers.push(container); parts.push($(this).serialize()); } }); $.post(url, parts.join('&'), 'json') .success(function () { $(containers).removeClass('modified').removeClass('unsaved'); }) .error(function () { $(containers).filter('.modified').addClass('unsaved'); $.getJSON($.service('object', 'report_error')); }) ; }); }; $(document).on('click', '.editable-inline:not(.loaded)', function () { var container = this , url = $(this).data('field-fetch-url') ; $(container).addClass('loaded'); if (url) { $.get(url) .success(function (data) { $(container).html(data); }) .error(function () { $(container).addClass('failure'); }) ; } }); $(document).on('change', '.editable-inline.loaded :input', function () { var container, executor; container = $(this).closest('.editable-inline')[0]; executor = obtainExecutor(container); $(container).addClass('modified'); executor(); }); })(jQuery);
[FIX] inline edit: Show the rendered output of the field after it's been saved git-svn-id: bf8acf6ea2e0c2f171d9237652733ab0075b5b4c@45973 b456876b-0849-0410-b77d-98878d47e9d5
lib/jquery_tiki/inline_edit.js
[FIX] inline edit: Show the rendered output of the field after it's been saved
<ide><path>ib/jquery_tiki/inline_edit.js <ide> <ide> $.post(url, parts.join('&'), 'json') <ide> .success(function () { <del> $(containers).removeClass('modified').removeClass('unsaved'); <add> $(containers). <add> removeClass('modified'). <add> removeClass('unsaved'). <add> each( function () { <add> var $input = $("input:first, select:first option:selected", this), newVal; <add> if ($input.length) { <add> var html = $(this).data("saved_html"); <add> var oldVal = $(this).data("saved_text"); <add> if ($input.is("input[type=checkbox]")) { <add> if ($input.prop("checked")) { <add> newVal = tr("Yes"); <add> } else { <add> newVal = tr("No"); <add> } <add> } else if ($input.is("option")) { <add> newVal = $input.text(); <add> } else { <add> newVal = $input.val(); <add> } <add> var newHtml = html.replace(new RegExp(oldVal.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")), $.trim(newVal)); <add> $(this).removeClass("loaded").html(newHtml); <add> } <add> }); <ide> }) <ide> .error(function () { <ide> $(containers).filter('.modified').addClass('unsaved'); <ide> , url = $(this).data('field-fetch-url') <ide> ; <ide> <del> $(container).addClass('loaded'); <add> $(container). <add> addClass('loaded'). <add> data("saved_html", $(container).html()). <add> data("saved_text", $(container).text()); <ide> <ide> if (url) { <ide> $.get(url)
Java
apache-2.0
5a6792e70242851e77fc3d3c6e75b625b7afc0e0
0
researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds
package won.protocol.util; import org.apache.jena.datatypes.xsd.XSDDatatype; import org.apache.jena.query.*; import org.apache.jena.rdf.model.*; import org.apache.jena.rdf.model.impl.PropertyImpl; import org.apache.jena.rdf.model.impl.ResourceImpl; import org.apache.jena.riot.Lang; import org.apache.jena.sparql.path.Path; import org.apache.jena.sparql.path.PathParser; import org.apache.jena.tdb.TDB; import org.apache.jena.vocabulary.RDF; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import won.protocol.exception.IncorrectPropertyCountException; import won.protocol.message.WonMessage; import won.protocol.message.WonSignatureData; import won.protocol.model.ConnectionState; import won.protocol.model.Match; import won.protocol.service.WonNodeInfo; import won.protocol.service.WonNodeInfoBuilder; import won.protocol.vocabulary.SFSIG; import won.protocol.vocabulary.WON; import won.protocol.vocabulary.WONMSG; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import static won.protocol.util.RdfUtils.findOnePropertyFromResource; import static won.protocol.util.RdfUtils.findOrCreateBaseResource; /** * Utilities for populating/manipulating the RDF models used throughout the WON application. */ public class WonRdfUtils { public static final String NAMED_GRAPH_SUFFIX = "#data"; private static final Logger logger = LoggerFactory.getLogger(WonRdfUtils.class); public static class SignatureUtils { public static boolean isSignatureGraph(String graphUri, Model model) { // TODO check the presence of all the required triples Resource resource = model.getResource(graphUri); StmtIterator si = model.listStatements(resource, RDF.type, SFSIG.SIGNATURE); if (si.hasNext()) { return true; } return false; } public static boolean isSignature(Model model, String modelName) { // TODO check the presence of all the required triples return model.contains(model.getResource(modelName), RDF.type, SFSIG.SIGNATURE); } public static String getSignedGraphUri(String signatureGraphUri, Model signatureGraph) { String signedGraphUri = null; Resource resource = signatureGraph.getResource(signatureGraphUri); NodeIterator ni = signatureGraph.listObjectsOfProperty(resource, WONMSG.HAS_SIGNED_GRAPH_PROPERTY); if (ni.hasNext()) { signedGraphUri = ni.next().asResource().getURI(); } return signedGraphUri; } public static String getSignatureValue(String signatureGraphUri, Model signatureGraph) { String signatureValue = null; Resource resource = signatureGraph.getResource(signatureGraphUri); NodeIterator ni2 = signatureGraph.listObjectsOfProperty(resource, SFSIG.HAS_SIGNATURE_VALUE); if (ni2.hasNext()) { signatureValue = ni2.next().asLiteral().toString(); } return signatureValue; } public static WonSignatureData extractWonSignatureData(final String uri, final Model model) { return extractWonSignatureData(model.getResource(uri)); } public static WonSignatureData extractWonSignatureData(final Resource resource) { Statement stmt = resource.getRequiredProperty(WONMSG.HAS_SIGNED_GRAPH_PROPERTY); String signedGraphUri = stmt.getObject().asResource().getURI(); stmt = resource.getRequiredProperty(SFSIG.HAS_SIGNATURE_VALUE); String signatureValue = stmt.getObject().asLiteral().getString(); stmt = resource.getRequiredProperty(WONMSG.HAS_HASH_PROPERTY); String hash = stmt.getObject().asLiteral().getString(); stmt = resource.getRequiredProperty(WONMSG.HAS_PUBLIC_KEY_FINGERPRINT_PROPERTY); String fingerprint = stmt.getObject().asLiteral().getString(); stmt = resource.getRequiredProperty(SFSIG.HAS_VERIFICATION_CERT); String cert = stmt.getObject().asResource().getURI(); return new WonSignatureData(signedGraphUri, resource.getURI(), signatureValue, hash, fingerprint, cert); } /** * Adds the triples holding the signature data to the model of the specified resource, using the resource as the * subject. * @param subject * @param wonSignatureData */ public static void addSignature(Resource subject, WonSignatureData wonSignatureData){ assert wonSignatureData.getHash() != null; assert wonSignatureData.getSignatureValue() != null; assert wonSignatureData.getPublicKeyFingerprint() != null; assert wonSignatureData.getSignedGraphUri() != null; assert wonSignatureData.getVerificationCertificateUri() != null; Model containingGraph = subject.getModel(); subject.addProperty(RDF.type, SFSIG.SIGNATURE); subject.addProperty(WONMSG.HAS_HASH_PROPERTY, wonSignatureData.getHash()); subject.addProperty(SFSIG.HAS_SIGNATURE_VALUE, wonSignatureData.getSignatureValue()); subject.addProperty(WONMSG.HAS_SIGNED_GRAPH_PROPERTY, containingGraph.createResource(wonSignatureData.getSignedGraphUri())); subject.addProperty(WONMSG.HAS_PUBLIC_KEY_FINGERPRINT_PROPERTY, wonSignatureData.getPublicKeyFingerprint()); subject.addProperty(SFSIG.HAS_VERIFICATION_CERT, containingGraph.createResource(wonSignatureData .getVerificationCertificateUri())); } } public static class WonNodeUtils { /** * Creates a WonNodeInfo object based on the specified dataset. The first model * found in the dataset that seems to contain the data needed for a WonNodeInfo * object is used. * @param wonNodeUri * @param dataset * @return */ public static WonNodeInfo getWonNodeInfo(final URI wonNodeUri, Dataset dataset){ assert wonNodeUri != null: "wonNodeUri must not be null"; assert dataset != null: "dataset must not be null"; return RdfUtils.findFirst(dataset, new RdfUtils.ModelVisitor<WonNodeInfo>() { @Override public WonNodeInfo visit(final Model model) { //use the first blank node found for [wonNodeUri] won:hasUriPatternSpecification [blanknode] NodeIterator it = model.listObjectsOfProperty(model.getResource(wonNodeUri.toString()), WON.HAS_URI_PATTERN_SPECIFICATION); if (!it.hasNext()) return null; WonNodeInfoBuilder wonNodeInfoBuilder = new WonNodeInfoBuilder(); wonNodeInfoBuilder.setWonNodeURI(wonNodeUri.toString()); RDFNode node = it.next(); // set the URI prefixes it = model.listObjectsOfProperty(node.asResource(), WON.HAS_NEED_URI_PREFIX); if (! it.hasNext() ) return null; String needUriPrefix = it.next().asLiteral().getString(); wonNodeInfoBuilder.setNeedURIPrefix(needUriPrefix); it = model.listObjectsOfProperty(node.asResource(), WON.HAS_CONNECTION_URI_PREFIX); if (! it.hasNext() ) return null; wonNodeInfoBuilder.setConnectionURIPrefix(it.next().asLiteral().getString()); it = model.listObjectsOfProperty(node.asResource(), WON.HAS_EVENT_URI_PREFIX); if (! it.hasNext() ) return null; wonNodeInfoBuilder.setEventURIPrefix(it.next().asLiteral().getString()); // set the need list URI it = model.listObjectsOfProperty(model.getResource(wonNodeUri.toString()), WON.HAS_NEED_LIST); if (it.hasNext() ) { wonNodeInfoBuilder.setNeedListURI(it.next().asNode().getURI()); } else { wonNodeInfoBuilder.setNeedListURI(needUriPrefix); } // set the supported protocol implementations String queryString = "SELECT ?protocol ?param ?value WHERE { ?a <%s> ?c. " + "?c <%s> ?protocol. ?c ?param ?value. FILTER ( ?value != ?protocol ) }"; queryString = String.format(queryString, WON.SUPPORTS_WON_PROTOCOL_IMPL.toString(), RDF.getURI() + "type"); Query protocolQuery = QueryFactory.create(queryString); QueryExecution qexec = QueryExecutionFactory.create(protocolQuery, model); ResultSet rs = qexec.execSelect(); while (rs.hasNext()) { QuerySolution qs = rs.nextSolution(); String protocol = rdfNodeToString(qs.get("protocol")); String param = rdfNodeToString(qs.get("param")); String value = rdfNodeToString(qs.get("value")); wonNodeInfoBuilder.addSupportedProtocolImplParamValue(protocol, param, value); } return wonNodeInfoBuilder.build(); } }); } private static String rdfNodeToString(RDFNode node) { if (node.isLiteral()) { return node.asLiteral().getString(); } else if (node.isResource()) { return node.asResource().getURI(); } return null; } } public static class MessageUtils { /** * Adds the specified text as a won:hasTextMessage to the model's base resource. * @param message * @return */ public static Model addMessage(Model model, String message) { Resource baseRes = RdfUtils.findOrCreateBaseResource(model); baseRes.addProperty(WON.HAS_TEXT_MESSAGE, message, XSDDatatype.XSDstring); return model; } /** * Creates an RDF model containing a text message. * @param message * @return */ public static Model textMessage(String message) { Model messageModel = createModelWithBaseResource(); Resource baseRes = messageModel.createResource(messageModel.getNsPrefixURI("")); baseRes.addProperty(WON.HAS_TEXT_MESSAGE,message, XSDDatatype.XSDstring); return messageModel; } /** * Creates an RDF model containing a generic message. * * @return */ public static Model genericMessage(URI predicate, URI object) { return genericMessage(new PropertyImpl(predicate.toString()), new ResourceImpl(object.toString())); } /** * Creates an RDF model containing a generic message. * * @return */ public static Model genericMessage(Property predicate, Resource object) { Model messageModel = createModelWithBaseResource(); Resource baseRes = RdfUtils.getBaseResource(messageModel); baseRes.addProperty(RDF.type, WONMSG.TYPE_CONNECTION_MESSAGE); baseRes.addProperty(predicate, object); return messageModel; } /** * Creates an RDF model containing a feedback message referring to the specified resource * that is either positive or negative. * @return */ public static Model binaryFeedbackMessage(URI forResource, boolean isFeedbackPositive) { Model messageModel = createModelWithBaseResource(); Resource baseRes = RdfUtils.getBaseResource(messageModel); Resource feedbackNode = messageModel.createResource(); baseRes.addProperty(WON.HAS_FEEDBACK, feedbackNode); feedbackNode.addProperty(WON.HAS_BINARY_RATING, isFeedbackPositive ? WON.GOOD : WON.BAD); feedbackNode.addProperty(WON.FOR_RESOURCE, messageModel.createResource(forResource.toString())); return messageModel; } /** * Returns the first won:hasTextMessage object, or null if none is found. * Won't work on WonMessage models, removal depends on refactoring of BA facet code * @param model * @return */ @Deprecated public static String getTextMessage(Model model){ Statement stmt = model.getProperty(RdfUtils.getBaseResource(model), WON.HAS_TEXT_MESSAGE); if (stmt != null) { return stmt.getObject().asLiteral().getLexicalForm(); } return null; } /** * Returns the first won:hasTextMessage object, or null if none is found. * tries the message, its corresponding remote message, and any forwarded message, * if any of those are contained in the dataset * * @param wonMessage * @return */ public static String getTextMessage(final WonMessage wonMessage) { URI messageURI = wonMessage.getMessageURI(); //find the text message in the message, the remote message, or any forwarded message String queryString = "prefix msg: <http://purl.org/webofneeds/message#>\n" + "prefix won: <http://purl.org/webofneeds/model#>\n" + "\n" + "SELECT distinct ?txt WHERE {\n" + " {\n" + " graph ?gA { ?msg won:hasTextMessage ?txt }\n" + " } union {\n" + " graph ?gB { ?msg2 msg:hasCorrespondingRemoteMessage ?msg }\n" + " graph ?gA { ?msg won:hasTextMessage ?txt }\n" + " } union {\n" + " graph ?gC { ?msg3 msg:hasForwardedMessage ?msg2 }\n" + "\tgraph ?gB { ?msg2 msg:hasCorrespondingRemoteMessage ?msg }\n" + " graph ?gA { ?msg won:hasTextMessage ?txt }\n" + " } union {\n" + " graph ?gD { ?msg4 msg:hasCorrespondingRemoteMessage ?msg3 }\n" + " graph ?gC { ?msg3 msg:hasForwardedMessage ?msg2 }\n" + "\tgraph ?gB { ?msg2 msg:hasCorrespondingRemoteMessage ?msg }\n" + " graph ?gA { ?msg won:hasTextMessage ?txt }\n" + " } union {\n" + " graph ?gE { ?msg5 msg:hasForwardedMessage ?msg4 }\n" + " graph ?gD { ?msg4 msg:hasCorrespondingRemoteMessage ?msg3 }\n" + " graph ?gC { ?msg3 msg:hasForwardedMessage ?msg2 }\n" + "\tgraph ?gB { ?msg2 msg:hasCorrespondingRemoteMessage ?msg }\n" + " graph ?gA { ?msg won:hasTextMessage ?txt }\n" + " } union {\n" + " graph ?gF { ?msg6 msg:hasCorrespondingRemoteMessage ?msg5 }\n" + " graph ?gE { ?msg5 msg:hasForwardedMessage ?msg4 }\n" + " graph ?gD { ?msg4 msg:hasCorrespondingRemoteMessage ?msg3 }\n" + " graph ?gC { ?msg3 msg:hasForwardedMessage ?msg2 }\n" + "\tgraph ?gB { ?msg2 msg:hasCorrespondingRemoteMessage ?msg }\n" + " graph ?gA { ?msg won:hasTextMessage ?txt }\n" + " } union {\n" + " graph ?gG { ?msg7 msg:hasForwardedMessage ?msg6 }\n" + " graph ?gF { ?msg6 msg:hasCorrespondingRemoteMessage ?msg5 }\n" + " graph ?gE { ?msg5 msg:hasForwardedMessage ?msg4 }\n" + " graph ?gD { ?msg4 msg:hasCorrespondingRemoteMessage ?msg3 }\n" + " graph ?gC { ?msg3 msg:hasForwardedMessage ?msg2 }\n" + "\tgraph ?gB { ?msg2 msg:hasCorrespondingRemoteMessage ?msg }\n" + " graph ?gA { ?msg won:hasTextMessage ?txt }\n" + " }\n" + "\n" + "}"; Query query = QueryFactory.create(queryString); QuerySolutionMap initialBinding = new QuerySolutionMap(); Model tmpModel = ModelFactory.createDefaultModel(); initialBinding.add("msg", tmpModel.getResource(messageURI.toString())); try (QueryExecution qexec = QueryExecutionFactory .create(query, wonMessage.getCompleteDataset())) { qexec.getContext().set(TDB.symUnionDefaultGraph, true); ResultSet rs = qexec.execSelect(); if (rs.hasNext()) { QuerySolution qs = rs.nextSolution(); String textMessage = rdfNodeToString(qs.get("txt")); if (rs.hasNext()) { //TODO as soon as we have use cases for multiple messages, we need to refactor this throw new IllegalArgumentException("wonMessage has more than one text messages"); } return textMessage; } } return null; } private static String rdfNodeToString(RDFNode node) { if (node.isLiteral()) { return node.asLiteral().getString(); } else if (node.isResource()) { return node.asResource().getURI(); } return null; } private static RDFNode getTextMessageForResource(Dataset dataset, URI uri){ if (uri == null) return null; return RdfUtils.findFirstPropertyFromResource(dataset, uri, WON.HAS_TEXT_MESSAGE); } private static RDFNode getTextMessageForResource(Dataset dataset, Resource resource){ if (resource == null) return null; return RdfUtils.findFirstPropertyFromResource(dataset, resource, WON.HAS_TEXT_MESSAGE); } /** * Converts the specified hint message into a Match object. * @param wonMessage * @return a match object or null if the message is not a hint message. */ public static Match toMatch(final WonMessage wonMessage) { if (!WONMSG.TYPE_HINT.equals(wonMessage.getMessageType().getResource())){ return null; } Match match = new Match(); match.setFromNeed(wonMessage.getReceiverNeedURI()); Dataset messageContent = wonMessage.getMessageContent(); RDFNode score = findOnePropertyFromResource(messageContent, wonMessage.getMessageURI(), WON.HAS_MATCH_SCORE); if (!score.isLiteral()) return null; match.setScore(score.asLiteral().getDouble()); RDFNode counterpart = findOnePropertyFromResource(messageContent, wonMessage.getMessageURI(), WON.HAS_MATCH_COUNTERPART); if (!counterpart.isResource()) return null; match.setToNeed(URI.create(counterpart.asResource().getURI())); return match; } public static WonMessage copyByDatasetSerialization(final WonMessage toWrap) { WonMessage copied = new WonMessage(RdfUtils.readDatasetFromString( RdfUtils.writeDatasetToString(toWrap.getCompleteDataset(), Lang.TRIG) ,Lang.TRIG)); return copied; } } public static class FacetUtils { /** * Returns the facet in a connect message. Attempts to get it from the specified message itself. * If no such facet is found there, the remoteFacet of the correspondingRemoteMessage is used. * @param message * @return */ public static URI getFacet(WonMessage message){ URI uri = getObjectOfMessageProperty(message, WON.HAS_FACET); if (uri == null) { uri = getObjectOfRemoteMessageProperty(message, WON.HAS_REMOTE_FACET); } return uri; } /** * Returns the remoteFacet in a connect message. Attempts to get it from the specified message itself. * If no such facet is found there, the facet of the correspondingRemoteMessage is used. * @param message * @return */ public static URI getRemoteFacet(WonMessage message) { URI uri = getObjectOfMessageProperty(message, WON.HAS_REMOTE_FACET); if (uri == null) { uri = getObjectOfRemoteMessageProperty(message, WON.HAS_FACET); } return uri; } /** * Returns a property of the message (i.e. the object of the first triple ( [message-uri] [property] X ) * found in one of the content graphs of the specified message. */ private static URI getObjectOfMessageProperty(final WonMessage message, final Property property) { List<String> contentGraphUris = message.getContentGraphURIs(); Dataset contentGraphs = message.getMessageContent(); URI messageURI = message.getMessageURI(); for (String graphUri: contentGraphUris) { Model contentGraph = contentGraphs.getNamedModel(graphUri); StmtIterator smtIter = contentGraph.getResource(messageURI.toString()).listProperties(property); if (smtIter.hasNext()) { return URI.create(smtIter.nextStatement().getObject().asResource().getURI()); } } return null; } /** * Returns a property of the corresponding remote message (i.e. the object of the first triple ( * [corresponding-remote-message-uri] [property] X ) * found in one of the content graphs of the specified message. */ private static URI getObjectOfRemoteMessageProperty(final WonMessage message, final Property property) { List<String> contentGraphUris = message.getContentGraphURIs(); Dataset contentGraphs = message.getMessageContent(); URI messageURI = message.getCorrespondingRemoteMessageURI(); if (messageURI != null) { for (String graphUri : contentGraphUris) { Model contentGraph = contentGraphs.getNamedModel(graphUri); StmtIterator smtIter = contentGraph.getResource(messageURI.toString()).listProperties(property); if (smtIter.hasNext()) { return URI.create(smtIter.nextStatement().getObject().asResource().getURI()); } } } return null; } /** * Returns all facets found in the model, attached to the null relative URI '<>'. * Returns an empty collection if there is no such facet. * @param content * @return */ public static Collection<URI> getFacets(Model content) { Resource baseRes = RdfUtils.getBaseResource(content); StmtIterator stmtIterator = baseRes.listProperties(WON.HAS_FACET); LinkedList<URI> ret = new LinkedList<URI>(); while (stmtIterator.hasNext()){ RDFNode object = stmtIterator.nextStatement().getObject(); if (object.isURIResource()){ ret.add(URI.create(object.asResource().getURI())); } } return ret; } /** * Adds a triple to the model of the form <> won:hasFacet [facetURI]. * @param content * @param facetURI */ public static void addFacet(final Model content, final URI facetURI) { Resource baseRes = RdfUtils.getBaseResource(content); baseRes.addProperty(WON.HAS_FACET, content.createResource(facetURI.toString())); } /** * Adds a triple to the model of the form <> won:hasRemoteFacet [facetURI]. * @param content * @param facetURI */ public static void addRemoteFacet(final Model content, final URI facetURI) { Resource baseRes = RdfUtils.getBaseResource(content); baseRes.addProperty(WON.HAS_REMOTE_FACET, content.createResource(facetURI.toString())); } /** * Creates a model for connecting two facets.CONNECTED.getURI().equals(connectionState) * @return */ public static Model createFacetModelForHintOrConnect(URI facet, URI remoteFacet) { Model model = ModelFactory.createDefaultModel(); Resource baseResource = findOrCreateBaseResource(model); WonRdfUtils.FacetUtils.addFacet(model, facet); WonRdfUtils.FacetUtils.addRemoteFacet(model, remoteFacet); logger.debug("facet model contains these facets: from:{} to:{}", facet, remoteFacet); return model; } } public static class ConnectionUtils { public static boolean isConnected(Dataset connectionDataset, URI connectionUri) { URI connectionState = getConnectionState(connectionDataset, connectionUri); return ConnectionState.CONNECTED.getURI().equals(connectionState); } public static URI getConnectionState(Dataset connectionDataset, URI connectionUri) { Path statePath = PathParser.parse("won:hasConnectionState", DefaultPrefixUtils.getDefaultPrefixes()); return RdfUtils.getURIPropertyForPropertyPath(connectionDataset, connectionUri, statePath); } /** * return the needURI of a connection * * @param dataset <code>Dataset</code> object which contains connection information * @param connectionURI * @return <code>URI</code> of the need */ public static URI getLocalNeedURIFromConnection(Dataset dataset, final URI connectionURI) { return URI.create(findOnePropertyFromResource( dataset, connectionURI, WON.BELONGS_TO_NEED).asResource().getURI()); } public static URI getRemoteNeedURIFromConnection(Dataset dataset, final URI connectionURI) { return URI.create(findOnePropertyFromResource( dataset, connectionURI, WON.HAS_REMOTE_NEED).asResource().getURI()); } public static URI getWonNodeURIFromConnection(Dataset dataset, final URI connectionURI) { return URI.create(findOnePropertyFromResource( dataset, connectionURI, WON.HAS_WON_NODE).asResource().getURI()); } public static URI getRemoteConnectionURIFromConnection(Dataset dataset, final URI connectionURI) { return URI.create(findOnePropertyFromResource( dataset, connectionURI, WON.HAS_REMOTE_CONNECTION).asResource().getURI()); } } private static Model createModelWithBaseResource() { Model model = ModelFactory.createDefaultModel(); model.setNsPrefix("", "no:uri"); model.createResource(model.getNsPrefixURI("")); return model; } public static class NeedUtils { /** * searches for a subject of type won:Need and returns the NeedURI * * @param dataset <code>Dataset</code> object which will be searched for the NeedURI * @return <code>URI</code> which is of type won:Need */ public static URI getNeedURI(Dataset dataset) { return RdfUtils.findOne(dataset, new RdfUtils.ModelVisitor<URI>() { @Override public URI visit(final Model model) { return getNeedURI(model); } }, true); } /** * searches for a subject of type won:Need and returns the NeedURI * * @param model <code>Model</code> object which will be searched for the NeedURI * @return <code>URI</code> which is of type won:Need */ public static URI getNeedURI(Model model) { Resource res = getNeedResource(model); return res == null ? null : URI.create(res.getURI()); } /** * searches for a subject of type won:Need and returns the NeedURI * * @param model <code>Model</code> object which will be searched for the NeedURI * @return <code>URI</code> which is of type won:Need */ public static Resource getNeedResource(Model model) { List<Resource> needURIs = new ArrayList<>(); ResIterator iterator = model.listSubjectsWithProperty(RDF.type, WON.NEED); while (iterator.hasNext()) { needURIs.add(iterator.next()); } if (needURIs.size() == 0) return null; else if (needURIs.size() == 1) return needURIs.get(0); else if (needURIs.size() > 1) { Resource u = needURIs.get(0); for (Resource uri : needURIs) { if (!uri.equals(u)) throw new IncorrectPropertyCountException(1,2); } return u; } else return null; } public static URI getWonNodeURIFromNeed(Dataset dataset, final URI needURI) { return URI.create(findOnePropertyFromResource( dataset, needURI, WON.HAS_WON_NODE).asResource().getURI()); } } }
webofneeds/won-core/src/main/java/won/protocol/util/WonRdfUtils.java
package won.protocol.util; import org.apache.jena.datatypes.xsd.XSDDatatype; import org.apache.jena.query.*; import org.apache.jena.rdf.model.*; import org.apache.jena.rdf.model.impl.PropertyImpl; import org.apache.jena.rdf.model.impl.ResourceImpl; import org.apache.jena.riot.Lang; import org.apache.jena.sparql.path.Path; import org.apache.jena.sparql.path.PathParser; import org.apache.jena.vocabulary.RDF; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import won.protocol.exception.IncorrectPropertyCountException; import won.protocol.message.WonMessage; import won.protocol.message.WonSignatureData; import won.protocol.model.ConnectionState; import won.protocol.model.Match; import won.protocol.service.WonNodeInfo; import won.protocol.service.WonNodeInfoBuilder; import won.protocol.vocabulary.SFSIG; import won.protocol.vocabulary.WON; import won.protocol.vocabulary.WONMSG; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import static won.protocol.util.RdfUtils.findOnePropertyFromResource; import static won.protocol.util.RdfUtils.findOrCreateBaseResource; /** * Utilities for populating/manipulating the RDF models used throughout the WON application. */ public class WonRdfUtils { public static final String NAMED_GRAPH_SUFFIX = "#data"; private static final Logger logger = LoggerFactory.getLogger(WonRdfUtils.class); public static class SignatureUtils { public static boolean isSignatureGraph(String graphUri, Model model) { // TODO check the presence of all the required triples Resource resource = model.getResource(graphUri); StmtIterator si = model.listStatements(resource, RDF.type, SFSIG.SIGNATURE); if (si.hasNext()) { return true; } return false; } public static boolean isSignature(Model model, String modelName) { // TODO check the presence of all the required triples return model.contains(model.getResource(modelName), RDF.type, SFSIG.SIGNATURE); } public static String getSignedGraphUri(String signatureGraphUri, Model signatureGraph) { String signedGraphUri = null; Resource resource = signatureGraph.getResource(signatureGraphUri); NodeIterator ni = signatureGraph.listObjectsOfProperty(resource, WONMSG.HAS_SIGNED_GRAPH_PROPERTY); if (ni.hasNext()) { signedGraphUri = ni.next().asResource().getURI(); } return signedGraphUri; } public static String getSignatureValue(String signatureGraphUri, Model signatureGraph) { String signatureValue = null; Resource resource = signatureGraph.getResource(signatureGraphUri); NodeIterator ni2 = signatureGraph.listObjectsOfProperty(resource, SFSIG.HAS_SIGNATURE_VALUE); if (ni2.hasNext()) { signatureValue = ni2.next().asLiteral().toString(); } return signatureValue; } public static WonSignatureData extractWonSignatureData(final String uri, final Model model) { return extractWonSignatureData(model.getResource(uri)); } public static WonSignatureData extractWonSignatureData(final Resource resource) { Statement stmt = resource.getRequiredProperty(WONMSG.HAS_SIGNED_GRAPH_PROPERTY); String signedGraphUri = stmt.getObject().asResource().getURI(); stmt = resource.getRequiredProperty(SFSIG.HAS_SIGNATURE_VALUE); String signatureValue = stmt.getObject().asLiteral().getString(); stmt = resource.getRequiredProperty(WONMSG.HAS_HASH_PROPERTY); String hash = stmt.getObject().asLiteral().getString(); stmt = resource.getRequiredProperty(WONMSG.HAS_PUBLIC_KEY_FINGERPRINT_PROPERTY); String fingerprint = stmt.getObject().asLiteral().getString(); stmt = resource.getRequiredProperty(SFSIG.HAS_VERIFICATION_CERT); String cert = stmt.getObject().asResource().getURI(); return new WonSignatureData(signedGraphUri, resource.getURI(), signatureValue, hash, fingerprint, cert); } /** * Adds the triples holding the signature data to the model of the specified resource, using the resource as the * subject. * @param subject * @param wonSignatureData */ public static void addSignature(Resource subject, WonSignatureData wonSignatureData){ assert wonSignatureData.getHash() != null; assert wonSignatureData.getSignatureValue() != null; assert wonSignatureData.getPublicKeyFingerprint() != null; assert wonSignatureData.getSignedGraphUri() != null; assert wonSignatureData.getVerificationCertificateUri() != null; Model containingGraph = subject.getModel(); subject.addProperty(RDF.type, SFSIG.SIGNATURE); subject.addProperty(WONMSG.HAS_HASH_PROPERTY, wonSignatureData.getHash()); subject.addProperty(SFSIG.HAS_SIGNATURE_VALUE, wonSignatureData.getSignatureValue()); subject.addProperty(WONMSG.HAS_SIGNED_GRAPH_PROPERTY, containingGraph.createResource(wonSignatureData.getSignedGraphUri())); subject.addProperty(WONMSG.HAS_PUBLIC_KEY_FINGERPRINT_PROPERTY, wonSignatureData.getPublicKeyFingerprint()); subject.addProperty(SFSIG.HAS_VERIFICATION_CERT, containingGraph.createResource(wonSignatureData .getVerificationCertificateUri())); } } public static class WonNodeUtils { /** * Creates a WonNodeInfo object based on the specified dataset. The first model * found in the dataset that seems to contain the data needed for a WonNodeInfo * object is used. * @param wonNodeUri * @param dataset * @return */ public static WonNodeInfo getWonNodeInfo(final URI wonNodeUri, Dataset dataset){ assert wonNodeUri != null: "wonNodeUri must not be null"; assert dataset != null: "dataset must not be null"; return RdfUtils.findFirst(dataset, new RdfUtils.ModelVisitor<WonNodeInfo>() { @Override public WonNodeInfo visit(final Model model) { //use the first blank node found for [wonNodeUri] won:hasUriPatternSpecification [blanknode] NodeIterator it = model.listObjectsOfProperty(model.getResource(wonNodeUri.toString()), WON.HAS_URI_PATTERN_SPECIFICATION); if (!it.hasNext()) return null; WonNodeInfoBuilder wonNodeInfoBuilder = new WonNodeInfoBuilder(); wonNodeInfoBuilder.setWonNodeURI(wonNodeUri.toString()); RDFNode node = it.next(); // set the URI prefixes it = model.listObjectsOfProperty(node.asResource(), WON.HAS_NEED_URI_PREFIX); if (! it.hasNext() ) return null; String needUriPrefix = it.next().asLiteral().getString(); wonNodeInfoBuilder.setNeedURIPrefix(needUriPrefix); it = model.listObjectsOfProperty(node.asResource(), WON.HAS_CONNECTION_URI_PREFIX); if (! it.hasNext() ) return null; wonNodeInfoBuilder.setConnectionURIPrefix(it.next().asLiteral().getString()); it = model.listObjectsOfProperty(node.asResource(), WON.HAS_EVENT_URI_PREFIX); if (! it.hasNext() ) return null; wonNodeInfoBuilder.setEventURIPrefix(it.next().asLiteral().getString()); // set the need list URI it = model.listObjectsOfProperty(model.getResource(wonNodeUri.toString()), WON.HAS_NEED_LIST); if (it.hasNext() ) { wonNodeInfoBuilder.setNeedListURI(it.next().asNode().getURI()); } else { wonNodeInfoBuilder.setNeedListURI(needUriPrefix); } // set the supported protocol implementations String queryString = "SELECT ?protocol ?param ?value WHERE { ?a <%s> ?c. " + "?c <%s> ?protocol. ?c ?param ?value. FILTER ( ?value != ?protocol ) }"; queryString = String.format(queryString, WON.SUPPORTS_WON_PROTOCOL_IMPL.toString(), RDF.getURI() + "type"); Query protocolQuery = QueryFactory.create(queryString); QueryExecution qexec = QueryExecutionFactory.create(protocolQuery, model); ResultSet rs = qexec.execSelect(); while (rs.hasNext()) { QuerySolution qs = rs.nextSolution(); String protocol = rdfNodeToString(qs.get("protocol")); String param = rdfNodeToString(qs.get("param")); String value = rdfNodeToString(qs.get("value")); wonNodeInfoBuilder.addSupportedProtocolImplParamValue(protocol, param, value); } return wonNodeInfoBuilder.build(); } }); } private static String rdfNodeToString(RDFNode node) { if (node.isLiteral()) { return node.asLiteral().getString(); } else if (node.isResource()) { return node.asResource().getURI(); } return null; } } public static class MessageUtils { /** * Adds the specified text as a won:hasTextMessage to the model's base resource. * @param message * @return */ public static Model addMessage(Model model, String message) { Resource baseRes = RdfUtils.findOrCreateBaseResource(model); baseRes.addProperty(WON.HAS_TEXT_MESSAGE, message, XSDDatatype.XSDstring); return model; } /** * Creates an RDF model containing a text message. * @param message * @return */ public static Model textMessage(String message) { Model messageModel = createModelWithBaseResource(); Resource baseRes = messageModel.createResource(messageModel.getNsPrefixURI("")); baseRes.addProperty(WON.HAS_TEXT_MESSAGE,message, XSDDatatype.XSDstring); return messageModel; } /** * Creates an RDF model containing a generic message. * * @return */ public static Model genericMessage(URI predicate, URI object) { return genericMessage(new PropertyImpl(predicate.toString()), new ResourceImpl(object.toString())); } /** * Creates an RDF model containing a generic message. * * @return */ public static Model genericMessage(Property predicate, Resource object) { Model messageModel = createModelWithBaseResource(); Resource baseRes = RdfUtils.getBaseResource(messageModel); baseRes.addProperty(RDF.type, WONMSG.TYPE_CONNECTION_MESSAGE); baseRes.addProperty(predicate, object); return messageModel; } /** * Creates an RDF model containing a feedback message referring to the specified resource * that is either positive or negative. * @return */ public static Model binaryFeedbackMessage(URI forResource, boolean isFeedbackPositive) { Model messageModel = createModelWithBaseResource(); Resource baseRes = RdfUtils.getBaseResource(messageModel); Resource feedbackNode = messageModel.createResource(); baseRes.addProperty(WON.HAS_FEEDBACK, feedbackNode); feedbackNode.addProperty(WON.HAS_BINARY_RATING, isFeedbackPositive ? WON.GOOD : WON.BAD); feedbackNode.addProperty(WON.FOR_RESOURCE, messageModel.createResource(forResource.toString())); return messageModel; } /** * Returns the first won:hasTextMessage object, or null if none is found. * Won't work on WonMessage models, removal depends on refactoring of BA facet code * @param model * @return */ @Deprecated public static String getTextMessage(Model model){ Statement stmt = model.getProperty(RdfUtils.getBaseResource(model), WON.HAS_TEXT_MESSAGE); if (stmt != null) { return stmt.getObject().asLiteral().getLexicalForm(); } return null; } /** * Returns the first won:hasTextMessage object, or null if none is found. * @param wonMessage * @return */ public static String getTextMessage(final WonMessage wonMessage){ Dataset dataset = wonMessage.getCompleteDataset(); RDFNode node = getTextMessageForResource(dataset, wonMessage.getMessageURI()); if (node != null) return node.asLiteral().toString(); node = getTextMessageForResource(dataset, wonMessage.getCorrespondingRemoteMessageURI()); if (node != null) return node.asLiteral().toString(); URI forwardedMessageURI = wonMessage.getForwardedMessageURI(); if (forwardedMessageURI != null){ node = getTextMessageForResource(dataset, forwardedMessageURI); if (node != null) return node.asLiteral().toString(); //get the remote message for the forwarded message RDFNode msgNode = RdfUtils.findOnePropertyFromResource(dataset, forwardedMessageURI, WONMSG.HAS_CORRESPONDING_REMOTE_MESSAGE); if (msgNode != null && msgNode.isResource()){ node = getTextMessageForResource(dataset, msgNode.asResource()); if (node != null) return node.asLiteral().toString(); } } return null; } private static RDFNode getTextMessageForResource(Dataset dataset, URI uri){ if (uri == null) return null; return RdfUtils.findFirstPropertyFromResource(dataset, uri, WON.HAS_TEXT_MESSAGE); } private static RDFNode getTextMessageForResource(Dataset dataset, Resource resource){ if (resource == null) return null; return RdfUtils.findFirstPropertyFromResource(dataset, resource, WON.HAS_TEXT_MESSAGE); } /** * Converts the specified hint message into a Match object. * @param wonMessage * @return a match object or null if the message is not a hint message. */ public static Match toMatch(final WonMessage wonMessage) { if (!WONMSG.TYPE_HINT.equals(wonMessage.getMessageType().getResource())){ return null; } Match match = new Match(); match.setFromNeed(wonMessage.getReceiverNeedURI()); Dataset messageContent = wonMessage.getMessageContent(); RDFNode score = findOnePropertyFromResource(messageContent, wonMessage.getMessageURI(), WON.HAS_MATCH_SCORE); if (!score.isLiteral()) return null; match.setScore(score.asLiteral().getDouble()); RDFNode counterpart = findOnePropertyFromResource(messageContent, wonMessage.getMessageURI(), WON.HAS_MATCH_COUNTERPART); if (!counterpart.isResource()) return null; match.setToNeed(URI.create(counterpart.asResource().getURI())); return match; } public static WonMessage copyByDatasetSerialization(final WonMessage toWrap) { WonMessage copied = new WonMessage(RdfUtils.readDatasetFromString( RdfUtils.writeDatasetToString(toWrap.getCompleteDataset(), Lang.TRIG) ,Lang.TRIG)); return copied; } } public static class FacetUtils { /** * Returns the facet in a connect message. Attempts to get it from the specified message itself. * If no such facet is found there, the remoteFacet of the correspondingRemoteMessage is used. * @param message * @return */ public static URI getFacet(WonMessage message){ URI uri = getObjectOfMessageProperty(message, WON.HAS_FACET); if (uri == null) { uri = getObjectOfRemoteMessageProperty(message, WON.HAS_REMOTE_FACET); } return uri; } /** * Returns the remoteFacet in a connect message. Attempts to get it from the specified message itself. * If no such facet is found there, the facet of the correspondingRemoteMessage is used. * @param message * @return */ public static URI getRemoteFacet(WonMessage message) { URI uri = getObjectOfMessageProperty(message, WON.HAS_REMOTE_FACET); if (uri == null) { uri = getObjectOfRemoteMessageProperty(message, WON.HAS_FACET); } return uri; } /** * Returns a property of the message (i.e. the object of the first triple ( [message-uri] [property] X ) * found in one of the content graphs of the specified message. */ private static URI getObjectOfMessageProperty(final WonMessage message, final Property property) { List<String> contentGraphUris = message.getContentGraphURIs(); Dataset contentGraphs = message.getMessageContent(); URI messageURI = message.getMessageURI(); for (String graphUri: contentGraphUris) { Model contentGraph = contentGraphs.getNamedModel(graphUri); StmtIterator smtIter = contentGraph.getResource(messageURI.toString()).listProperties(property); if (smtIter.hasNext()) { return URI.create(smtIter.nextStatement().getObject().asResource().getURI()); } } return null; } /** * Returns a property of the corresponding remote message (i.e. the object of the first triple ( * [corresponding-remote-message-uri] [property] X ) * found in one of the content graphs of the specified message. */ private static URI getObjectOfRemoteMessageProperty(final WonMessage message, final Property property) { List<String> contentGraphUris = message.getContentGraphURIs(); Dataset contentGraphs = message.getMessageContent(); URI messageURI = message.getCorrespondingRemoteMessageURI(); if (messageURI != null) { for (String graphUri : contentGraphUris) { Model contentGraph = contentGraphs.getNamedModel(graphUri); StmtIterator smtIter = contentGraph.getResource(messageURI.toString()).listProperties(property); if (smtIter.hasNext()) { return URI.create(smtIter.nextStatement().getObject().asResource().getURI()); } } } return null; } /** * Returns all facets found in the model, attached to the null relative URI '<>'. * Returns an empty collection if there is no such facet. * @param content * @return */ public static Collection<URI> getFacets(Model content) { Resource baseRes = RdfUtils.getBaseResource(content); StmtIterator stmtIterator = baseRes.listProperties(WON.HAS_FACET); LinkedList<URI> ret = new LinkedList<URI>(); while (stmtIterator.hasNext()){ RDFNode object = stmtIterator.nextStatement().getObject(); if (object.isURIResource()){ ret.add(URI.create(object.asResource().getURI())); } } return ret; } /** * Adds a triple to the model of the form <> won:hasFacet [facetURI]. * @param content * @param facetURI */ public static void addFacet(final Model content, final URI facetURI) { Resource baseRes = RdfUtils.getBaseResource(content); baseRes.addProperty(WON.HAS_FACET, content.createResource(facetURI.toString())); } /** * Adds a triple to the model of the form <> won:hasRemoteFacet [facetURI]. * @param content * @param facetURI */ public static void addRemoteFacet(final Model content, final URI facetURI) { Resource baseRes = RdfUtils.getBaseResource(content); baseRes.addProperty(WON.HAS_REMOTE_FACET, content.createResource(facetURI.toString())); } /** * Creates a model for connecting two facets.CONNECTED.getURI().equals(connectionState) * @return */ public static Model createFacetModelForHintOrConnect(URI facet, URI remoteFacet) { Model model = ModelFactory.createDefaultModel(); Resource baseResource = findOrCreateBaseResource(model); WonRdfUtils.FacetUtils.addFacet(model, facet); WonRdfUtils.FacetUtils.addRemoteFacet(model, remoteFacet); logger.debug("facet model contains these facets: from:{} to:{}", facet, remoteFacet); return model; } } public static class ConnectionUtils { public static boolean isConnected(Dataset connectionDataset, URI connectionUri) { URI connectionState = getConnectionState(connectionDataset, connectionUri); return ConnectionState.CONNECTED.getURI().equals(connectionState); } public static URI getConnectionState(Dataset connectionDataset, URI connectionUri) { Path statePath = PathParser.parse("won:hasConnectionState", DefaultPrefixUtils.getDefaultPrefixes()); return RdfUtils.getURIPropertyForPropertyPath(connectionDataset, connectionUri, statePath); } /** * return the needURI of a connection * * @param dataset <code>Dataset</code> object which contains connection information * @param connectionURI * @return <code>URI</code> of the need */ public static URI getLocalNeedURIFromConnection(Dataset dataset, final URI connectionURI) { return URI.create(findOnePropertyFromResource( dataset, connectionURI, WON.BELONGS_TO_NEED).asResource().getURI()); } public static URI getRemoteNeedURIFromConnection(Dataset dataset, final URI connectionURI) { return URI.create(findOnePropertyFromResource( dataset, connectionURI, WON.HAS_REMOTE_NEED).asResource().getURI()); } public static URI getWonNodeURIFromConnection(Dataset dataset, final URI connectionURI) { return URI.create(findOnePropertyFromResource( dataset, connectionURI, WON.HAS_WON_NODE).asResource().getURI()); } public static URI getRemoteConnectionURIFromConnection(Dataset dataset, final URI connectionURI) { return URI.create(findOnePropertyFromResource( dataset, connectionURI, WON.HAS_REMOTE_CONNECTION).asResource().getURI()); } } private static Model createModelWithBaseResource() { Model model = ModelFactory.createDefaultModel(); model.setNsPrefix("", "no:uri"); model.createResource(model.getNsPrefixURI("")); return model; } public static class NeedUtils { /** * searches for a subject of type won:Need and returns the NeedURI * * @param dataset <code>Dataset</code> object which will be searched for the NeedURI * @return <code>URI</code> which is of type won:Need */ public static URI getNeedURI(Dataset dataset) { return RdfUtils.findOne(dataset, new RdfUtils.ModelVisitor<URI>() { @Override public URI visit(final Model model) { return getNeedURI(model); } }, true); } /** * searches for a subject of type won:Need and returns the NeedURI * * @param model <code>Model</code> object which will be searched for the NeedURI * @return <code>URI</code> which is of type won:Need */ public static URI getNeedURI(Model model) { Resource res = getNeedResource(model); return res == null ? null : URI.create(res.getURI()); } /** * searches for a subject of type won:Need and returns the NeedURI * * @param model <code>Model</code> object which will be searched for the NeedURI * @return <code>URI</code> which is of type won:Need */ public static Resource getNeedResource(Model model) { List<Resource> needURIs = new ArrayList<>(); ResIterator iterator = model.listSubjectsWithProperty(RDF.type, WON.NEED); while (iterator.hasNext()) { needURIs.add(iterator.next()); } if (needURIs.size() == 0) return null; else if (needURIs.size() == 1) return needURIs.get(0); else if (needURIs.size() > 1) { Resource u = needURIs.get(0); for (Resource uri : needURIs) { if (!uri.equals(u)) throw new IncorrectPropertyCountException(1,2); } return u; } else return null; } public static URI getWonNodeURIFromNeed(Dataset dataset, final URI needURI) { return URI.create(findOnePropertyFromResource( dataset, needURI, WON.HAS_WON_NODE).asResource().getURI()); } } }
Improve text message retrieval getTextMessage now handles up to 3 forwards.
webofneeds/won-core/src/main/java/won/protocol/util/WonRdfUtils.java
Improve text message retrieval
<ide><path>ebofneeds/won-core/src/main/java/won/protocol/util/WonRdfUtils.java <ide> import org.apache.jena.riot.Lang; <ide> import org.apache.jena.sparql.path.Path; <ide> import org.apache.jena.sparql.path.PathParser; <add>import org.apache.jena.tdb.TDB; <ide> import org.apache.jena.vocabulary.RDF; <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> return null; <ide> } <ide> <del> /** <del> * Returns the first won:hasTextMessage object, or null if none is found. <del> * @param wonMessage <del> * @return <del> */ <del> public static String getTextMessage(final WonMessage wonMessage){ <del> Dataset dataset = wonMessage.getCompleteDataset(); <del> RDFNode node = getTextMessageForResource(dataset, wonMessage.getMessageURI()); <del> if (node != null) return node.asLiteral().toString(); <del> node = getTextMessageForResource(dataset, wonMessage.getCorrespondingRemoteMessageURI()); <del> if (node != null) return node.asLiteral().toString(); <del> URI forwardedMessageURI = wonMessage.getForwardedMessageURI(); <del> if (forwardedMessageURI != null){ <del> node = getTextMessageForResource(dataset, forwardedMessageURI); <del> if (node != null) return node.asLiteral().toString(); <del> //get the remote message for the forwarded message <del> RDFNode msgNode = RdfUtils.findOnePropertyFromResource(dataset, forwardedMessageURI, WONMSG.HAS_CORRESPONDING_REMOTE_MESSAGE); <del> if (msgNode != null && msgNode.isResource()){ <del> node = getTextMessageForResource(dataset, msgNode.asResource()); <del> if (node != null) return node.asLiteral().toString(); <del> } <del> } <del> return null; <del> } <add> <add> /** <add> * Returns the first won:hasTextMessage object, or null if none is found. <add> * tries the message, its corresponding remote message, and any forwarded message, <add> * if any of those are contained in the dataset <add> * <add> * @param wonMessage <add> * @return <add> */ <add> public static String getTextMessage(final WonMessage wonMessage) { <add> URI messageURI = wonMessage.getMessageURI(); <add> <add> //find the text message in the message, the remote message, or any forwarded message <add> String queryString = <add> "prefix msg: <http://purl.org/webofneeds/message#>\n" + <add> "prefix won: <http://purl.org/webofneeds/model#>\n" + <add> "\n" + <add> "SELECT distinct ?txt WHERE {\n" + <add> " {\n" + <add> " graph ?gA { ?msg won:hasTextMessage ?txt }\n" + <add> " } union {\n" + <add> " graph ?gB { ?msg2 msg:hasCorrespondingRemoteMessage ?msg }\n" + <add> " graph ?gA { ?msg won:hasTextMessage ?txt }\n" + <add> " } union {\n" + <add> " graph ?gC { ?msg3 msg:hasForwardedMessage ?msg2 }\n" + <add> "\tgraph ?gB { ?msg2 msg:hasCorrespondingRemoteMessage ?msg }\n" + <add> " graph ?gA { ?msg won:hasTextMessage ?txt }\n" + <add> " } union {\n" + <add> " graph ?gD { ?msg4 msg:hasCorrespondingRemoteMessage ?msg3 }\n" + <add> " graph ?gC { ?msg3 msg:hasForwardedMessage ?msg2 }\n" + <add> "\tgraph ?gB { ?msg2 msg:hasCorrespondingRemoteMessage ?msg }\n" + <add> " graph ?gA { ?msg won:hasTextMessage ?txt }\n" + <add> " } union {\n" + <add> " graph ?gE { ?msg5 msg:hasForwardedMessage ?msg4 }\n" + <add> " graph ?gD { ?msg4 msg:hasCorrespondingRemoteMessage ?msg3 }\n" + <add> " graph ?gC { ?msg3 msg:hasForwardedMessage ?msg2 }\n" + <add> "\tgraph ?gB { ?msg2 msg:hasCorrespondingRemoteMessage ?msg }\n" + <add> " graph ?gA { ?msg won:hasTextMessage ?txt }\n" + <add> " } union {\n" + <add> " graph ?gF { ?msg6 msg:hasCorrespondingRemoteMessage ?msg5 }\n" + <add> " graph ?gE { ?msg5 msg:hasForwardedMessage ?msg4 }\n" + <add> " graph ?gD { ?msg4 msg:hasCorrespondingRemoteMessage ?msg3 }\n" + <add> " graph ?gC { ?msg3 msg:hasForwardedMessage ?msg2 }\n" + <add> "\tgraph ?gB { ?msg2 msg:hasCorrespondingRemoteMessage ?msg }\n" + <add> " graph ?gA { ?msg won:hasTextMessage ?txt }\n" + <add> " } union {\n" + <add> " graph ?gG { ?msg7 msg:hasForwardedMessage ?msg6 }\n" + <add> " graph ?gF { ?msg6 msg:hasCorrespondingRemoteMessage ?msg5 }\n" + <add> " graph ?gE { ?msg5 msg:hasForwardedMessage ?msg4 }\n" + <add> " graph ?gD { ?msg4 msg:hasCorrespondingRemoteMessage ?msg3 }\n" + <add> " graph ?gC { ?msg3 msg:hasForwardedMessage ?msg2 }\n" + <add> "\tgraph ?gB { ?msg2 msg:hasCorrespondingRemoteMessage ?msg }\n" + <add> " graph ?gA { ?msg won:hasTextMessage ?txt }\n" + <add> " }\n" + <add> "\n" + <add> "}"; <add> Query query = QueryFactory.create(queryString); <add> <add> QuerySolutionMap initialBinding = new QuerySolutionMap(); <add> Model tmpModel = ModelFactory.createDefaultModel(); <add> initialBinding.add("msg", tmpModel.getResource(messageURI.toString())); <add> try (QueryExecution qexec = QueryExecutionFactory <add> .create(query, wonMessage.getCompleteDataset())) { <add> qexec.getContext().set(TDB.symUnionDefaultGraph, true); <add> ResultSet rs = qexec.execSelect(); <add> if (rs.hasNext()) { <add> QuerySolution qs = rs.nextSolution(); <add> String textMessage = rdfNodeToString(qs.get("txt")); <add> if (rs.hasNext()) { <add> //TODO as soon as we have use cases for multiple messages, we need to refactor this <add> throw new IllegalArgumentException("wonMessage has more than one text messages"); <add> } <add> return textMessage; <add> } <add> } <add> return null; <add> } <add> <add> private static String rdfNodeToString(RDFNode node) { <add> if (node.isLiteral()) { <add> return node.asLiteral().getString(); <add> } else if (node.isResource()) { <add> return node.asResource().getURI(); <add> } <add> return null; <add> } <ide> <ide> private static RDFNode getTextMessageForResource(Dataset dataset, URI uri){ <ide> if (uri == null) return null;
JavaScript
mit
0b2a28590d8b71cf7ad7eafa1aed849988e41099
0
quirkycorgi/Agamari,quirkycorgi/Agamari
import store from '../store'; import {launch , launchReady, buildUp } from '../reducers/abilities'; import { scene } from './main'; const THREE = require('three'); const CANNON = require('../../public/cannon.min.js'); THREE.PlayerControls = function ( camera, player, cannonMesh, raycastReference , id) { this.domElement = document; this.camera = camera; this.player = player; this.cannonMesh = cannonMesh; this.id = id; this.cooldown = Date.now(); this.scale; var keyState = {}; var scope = this; var curCamZoom = 60; var curCamHeight = 70; this.left = false; this.right = false; this.speedMult = 1; this.launchMult = 1; this.i = 1; // helpful dev tool, yo // var geometry = new THREE.BoxGeometry( 30,3,2 ); // var material = new THREE.MeshPhongMaterial({ // shading: THREE.FlatShading }); // this.devTestMesh = new THREE.Mesh( geometry, material ); // scene.add(this.devTestMesh) this.playerRotation = new THREE.Quaternion(); var cameraReferenceOrientation = new THREE.Quaternion(); var cameraReferenceOrientationObj = new THREE.Object3D(); var poleDir = new THREE.Vector3(1,0,0); this.update = function() { scope.scale = store.getState().players[scope.id].scale; this.camera.fov = Math.max(55, Math.min(45 + this.speedMult*10, 65/(1 + (scope.scale * 0.01) ))); //console.log(this.camera.fov, this.speedMult) this.camera.updateProjectionMatrix(); //cameraReferenceOrientation.copy(cameraReferenceOrientationObj.quaternion); //console.log(store.getState().abilities && ) if(!store.getState().abilities.launch && Date.now() - scope.cooldown > 12000){ // console.log("launchReady") store.dispatch(launchReady()); } this.checkKeyStates(); //console.log(this.speedMult); var playerPosition = new THREE.Vector3(this.player.position.x, this.player.position.y, this.player.position.z); //var cameraReferenceOrientation = new THREE.Quaternion(); var cameraPosition = this.player.position.clone(); var poleDirection = new THREE.Vector3(1,0,0) var localUp = cameraPosition.clone().normalize(); // no orientation for now, change cameraReforient if necessary if(this.left){ // var cameraRot2 = new THREE.Matrix4(); // cameraRot2.makeRotationY(0.005); // noClue.multiplyMatrices(noClue, cameraRot2) cameraReferenceOrientationObj.rotation.y = 0.04;// change to rotation this.left = false; } else if(this.right){ // var cameraRot2 = new THREE.Matrix4(); // cameraRot2.makeRotationY(-0.005); // noClue.multiplyMatrices(noClue, cameraRot2) cameraReferenceOrientationObj.rotation.y = -0.04; this.right = false; } var referenceForward = new THREE.Vector3(0, 0, 1); referenceForward.applyQuaternion(cameraReferenceOrientationObj.quaternion); var correctionAngle = Math.atan2(referenceForward.x, referenceForward.z) var cameraPoru = new THREE.Vector3(0,-1,0); cameraReferenceOrientationObj.quaternion.setFromAxisAngle(cameraPoru,correctionAngle); poleDir.applyAxisAngle(localUp,correctionAngle).normalize(); cameraReferenceOrientationObj.quaternion.copy(cameraReferenceOrientation); var cross = new THREE.Vector3(); cross.crossVectors(poleDir,localUp); var dot = localUp.dot(poleDir); poleDir.subVectors(poleDir , localUp.clone().multiplyScalar(dot)); var noClue = new THREE.Matrix4(); noClue.set( poleDir.x,localUp.x,cross.x,cameraPosition.x, poleDir.y,localUp.y,cross.y,cameraPosition.y, poleDir.z,localUp.z,cross.z,cameraPosition.z, 0,0,0,1); this.camera.matrixAutoUpdate = false; var cameraPlace = new THREE.Matrix4(); cameraPlace.makeTranslation ( 0, curCamHeight * scope.scale * .8, curCamZoom * scope.scale * .8) var cameraRot = new THREE.Matrix4(); cameraRot.makeRotationX(-0.32 - (playerPosition.length()/1200));// scale this with height to planet! var oneTwo = new THREE.Matrix4(); oneTwo.multiplyMatrices(noClue , cameraPlace); var oneTwoThree = new THREE.Matrix4(); oneTwoThree.multiplyMatrices(oneTwo, cameraRot); this.camera.matrix = oneTwoThree; }; this.checkKeyStates = function () { if(this.speedMult < 1){ this.speedMult = 1} if(this.speedMult < 1){ this.speedMult = 1} // get quaternion and position to apply impulse var playerPositionCannon = new CANNON.Vec3(scope.cannonMesh.position.x, scope.cannonMesh.position.y, scope.cannonMesh.position.z); // get unit (directional) vector for position var norm = playerPositionCannon.normalize(); var localTopPoint = new CANNON.Vec3(0,0,500); var topVec = new CANNON.Vec3(0,0,1); var quaternionOnPlanet = new CANNON.Quaternion(); quaternionOnPlanet.setFromVectors(topVec, playerPositionCannon); var topOfBall = quaternionOnPlanet.vmult(new CANNON.Vec3(0,0,norm).vadd(new CANNON.Vec3(0,0, scope.scale * 10))); // this.devTestMesh.position.set(topOfBall.x, topOfBall.z, topOfBall.y) // find direction on planenormal by crossing the cross cross prods of localUp and camera dir var camVec = new THREE.Vector3(); camera.getWorldDirection( camVec ); camVec.normalize(); // apply downward force to keep ball rolling var downforce = new THREE.Vector3(0,-1,0); var dfQuat = new THREE.Quaternion() camera.getWorldQuaternion( dfQuat ); downforce.applyQuaternion(dfQuat); camVec.add(downforce.divideScalar(2)); camVec.normalize() var playerPosition = new THREE.Vector3(this.player.position.x, this.player.position.y, this.player.position.z); playerPosition.normalize(); // lateral directional vector var cross1 = new THREE.Vector3(); cross1.crossVectors(playerPosition, camVec); //cross1.multiplyScalar(10); //cross1.addScalar(20 + Math.pow(this.scale, 3)); // front/back vector var cross2 = new THREE.Vector3(); cross2.crossVectors(playerPosition, cross1); //cross2.multiplyScalar(10); //cross2.addScalar(20 + Math.pow(this.scale, 3)); if (keyState[32]) { if(store.getState().abilities.launch){ if(this.launchMult < 6) this.launchMult += 1/(this.i++ * 1.1); var buildLaunch = ~~(this.launchMult * 3 - 3); //console.log(buildLaunch) store.dispatch(buildUp(buildLaunch)); } } if (keyState[38] || keyState[87]) { if(this.speedMult < 3.5) this.speedMult += 0.005; // up arrow or 'w' - move forward this.cannonMesh.applyImpulse(new CANNON.Vec3(-cross2.x * 140 * (0.833 + this.scale/6) *this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/, -cross2.z * 140 * (0.833 + this.scale/6) *this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/, -cross2.y * 140 * (0.833 + this.scale/6) *this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/) ,topOfBall); } if (keyState[40] || keyState[83]) { if(this.speedMult < 3.5) this.speedMult += 0.005; // down arrow or 's' - move backward this.cannonMesh.applyImpulse(new CANNON.Vec3(cross2.x * 140 * (0.833 + this.scale/6) *this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/, cross2.z * 140 * (0.833 + this.scale/6) *this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/, cross2.y * 140 * (0.833 + this.scale/6) *this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/) ,topOfBall); } if (keyState[37] || keyState[65]) { if(this.speedMult < 3.5) this.speedMult += 0.005; // left arrow or 'a' - rotate left this.cannonMesh.applyImpulse(new CANNON.Vec3(cross1.x * 100 * (0.833 + this.scale/6) * this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/, cross1.z * 100 * (0.833 + this.scale/6) * this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/, cross1.y * 100 * (0.833 + this.scale/6) * this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/) ,topOfBall); this.left = true; } if (keyState[39] || keyState[68]) { if(this.speedMult < 3.5) this.speedMult += 0.005; // right arrow or 'd' - rotate right this.cannonMesh.applyImpulse(new CANNON.Vec3(-cross1.x * 120 * (0.833 + this.scale/6) * this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/,-cross1.z * 120 * (0.833 + this.scale/6) * this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/,-cross1.y * 120 * (0.833 + this.scale/6) * this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/), topOfBall); this.right = true; } if(!(keyState[38] || keyState[87] || keyState[40] || keyState[83] || keyState[37] || keyState[65] || keyState[39] || keyState[68])){ this.speedMult -= .06; } // if(!keyState[32]){ // } if (!keyState[32] && this.launchMult > 1) { if(this.launchMult < 3) this.launchMult += 0.1; var camVec2 = new THREE.Vector3(); camera.getWorldDirection( camVec2 ); camVec2.normalize(); // apply upward force to launch var upforce = new THREE.Vector3(0,1,0); var ufQuat = new THREE.Quaternion() camera.getWorldQuaternion( ufQuat ); upforce.applyQuaternion(ufQuat); camVec2.add(upforce.divideScalar(1)); camVec2.normalize(); var cross1o = new THREE.Vector3(); cross1o.crossVectors(playerPosition, camVec2); var cross2o = new THREE.Vector3(); cross2o.crossVectors(playerPosition, cross1o); // spacebar - orbital launch var launchIntoOrbit = new THREE.Vector3(); if(keyState[38] || keyState[87]){ launchIntoOrbit.copy(cross2o).negate(); }else if (keyState[40] || keyState[83]) { launchIntoOrbit.copy(cross2o); }else if (keyState[37] || keyState[65]) { launchIntoOrbit.copy(cross1o); }else if (keyState[39] || keyState[68]) { launchIntoOrbit.copy(cross1o).negate(); } else{ launchIntoOrbit.copy(playerPosition).normalize().divideScalar(1); } // console.log(cannonMesh, launchIntoOrbit.x) store.dispatch(launch()); this.cannonMesh.applyImpulse(new CANNON.Vec3(launchIntoOrbit.x * 3000 * this.launchMult , launchIntoOrbit.z * 3000 * this.launchMult , launchIntoOrbit.y * 3000 * this.launchMult ), topOfBall); scope.cooldown = Date.now(); this.launchMult = 1; this.i = 1; } }; function onKeyDown( event ) { event = event || window.event; keyState[event.keyCode || event.which] = true; } function onKeyUp( event ) { event = event || window.event; keyState[event.keyCode || event.which] = false; } this.domElement.addEventListener('contextmenu', function( event ) { event.preventDefault(); }, false ); this.domElement.addEventListener('keydown', onKeyDown, false ); this.domElement.addEventListener('keyup', onKeyUp, false ); }; THREE.PlayerControls.prototype = Object.create( THREE.EventDispatcher.prototype );
browser/game/PlayerControls.js
import store from '../store'; import {launch , launchReady, buildUp } from '../reducers/abilities'; import { scene } from './main'; const THREE = require('three'); const CANNON = require('../../public/cannon.min.js'); THREE.PlayerControls = function ( camera, player, cannonMesh, raycastReference , id) { this.domElement = document; this.camera = camera; this.player = player; this.cannonMesh = cannonMesh; this.id = id; this.cooldown = Date.now(); this.scale; var keyState = {}; var scope = this; var curCamZoom = 60; var curCamHeight = 70; this.left = false; this.right = false; this.speedMult = 1; this.launchMult = 1; // helpful dev tool, yo // var geometry = new THREE.BoxGeometry( 30,3,2 ); // var material = new THREE.MeshPhongMaterial({ // shading: THREE.FlatShading }); // this.devTestMesh = new THREE.Mesh( geometry, material ); // scene.add(this.devTestMesh) this.playerRotation = new THREE.Quaternion(); var cameraReferenceOrientation = new THREE.Quaternion(); var cameraReferenceOrientationObj = new THREE.Object3D(); var poleDir = new THREE.Vector3(1,0,0); this.update = function() { scope.scale = store.getState().players[scope.id].scale; this.camera.fov = Math.max(55, Math.min(45 + this.speedMult*10, 65/(1 + (scope.scale * 0.01) ))); //console.log(this.camera.fov, this.speedMult) this.camera.updateProjectionMatrix(); //cameraReferenceOrientation.copy(cameraReferenceOrientationObj.quaternion); //console.log(store.getState().abilities && ) if(!store.getState().abilities.launch && Date.now() - scope.cooldown > 5000){ // console.log("launchReady") store.dispatch(launchReady()); } this.checkKeyStates(); //console.log(this.speedMult); var playerPosition = new THREE.Vector3(this.player.position.x, this.player.position.y, this.player.position.z); //var cameraReferenceOrientation = new THREE.Quaternion(); var cameraPosition = this.player.position.clone(); var poleDirection = new THREE.Vector3(1,0,0) var localUp = cameraPosition.clone().normalize(); // no orientation for now, change cameraReforient if necessary if(this.left){ // var cameraRot2 = new THREE.Matrix4(); // cameraRot2.makeRotationY(0.005); // noClue.multiplyMatrices(noClue, cameraRot2) cameraReferenceOrientationObj.rotation.y = 0.04;// change to rotation this.left = false; } else if(this.right){ // var cameraRot2 = new THREE.Matrix4(); // cameraRot2.makeRotationY(-0.005); // noClue.multiplyMatrices(noClue, cameraRot2) cameraReferenceOrientationObj.rotation.y = -0.04; this.right = false; } var referenceForward = new THREE.Vector3(0, 0, 1); referenceForward.applyQuaternion(cameraReferenceOrientationObj.quaternion); var correctionAngle = Math.atan2(referenceForward.x, referenceForward.z) var cameraPoru = new THREE.Vector3(0,-1,0); cameraReferenceOrientationObj.quaternion.setFromAxisAngle(cameraPoru,correctionAngle); poleDir.applyAxisAngle(localUp,correctionAngle).normalize(); cameraReferenceOrientationObj.quaternion.copy(cameraReferenceOrientation); var cross = new THREE.Vector3(); cross.crossVectors(poleDir,localUp); var dot = localUp.dot(poleDir); poleDir.subVectors(poleDir , localUp.clone().multiplyScalar(dot)); var noClue = new THREE.Matrix4(); noClue.set( poleDir.x,localUp.x,cross.x,cameraPosition.x, poleDir.y,localUp.y,cross.y,cameraPosition.y, poleDir.z,localUp.z,cross.z,cameraPosition.z, 0,0,0,1); this.camera.matrixAutoUpdate = false; var cameraPlace = new THREE.Matrix4(); cameraPlace.makeTranslation ( 0, curCamHeight * scope.scale * .8, curCamZoom * scope.scale * .8) var cameraRot = new THREE.Matrix4(); cameraRot.makeRotationX(-0.32 - (playerPosition.length()/1200));// scale this with height to planet! var oneTwo = new THREE.Matrix4(); oneTwo.multiplyMatrices(noClue , cameraPlace); var oneTwoThree = new THREE.Matrix4(); oneTwoThree.multiplyMatrices(oneTwo, cameraRot); this.camera.matrix = oneTwoThree; }; this.checkKeyStates = function () { if(this.speedMult < 1){ this.speedMult = 1} if(this.speedMult < 1){ this.speedMult = 1} // get quaternion and position to apply impulse var playerPositionCannon = new CANNON.Vec3(scope.cannonMesh.position.x, scope.cannonMesh.position.y, scope.cannonMesh.position.z); // get unit (directional) vector for position var norm = playerPositionCannon.normalize(); var localTopPoint = new CANNON.Vec3(0,0,500); var topVec = new CANNON.Vec3(0,0,1); var quaternionOnPlanet = new CANNON.Quaternion(); quaternionOnPlanet.setFromVectors(topVec, playerPositionCannon); var topOfBall = quaternionOnPlanet.vmult(new CANNON.Vec3(0,0,norm).vadd(new CANNON.Vec3(0,0, scope.scale * 10))); // this.devTestMesh.position.set(topOfBall.x, topOfBall.z, topOfBall.y) // find direction on planenormal by crossing the cross cross prods of localUp and camera dir var camVec = new THREE.Vector3(); camera.getWorldDirection( camVec ); camVec.normalize(); // apply downward force to keep ball rolling var downforce = new THREE.Vector3(0,-1,0); var dfQuat = new THREE.Quaternion() camera.getWorldQuaternion( dfQuat ); downforce.applyQuaternion(dfQuat); camVec.add(downforce.divideScalar(2)); camVec.normalize() var playerPosition = new THREE.Vector3(this.player.position.x, this.player.position.y, this.player.position.z); playerPosition.normalize(); // lateral directional vector var cross1 = new THREE.Vector3(); cross1.crossVectors(playerPosition, camVec); //cross1.multiplyScalar(10); //cross1.addScalar(20 + Math.pow(this.scale, 3)); // front/back vector var cross2 = new THREE.Vector3(); cross2.crossVectors(playerPosition, cross1); //cross2.multiplyScalar(10); //cross2.addScalar(20 + Math.pow(this.scale, 3)); if (keyState[32]) { if(store.getState().abilities.launch){ if(this.launchMult < 6) this.launchMult += 0.04; var buildLaunch = ~~(this.launchMult * 3 - 3); //console.log(buildLaunch) store.dispatch(buildUp(buildLaunch)); } } if (keyState[38] || keyState[87]) { if(this.speedMult < 3.5) this.speedMult += 0.005; // up arrow or 'w' - move forward this.cannonMesh.applyImpulse(new CANNON.Vec3(-cross2.x * 140 * (0.833 + this.scale/6) *this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/, -cross2.z * 140 * (0.833 + this.scale/6) *this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/, -cross2.y * 140 * (0.833 + this.scale/6) *this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/) ,topOfBall); } if (keyState[40] || keyState[83]) { if(this.speedMult < 3.5) this.speedMult += 0.005; // down arrow or 's' - move backward this.cannonMesh.applyImpulse(new CANNON.Vec3(cross2.x * 140 * (0.833 + this.scale/6) *this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/, cross2.z * 140 * (0.833 + this.scale/6) *this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/, cross2.y * 140 * (0.833 + this.scale/6) *this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/) ,topOfBall); } if (keyState[37] || keyState[65]) { if(this.speedMult < 3.5) this.speedMult += 0.005; // left arrow or 'a' - rotate left this.cannonMesh.applyImpulse(new CANNON.Vec3(cross1.x * 100 * (0.833 + this.scale/6) * this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/, cross1.z * 100 * (0.833 + this.scale/6) * this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/, cross1.y * 100 * (0.833 + this.scale/6) * this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/) ,topOfBall); this.left = true; } if (keyState[39] || keyState[68]) { if(this.speedMult < 3.5) this.speedMult += 0.005; // right arrow or 'd' - rotate right this.cannonMesh.applyImpulse(new CANNON.Vec3(-cross1.x * 120 * (0.833 + this.scale/6) * this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/,-cross1.z * 120 * (0.833 + this.scale/6) * this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/,-cross1.y * 120 * (0.833 + this.scale/6) * this.speedMult /*Math.pow(scope.scale, 1 + (scope.scale * 1))*/), topOfBall); this.right = true; } if(!(keyState[38] || keyState[87] || keyState[40] || keyState[83] || keyState[37] || keyState[65] || keyState[39] || keyState[68])){ this.speedMult -= .06; } // if(!keyState[32]){ // } if (!keyState[32] && this.launchMult > 1) { if(this.launchMult < 3) this.launchMult += 0.1; var camVec2 = new THREE.Vector3(); camera.getWorldDirection( camVec2 ); camVec2.normalize(); // apply upward force to launch var upforce = new THREE.Vector3(0,1,0); var ufQuat = new THREE.Quaternion() camera.getWorldQuaternion( ufQuat ); upforce.applyQuaternion(ufQuat); camVec2.add(upforce.divideScalar(1)); camVec2.normalize(); var cross1o = new THREE.Vector3(); cross1o.crossVectors(playerPosition, camVec2); var cross2o = new THREE.Vector3(); cross2o.crossVectors(playerPosition, cross1o); // spacebar - orbital launch var launchIntoOrbit = new THREE.Vector3(); if(keyState[38] || keyState[87]){ launchIntoOrbit.copy(cross2o).negate(); }else if (keyState[40] || keyState[83]) { launchIntoOrbit.copy(cross2o); }else if (keyState[37] || keyState[65]) { launchIntoOrbit.copy(cross1o); }else if (keyState[39] || keyState[68]) { launchIntoOrbit.copy(cross1o).negate(); } else{ launchIntoOrbit.copy(playerPosition).normalize().divideScalar(1); } // console.log(cannonMesh, launchIntoOrbit.x) store.dispatch(launch()); this.cannonMesh.applyImpulse(new CANNON.Vec3(launchIntoOrbit.x * 3000 * this.launchMult , launchIntoOrbit.z * 3000 * this.launchMult , launchIntoOrbit.y * 3000 * this.launchMult ), topOfBall); scope.cooldown = Date.now(); this.launchMult = 1; } }; function onKeyDown( event ) { event = event || window.event; keyState[event.keyCode || event.which] = true; } function onKeyUp( event ) { event = event || window.event; keyState[event.keyCode || event.which] = false; } this.domElement.addEventListener('contextmenu', function( event ) { event.preventDefault(); }, false ); this.domElement.addEventListener('keydown', onKeyDown, false ); this.domElement.addEventListener('keyup', onKeyUp, false ); }; THREE.PlayerControls.prototype = Object.create( THREE.EventDispatcher.prototype );
logarithmic launch charge replaces linear launch charge
browser/game/PlayerControls.js
logarithmic launch charge replaces linear launch charge
<ide><path>rowser/game/PlayerControls.js <ide> <ide> this.speedMult = 1; <ide> this.launchMult = 1; <del> <add> this.i = 1; <ide> // helpful dev tool, yo <ide> // var geometry = new THREE.BoxGeometry( 30,3,2 ); <ide> // var material = new THREE.MeshPhongMaterial({ <ide> //cameraReferenceOrientation.copy(cameraReferenceOrientationObj.quaternion); <ide> <ide> //console.log(store.getState().abilities && ) <del> if(!store.getState().abilities.launch && Date.now() - scope.cooldown > 5000){ <add> if(!store.getState().abilities.launch && Date.now() - scope.cooldown > 12000){ <ide> // console.log("launchReady") <ide> store.dispatch(launchReady()); <ide> } <ide> //cross2.addScalar(20 + Math.pow(this.scale, 3)); <ide> <ide> <del> <add> <ide> if (keyState[32]) { <ide> if(store.getState().abilities.launch){ <del> if(this.launchMult < 6) this.launchMult += 0.04; <add> if(this.launchMult < 6) this.launchMult += 1/(this.i++ * 1.1); <ide> <ide> var buildLaunch = ~~(this.launchMult * 3 - 3); <ide> //console.log(buildLaunch) <ide> scope.cooldown = Date.now(); <ide> <ide> this.launchMult = 1; <add> this.i = 1; <ide> } <ide> }; <ide>
Java
lgpl-2.1
b1eab87a2f1f9bc95f5f91db0b676011f36321c9
0
4ment/beast-mcmc,beast-dev/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,4ment/beast-mcmc,adamallo/beast-mcmc,4ment/beast-mcmc,4ment/beast-mcmc,maxbiostat/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,beast-dev/beast-mcmc,beast-dev/beast-mcmc,4ment/beast-mcmc,adamallo/beast-mcmc,adamallo/beast-mcmc,maxbiostat/beast-mcmc,adamallo/beast-mcmc,maxbiostat/beast-mcmc,4ment/beast-mcmc,maxbiostat/beast-mcmc,beast-dev/beast-mcmc,maxbiostat/beast-mcmc,maxbiostat/beast-mcmc
/* * PartitionParser.java * * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST 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 * of the License, or (at your option) any later version. * * BEAST 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 BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.app.beagle.tools.parsers; import dr.evomodel.branchmodel.BranchModel; import dr.evomodel.branchmodel.HomogeneousBranchModel; import dr.evomodel.siteratemodel.GammaSiteRateModel; import dr.evomodel.substmodel.FrequencyModel; import dr.evomodel.substmodel.SubstitutionModel; import dr.app.beagle.tools.Partition; import dr.evolution.sequence.Sequence; import dr.evolution.datatype.DataType; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.branchratemodel.DefaultBranchRateModel; import dr.evomodel.tree.TreeModel; import dr.evoxml.util.DataTypeUtils; import dr.xml.AbstractXMLObjectParser; import dr.xml.AttributeRule; import dr.xml.ElementRule; import dr.xml.XMLObject; import dr.xml.XMLParseException; import dr.xml.XMLSyntaxRule; import dr.xml.XORRule; import java.util.ArrayList; import java.util.List; /** * @author Filip Bielejec * @version $Id$ */ public class PartitionParser extends AbstractXMLObjectParser { public static final String PARTITION = "partition"; public static final String FROM = "from"; public static final String TO = "to"; public static final String EVERY = "every"; public static final String DATA_TYPE = "dataType"; @Override public String getParserName() { return PARTITION; } @Override public String getParserDescription() { return "Partition element"; } @Override public Class<Partition> getReturnType() { return Partition.class; } @Override public Object parseXMLObject(XMLObject xo) throws XMLParseException { int from = 0; int to = -1; int every = xo.getAttribute(EVERY, 1); DataType dataType = null; if (xo.hasAttribute(FROM)) { from = xo.getIntegerAttribute(FROM) - 1; if (from < 0) { throw new XMLParseException( "Illegal 'from' attribute in patterns element"); } }// END: from check if (xo.hasAttribute(TO)) { to = xo.getIntegerAttribute(TO) - 1; if (to < 0 || to < from) { throw new XMLParseException( "Illegal 'to' attribute in patterns element"); } }// END: to check if (every <= 0) { throw new XMLParseException( "Illegal 'every' attribute in patterns element"); }// END: every check if (xo.hasAttribute(DATA_TYPE)){ dataType = DataTypeUtils.getDataType(xo); } TreeModel tree = (TreeModel) xo.getChild(TreeModel.class); GammaSiteRateModel siteModel = (GammaSiteRateModel) xo.getChild(GammaSiteRateModel.class); //FrequencyModel freqModel = (FrequencyModel) xo.getChild(FrequencyModel.class); FrequencyModel freqModel; List<FrequencyModel> freqModels = new ArrayList<FrequencyModel>(); for (int i = 0; i < xo.getChildCount(); i++) { Object cxo = xo.getChild(i); if (cxo instanceof FrequencyModel) { freqModels.add((FrequencyModel) cxo); } } if(freqModels.size()==1){ freqModel = freqModels.get(0); }else{ double [] freqParameter = new double[freqModels.size()*freqModels.get(0).getFrequencyCount()]; int index = 0; for(int i = 0; i < freqModels.size(); i++){ for(int j = 0; j < freqModels.get(i).getFrequencyCount(); j++){ freqParameter[index] = (freqModels.get(i).getFrequency(j))/freqModels.size(); index++; } } freqModel = new FrequencyModel(dataType, freqParameter); } Sequence rootSequence = (Sequence) xo.getChild(Sequence.class); BranchRateModel rateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); if (rateModel == null) { rateModel = new DefaultBranchRateModel(); } BranchModel branchModel = (BranchModel) xo.getChild(BranchModel.class); if (branchModel == null) { SubstitutionModel substitutionModel = (SubstitutionModel) xo.getChild(SubstitutionModel.class); branchModel = new HomogeneousBranchModel(substitutionModel); } Partition partition = new Partition(tree, branchModel, siteModel, rateModel, freqModel, from, to, every, dataType); if (rootSequence != null) { partition.setRootSequence(rootSequence); }// END: ancestralSequence check return partition; }//END: parseXMLObject @Override public XMLSyntaxRule[] getSyntaxRules() { return new XMLSyntaxRule[] { AttributeRule.newIntegerRule(FROM, true, "The site position to start at, default is 1 (the first position)"), // AttributeRule.newIntegerRule(TO, true, "The site position to finish at, must be greater than <b>" + FROM + "</b>, default is number of sites"), // AttributeRule.newIntegerRule( EVERY, true, "Determines how many sites are selected. A value of 3 will select every third site starting from <b>" + FROM + "</b>, default is 1 (every site)"), // AttributeRule.newStringRule(DataType.DATA_TYPE, true), new ElementRule(TreeModel.class), // new XORRule(new ElementRule(BranchModel.class), new ElementRule(SubstitutionModel.class), false), // new ElementRule(GammaSiteRateModel.class), // new ElementRule(BranchRateModel.class, true), // new ElementRule(FrequencyModel.class, 1, Integer.MAX_VALUE), // new ElementRule(Sequence.class, true) // }; }// END: getSyntaxRules }// END: class
src/dr/app/beagle/tools/parsers/PartitionParser.java
/* * PartitionParser.java * * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST 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 * of the License, or (at your option) any later version. * * BEAST 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 BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.app.beagle.tools.parsers; import dr.evomodel.branchmodel.BranchModel; import dr.evomodel.branchmodel.HomogeneousBranchModel; import dr.evomodel.siteratemodel.GammaSiteRateModel; import dr.evomodel.substmodel.FrequencyModel; import dr.evomodel.substmodel.SubstitutionModel; import dr.app.beagle.tools.Partition; import dr.evolution.sequence.Sequence; import dr.evolution.datatype.DataType; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.branchratemodel.DefaultBranchRateModel; import dr.evomodel.tree.TreeModel; import dr.evoxml.util.DataTypeUtils; import dr.xml.AbstractXMLObjectParser; import dr.xml.AttributeRule; import dr.xml.ElementRule; import dr.xml.XMLObject; import dr.xml.XMLParseException; import dr.xml.XMLSyntaxRule; import dr.xml.XORRule; import java.util.ArrayList; import java.util.List; /** * @author Filip Bielejec * @version $Id$ */ public class PartitionParser extends AbstractXMLObjectParser { public static final String PARTITION = "partition"; public static final String FROM = "from"; public static final String TO = "to"; public static final String EVERY = "every"; public static final String DATA_TYPE = "dataType"; @Override public String getParserName() { return PARTITION; } @Override public String getParserDescription() { return "Partition element"; } @Override public Class<Partition> getReturnType() { return Partition.class; } @Override public Object parseXMLObject(XMLObject xo) throws XMLParseException { int from = 0; int to = -1; int every = xo.getAttribute(EVERY, 1); DataType dataType = null; if (xo.hasAttribute(FROM)) { from = xo.getIntegerAttribute(FROM) - 1; if (from < 0) { throw new XMLParseException( "Illegal 'from' attribute in patterns element"); } }// END: from check if (xo.hasAttribute(TO)) { to = xo.getIntegerAttribute(TO) - 1; if (to < 0 || to < from) { throw new XMLParseException( "Illegal 'to' attribute in patterns element"); } }// END: to check if (every <= 0) { throw new XMLParseException( "Illegal 'every' attribute in patterns element"); }// END: every check if (xo.hasAttribute(DATA_TYPE)){ dataType = DataTypeUtils.getDataType(xo); } TreeModel tree = (TreeModel) xo.getChild(TreeModel.class); GammaSiteRateModel siteModel = (GammaSiteRateModel) xo.getChild(GammaSiteRateModel.class); //FrequencyModel freqModel = (FrequencyModel) xo.getChild(FrequencyModel.class); FrequencyModel freqModel; List<FrequencyModel> freqModels = new ArrayList<>(); for (int i = 0; i < xo.getChildCount(); i++) { Object cxo = xo.getChild(i); if (cxo instanceof FrequencyModel) { freqModels.add((FrequencyModel) cxo); } } if(freqModels.size()==1){ freqModel = freqModels.get(0); }else{ double [] freqParameter = new double[freqModels.size()*freqModels.get(0).getFrequencyCount()]; int index = 0; for(int i = 0; i < freqModels.size(); i++){ for(int j = 0; j < freqModels.get(i).getFrequencyCount(); j++){ freqParameter[index] = (freqModels.get(i).getFrequency(j))/freqModels.size(); index++; } } freqModel = new FrequencyModel(dataType, freqParameter); } Sequence rootSequence = (Sequence) xo.getChild(Sequence.class); BranchRateModel rateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); if (rateModel == null) { rateModel = new DefaultBranchRateModel(); } BranchModel branchModel = (BranchModel) xo.getChild(BranchModel.class); if (branchModel == null) { SubstitutionModel substitutionModel = (SubstitutionModel) xo.getChild(SubstitutionModel.class); branchModel = new HomogeneousBranchModel(substitutionModel); } Partition partition = new Partition(tree, branchModel, siteModel, rateModel, freqModel, from, to, every, dataType); if (rootSequence != null) { partition.setRootSequence(rootSequence); }// END: ancestralSequence check return partition; }//END: parseXMLObject @Override public XMLSyntaxRule[] getSyntaxRules() { return new XMLSyntaxRule[] { AttributeRule.newIntegerRule(FROM, true, "The site position to start at, default is 1 (the first position)"), // AttributeRule.newIntegerRule(TO, true, "The site position to finish at, must be greater than <b>" + FROM + "</b>, default is number of sites"), // AttributeRule.newIntegerRule( EVERY, true, "Determines how many sites are selected. A value of 3 will select every third site starting from <b>" + FROM + "</b>, default is 1 (every site)"), // AttributeRule.newStringRule(DataType.DATA_TYPE, true), new ElementRule(TreeModel.class), // new XORRule(new ElementRule(BranchModel.class), new ElementRule(SubstitutionModel.class), false), // new ElementRule(GammaSiteRateModel.class), // new ElementRule(BranchRateModel.class, true), // new ElementRule(FrequencyModel.class, 1, Integer.MAX_VALUE), // new ElementRule(Sequence.class, true) // }; }// END: getSyntaxRules }// END: class
Change to avoid diamond operator
src/dr/app/beagle/tools/parsers/PartitionParser.java
Change to avoid diamond operator
<ide><path>rc/dr/app/beagle/tools/parsers/PartitionParser.java <ide> <ide> FrequencyModel freqModel; <ide> <del> List<FrequencyModel> freqModels = new ArrayList<>(); <add> List<FrequencyModel> freqModels = new ArrayList<FrequencyModel>(); <ide> for (int i = 0; i < xo.getChildCount(); i++) { <ide> Object cxo = xo.getChild(i); <ide> if (cxo instanceof FrequencyModel) {
Java
apache-2.0
3503f575a771a306870472050ff77a3597a45225
0
kylycht/concourse,cinchapi/concourse,remiemalik/concourse,vrnithinkumar/concourse,vrnithinkumar/concourse,kylycht/concourse,hcuffy/concourse,dubex/concourse,dubex/concourse,remiemalik/concourse,remiemalik/concourse,vrnithinkumar/concourse,dubex/concourse,hcuffy/concourse,JerJohn15/concourse,cinchapi/concourse,JerJohn15/concourse,JerJohn15/concourse,vrnithinkumar/concourse,remiemalik/concourse,hcuffy/concourse,kylycht/concourse,dubex/concourse,JerJohn15/concourse,cinchapi/concourse,remiemalik/concourse,cinchapi/concourse,hcuffy/concourse,cinchapi/concourse,hcuffy/concourse,kylycht/concourse,cinchapi/concourse,hcuffy/concourse,dubex/concourse,JerJohn15/concourse,vrnithinkumar/concourse,JerJohn15/concourse,kylycht/concourse,kylycht/concourse,vrnithinkumar/concourse,dubex/concourse,remiemalik/concourse
/* * Copyright (c) 2015 Cinchapi, 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.cinchapi.concourse.server; import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.ServerSocket; import java.net.SocketException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.MessageFormat; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import jline.TerminalFactory; import com.cinchapi.concourse.Concourse; import com.cinchapi.concourse.DuplicateEntryException; import com.cinchapi.concourse.Timestamp; import com.cinchapi.concourse.config.ConcourseServerPreferences; import com.cinchapi.concourse.lang.Criteria; import com.cinchapi.concourse.lang.Symbol; import com.cinchapi.concourse.thrift.Diff; import com.cinchapi.concourse.thrift.Operator; import com.cinchapi.concourse.time.Time; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Level; import com.cinchapi.concourse.util.ConcourseServerDownloader; import com.cinchapi.concourse.util.Processes; import com.google.common.base.Stopwatch; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; /** * A {@link ManagedConcourseServer} is an external server process that can be * programmatically controlled within another application. This class is useful * for applications that want to "embed" a Concourse Server for the duration of * the application's life cycle and then forget about its existence afterwards. * * @author jnelson */ public class ManagedConcourseServer { /** * Give the path to a local concourse {@code repo}, build an installer and * return the path to the installer. * * @param repo * @return the installer path */ public static String buildInstallerFromRepo(String repo) { try { Process p; p = new ProcessBuilder("bash", "gradlew", "clean", "installer") .directory(new File(repo)).start(); Processes.waitForSuccessfulCompletion(p); p = new ProcessBuilder("ls", repo + "/concourse-server/build/distributions").start(); Processes.waitForSuccessfulCompletion(p); String installer = Processes.getStdOut(p).get(0); installer = repo + "/concourse-server/build/distributions/" + installer; return installer; } catch (Exception e) { throw Throwables.propagate(e); } } /** * Return an {@link ManagedConcourseServer} that controls an instance * located in the {@code installDirectory}. * * @param installDirectory * @return the ManagedConcourseServer */ public static ManagedConcourseServer manageExistingServer( String installDirectory) { return new ManagedConcourseServer(installDirectory); } /** * Create an {@link ManagedConcourseServer from the {@code installer}. * * @param installer * @return the ManagedConcourseServer */ public static ManagedConcourseServer manageNewServer(File installer) { return manageNewServer(installer, DEFAULT_INSTALL_HOME + File.separator + Time.now()); } /** * Create an {@link ManagedConcourseServer} from the {@code installer} in * {@code directory}. * * @param installer * @param directory * @return the EmbeddedConcourseServer */ public static ManagedConcourseServer manageNewServer(File installer, String directory) { return new ManagedConcourseServer(install(installer.getAbsolutePath(), directory)); } /** * Create an {@link ManagedConcourseServer} at {@code version}. * * @param version * @return the ManagedConcourseServer */ public static ManagedConcourseServer manageNewServer(String version) { return manageNewServer(version, DEFAULT_INSTALL_HOME + File.separator + Time.now()); } /** * Create an {@link ManagedConcourseServer} at {@code version} in * {@code directory}. * * @param version * @param directory * @return the ManagedConcourseServer */ public static ManagedConcourseServer manageNewServer(String version, String directory) { return manageNewServer( new File(ConcourseServerDownloader.download(version)), directory); } /** * Tweak some of the preferences to make this more palatable for testing * (i.e. reduce the possibility of port conflicts, etc). * * @param installDirectory */ private static void configure(String installDirectory) { ConcourseServerPreferences prefs = ConcourseServerPreferences .open(installDirectory + File.separator + CONF + File.separator + "concourse.prefs"); String data = installDirectory + File.separator + "data"; prefs.setBufferDirectory(data + File.separator + "buffer"); prefs.setDatabaseDirectory(data + File.separator + "database"); prefs.setClientPort(getOpenPort()); prefs.setJmxPort(getOpenPort()); prefs.setLogLevel(Level.DEBUG); prefs.setShutdownPort(getOpenPort()); } /** * Collect and return all the {@code jar} files that are located in the * directory at {@code path}. If {@code path} is not a directory, but is * instead, itself, a jar file, then return a list that contains in. * * @param path * @return the list of jar file URL paths */ private static URL[] gatherJars(String path) { List<URL> jars = Lists.newArrayList(); gatherJars(path, jars); return jars.toArray(new URL[] {}); } /** * Collect all the {@code jar} files that are located in the directory at * {@code path} and place them into the list of {@code jars}. If * {@code path} is not a directory, but is instead, itself a jar file, then * place it in the list. * * @param path * @param jars */ private static void gatherJars(String path, List<URL> jars) { try { if(Files.isDirectory(Paths.get(path))) { for (Path p : Files.newDirectoryStream(Paths.get(path))) { gatherJars(p.toString(), jars); } } else if(path.endsWith(".jar")) { jars.add(new URL("file://" + path.toString())); } } catch (IOException e) { throw Throwables.propagate(e); } } /** * Get an open port. * * @return the port */ private static int getOpenPort() { int min = 49512; int max = 65535; int port = RAND.nextInt(min) + (max - min); return isPortAvailable(port) ? port : getOpenPort(); } /** * Install a Concourse Server in {@code directory} using {@code installer}. * * @param installer * @param directory * @return the server install directory */ private static String install(String installer, String directory) { try { Files.createDirectories(Paths.get(directory)); Path binary = Paths.get(directory + File.separator + TARGET_BINARY_NAME); Files.deleteIfExists(binary); Files.copy(Paths.get(installer), binary); ProcessBuilder builder = new ProcessBuilder(Lists.newArrayList( "sh", binary.toString())); builder.directory(new File(directory)); builder.redirectErrorStream(); Process process = builder.start(); // The concourse-server installer prompts for an admin password in // order to make optional system wide In order to get around this // prompt, we have to "kill" the process, otherwise the server // install will hang. Stopwatch watch = Stopwatch.createStarted(); while (watch.elapsed(TimeUnit.SECONDS) < 1) { continue; } watch.stop(); process.destroy(); TerminalFactory.get().restore(); String application = directory + File.separator + "concourse-server"; // the install directory for the // concourse-server application process = Runtime.getRuntime().exec("ls " + application); List<String> output = Processes.getStdOut(process); if(!output.isEmpty()) { configure(application); log.info("Successfully installed server in {}", application); return application; } else { throw new RuntimeException( MessageFormat .format("Unsuccesful attempt to " + "install server at {0} " + "using binary from {1}", directory, installer)); } } catch (Exception e) { throw Throwables.propagate(e); } } /** * Return {@code true} if the {@code port} is available on the local * machine. * * @param port * @return {@code true} if the port is available */ private static boolean isPortAvailable(int port) { try { new ServerSocket(port).close(); return true; } catch (SocketException e) { return false; } catch (IOException e) { throw Throwables.propagate(e); } } private static final String BIN = "bin"; // ---relative paths private static final String CONF = "conf"; /** * The default location where the the test server is installed if a * particular location is not specified. */ private static final String DEFAULT_INSTALL_HOME = System .getProperty("user.home") + File.separator + ".concourse-testing"; // ---logger private static final Logger log = LoggerFactory .getLogger(ManagedConcourseServer.class); // ---random private static final Random RAND = new Random(); /** * The filename of the binary installer from which the test server will be * created. */ private static final String TARGET_BINARY_NAME = "concourse-server.bin"; /** * The server application install directory; */ private final String installDirectory; /** * A connection to the remote MBean server running in the managed * concourse-server process. */ private MBeanServerConnection mBeanServerConnection = null; /** * The handler for the server's preferences. */ private final ConcourseServerPreferences prefs; /** * Construct a new instance. * * @param installDirectory */ private ManagedConcourseServer(String installDirectory) { this.installDirectory = installDirectory; this.prefs = ConcourseServerPreferences.open(installDirectory + File.separator + CONF + File.separator + "concourse.prefs"); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { destroy(); } })); } /** * Return a connection handler to the server using the default "admin" * credentials. * * @return the connection handler */ public Concourse connect() { return connect("admin", "admin"); } /** * Return a connection handler to the server using the specified * {@code username} and {@code password}. * * @param username * @param password * @return the connection handler */ public Concourse connect(String username, String password) { return new Client(username, password); } /** * Stop the server, if it is running, and permanently delete the application * files and associated data. */ public void destroy() { if(Files.exists(Paths.get(installDirectory))) { // check if server has // been manually // destroyed if(isRunning()) { stop(); } try { deleteDirectory(Paths.get(installDirectory).getParent() .toString()); log.info("Deleted server install directory at {}", installDirectory); } catch (Exception e) { throw Throwables.propagate(e); } } } /** * Return the client port for this server. * * @return the client port */ public int getClientPort() { return prefs.getClientPort(); } /** * Get a collection of stats about the heap memory usage for the managed * concourse-server process. * * @return the heap memory usage */ public MemoryUsage getHeapMemoryStats() { try { MemoryMXBean memory = ManagementFactory.newPlatformMXBeanProxy( getMBeanServerConnection(), ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class); return memory.getHeapMemoryUsage(); } catch (Exception e) { throw Throwables.propagate(e); } } /** * Return the {@link #installDirectory} for this server. * * @return the install directory */ public String getInstallDirectory() { return installDirectory; } /** * Return the connection to the MBean sever of the managed concourse-server * process. * * @return the mbean server connection */ public MBeanServerConnection getMBeanServerConnection() { if(mBeanServerConnection == null) { try { JMXServiceURL url = new JMXServiceURL( "service:jmx:rmi:///jndi/rmi://localhost:" + prefs.getJmxPort() + "/jmxrmi"); JMXConnector connector = JMXConnectorFactory.connect(url); mBeanServerConnection = connector.getMBeanServerConnection(); } catch (Exception e) { throw Throwables.propagate(e); } } return mBeanServerConnection; } /** * Get a collection of stats about the non heap memory usage for the managed * concourse-server process. * * @return the non-heap memory usage */ public MemoryUsage getNonHeapMemoryStats() { try { MemoryMXBean memory = ManagementFactory.newPlatformMXBeanProxy( getMBeanServerConnection(), ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class); return memory.getNonHeapMemoryUsage(); } catch (Exception e) { throw Throwables.propagate(e); } } /** * Return {@code true} if the server is currently running. * * @return {@code true} if the server is running */ public boolean isRunning() { return Iterables.get(execute("concourse", "status"), 0).contains( "is running"); } /** * Start the server. */ public void start() { try { for (String line : execute("start")) { log.info(line); } } catch (Exception e) { throw Throwables.propagate(e); } } /** * Stop the server. */ public void stop() { try { for (String line : execute("stop")) { log.info(line); } } catch (Exception e) { throw Throwables.propagate(e); } } /** * Recursively delete a directory and all of its contents. * * @param directory */ private void deleteDirectory(String directory) { try { File dir = new File(directory); for (File file : dir.listFiles()) { if(file.isDirectory()) { deleteDirectory(file.getAbsolutePath()); } else { file.delete(); } } dir.delete(); } catch (Exception e) { throw Throwables.propagate(e); } } /** * Execute a command line interface script and return the output. * * @param cli * @param args * @return the script output */ private List<String> execute(String cli, String... args) { try { String command = "sh " + cli; for (String arg : args) { command += " " + arg; } Process process = Runtime.getRuntime().exec(command, null, new File(installDirectory + File.separator + BIN)); return Processes.getStdOut(process); } catch (Exception e) { throw Throwables.propagate(e); } } /** * A class that extends {@link Concourse} with additional methods. This * abstraction allows casting while keeping the {@link Client} class * private. * * @author Jeff Nelson */ public abstract class ReflectiveClient extends Concourse { /** * Reflectively call a client method. This is useful for cases where * this API depends on an older version of the Concourse API and a test * needs to use a method added in a later version. This procedure will * work because the underlying client delegates to a client that uses * the classpath of the managed server. * * @param methodName * @param args * @return the result */ public abstract <T> T call(String methodName, Object... args); } /** * A {@link Concourse} client wrapper that delegates to the jars located in * the server's lib directory so that it uses the same version of the code. * * @author jnelson */ private final class Client extends ReflectiveClient { private Class<?> clazz; private final Object delegate; private ClassLoader loader; /** * The top level package under which all Concourse classes exist in the * remote server. */ private String packageBase = "com.cinchapi.concourse."; /** * Construct a new instance. * * @param username * @param password * @throws Exception */ public Client(String username, String password) { try { this.loader = new URLClassLoader( gatherJars(getInstallDirectory()), null); try { clazz = loader.loadClass(packageBase + "Concourse"); } catch (ClassNotFoundException e) { // Prior to version 0.5.0, Concourse classes were located in // the "org.cinchapi.concourse" package, so we attempt to // use that if the default does not work. packageBase = "org.cinchapi.concourse."; clazz = loader.loadClass(packageBase + "Concourse"); } this.delegate = clazz.getMethod("connect", String.class, int.class, String.class, String.class).invoke(null, "localhost", getClientPort(), username, password); } catch (Exception e) { throw Throwables.propagate(e); } } @Override public void abort() { invoke("abort").with(); } @Override public <T> Map<Long, Boolean> add(String key, T value, Collection<Long> records) { return invoke("add", String.class, Object.class, Collection.class) .with(key, value, records); } @Override public <T> long add(String key, T value) { return invoke("add", String.class, Object.class).with(key, value); } @Override public <T> boolean add(String key, T value, long record) { return invoke("add", String.class, Object.class, long.class).with( key, value, record); } @Override public Map<Timestamp, String> audit(long record) { return invoke("audit", long.class).with(record); } @Override public Map<Timestamp, String> audit(long record, Timestamp start) { return invoke("audit", long.class, Timestamp.class).with(record, start); } @Override public Map<Timestamp, String> audit(long record, Timestamp start, Timestamp end) { return invoke("audit", long.class, Timestamp.class, Timestamp.class) .with(start, end); } @Override public Map<Timestamp, String> audit(String key, long record) { return invoke("audit", String.class, long.class).with(key, record); } @Override public Map<Timestamp, String> audit(String key, long record, Timestamp start) { return invoke("audit", String.class, long.class, Timestamp.class) .with(key, record, start); } @Override public Map<Timestamp, String> audit(String key, long record, Timestamp start, Timestamp end) { return invoke("audit", String.class, long.class, Timestamp.class, Timestamp.class).with(key, record, start, end); } @Override public Map<String, Map<Object, Set<Long>>> browse( Collection<String> keys) { return invoke("browse", Collection.class, Object.class).with(keys); } @Override public Map<String, Map<Object, Set<Long>>> browse( Collection<String> keys, Timestamp timestamp) { return invoke("browse", Collection.class, Timestamp.class).with( keys, timestamp); } @Override public Map<Object, Set<Long>> browse(String key) { return invoke("browse", String.class).with(key); } @Override public Map<Object, Set<Long>> browse(String key, Timestamp timestamp) { return invoke("browse", String.class, Timestamp.class).with(key, timestamp); } @Override public <T> T call(String methodName, Object... args) { Class<?>[] classes = new Class<?>[args.length]; for (int i = 0; i < classes.length; ++i) { classes[i] = args[i].getClass(); } return invoke(methodName, classes).with(args); } @Override public Map<Timestamp, Set<Object>> chronologize(String key, long record) { return invoke("chronologize", String.class, long.class).with(key, record); } @Override public Map<Timestamp, Set<Object>> chronologize(String key, long record, Timestamp start) { return invoke("chronologize", String.class, long.class, Timestamp.class).with(key, record, start); } @Override public Map<Timestamp, Set<Object>> chronologize(String key, long record, Timestamp start, Timestamp end) { return invoke("chronologize", String.class, long.class, Timestamp.class, Timestamp.class).with(key, record, start, end); } @Override public void clear(Collection<Long> records) { invoke("clear", Collection.class).with(records); } @Override public void clear(Collection<String> keys, Collection<Long> records) { invoke("clear", Collection.class, Collection.class).with(keys, records); } @Override public void clear(Collection<String> keys, long record) { invoke("clear", Collection.class, long.class).with(keys, record); } @Override public void clear(long record) { invoke("clear", long.class).with(record); } @Override public void clear(String key, Collection<Long> records) { invoke("clear", String.class, Collection.class).with(key, records); } @Override public void clear(String key, long record) { invoke("clear", String.class, long.class).with(key, record); } @Override public boolean commit() { return invoke("commit").with(); } @Override public long create() { return invoke("create").with(); } @Override public Map<Long, Set<String>> describe(Collection<Long> records) { return invoke("describe", Collection.class).with(records); } @Override public Map<Long, Set<String>> describe(Collection<Long> records, Timestamp timestamp) { return invoke("describe", Collection.class, Timestamp.class).with( records, timestamp); } @Override public Set<String> describe(long record) { return invoke("describe", long.class).with(record); } @Override public Set<String> describe(long record, Timestamp timestamp) { return invoke("describe", long.class, Timestamp.class).with(record, timestamp); } @Override public <T> Map<String, Map<Diff, Set<T>>> diff(long record, Timestamp start) { return invoke("diff", long.class, Timestamp.class).with(record, start); } @Override public <T> Map<String, Map<Diff, Set<T>>> diff(long record, Timestamp start, Timestamp end) { return invoke("diff", long.class, Timestamp.class, Timestamp.class) .with(record, start, end); } @Override public <T> Map<Diff, Set<T>> diff(String key, long record, Timestamp start) { return invoke("diff", String.class, long.class, Timestamp.class) .with(record, start); } @Override public <T> Map<Diff, Set<T>> diff(String key, long record, Timestamp start, Timestamp end) { return invoke("diff", String.class, long.class, Timestamp.class, Timestamp.class).with(key, record, start, end); } @Override public <T> Map<T, Map<Diff, Set<Long>>> diff(String key, Timestamp start) { return invoke("diff", String.class, Timestamp.class).with(key, start); } @Override public <T> Map<T, Map<Diff, Set<Long>>> diff(String key, Timestamp start, Timestamp end) { return invoke("diff", String.class, Timestamp.class).with(key, start); } @Override public void exit() { invoke("exit").with(); } @Override public Set<Long> find(Criteria criteria) { return invoke("find", Criteria.class).with(criteria); } @Override public Set<Long> find(Object criteria) { return invoke("find", Object.class).with(criteria); } @Override public Set<Long> find(String ccl) { return invoke("find", String.class, Object.class).with(ccl); } @Override public Set<Long> find(String key, Object value) { return invoke("find", String.class, Object.class).with(key, value); } @Override public Set<Long> find(String key, Operator operator, Object value) { return invoke("find", String.class, Operator.class, Object.class) .with(key, operator, value); } @Override public Set<Long> find(String key, Operator operator, Object value, Object value2) { return invoke("find", String.class, Operator.class, Object.class, Object.class).with(key, operator, value, value2); } @Override public Set<Long> find(String key, Operator operator, Object value, Object value2, Timestamp timestamp) { return invoke("find", String.class, Operator.class, Object.class, Object.class, Timestamp.class).with(key, operator, value, value2); } @Override public Set<Long> find(String key, Operator operator, Object value, Timestamp timestamp) { return invoke("find", String.class, Operator.class, Object.class, Timestamp.class).with(key, operator, value, timestamp); } @Override public Set<Long> find(String key, String operator, Object value) { return invoke("find", String.class, String.class, Object.class) .with(key, operator, value); } @Override public Set<Long> find(String key, String operator, Object value, Object value2) { return invoke("find", String.class, String.class, Object.class, Object.class).with(key, operator, value, value2); } @Override public Set<Long> find(String key, String operator, Object value, Object value2, Timestamp timestamp) { return invoke("find", String.class, String.class, Object.class, Object.class, Timestamp.class).with(key, operator, value, value2, timestamp); } @Override public Set<Long> find(String key, String operator, Object value, Timestamp timestamp) { return invoke("find", String.class, String.class, Object.class, Timestamp.class).with(key, operator, value, timestamp); } @Override public <T> long findOrAdd(String key, T value) throws DuplicateEntryException { return invoke("findOrAdd", String.class, Object.class).with(key, value); } @Override public long findOrInsert(Criteria criteria, String json) throws DuplicateEntryException { return invoke("findOrInsert", Criteria.class, String.class).with( criteria, json); } @Override public long findOrInsert(String ccl, String json) throws DuplicateEntryException { return invoke("findOrInsert", String.class, String.class).with(ccl, json); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, Collection<Long> records) { return invoke("get", Collection.class, Collection.class).with(keys, records); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, Collection<Long> records, Timestamp timestamp) { return invoke("get", Collection.class, Collection.class, Timestamp.class).with(keys, records, timestamp); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, Criteria criteria) { return invoke("get", Collection.class, Criteria.class).with(keys, criteria); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, Criteria criteria, Timestamp timestamp) { return invoke("get", Collection.class, Criteria.class, Timestamp.class).with(keys, criteria, timestamp); } @Override public <T> Map<String, T> get(Collection<String> keys, long record) { return invoke("get", String.class, long.class).with(keys, record); } @Override public <T> Map<String, T> get(Collection<String> keys, long record, Timestamp timestamp) { return invoke("get", Collection.class, long.class, Timestamp.class) .with(keys, record, timestamp); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, Object criteria) { return invoke("get", Collection.class, Object.class).with(keys, criteria); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, Object criteria, Timestamp timestamp) { return invoke("get", Collection.class, Object.class, Timestamp.class).with(keys, criteria, timestamp); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, String ccl) { return invoke("get", Collection.class, String.class) .with(keys, ccl); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, String ccl, Timestamp timestamp) { return invoke("get", Collection.class, String.class, Timestamp.class).with(keys, ccl, timestamp); } @Override public <T> Map<Long, Map<String, T>> get(Criteria criteria) { return invoke("get", Criteria.class).with(criteria); } @Override public <T> Map<Long, Map<String, T>> get(Criteria criteria, Timestamp timestamp) { return invoke("get", Criteria.class, Timestamp.class).with( criteria, timestamp); } @Override public <T> Map<Long, Map<String, T>> get(Object criteria) { return invoke("get", Object.class).with(criteria); } @Override public <T> Map<Long, Map<String, T>> get(Object criteria, Timestamp timestamp) { return invoke("get", Object.class, Timestamp.class).with(criteria, timestamp); } @Override public <T> Map<Long, Map<String, T>> get(String ccl) { return invoke("get", String.class).with(ccl); } @Override public <T> Map<Long, T> get(String key, Collection<Long> records) { return invoke("get", String.class, Collection.class).with(key, records); } @Override public <T> Map<Long, T> get(String key, Collection<Long> records, Timestamp timestamp) { return invoke("get", String.class, Collection.class, Timestamp.class).with(key, records, timestamp); } @Override public <T> Map<Long, T> get(String key, Criteria criteria) { return invoke("get", String.class, Criteria.class).with(key, criteria); } @Override public <T> Map<Long, T> get(String key, Criteria criteria, Timestamp timestamp) { return invoke("get", String.class, Criteria.class, Timestamp.class) .with(key, criteria, timestamp); } @Override public <T> T get(String key, long record) { return invoke("get", String.class, long.class).with(key, record); } @Override public <T> T get(String key, long record, Timestamp timestamp) { return invoke("get", String.class, long.class, Timestamp.class) .with(key, record, timestamp); } @Override public <T> Map<Long, T> get(String key, Object criteria) { return invoke("find", String.class, Object.class).with(key, criteria); } @Override public <T> Map<Long, T> get(String key, Object criteria, Timestamp timestamp) { return invoke("get", String.class, Object.class, Timestamp.class) .with(key, criteria, timestamp); } @Override public <T> Map<Long, T> get(String key, String ccl) { return invoke("find", String.class, String.class).with(key, ccl); } @Override public <T> Map<Long, T> get(String key, String ccl, Timestamp timestamp) { return invoke("find", String.class, String.class, Timestamp.class) .with(key, ccl, timestamp); } @Override public <T> Map<Long, Map<String, T>> get(String ccl, Timestamp timestamp) { return invoke("get", String.class, Timestamp.class).with(ccl, timestamp); } @Override public String getServerEnvironment() { return invoke("getServerEnvironment").with(); } @Override public String getServerVersion() { return invoke("getServerVersion").with(); } @Override public Set<Long> insert(String json) { return invoke("insert", String.class).with(json); } @Override public Map<Long, Boolean> insert(String json, Collection<Long> records) { return invoke("insert", String.class, Collection.class).with(json, records); } @Override public boolean insert(String json, long record) { return invoke("insert", String.class, long.class) .with(json, record); } @Override public Set<Long> inventory() { return invoke("inventory").with(); } @Override public String jsonify(Collection<Long> records) { return invoke("jsonify", Collection.class).with(records); } @Override public String jsonify(Collection<Long> records, boolean identifier) { return invoke("jsonify", Collection.class, boolean.class).with( records, identifier); } @Override public String jsonify(Collection<Long> records, Timestamp timestamp) { return invoke("jsonify", Collection.class, Timestamp.class).with( records, timestamp); } @Override public String jsonify(Collection<Long> records, Timestamp timestamp, boolean identifier) { return invoke("jsonify", Collection.class, Timestamp.class, boolean.class).with(records, timestamp, identifier); } @Override public String jsonify(long record) { return invoke("jsonify", long.class).with(record); } @Override public String jsonify(long record, boolean identifier) { return invoke("jsonify", long.class, boolean.class).with(record, identifier); } @Override public String jsonify(long record, Timestamp timestamp) { return invoke("jsonify", long.class, Timestamp.class).with(record, timestamp); } @Override public String jsonify(long record, Timestamp timestamp, boolean identifier) { return invoke("jsonify", long.class, Timestamp.class, boolean.class) .with(record, timestamp, identifier); } @Override public Map<Long, Boolean> link(String key, long source, Collection<Long> destinations) { return invoke("link", String.class, long.class, Collection.class) .with(key, source, destinations); } @Override public boolean link(String key, long source, long destination) { return invoke("link", String.class, long.class, long.class).with( key, source, destination); } @Override public Map<Long, Boolean> ping(Collection<Long> records) { return invoke("ping", Collection.class).with(records); } @Override public boolean ping(long record) { return invoke("ping", long.class).with(record); } @Override public <T> Map<Long, Boolean> remove(String key, T value, Collection<Long> records) { return invoke("remove", String.class, Object.class, Collection.class).with(key, value, records); } @Override public <T> boolean remove(String key, T value, long record) { return invoke("remove", String.class, Object.class, long.class) .with(key, value, record); } @Override public void revert(Collection<String> keys, Collection<Long> records, Timestamp timestamp) { invoke("revert", Collection.class, Collection.class, Timestamp.class).with(keys, records, timestamp); } @Override public void revert(Collection<String> keys, long record, Timestamp timestamp) { invoke("revert", String.class, long.class, Timestamp.class).with( keys, record, timestamp); } @Override public void revert(String key, Collection<Long> records, Timestamp timestamp) { invoke("revert", String.class, Collection.class, Timestamp.class) .with(key, records, timestamp); } @Override public void revert(String key, long record, Timestamp timestamp) { invoke("revert", String.class, long.class, Timestamp.class).with( key, record, timestamp); } @Override public Set<Long> search(String key, String query) { return invoke("search", String.class, String.class) .with(key, query); } @Override public Map<Long, Map<String, Set<Object>>> select( Collection<Long> records) { return invoke("select", Collection.class).with(records); } @Override public Map<Long, Map<String, Set<Object>>> select( Collection<Long> records, Timestamp timestamp) { return invoke("select", Collection.class, Timestamp.class).with( records, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, Collection<Long> records) { return invoke("select", Collection.class, Collection.class).with( keys, records); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, Collection<Long> records, Timestamp timestamp) { return invoke("select", Collection.class, Collection.class, Timestamp.class).with(keys, records, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, Criteria criteria) { return invoke("select", Collection.class, Criteria.class).with( keys, criteria); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, Criteria criteria, Timestamp timestamp) { return invoke("select", Collection.class, Criteria.class, Timestamp.class).with(keys, criteria, timestamp); } @Override public <T> Map<String, Set<T>> select(Collection<String> keys, long record) { return invoke("select", Collection.class, long.class).with(keys, record); } @Override public <T> Map<String, Set<T>> select(Collection<String> keys, long record, Timestamp timestamp) { return invoke("select", Collection.class, long.class, Timestamp.class).with(keys, record, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, Object criteria) { return invoke("select", Collection.class, Object.class).with(keys, criteria); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, Object criteria, Timestamp timestamp) { return invoke("select", Collection.class, Object.class, Timestamp.class).with(keys, criteria, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, String ccl) { return invoke("select", Collection.class, String.class).with(keys, ccl); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, String ccl, Timestamp timestamp) { return invoke("select", Collection.class, String.class, Timestamp.class).with(keys, ccl, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select(Criteria criteria) { return invoke("select", Criteria.class).with(criteria); } @Override public <T> Map<Long, Map<String, Set<T>>> select(Criteria criteria, Timestamp timestamp) { return invoke("select", Criteria.class, Timestamp.class).with( criteria, timestamp); } @Override public Map<String, Set<Object>> select(long record) { return invoke("select", long.class).with(record); } @Override public Map<String, Set<Object>> select(long record, Timestamp timestamp) { return invoke("select", long.class, Timestamp.class).with(record, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select(Object criteria) { return invoke("select", Object.class).with(criteria); } @Override public <T> Map<Long, Map<String, Set<T>>> select(Object criteria, Timestamp timestamp) { return invoke("select", Object.class, Timestamp.class).with( criteria, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select(String ccl) { return invoke("select", String.class).with(ccl); } @Override public <T> Map<Long, Set<T>> select(String key, Collection<Long> records) { return invoke("select", String.class, Collection.class).with(key, records); } @Override public <T> Map<Long, Set<T>> select(String key, Collection<Long> records, Timestamp timestamp) { return invoke("select", String.class, Collection.class, Timestamp.class).with(key, records, timestamp); } @Override public <T> Map<Long, Set<T>> select(String key, Criteria criteria) { return invoke("select", String.class, Criteria.class).with(key, criteria); } @Override public <T> Map<Long, Set<T>> select(String key, Criteria criteria, Timestamp timestamp) { return invoke("select", String.class, Criteria.class, Timestamp.class).with(key, criteria, timestamp); } @Override public <T> Set<T> select(String key, long record) { return invoke("select", String.class, long.class).with(key, record); } @Override public <T> Set<T> select(String key, long record, Timestamp timestamp) { return invoke("select", String.class, long.class, Timestamp.class) .with(key, record, timestamp); } @Override public <T> Map<Long, Set<T>> select(String key, Object criteria) { return invoke("select", String.class, Object.class).with(key, criteria); } @Override public <T> Map<Long, Set<T>> select(String key, Object criteria, Timestamp timestamp) { return invoke("select", String.class, Object.class, Timestamp.class) .with(key, criteria, timestamp); } @Override public <T> Map<Long, Set<T>> select(String key, String ccl) { return invoke("select", String.class, String.class).with(key, ccl); } @Override public <T> Map<Long, Set<T>> select(String key, String ccl, Timestamp timestamp) { return invoke("select", String.class, String.class, Timestamp.class) .with(key, ccl, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select(String ccl, Timestamp timestamp) { return invoke("select", String.class, Timestamp.class).with(ccl, timestamp); } @Override public void set(String key, Object value, Collection<Long> records) { invoke("set", String.class, Object.class, Collection.class).with( key, value, records); } @Override public <T> void set(String key, T value, long record) { invoke("set", String.class, Object.class, long.class).with(key, value, record); } @Override public void stage() { invoke("stage").with(); } @Override public Timestamp time() { return invoke("time").with(); } @Override public Timestamp time(String phrase) { return invoke("time", String.class).with(phrase); } @Override public boolean unlink(String key, long source, long destination) { return invoke("unlink", String.class, long.class, long.class).with( key, source, destination); } @Override public boolean verify(String key, Object value, long record) { return invoke("verify", String.class, Object.class, long.class) .with(key, value, record); } @Override public boolean verify(String key, Object value, long record, Timestamp timestamp) { return invoke("audit", String.class, Object.class, long.class, Timestamp.class).with(key, value, record, timestamp); } @Override public boolean verifyAndSwap(String key, Object expected, long record, Object replacement) { return invoke("verifyAndSwap", String.class, Object.class, long.class, Object.class).with(key, expected, record, replacement); } @Override public void verifyOrSet(String key, Object value, long record) { invoke("verifyOrSet", String.class, Object.class, long.class).with( key, value, record); } /** * Return an invocation wrapper for the named {@code method} with the * specified {@code parameterTypes}. * * @param method * @param parameterTypes * @return the invocation wrapper */ private MethodProxy invoke(String method, Class<?>... parameterTypes) { try { for (int i = 0; i < parameterTypes.length; i++) { // NOTE: We must search through each of the parameterTypes // to see if they should be loaded from the server's // classpath. if(parameterTypes[i] == Timestamp.class) { parameterTypes[i] = loader.loadClass(packageBase + "Timestamp"); } else if(parameterTypes[i] == Operator.class) { parameterTypes[i] = loader.loadClass(packageBase + "thrift.Operator"); } else if(parameterTypes[i] == Criteria.class) { parameterTypes[i] = loader.loadClass(packageBase + "lang.Criteria"); } else { continue; } } return new MethodProxy(clazz.getMethod(method, parameterTypes)); } catch (Exception e) { throw Throwables.propagate(e); } } /** * A wrapper around a {@link Method} object that funnels all invocations * to the {@link #delegate}. * * @author jnelson */ private class MethodProxy { /** * The method to invoke. */ Method method; /** * Construct a new instance. * * @param method */ public MethodProxy(Method method) { this.method = method; } /** * Invoke the wrapped method against the {@link #delegate} with the * specified args. * * @param args * @return the result of invocation */ @SuppressWarnings("unchecked") public <T> T with(Object... args) { try { for (int i = 0; i < args.length; i++) { // NOTE: We must go through each of the args to see if // they must be converted to an object that is loaded // from the server's classpath. if(args[i] instanceof Timestamp) { Timestamp obj = (Timestamp) args[i]; args[i] = loader .loadClass(packageBase + "Timestamp") .getMethod("fromMicros", long.class) .invoke(null, obj.getMicros()); } else if(args[i] instanceof Operator) { Operator obj = (Operator) args[i]; args[i] = loader .loadClass(packageBase + "thrift.Operator") .getMethod("findByValue", int.class) .invoke(null, obj.ordinal() + 1); } else if(args[i] instanceof Criteria) { Criteria obj = (Criteria) args[i]; Field symbolField = Criteria.class .getDeclaredField("symbols"); symbolField.setAccessible(true); List<Symbol> symbols = (List<Symbol>) symbolField .get(obj); Class<?> rclazz = loader.loadClass(packageBase + "lang.Criteria"); Constructor<?> rconstructor = rclazz .getDeclaredConstructor(); rconstructor.setAccessible(true); Object robj = rconstructor.newInstance(); Method rmethod = rclazz.getDeclaredMethod( "add", loader.loadClass(packageBase + "lang.Symbol")); rmethod.setAccessible(true); for (Symbol symbol : symbols) { Object rsymbol = null; if(symbol instanceof Enum) { rsymbol = loader .loadClass( symbol.getClass().getName()) .getMethod("valueOf", String.class) .invoke(null, ((Enum<?>) symbol).name()); } else { Method symFactory = loader.loadClass( symbol.getClass().getName()) .getMethod("parse", String.class); symFactory.setAccessible(true); rsymbol = symFactory.invoke(null, symbol.toString()); } rmethod.invoke(robj, rsymbol); } args[i] = robj; } else { continue; } } return (T) method.invoke(delegate, args); } catch (Exception e) { throw Throwables.propagate(e); } } } } }
concourse-ete-test-core/src/main/java/com/cinchapi/concourse/server/ManagedConcourseServer.java
/* * Copyright (c) 2015 Cinchapi, 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.cinchapi.concourse.server; import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.ServerSocket; import java.net.SocketException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.MessageFormat; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import jline.TerminalFactory; import com.cinchapi.concourse.Concourse; import com.cinchapi.concourse.DuplicateEntryException; import com.cinchapi.concourse.Timestamp; import com.cinchapi.concourse.config.ConcourseServerPreferences; import com.cinchapi.concourse.lang.Criteria; import com.cinchapi.concourse.lang.Symbol; import com.cinchapi.concourse.thrift.Diff; import com.cinchapi.concourse.thrift.Operator; import com.cinchapi.concourse.time.Time; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Level; import com.cinchapi.concourse.util.ConcourseServerDownloader; import com.cinchapi.concourse.util.Processes; import com.google.common.base.Stopwatch; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; /** * A {@link ManagedConcourseServer} is an external server process that can be * programmatically controlled within another application. This class is useful * for applications that want to "embed" a Concourse Server for the duration of * the application's life cycle and then forget about its existence afterwards. * * @author jnelson */ public class ManagedConcourseServer { /** * Give the path to a local concourse {@code repo}, build an installer and * return the path to the installer. * * @param repo * @return the installer path */ public static String buildInstallerFromRepo(String repo) { try { Process p; p = new ProcessBuilder("bash", "gradlew", "clean", "installer") .directory(new File(repo)).start(); Processes.waitForSuccessfulCompletion(p); p = new ProcessBuilder("ls", repo + "/concourse-server/build/distributions").start(); Processes.waitForSuccessfulCompletion(p); String installer = Processes.getStdOut(p).get(0); installer = repo + "/concourse-server/build/distributions/" + installer; return installer; } catch (Exception e) { throw Throwables.propagate(e); } } /** * Return an {@link ManagedConcourseServer} that controls an instance * located in the {@code installDirectory}. * * @param installDirectory * @return the ManagedConcourseServer */ public static ManagedConcourseServer manageExistingServer( String installDirectory) { return new ManagedConcourseServer(installDirectory); } /** * Create an {@link ManagedConcourseServer from the {@code installer}. * * @param installer * @return the ManagedConcourseServer */ public static ManagedConcourseServer manageNewServer(File installer) { return manageNewServer(installer, DEFAULT_INSTALL_HOME + File.separator + Time.now()); } /** * Create an {@link ManagedConcourseServer} from the {@code installer} in * {@code directory}. * * @param installer * @param directory * @return the EmbeddedConcourseServer */ public static ManagedConcourseServer manageNewServer(File installer, String directory) { return new ManagedConcourseServer(install(installer.getAbsolutePath(), directory)); } /** * Create an {@link ManagedConcourseServer} at {@code version}. * * @param version * @return the ManagedConcourseServer */ public static ManagedConcourseServer manageNewServer(String version) { return manageNewServer(version, DEFAULT_INSTALL_HOME + File.separator + Time.now()); } /** * Create an {@link ManagedConcourseServer} at {@code version} in * {@code directory}. * * @param version * @param directory * @return the ManagedConcourseServer */ public static ManagedConcourseServer manageNewServer(String version, String directory) { return manageNewServer( new File(ConcourseServerDownloader.download(version)), directory); } /** * Tweak some of the preferences to make this more palatable for testing * (i.e. reduce the possibility of port conflicts, etc). * * @param installDirectory */ private static void configure(String installDirectory) { ConcourseServerPreferences prefs = ConcourseServerPreferences .open(installDirectory + File.separator + CONF + File.separator + "concourse.prefs"); String data = installDirectory + File.separator + "data"; prefs.setBufferDirectory(data + File.separator + "buffer"); prefs.setDatabaseDirectory(data + File.separator + "database"); prefs.setClientPort(getOpenPort()); prefs.setJmxPort(getOpenPort()); prefs.setLogLevel(Level.DEBUG); prefs.setShutdownPort(getOpenPort()); } /** * Collect and return all the {@code jar} files that are located in the * directory at {@code path}. If {@code path} is not a directory, but is * instead, itself, a jar file, then return a list that contains in. * * @param path * @return the list of jar file URL paths */ private static URL[] gatherJars(String path) { List<URL> jars = Lists.newArrayList(); gatherJars(path, jars); return jars.toArray(new URL[] {}); } /** * Collect all the {@code jar} files that are located in the directory at * {@code path} and place them into the list of {@code jars}. If * {@code path} is not a directory, but is instead, itself a jar file, then * place it in the list. * * @param path * @param jars */ private static void gatherJars(String path, List<URL> jars) { try { if(Files.isDirectory(Paths.get(path))) { for (Path p : Files.newDirectoryStream(Paths.get(path))) { gatherJars(p.toString(), jars); } } else if(path.endsWith(".jar")) { jars.add(new URL("file://" + path.toString())); } } catch (IOException e) { throw Throwables.propagate(e); } } /** * Get an open port. * * @return the port */ private static int getOpenPort() { int min = 49512; int max = 65535; int port = RAND.nextInt(min) + (max - min); return isPortAvailable(port) ? port : getOpenPort(); } /** * Install a Concourse Server in {@code directory} using {@code installer}. * * @param installer * @param directory * @return the server install directory */ private static String install(String installer, String directory) { try { Files.createDirectories(Paths.get(directory)); Path binary = Paths.get(directory + File.separator + TARGET_BINARY_NAME); Files.deleteIfExists(binary); Files.copy(Paths.get(installer), binary); ProcessBuilder builder = new ProcessBuilder(Lists.newArrayList( "sh", binary.toString())); builder.directory(new File(directory)); builder.redirectErrorStream(); Process process = builder.start(); // The concourse-server installer prompts for an admin password in // order to make optional system wide In order to get around this // prompt, we have to "kill" the process, otherwise the server // install will hang. Stopwatch watch = Stopwatch.createStarted(); while (watch.elapsed(TimeUnit.SECONDS) < 1) { continue; } watch.stop(); process.destroy(); TerminalFactory.get().restore(); String application = directory + File.separator + "concourse-server"; // the install directory for the // concourse-server application process = Runtime.getRuntime().exec("ls " + application); List<String> output = Processes.getStdOut(process); if(!output.isEmpty()) { configure(application); log.info("Successfully installed server in {}", application); return application; } else { throw new RuntimeException( MessageFormat .format("Unsuccesful attempt to " + "install server at {0} " + "using binary from {1}", directory, installer)); } } catch (Exception e) { throw Throwables.propagate(e); } } /** * Return {@code true} if the {@code port} is available on the local * machine. * * @param port * @return {@code true} if the port is available */ private static boolean isPortAvailable(int port) { try { new ServerSocket(port).close(); return true; } catch (SocketException e) { return false; } catch (IOException e) { throw Throwables.propagate(e); } } private static final String BIN = "bin"; // ---relative paths private static final String CONF = "conf"; /** * The default location where the the test server is installed if a * particular location is not specified. */ private static final String DEFAULT_INSTALL_HOME = System .getProperty("user.home") + File.separator + ".concourse-testing"; // ---logger private static final Logger log = LoggerFactory .getLogger(ManagedConcourseServer.class); // ---random private static final Random RAND = new Random(); /** * The filename of the binary installer from which the test server will be * created. */ private static final String TARGET_BINARY_NAME = "concourse-server.bin"; /** * The server application install directory; */ private final String installDirectory; /** * A connection to the remote MBean server running in the managed * concourse-server process. */ private MBeanServerConnection mBeanServerConnection = null; /** * The handler for the server's preferences. */ private final ConcourseServerPreferences prefs; /** * Construct a new instance. * * @param installDirectory */ private ManagedConcourseServer(String installDirectory) { this.installDirectory = installDirectory; this.prefs = ConcourseServerPreferences.open(installDirectory + File.separator + CONF + File.separator + "concourse.prefs"); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { destroy(); } })); } /** * Return a connection handler to the server using the default "admin" * credentials. * * @return the connection handler */ public Concourse connect() { return connect("admin", "admin"); } /** * Return a connection handler to the server using the specified * {@code username} and {@code password}. * * @param username * @param password * @return the connection handler */ public Concourse connect(String username, String password) { return new Client(username, password); } /** * Stop the server, if it is running, and permanently delete the application * files and associated data. */ public void destroy() { if(Files.exists(Paths.get(installDirectory))) { // check if server has // been manually // destroyed if(isRunning()) { stop(); } try { deleteDirectory(Paths.get(installDirectory).getParent() .toString()); log.info("Deleted server install directory at {}", installDirectory); } catch (Exception e) { throw Throwables.propagate(e); } } } /** * Return the client port for this server. * * @return the client port */ public int getClientPort() { return prefs.getClientPort(); } /** * Get a collection of stats about the heap memory usage for the managed * concourse-server process. * * @return the heap memory usage */ public MemoryUsage getHeapMemoryStats() { try { MemoryMXBean memory = ManagementFactory.newPlatformMXBeanProxy( getMBeanServerConnection(), ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class); return memory.getHeapMemoryUsage(); } catch (Exception e) { throw Throwables.propagate(e); } } /** * Return the {@link #installDirectory} for this server. * * @return the install directory */ public String getInstallDirectory() { return installDirectory; } /** * Return the connection to the MBean sever of the managed concourse-server * process. * * @return the mbean server connection */ public MBeanServerConnection getMBeanServerConnection() { if(mBeanServerConnection == null) { try { JMXServiceURL url = new JMXServiceURL( "service:jmx:rmi:///jndi/rmi://localhost:" + prefs.getJmxPort() + "/jmxrmi"); JMXConnector connector = JMXConnectorFactory.connect(url); mBeanServerConnection = connector.getMBeanServerConnection(); } catch (Exception e) { throw Throwables.propagate(e); } } return mBeanServerConnection; } /** * Get a collection of stats about the non heap memory usage for the managed * concourse-server process. * * @return the non-heap memory usage */ public MemoryUsage getNonHeapMemoryStats() { try { MemoryMXBean memory = ManagementFactory.newPlatformMXBeanProxy( getMBeanServerConnection(), ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class); return memory.getNonHeapMemoryUsage(); } catch (Exception e) { throw Throwables.propagate(e); } } /** * Return {@code true} if the server is currently running. * * @return {@code true} if the server is running */ public boolean isRunning() { return Iterables.get(execute("concourse", "status"), 0).contains( "is running"); } /** * Start the server. */ public void start() { try { for (String line : execute("start")) { log.info(line); } } catch (Exception e) { throw Throwables.propagate(e); } } /** * Stop the server. */ public void stop() { try { for (String line : execute("stop")) { log.info(line); } } catch (Exception e) { throw Throwables.propagate(e); } } /** * Recursively delete a directory and all of its contents. * * @param directory */ private void deleteDirectory(String directory) { try { File dir = new File(directory); for (File file : dir.listFiles()) { if(file.isDirectory()) { deleteDirectory(file.getAbsolutePath()); } else { file.delete(); } } dir.delete(); } catch (Exception e) { throw Throwables.propagate(e); } } /** * Execute a command line interface script and return the output. * * @param cli * @param args * @return the script output */ private List<String> execute(String cli, String... args) { try { String command = "sh " + cli; for (String arg : args) { command += " " + arg; } Process process = Runtime.getRuntime().exec(command, null, new File(installDirectory + File.separator + BIN)); return Processes.getStdOut(process); } catch (Exception e) { throw Throwables.propagate(e); } } /** * A class that extends {@link Concourse} with additional methods. This * abstraction allows casting while keeping the {@link Client} class * private. * * @author Jeff Nelson */ public abstract class ReflectiveClient extends Concourse { /** * Reflectively call a client method. This is useful for cases where * this API depends on an older version of the Concourse API and a test * needs to use a method added in a later version. This procedure will * work because the underlying client delegates to a client that uses * the classpath of the managed server. * * @param methodName * @param args * @return the result */ public abstract <T> T call(String methodName, Object... args); } /** * A {@link Concourse} client wrapper that delegates to the jars located in * the server's lib directory so that it uses the same version of the code. * * @author jnelson */ private final class Client extends ReflectiveClient { private Class<?> clazz; private final Object delegate; private ClassLoader loader; /** * The top level package under which all Concourse classes exist in the * remote server. */ private String packageBase = "com.cinchapi.concourse."; /** * Construct a new instance. * * @param username * @param password * @throws Exception */ public Client(String username, String password) { try { this.loader = new URLClassLoader( gatherJars(getInstallDirectory()), null); try { clazz = loader.loadClass(packageBase + "Concourse"); } catch (ClassNotFoundException e) { // Prior to version 0.5.0, Concourse classes were located in // the "org.cinchapi.concourse" package, so we attempt to // use that if the default does not work. packageBase = "org.cinchapi.concourse."; clazz = loader.loadClass(packageBase + "Concourse"); } this.delegate = clazz.getMethod("connect", String.class, int.class, String.class, String.class).invoke(null, "localhost", getClientPort(), username, password); } catch (Exception e) { throw Throwables.propagate(e); } } @Override public void abort() { invoke("abort").with(); } @Override public Map<Long, Boolean> add(String key, Object value, Collection<Long> records) { return invoke("add", String.class, Object.class, Collection.class) .with(key, value, records); } @Override public <T> long add(String key, T value) { return invoke("add", String.class, Object.class).with(key, value); } @Override public <T> boolean add(String key, T value, long record) { return invoke("add", String.class, Object.class, long.class).with( key, value, record); } @Override public Map<Timestamp, String> audit(long record) { return invoke("audit", long.class).with(record); } @Override public Map<Timestamp, String> audit(long record, Timestamp start) { return invoke("audit", long.class, Timestamp.class).with(record, start); } @Override public Map<Timestamp, String> audit(long record, Timestamp start, Timestamp end) { return invoke("audit", long.class, Timestamp.class, Timestamp.class) .with(start, end); } @Override public Map<Timestamp, String> audit(String key, long record) { return invoke("audit", String.class, long.class).with(key, record); } @Override public Map<Timestamp, String> audit(String key, long record, Timestamp start) { return invoke("audit", String.class, long.class, Timestamp.class) .with(key, record, start); } @Override public Map<Timestamp, String> audit(String key, long record, Timestamp start, Timestamp end) { return invoke("audit", String.class, long.class, Timestamp.class, Timestamp.class).with(key, record, start, end); } @Override public Map<String, Map<Object, Set<Long>>> browse( Collection<String> keys) { return invoke("browse", Collection.class, Object.class).with(keys); } @Override public Map<String, Map<Object, Set<Long>>> browse( Collection<String> keys, Timestamp timestamp) { return invoke("browse", Collection.class, Timestamp.class).with( keys, timestamp); } @Override public Map<Object, Set<Long>> browse(String key) { return invoke("browse", String.class).with(key); } @Override public Map<Object, Set<Long>> browse(String key, Timestamp timestamp) { return invoke("browse", String.class, Timestamp.class).with(key, timestamp); } @Override public <T> T call(String methodName, Object... args) { Class<?>[] classes = new Class<?>[args.length]; for (int i = 0; i < classes.length; ++i) { classes[i] = args[i].getClass(); } return invoke(methodName, classes).with(args); } @Override public Map<Timestamp, Set<Object>> chronologize(String key, long record) { return invoke("chronologize", String.class, long.class).with(key, record); } @Override public Map<Timestamp, Set<Object>> chronologize(String key, long record, Timestamp start) { return invoke("chronologize", String.class, long.class, Timestamp.class).with(key, record, start); } @Override public Map<Timestamp, Set<Object>> chronologize(String key, long record, Timestamp start, Timestamp end) { return invoke("chronologize", String.class, long.class, Timestamp.class, Timestamp.class).with(key, record, start, end); } @Override public void clear(Collection<Long> records) { invoke("clear", Collection.class).with(records); } @Override public void clear(Collection<String> keys, Collection<Long> records) { invoke("clear", Collection.class, Collection.class).with(keys, records); } @Override public void clear(Collection<String> keys, long record) { invoke("clear", Collection.class, long.class).with(keys, record); } @Override public void clear(long record) { invoke("clear", long.class).with(record); } @Override public void clear(String key, Collection<Long> records) { invoke("clear", String.class, Collection.class).with(key, records); } @Override public void clear(String key, long record) { invoke("clear", String.class, long.class).with(key, record); } @Override public boolean commit() { return invoke("commit").with(); } @Override public long create() { return invoke("create").with(); } @Override public Map<Long, Set<String>> describe(Collection<Long> records) { return invoke("describe", Collection.class).with(records); } @Override public Map<Long, Set<String>> describe(Collection<Long> records, Timestamp timestamp) { return invoke("describe", Collection.class, Timestamp.class).with( records, timestamp); } @Override public Set<String> describe(long record) { return invoke("describe", long.class).with(record); } @Override public Set<String> describe(long record, Timestamp timestamp) { return invoke("describe", long.class, Timestamp.class).with(record, timestamp); } @Override public <T> Map<String, Map<Diff, Set<T>>> diff(long record, Timestamp start) { return invoke("diff", long.class, Timestamp.class).with(record, start); } @Override public <T> Map<String, Map<Diff, Set<T>>> diff(long record, Timestamp start, Timestamp end) { return invoke("diff", long.class, Timestamp.class, Timestamp.class) .with(record, start, end); } @Override public <T> Map<Diff, Set<T>> diff(String key, long record, Timestamp start) { return invoke("diff", String.class, long.class, Timestamp.class) .with(record, start); } @Override public <T> Map<Diff, Set<T>> diff(String key, long record, Timestamp start, Timestamp end) { return invoke("diff", String.class, long.class, Timestamp.class, Timestamp.class).with(key, record, start, end); } @Override public <T> Map<T, Map<Diff, Set<Long>>> diff(String key, Timestamp start) { return invoke("diff", String.class, Timestamp.class).with(key, start); } @Override public <T> Map<T, Map<Diff, Set<Long>>> diff(String key, Timestamp start, Timestamp end) { return invoke("diff", String.class, Timestamp.class).with(key, start); } @Override public void exit() { invoke("exit").with(); } @Override public Set<Long> find(Criteria criteria) { return invoke("find", Criteria.class).with(criteria); } @Override public Set<Long> find(Object criteria) { return invoke("find", Object.class).with(criteria); } @Override public Set<Long> find(String ccl) { return invoke("find", String.class, Object.class).with(ccl); } @Override public Set<Long> find(String key, Object value) { return invoke("find", String.class, Object.class).with(key, value); } @Override public Set<Long> find(String key, Operator operator, Object value) { return invoke("find", String.class, Operator.class, Object.class) .with(key, operator, value); } @Override public Set<Long> find(String key, Operator operator, Object value, Object value2) { return invoke("find", String.class, Operator.class, Object.class, Object.class).with(key, operator, value, value2); } @Override public Set<Long> find(String key, Operator operator, Object value, Object value2, Timestamp timestamp) { return invoke("find", String.class, Operator.class, Object.class, Object.class, Timestamp.class).with(key, operator, value, value2); } @Override public Set<Long> find(String key, Operator operator, Object value, Timestamp timestamp) { return invoke("find", String.class, Operator.class, Object.class, Timestamp.class).with(key, operator, value, timestamp); } @Override public Set<Long> find(String key, String operator, Object value) { return invoke("find", String.class, String.class, Object.class) .with(key, operator, value); } @Override public Set<Long> find(String key, String operator, Object value, Object value2) { return invoke("find", String.class, String.class, Object.class, Object.class).with(key, operator, value, value2); } @Override public Set<Long> find(String key, String operator, Object value, Object value2, Timestamp timestamp) { return invoke("find", String.class, String.class, Object.class, Object.class, Timestamp.class).with(key, operator, value, value2, timestamp); } @Override public Set<Long> find(String key, String operator, Object value, Timestamp timestamp) { return invoke("find", String.class, String.class, Object.class, Timestamp.class).with(key, operator, value, timestamp); } @Override public <T> long findOrAdd(String key, T value) throws DuplicateEntryException { return invoke("findOrAdd", String.class, Object.class).with(key, value); } @Override public long findOrInsert(Criteria criteria, String json) throws DuplicateEntryException { return invoke("findOrInsert", Criteria.class, String.class).with( criteria, json); } @Override public long findOrInsert(String ccl, String json) throws DuplicateEntryException { return invoke("findOrInsert", String.class, String.class).with(ccl, json); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, Collection<Long> records) { return invoke("get", Collection.class, Collection.class).with(keys, records); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, Collection<Long> records, Timestamp timestamp) { return invoke("get", Collection.class, Collection.class, Timestamp.class).with(keys, records, timestamp); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, Criteria criteria) { return invoke("get", Collection.class, Criteria.class).with(keys, criteria); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, Criteria criteria, Timestamp timestamp) { return invoke("get", Collection.class, Criteria.class, Timestamp.class).with(keys, criteria, timestamp); } @Override public <T> Map<String, T> get(Collection<String> keys, long record) { return invoke("get", String.class, long.class).with(keys, record); } @Override public <T> Map<String, T> get(Collection<String> keys, long record, Timestamp timestamp) { return invoke("get", Collection.class, long.class, Timestamp.class) .with(keys, record, timestamp); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, Object criteria) { return invoke("get", Collection.class, Object.class).with(keys, criteria); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, Object criteria, Timestamp timestamp) { return invoke("get", Collection.class, Object.class, Timestamp.class).with(keys, criteria, timestamp); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, String ccl) { return invoke("get", Collection.class, String.class) .with(keys, ccl); } @Override public <T> Map<Long, Map<String, T>> get(Collection<String> keys, String ccl, Timestamp timestamp) { return invoke("get", Collection.class, String.class, Timestamp.class).with(keys, ccl, timestamp); } @Override public <T> Map<Long, Map<String, T>> get(Criteria criteria) { return invoke("get", Criteria.class).with(criteria); } @Override public <T> Map<Long, Map<String, T>> get(Criteria criteria, Timestamp timestamp) { return invoke("get", Criteria.class, Timestamp.class).with( criteria, timestamp); } @Override public <T> Map<Long, Map<String, T>> get(Object criteria) { return invoke("get", Object.class).with(criteria); } @Override public <T> Map<Long, Map<String, T>> get(Object criteria, Timestamp timestamp) { return invoke("get", Object.class, Timestamp.class).with(criteria, timestamp); } @Override public <T> Map<Long, Map<String, T>> get(String ccl) { return invoke("get", String.class).with(ccl); } @Override public <T> Map<Long, T> get(String key, Collection<Long> records) { return invoke("get", String.class, Collection.class).with(key, records); } @Override public <T> Map<Long, T> get(String key, Collection<Long> records, Timestamp timestamp) { return invoke("get", String.class, Collection.class, Timestamp.class).with(key, records, timestamp); } @Override public <T> Map<Long, T> get(String key, Criteria criteria) { return invoke("get", String.class, Criteria.class).with(key, criteria); } @Override public <T> Map<Long, T> get(String key, Criteria criteria, Timestamp timestamp) { return invoke("get", String.class, Criteria.class, Timestamp.class) .with(key, criteria, timestamp); } @Override public <T> T get(String key, long record) { return invoke("get", String.class, long.class).with(key, record); } @Override public <T> T get(String key, long record, Timestamp timestamp) { return invoke("get", String.class, long.class, Timestamp.class) .with(key, record, timestamp); } @Override public <T> Map<Long, T> get(String key, Object criteria) { return invoke("find", String.class, Object.class).with(key, criteria); } @Override public <T> Map<Long, T> get(String key, Object criteria, Timestamp timestamp) { return invoke("get", String.class, Object.class, Timestamp.class) .with(key, criteria, timestamp); } @Override public <T> Map<Long, T> get(String key, String ccl) { return invoke("find", String.class, String.class).with(key, ccl); } @Override public <T> Map<Long, T> get(String key, String ccl, Timestamp timestamp) { return invoke("find", String.class, String.class, Timestamp.class) .with(key, ccl, timestamp); } @Override public <T> Map<Long, Map<String, T>> get(String ccl, Timestamp timestamp) { return invoke("get", String.class, Timestamp.class).with(ccl, timestamp); } @Override public String getServerEnvironment() { return invoke("getServerEnvironment").with(); } @Override public String getServerVersion() { return invoke("getServerVersion").with(); } @Override public Set<Long> insert(String json) { return invoke("insert", String.class).with(json); } @Override public Map<Long, Boolean> insert(String json, Collection<Long> records) { return invoke("insert", String.class, Collection.class).with(json, records); } @Override public boolean insert(String json, long record) { return invoke("insert", String.class, long.class) .with(json, record); } @Override public Set<Long> inventory() { return invoke("inventory").with(); } @Override public String jsonify(Collection<Long> records) { return invoke("jsonify", Collection.class).with(records); } @Override public String jsonify(Collection<Long> records, boolean identifier) { return invoke("jsonify", Collection.class, boolean.class).with( records, identifier); } @Override public String jsonify(Collection<Long> records, Timestamp timestamp) { return invoke("jsonify", Collection.class, Timestamp.class).with( records, timestamp); } @Override public String jsonify(Collection<Long> records, Timestamp timestamp, boolean identifier) { return invoke("jsonify", Collection.class, Timestamp.class, boolean.class).with(records, timestamp, identifier); } @Override public String jsonify(long record) { return invoke("jsonify", long.class).with(record); } @Override public String jsonify(long record, boolean identifier) { return invoke("jsonify", long.class, boolean.class).with(record, identifier); } @Override public String jsonify(long record, Timestamp timestamp) { return invoke("jsonify", long.class, Timestamp.class).with(record, timestamp); } @Override public String jsonify(long record, Timestamp timestamp, boolean identifier) { return invoke("jsonify", long.class, Timestamp.class, boolean.class) .with(record, timestamp, identifier); } @Override public Map<Long, Boolean> link(String key, long source, Collection<Long> destinations) { return invoke("link", String.class, long.class, Collection.class) .with(key, source, destinations); } @Override public boolean link(String key, long source, long destination) { return invoke("link", String.class, long.class, long.class).with( key, source, destination); } @Override public Map<Long, Boolean> ping(Collection<Long> records) { return invoke("ping", Collection.class).with(records); } @Override public boolean ping(long record) { return invoke("ping", long.class).with(record); } @Override public <T> Map<Long, Boolean> remove(String key, T value, Collection<Long> records) { return invoke("remove", String.class, Object.class, Collection.class).with(key, value, records); } @Override public <T> boolean remove(String key, T value, long record) { return invoke("remove", String.class, Object.class, long.class) .with(key, value, record); } @Override public void revert(Collection<String> keys, Collection<Long> records, Timestamp timestamp) { invoke("revert", Collection.class, Collection.class, Timestamp.class).with(keys, records, timestamp); } @Override public void revert(Collection<String> keys, long record, Timestamp timestamp) { invoke("revert", String.class, long.class, Timestamp.class).with( keys, record, timestamp); } @Override public void revert(String key, Collection<Long> records, Timestamp timestamp) { invoke("revert", String.class, Collection.class, Timestamp.class) .with(key, records, timestamp); } @Override public void revert(String key, long record, Timestamp timestamp) { invoke("revert", String.class, long.class, Timestamp.class).with( key, record, timestamp); } @Override public Set<Long> search(String key, String query) { return invoke("search", String.class, String.class) .with(key, query); } @Override public Map<Long, Map<String, Set<Object>>> select( Collection<Long> records) { return invoke("select", Collection.class).with(records); } @Override public Map<Long, Map<String, Set<Object>>> select( Collection<Long> records, Timestamp timestamp) { return invoke("select", Collection.class, Timestamp.class).with( records, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, Collection<Long> records) { return invoke("select", Collection.class, Collection.class).with( keys, records); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, Collection<Long> records, Timestamp timestamp) { return invoke("select", Collection.class, Collection.class, Timestamp.class).with(keys, records, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, Criteria criteria) { return invoke("select", Collection.class, Criteria.class).with( keys, criteria); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, Criteria criteria, Timestamp timestamp) { return invoke("select", Collection.class, Criteria.class, Timestamp.class).with(keys, criteria, timestamp); } @Override public <T> Map<String, Set<T>> select(Collection<String> keys, long record) { return invoke("select", Collection.class, long.class).with(keys, record); } @Override public <T> Map<String, Set<T>> select(Collection<String> keys, long record, Timestamp timestamp) { return invoke("select", Collection.class, long.class, Timestamp.class).with(keys, record, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, Object criteria) { return invoke("select", Collection.class, Object.class).with(keys, criteria); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, Object criteria, Timestamp timestamp) { return invoke("select", Collection.class, Object.class, Timestamp.class).with(keys, criteria, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, String ccl) { return invoke("select", Collection.class, String.class).with(keys, ccl); } @Override public <T> Map<Long, Map<String, Set<T>>> select( Collection<String> keys, String ccl, Timestamp timestamp) { return invoke("select", Collection.class, String.class, Timestamp.class).with(keys, ccl, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select(Criteria criteria) { return invoke("select", Criteria.class).with(criteria); } @Override public <T> Map<Long, Map<String, Set<T>>> select(Criteria criteria, Timestamp timestamp) { return invoke("select", Criteria.class, Timestamp.class).with( criteria, timestamp); } @Override public Map<String, Set<Object>> select(long record) { return invoke("select", long.class).with(record); } @Override public Map<String, Set<Object>> select(long record, Timestamp timestamp) { return invoke("select", long.class, Timestamp.class).with(record, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select(Object criteria) { return invoke("select", Object.class).with(criteria); } @Override public <T> Map<Long, Map<String, Set<T>>> select(Object criteria, Timestamp timestamp) { return invoke("select", Object.class, Timestamp.class).with( criteria, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select(String ccl) { return invoke("select", String.class).with(ccl); } @Override public <T> Map<Long, Set<T>> select(String key, Collection<Long> records) { return invoke("select", String.class, Collection.class).with(key, records); } @Override public <T> Map<Long, Set<T>> select(String key, Collection<Long> records, Timestamp timestamp) { return invoke("select", String.class, Collection.class, Timestamp.class).with(key, records, timestamp); } @Override public <T> Map<Long, Set<T>> select(String key, Criteria criteria) { return invoke("select", String.class, Criteria.class).with(key, criteria); } @Override public <T> Map<Long, Set<T>> select(String key, Criteria criteria, Timestamp timestamp) { return invoke("select", String.class, Criteria.class, Timestamp.class).with(key, criteria, timestamp); } @Override public <T> Set<T> select(String key, long record) { return invoke("select", String.class, long.class).with(key, record); } @Override public <T> Set<T> select(String key, long record, Timestamp timestamp) { return invoke("select", String.class, long.class, Timestamp.class) .with(key, record, timestamp); } @Override public <T> Map<Long, Set<T>> select(String key, Object criteria) { return invoke("select", String.class, Object.class).with(key, criteria); } @Override public <T> Map<Long, Set<T>> select(String key, Object criteria, Timestamp timestamp) { return invoke("select", String.class, Object.class, Timestamp.class) .with(key, criteria, timestamp); } @Override public <T> Map<Long, Set<T>> select(String key, String ccl) { return invoke("select", String.class, String.class).with(key, ccl); } @Override public <T> Map<Long, Set<T>> select(String key, String ccl, Timestamp timestamp) { return invoke("select", String.class, String.class, Timestamp.class) .with(key, ccl, timestamp); } @Override public <T> Map<Long, Map<String, Set<T>>> select(String ccl, Timestamp timestamp) { return invoke("select", String.class, Timestamp.class).with(ccl, timestamp); } @Override public void set(String key, Object value, Collection<Long> records) { invoke("set", String.class, Object.class, Collection.class).with( key, value, records); } @Override public <T> void set(String key, T value, long record) { invoke("set", String.class, Object.class, long.class).with(key, value, record); } @Override public void stage() { invoke("stage").with(); } @Override public Timestamp time() { return invoke("time").with(); } @Override public Timestamp time(String phrase) { return invoke("time", String.class).with(phrase); } @Override public boolean unlink(String key, long source, long destination) { return invoke("unlink", String.class, long.class, long.class).with( key, source, destination); } @Override public boolean verify(String key, Object value, long record) { return invoke("verify", String.class, Object.class, long.class) .with(key, value, record); } @Override public boolean verify(String key, Object value, long record, Timestamp timestamp) { return invoke("audit", String.class, Object.class, long.class, Timestamp.class).with(key, value, record, timestamp); } @Override public boolean verifyAndSwap(String key, Object expected, long record, Object replacement) { return invoke("verifyAndSwap", String.class, Object.class, long.class, Object.class).with(key, expected, record, replacement); } @Override public void verifyOrSet(String key, Object value, long record) { invoke("verifyOrSet", String.class, Object.class, long.class).with( key, value, record); } /** * Return an invocation wrapper for the named {@code method} with the * specified {@code parameterTypes}. * * @param method * @param parameterTypes * @return the invocation wrapper */ private MethodProxy invoke(String method, Class<?>... parameterTypes) { try { for (int i = 0; i < parameterTypes.length; i++) { // NOTE: We must search through each of the parameterTypes // to see if they should be loaded from the server's // classpath. if(parameterTypes[i] == Timestamp.class) { parameterTypes[i] = loader.loadClass(packageBase + "Timestamp"); } else if(parameterTypes[i] == Operator.class) { parameterTypes[i] = loader.loadClass(packageBase + "thrift.Operator"); } else if(parameterTypes[i] == Criteria.class) { parameterTypes[i] = loader.loadClass(packageBase + "lang.Criteria"); } else { continue; } } return new MethodProxy(clazz.getMethod(method, parameterTypes)); } catch (Exception e) { throw Throwables.propagate(e); } } /** * A wrapper around a {@link Method} object that funnels all invocations * to the {@link #delegate}. * * @author jnelson */ private class MethodProxy { /** * The method to invoke. */ Method method; /** * Construct a new instance. * * @param method */ public MethodProxy(Method method) { this.method = method; } /** * Invoke the wrapped method against the {@link #delegate} with the * specified args. * * @param args * @return the result of invocation */ @SuppressWarnings("unchecked") public <T> T with(Object... args) { try { for (int i = 0; i < args.length; i++) { // NOTE: We must go through each of the args to see if // they must be converted to an object that is loaded // from the server's classpath. if(args[i] instanceof Timestamp) { Timestamp obj = (Timestamp) args[i]; args[i] = loader .loadClass(packageBase + "Timestamp") .getMethod("fromMicros", long.class) .invoke(null, obj.getMicros()); } else if(args[i] instanceof Operator) { Operator obj = (Operator) args[i]; args[i] = loader .loadClass(packageBase + "thrift.Operator") .getMethod("findByValue", int.class) .invoke(null, obj.ordinal() + 1); } else if(args[i] instanceof Criteria) { Criteria obj = (Criteria) args[i]; Field symbolField = Criteria.class .getDeclaredField("symbols"); symbolField.setAccessible(true); List<Symbol> symbols = (List<Symbol>) symbolField .get(obj); Class<?> rclazz = loader.loadClass(packageBase + "lang.Criteria"); Constructor<?> rconstructor = rclazz .getDeclaredConstructor(); rconstructor.setAccessible(true); Object robj = rconstructor.newInstance(); Method rmethod = rclazz.getDeclaredMethod( "add", loader.loadClass(packageBase + "lang.Symbol")); rmethod.setAccessible(true); for (Symbol symbol : symbols) { Object rsymbol = null; if(symbol instanceof Enum) { rsymbol = loader .loadClass( symbol.getClass().getName()) .getMethod("valueOf", String.class) .invoke(null, ((Enum<?>) symbol).name()); } else { Method symFactory = loader.loadClass( symbol.getClass().getName()) .getMethod("parse", String.class); symFactory.setAccessible(true); rsymbol = symFactory.invoke(null, symbol.toString()); } rmethod.invoke(robj, rsymbol); } args[i] = robj; } else { continue; } } return (T) method.invoke(delegate, args); } catch (Exception e) { throw Throwables.propagate(e); } } } } }
make method signature in ReflectiveClient match that defined in Concourse.java
concourse-ete-test-core/src/main/java/com/cinchapi/concourse/server/ManagedConcourseServer.java
make method signature in ReflectiveClient match that defined in Concourse.java
<ide><path>oncourse-ete-test-core/src/main/java/com/cinchapi/concourse/server/ManagedConcourseServer.java <ide> } <ide> <ide> @Override <del> public Map<Long, Boolean> add(String key, Object value, <add> public <T> Map<Long, Boolean> add(String key, T value, <ide> Collection<Long> records) { <ide> return invoke("add", String.class, Object.class, Collection.class) <ide> .with(key, value, records);
Java
mit
5595894992b188251a7e132724863532b0e24a2e
0
4pr0n/ripme,sleaze/ripme,rephormat/ripme,rephormat/ripme,metaprime/ripme,4pr0n/ripme,sleaze/ripme,rephormat/ripme,sleaze/ripme,metaprime/ripme,metaprime/ripme
package com.rarchives.ripme.ripper.rippers; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.rarchives.ripme.ripper.AbstractHTMLRipper; import com.rarchives.ripme.utils.Http; public class CheveretoRipper extends AbstractHTMLRipper { public CheveretoRipper(URL url) throws IOException { super(url); } public static List<String> explicit_domains_1 = Arrays.asList("hushpix.com"); @Override public String getHost() { String host = url.toExternalForm().split("/")[2]; return host; } @Override public String getDomain() { String host = url.toExternalForm().split("/")[2]; return host; } @Override public boolean canRip(URL url) { String url_name = url.toExternalForm(); if (explicit_domains_1.contains(url_name.split("/")[2]) == true) { Pattern pa = Pattern.compile("(?:https?://)?(?:www\\.)?[a-z1-9]*\\.[a-z1-9]*/album/([a-zA-Z1-9]*)/?$"); Matcher ma = pa.matcher(url.toExternalForm()); if (ma.matches()) { return true; } } return false; } @Override public String getGID(URL url) throws MalformedURLException { Pattern p = Pattern.compile("(?:https?://)?(?:www\\.)?[a-z1-9]*\\.[a-z1-9]*/album/([a-zA-Z1-9]*)/?$"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } throw new MalformedURLException("Expected chevereto URL format: " + "site.domain/album/albumName or site.domain/username/albums- got " + url + " instead"); } @Override public Document getFirstPage() throws IOException { // "url" is an instance field of the superclass return Http.url(url).get(); } @Override public List<String> getURLsFromPage(Document doc) { List<String> result = new ArrayList<String>(); for (Element el : doc.select("a.image-container > img")) { String imageSource = el.attr("src"); // We remove the .md from images so we download the full size image // not the medium ones imageSource = imageSource.replace(".md", ""); result.add(imageSource); } return result; } @Override public void downloadURL(URL url, int index) { addURLToDownload(url, getPrefix(index)); } }
src/main/java/com/rarchives/ripme/ripper/rippers/CheveretoRipper.java
package com.rarchives.ripme.ripper.rippers; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.rarchives.ripme.ripper.AbstractHTMLRipper; import com.rarchives.ripme.utils.Http; public class CheveretoRipper extends AbstractHTMLRipper { public CheveretoRipper(URL url) throws IOException { super(url); } public static List<String> explicit_domains_1 = Arrays.asList("www.ezphotoshare.com", "hushpix.com"); @Override public String getHost() { String host = url.toExternalForm().split("/")[2]; return host; } @Override public String getDomain() { String host = url.toExternalForm().split("/")[2]; return host; } @Override public boolean canRip(URL url) { String url_name = url.toExternalForm(); if (explicit_domains_1.contains(url_name.split("/")[2]) == true) { Pattern pa = Pattern.compile("(?:https?://)?(?:www\\.)?[a-z1-9]*\\.[a-z1-9]*/album/([a-zA-Z1-9]*)/?$"); Matcher ma = pa.matcher(url.toExternalForm()); if (ma.matches()) { return true; } } return false; } @Override public String getGID(URL url) throws MalformedURLException { Pattern p = Pattern.compile("(?:https?://)?(?:www\\.)?[a-z1-9]*\\.[a-z1-9]*/album/([a-zA-Z1-9]*)/?$"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } throw new MalformedURLException("Expected chevereto URL format: " + "site.domain/album/albumName or site.domain/username/albums- got " + url + " instead"); } @Override public Document getFirstPage() throws IOException { // "url" is an instance field of the superclass return Http.url(url).get(); } @Override public List<String> getURLsFromPage(Document doc) { List<String> result = new ArrayList<String>(); for (Element el : doc.select("a.image-container > img")) { String imageSource = el.attr("src"); // We remove the .md from images so we download the full size image // not the medium ones imageSource = imageSource.replace(".md", ""); result.add(imageSource); } return result; } @Override public void downloadURL(URL url, int index) { addURLToDownload(url, getPrefix(index)); } }
removed none working site
src/main/java/com/rarchives/ripme/ripper/rippers/CheveretoRipper.java
removed none working site
<ide><path>rc/main/java/com/rarchives/ripme/ripper/rippers/CheveretoRipper.java <ide> super(url); <ide> } <ide> <del> public static List<String> explicit_domains_1 = Arrays.asList("www.ezphotoshare.com", "hushpix.com"); <add> public static List<String> explicit_domains_1 = Arrays.asList("hushpix.com"); <ide> @Override <ide> public String getHost() { <ide> String host = url.toExternalForm().split("/")[2];
Java
mit
9770fc940c61348ef0e9fbba8287f04e71e6a676
0
leifhka/Qure
package no.uio.ifi.qure.spaces; import no.uio.ifi.qure.*; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.HashSet; import com.vividsolutions.jts.io.WKBWriter; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.CoordinateSequence; import com.vividsolutions.jts.geom.util.PolygonExtracter; import com.vividsolutions.jts.geom.impl.CoordinateArraySequence; import com.vividsolutions.jts.geom.TopologyException; import com.vividsolutions.jts.precision.EnhancedPrecisionOp; import com.vividsolutions.jts.geom.IntersectionMatrix; public class GeometrySpace implements Space { private Geometry geo; /* Roles */ public static int INTERIOR = 1; public static int BOUNDARY = 2; public GeometrySpace(Geometry geo) { this.geo = flatten(geo); } private static Geometry flatten(Geometry gc) { if (gc.getNumGeometries() <= 1) return gc; //Needed to convert GeometryCollection to Geometry List<Geometry> gs = new ArrayList<Geometry>(); for (int i = 0; i < gc.getNumGeometries(); i++) { gs.add(gc.getGeometryN(i)); } return gc.getFactory().buildGeometry(gs); } public Geometry getGeometry() { return geo; } public boolean isEmpty() { return geo.isEmpty(); } public GeometrySpace union(Space o) { Geometry go = ((GeometrySpace) o).getGeometry(); return new GeometrySpace(geo.union(go)); } public GeometrySpace intersection(Space o) { Geometry go = ((GeometrySpace) o).getGeometry(); return new GeometrySpace(geo.intersection(go)); //return new GeometrySpace(EnhancedPrecisionOp.intersection(geo, go)); } /** * Splits the argument envelope into two partition envelopes. The split is along the x-axis if xSplit, * and along the y-axis otherwise. */ private Envelope[] splitEnvelope(Envelope e, boolean xSplit) { Envelope e1,e2; if (xSplit) { //Making the new bintree blocks, dividing along the x-axis double xmid = e.getMinX() + (e.getMaxX() - e.getMinX())/2.0; e1 = new Envelope(e.getMinX(), xmid, e.getMinY(), e.getMaxY()); e2 = new Envelope(xmid, e.getMaxX(), e.getMinY(), e.getMaxY()); } else { //Dividing along the y-axis double ymid = e.getMinY() + (e.getMaxY() - e.getMinY())/2.0; e1 = new Envelope(e.getMinX(), e.getMaxX(), e.getMinY(), ymid); e2 = new Envelope(e.getMinX(), e.getMaxX(), ymid, e.getMaxY()); } return new Envelope[]{e1, e2}; } public GeometrySpace[] split(int dim) { Envelope te = geo.getEnvelopeInternal(); Envelope[] es = splitEnvelope(te, dim == 0); GeometryFactory gf = geo.getFactory(); GeometrySpace gs1 = new GeometrySpace(gf.toGeometry(es[0])); GeometrySpace gs2 = new GeometrySpace(gf.toGeometry(es[1])); return new GeometrySpace[]{gs1, gs2}; } public String toDBString() { WKBWriter writer = new WKBWriter(); String str = WKBWriter.toHex(writer.write(geo)); return "'" + str + "'"; } public String toString() { if (geo.isRectangle()) { return geo.getEnvelopeInternal().toString(); } else { return geo.toString(); } } public boolean equals(Object o) { return (o instanceof GeometrySpace) && geo.equals(((GeometrySpace) o).getGeometry()); } public int hashCode() { return geo.hashCode(); } public boolean overlaps(Space o) { if (!(o instanceof GeometrySpace)) return false; GeometrySpace ogs = (GeometrySpace) o; return geo.intersects(ogs.getGeometry()); } public boolean partOf(Space o) { if (!(o instanceof GeometrySpace)) return false; GeometrySpace ogs = (GeometrySpace) o; return geo.coveredBy(ogs.getGeometry()); } public boolean before(Space o) { return false; } public Relationship relate(Space o) { Geometry go = ((GeometrySpace) o).getGeometry(); IntersectionMatrix im = geo.relate(go); return new Relationship() { public boolean isCovers() { return im.isCovers(); } public boolean isCoveredBy() { return im.isCoveredBy(); } public boolean isIntersects() { return im.isIntersects(); } public boolean isBefore() { return false; } }; } public Set<Integer> extractRoles(Space o) { if (!(o instanceof GeometrySpace)) return null; GeometrySpace ogs = (GeometrySpace) o; Set<Integer> rs = new HashSet<Integer>(); GeometrySpace boundary = new GeometrySpace(geo.getBoundary()); if (boundary.overlaps(ogs)) { rs.add(BOUNDARY); } if (!intersection(ogs).equals(boundary)) { // Interior must intersect o rs.add(INTERIOR); } return rs; } public GeometrySpace getPart(int role) { if (role == 0) { return this; } else if ((role & BOUNDARY) == role) { return new GeometrySpace(geo.getBoundary()); } else if ((role & INTERIOR) == role) { // TODO: Fix this, does not work as geo.equals(geo.difference(geo.getBoundary())) return new GeometrySpace(geo.difference(geo.getBoundary())); } else { assert(role == (BOUNDARY | INTERIOR)); return new GeometrySpace(geo.getFactory().createPoint((CoordinateSequence) null)); } } }
src/no/uio/ifi/qure/spaces/GeometrySpace.java
package no.uio.ifi.qure.spaces; import no.uio.ifi.qure.*; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.HashSet; import com.vividsolutions.jts.io.WKBWriter; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.CoordinateSequence; import com.vividsolutions.jts.geom.util.PolygonExtracter; import com.vividsolutions.jts.geom.impl.CoordinateArraySequence; import com.vividsolutions.jts.geom.TopologyException; import com.vividsolutions.jts.precision.EnhancedPrecisionOp; import com.vividsolutions.jts.geom.IntersectionMatrix; public class GeometrySpace implements Space { private Geometry geo; /* Roles */ public static int INTERIOR = 1; public static int BOUNDARY = 2; public GeometrySpace(Geometry geo) { this.geo = flatten(geo); } private static Geometry flatten(Geometry gc) { if (gc.getNumGeometries() <= 1) return gc; //Needed to convert GeometryCollection to Geometry List<Geometry> gs = new ArrayList<Geometry>(); for (int i = 0; i < gc.getNumGeometries(); i++) { gs.add(gc.getGeometryN(i)); } return gc.getFactory().buildGeometry(gs); } public Geometry getGeometry() { return geo; } public boolean isEmpty() { return geo.isEmpty(); } public GeometrySpace union(Space o) { Geometry go = ((GeometrySpace) o).getGeometry(); return new GeometrySpace(geo.union(go)); } public GeometrySpace intersection(Space o) { Geometry go = ((GeometrySpace) o).getGeometry(); return new GeometrySpace(geo.intersection(go)); //return new GeometrySpace(EnhancedPrecisionOp.intersection(geo, go)); } /** * Splits the argument envelope into two partition envelopes. The split is along the x-axis if xSplit, * and along the y-axis otherwise. */ private Envelope[] splitEnvelope(Envelope e, boolean xSplit) { Envelope e1,e2; if (xSplit) { //Making the new bintree blocks, dividing along the x-axis double xmid = e.getMinX() + (e.getMaxX() - e.getMinX())/2.0; e1 = new Envelope(e.getMinX(), xmid, e.getMinY(), e.getMaxY()); e2 = new Envelope(xmid, e.getMaxX(), e.getMinY(), e.getMaxY()); } else { //Dividing along the y-axis double ymid = e.getMinY() + (e.getMaxY() - e.getMinY())/2.0; e1 = new Envelope(e.getMinX(), e.getMaxX(), e.getMinY(), ymid); e2 = new Envelope(e.getMinX(), e.getMaxX(), ymid, e.getMaxY()); } return new Envelope[]{e1, e2}; } public GeometrySpace[] split(int dim) { Envelope te = geo.getEnvelopeInternal(); Envelope[] es = splitEnvelope(te, dim == 0); GeometryFactory gf = geo.getFactory(); GeometrySpace gs1 = new GeometrySpace(gf.toGeometry(es[0])); GeometrySpace gs2 = new GeometrySpace(gf.toGeometry(es[1])); return new GeometrySpace[]{gs1, gs2}; } public String toDBString() { WKBWriter writer = new WKBWriter(); String str = WKBWriter.toHex(writer.write(geo)); return "'" + str + "'"; } public String toString() { if (geo.isRectangle()) { return geo.getEnvelopeInternal().toString(); } else { return geo.toString(); } } public boolean equals(Object o) { return (o instanceof GeometrySpace) && geo.equals(((GeometrySpace) o).getGeometry()); } public int hashCode() { return geo.hashCode(); } public boolean overlaps(Space o) { if (!(o instanceof GeometrySpace)) return false; GeometrySpace ogs = (GeometrySpace) o; return geo.intersects(ogs.getGeometry()); } public boolean partOf(Space o) { if (!(o instanceof GeometrySpace)) return false; GeometrySpace ogs = (GeometrySpace) o; return geo.coveredBy(ogs.getGeometry()); } public boolean before(Space o) { return false; } public Relationship relate(Space o) { Geometry go = ((GeometrySpace) o).getGeometry(); IntersectionMatrix im = geo.relate(go); return new Relationship() { public boolean isCovers() { return im.isCovers(); } public boolean isCoveredBy() { return im.isCoveredBy(); } public boolean isIntersects() { return im.isIntersects(); } public boolean isBefore() { return false; } }; } public Set<Integer> extractRoles(Space o) { if (!(o instanceof GeometrySpace)) return null; GeometrySpace ogs = (GeometrySpace) o; Set<Integer> rs = new HashSet<Integer>(); GeometrySpace boundary = new GeometrySpace(geo.getBoundary()); if (boundary.overlaps(ogs)) { rs.add(BOUNDARY); } if (!intersection(ogs).equals(boundary)) { // Interior must intersect o rs.add(INTERIOR); } return rs; } public GeometrySpace getPart(int role) { if (role == 0) { return this; } else if ((role & BOUNDARY) == role) { return new GeometrySpace(geo.getBoundary()); } else if ((role & INTERIOR) == role) { return new GeometrySpace(geo.difference(geo.getBoundary())); } else { assert(role == (BOUNDARY | INTERIOR)); return new GeometrySpace(geo.getFactory().createPoint((CoordinateSequence) null)); } } }
Added TODO.
src/no/uio/ifi/qure/spaces/GeometrySpace.java
Added TODO.
<ide><path>rc/no/uio/ifi/qure/spaces/GeometrySpace.java <ide> } else if ((role & BOUNDARY) == role) { <ide> return new GeometrySpace(geo.getBoundary()); <ide> } else if ((role & INTERIOR) == role) { <add> // TODO: Fix this, does not work as geo.equals(geo.difference(geo.getBoundary())) <ide> return new GeometrySpace(geo.difference(geo.getBoundary())); <ide> } else { <ide> assert(role == (BOUNDARY | INTERIOR));
Java
apache-2.0
76b9860e096dc0a60fe7e0f52de215088abdbda9
0
ndew623/k-9,k9mail/k-9,dgger/k-9,cketti/k-9,philipwhiuk/q-mail,cketti/k-9,ndew623/k-9,philipwhiuk/q-mail,CodingRmy/k-9,cketti/k-9,mawiegand/k-9,philipwhiuk/k-9,roscrazy/k-9,mawiegand/k-9,cketti/k-9,philipwhiuk/q-mail,jca02266/k-9,rishabhbitsg/k-9,vatsalsura/k-9,ndew623/k-9,CodingRmy/k-9,jca02266/k-9,mawiegand/k-9,philipwhiuk/k-9,vt0r/k-9,jca02266/k-9,dgger/k-9,k9mail/k-9,vatsalsura/k-9,roscrazy/k-9,rishabhbitsg/k-9,indus1/k-9,dgger/k-9,indus1/k-9,vt0r/k-9,k9mail/k-9
/* * Copyright 2012 Jay Weisskopf * * Licensed under the MIT License (see LICENSE.txt) * * 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. * * Source: https://github.com/jayschwa/AndroidSliderPreference */ package com.fsck.k9.activity.setup; import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.os.Parcelable; import android.preference.DialogPreference; import android.support.annotation.ArrayRes; import android.support.annotation.StringRes; import android.util.AttributeSet; import android.view.View; import android.widget.SeekBar; import com.fsck.k9.*; /** * @author Jay Weisskopf */ public class SliderPreference extends DialogPreference { private static final String STATE_KEY_SUPER = "super"; private static final String STATE_KEY_SEEK_BAR_VALUE = "seek_bar_value"; protected final static int SEEKBAR_RESOLUTION = 10000; protected float mValue; protected int mSeekBarValue; protected CharSequence[] mSummaries; /** * @param context * @param attrs */ public SliderPreference(Context context, AttributeSet attrs) { super(context, attrs); setup(context, attrs); } /** * @param context * @param attrs * @param defStyle */ public SliderPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setup(context, attrs); } private void setup(Context context, AttributeSet attrs) { setDialogLayoutResource(R.layout.slider_preference_dialog); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SliderPreference); try { setSummary(a.getTextArray(R.styleable.SliderPreference_android_summary)); } catch (Exception e) { // Do nothing } a.recycle(); } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getFloat(index, 0); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { setValue(restoreValue ? getPersistedFloat(mValue) : (Float) defaultValue); } @Override public CharSequence getSummary() { if (mSummaries != null && mSummaries.length > 0) { int index = (int) (mValue * mSummaries.length); index = Math.min(index, mSummaries.length - 1); return mSummaries[index]; } else { return super.getSummary(); } } public void setSummary(CharSequence[] summaries) { mSummaries = summaries; } @Override public void setSummary(CharSequence summary) { super.setSummary(summary); mSummaries = null; } @Override public void setSummary(@ArrayRes int summaryResId) { try { setSummary(getContext().getResources().getStringArray(summaryResId)); } catch (Exception e) { super.setSummary(summaryResId); } } public float getValue() { return mValue; } public void setValue(float value) { value = Math.max(0, Math.min(value, 1)); // clamp to [0, 1] if (shouldPersist()) { persistFloat(value); } if (value != mValue) { mValue = value; notifyChanged(); } } @Override protected View onCreateDialogView() { mSeekBarValue = (int) (mValue * SEEKBAR_RESOLUTION); View view = super.onCreateDialogView(); SeekBar seekbar = (SeekBar) view.findViewById(R.id.slider_preference_seekbar); seekbar.setMax(SEEKBAR_RESOLUTION); seekbar.setProgress(mSeekBarValue); seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { SliderPreference.this.mSeekBarValue = progress; callChangeListener((float) SliderPreference.this.mSeekBarValue / SEEKBAR_RESOLUTION); } } }); return view; } @Override protected void onDialogClosed(boolean positiveResult) { final float newValue = (float) mSeekBarValue / SEEKBAR_RESOLUTION; if (positiveResult && callChangeListener(newValue)) { setValue(newValue); } else { callChangeListener(mValue); } super.onDialogClosed(positiveResult); } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); Bundle state = new Bundle(); state.putParcelable(STATE_KEY_SUPER, superState); state.putInt(STATE_KEY_SEEK_BAR_VALUE, mSeekBarValue); return state; } @Override protected void onRestoreInstanceState(Parcelable state) { Bundle bundle = (Bundle) state; super.onRestoreInstanceState(bundle.getParcelable(STATE_KEY_SUPER)); mSeekBarValue = bundle.getInt(STATE_KEY_SEEK_BAR_VALUE); callChangeListener((float) mSeekBarValue / SEEKBAR_RESOLUTION); } }
k9mail/src/main/java/com/fsck/k9/activity/setup/SliderPreference.java
/* * Copyright 2012 Jay Weisskopf * * Licensed under the MIT License (see LICENSE.txt) * * 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. * * Source: https://github.com/jayschwa/AndroidSliderPreference */ package com.fsck.k9.activity.setup; import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.os.Parcelable; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.SeekBar; import com.fsck.k9.*; /** * @author Jay Weisskopf */ public class SliderPreference extends DialogPreference { private static final String STATE_KEY_SUPER = "super"; private static final String STATE_KEY_SEEK_BAR_VALUE = "seek_bar_value"; protected final static int SEEKBAR_RESOLUTION = 10000; protected float mValue; protected int mSeekBarValue; protected CharSequence[] mSummaries; /** * @param context * @param attrs */ public SliderPreference(Context context, AttributeSet attrs) { super(context, attrs); setup(context, attrs); } /** * @param context * @param attrs * @param defStyle */ public SliderPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setup(context, attrs); } private void setup(Context context, AttributeSet attrs) { setDialogLayoutResource(R.layout.slider_preference_dialog); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SliderPreference); try { setSummary(a.getTextArray(R.styleable.SliderPreference_android_summary)); } catch (Exception e) { // Do nothing } a.recycle(); } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getFloat(index, 0); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { setValue(restoreValue ? getPersistedFloat(mValue) : (Float) defaultValue); } @Override public CharSequence getSummary() { if (mSummaries != null && mSummaries.length > 0) { int index = (int) (mValue * mSummaries.length); index = Math.min(index, mSummaries.length - 1); return mSummaries[index]; } else { return super.getSummary(); } } public void setSummary(CharSequence[] summaries) { mSummaries = summaries; } @Override public void setSummary(CharSequence summary) { super.setSummary(summary); mSummaries = null; } @Override public void setSummary(int summaryResId) { try { setSummary(getContext().getResources().getStringArray(summaryResId)); } catch (Exception e) { super.setSummary(summaryResId); } } public float getValue() { return mValue; } public void setValue(float value) { value = Math.max(0, Math.min(value, 1)); // clamp to [0, 1] if (shouldPersist()) { persistFloat(value); } if (value != mValue) { mValue = value; notifyChanged(); } } @Override protected View onCreateDialogView() { mSeekBarValue = (int) (mValue * SEEKBAR_RESOLUTION); View view = super.onCreateDialogView(); SeekBar seekbar = (SeekBar) view.findViewById(R.id.slider_preference_seekbar); seekbar.setMax(SEEKBAR_RESOLUTION); seekbar.setProgress(mSeekBarValue); seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { SliderPreference.this.mSeekBarValue = progress; callChangeListener((float) SliderPreference.this.mSeekBarValue / SEEKBAR_RESOLUTION); } } }); return view; } @Override protected void onDialogClosed(boolean positiveResult) { final float newValue = (float) mSeekBarValue / SEEKBAR_RESOLUTION; if (positiveResult && callChangeListener(newValue)) { setValue(newValue); } else { callChangeListener(mValue); } super.onDialogClosed(positiveResult); } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); Bundle state = new Bundle(); state.putParcelable(STATE_KEY_SUPER, superState); state.putInt(STATE_KEY_SEEK_BAR_VALUE, mSeekBarValue); return state; } @Override protected void onRestoreInstanceState(Parcelable state) { Bundle bundle = (Bundle) state; super.onRestoreInstanceState(bundle.getParcelable(STATE_KEY_SUPER)); mSeekBarValue = bundle.getInt(STATE_KEY_SEEK_BAR_VALUE); callChangeListener((float) mSeekBarValue / SEEKBAR_RESOLUTION); } }
SliderPreference - Fix lint warning
k9mail/src/main/java/com/fsck/k9/activity/setup/SliderPreference.java
SliderPreference - Fix lint warning
<ide><path>9mail/src/main/java/com/fsck/k9/activity/setup/SliderPreference.java <ide> import android.os.Bundle; <ide> import android.os.Parcelable; <ide> import android.preference.DialogPreference; <add>import android.support.annotation.ArrayRes; <add>import android.support.annotation.StringRes; <ide> import android.util.AttributeSet; <ide> import android.view.View; <ide> import android.widget.SeekBar; <ide> } <ide> <ide> @Override <del> public void setSummary(int summaryResId) { <add> public void setSummary(@ArrayRes int summaryResId) { <ide> try { <ide> setSummary(getContext().getResources().getStringArray(summaryResId)); <ide> } catch (Exception e) {
JavaScript
mit
00fbed1a53c9bc597de2c6a3bf94a26bc7fc7ac8
0
wavesplatform/WavesGUI,wavesplatform/WavesGUI,wavesplatform/WavesGUI,wavesplatform/WavesGUI
/* eslint-disable no-console */ (function () { 'use strict'; const DISABLED_FEATURES = [ 'header_screenshot', 'header_symbol_search', 'symbol_search_hot_key', 'display_market_status', 'control_bar', 'timeframes_toolbar', 'volume_force_overlay' ]; // TODO : added in version 1.12 // const ENABLED_FEATURES = [ // 'hide_left_toolbar_by_default' // ]; function getOverrides(candleUpColor, candleDownColor) { return { 'mainSeriesProperties.candleStyle.upColor': candleUpColor, 'mainSeriesProperties.candleStyle.downColor': candleDownColor, 'mainSeriesProperties.candleStyle.drawBorder': false, 'mainSeriesProperties.hollowCandleStyle.upColor': candleUpColor, 'mainSeriesProperties.hollowCandleStyle.downColor': candleDownColor, 'mainSeriesProperties.hollowCandleStyle.drawBorder': false, 'mainSeriesProperties.barStyle.upColor': candleUpColor, 'mainSeriesProperties.barStyle.downColor': candleDownColor, 'mainSeriesProperties.haStyle.upColor': candleUpColor, 'mainSeriesProperties.haStyle.downColor': candleDownColor, 'mainSeriesProperties.haStyle.drawBorder': false, 'mainSeriesProperties.lineStyle.color': candleUpColor, 'mainSeriesProperties.areaStyle.color1': candleUpColor, 'mainSeriesProperties.areaStyle.color2': candleUpColor, 'mainSeriesProperties.areaStyle.linecolor': candleUpColor, 'volumePaneSize': 'medium' }; } function getStudiesOverrides({ volume0, volume1 }) { return { 'volume.volume.color.0': volume0, 'volume.volume.color.1': volume1 }; } let counter = 0; /** * * @param {Base} Base * @param candlesService * @param {$rootScope.Scope} $scope * @param {app.themes} themes * @return {DexCandleChart} */ const controller = function (Base, candlesService, $scope, themes, user) { class DexCandleChart extends Base { constructor() { super(); /** * @type {string} */ this.elementId = `tradingview${counter++}`; /** * @type {boolean} */ this.notLoaded = false; /** * @type {TradingView} * @private */ this._chart = null; /** * @type {boolean} * @private */ this._chartReady = false; /** * @type {boolean} * @private */ this._assetIdPairWasChanged = false; /** * @type {boolean} * @private */ this._changeTheme = true; /** * @type {{price: string, amount: string}} */ this._assetIdPair = null; /** * @type {boolean} * @private */ this.loadingTradingView = true; /** * @type {string} * @private */ this.theme = user.getSetting('theme'); /** * @type {string} * @private */ this.candle = user.getSetting('candle'); this.observe('_assetIdPair', this._onChangeAssetPair); this.observe('theme', () => { this._changeTheme = true; this._resetTradingView(); }); this.observe('candle', this._refreshTradingView); this.syncSettings({ _assetIdPair: 'dex.assetIdPair' }); this.syncSettings({ theme: 'theme' }); this.syncSettings({ candle: 'candle' }); } $postLink() { controller.load() .then(() => { this._createTradingView(); this.listenEventEmitter(i18next, 'languageChanged', this._changeLangHandler.bind(this)); }, () => { console.warn('Error 403!'); this.notLoaded = true; }) .then(() => { $scope.$apply(); }); } $onDestroy() { super.$onDestroy(); if (!this.loadingTradingView) { user.setSetting('lastInterval', this._chart.symbolInterval().interval); } this._removeTradingView(); } /** * @private */ _onChangeAssetPair() { if (this._chartReady) { this._setChartPair(); } else { this._assetIdPairWasChanged = true; } } /** * @return {*} * @private */ _resetTradingView() { try { return this._removeTradingView() ._createTradingView(); } catch (e) { // Trading view not loaded } } /** * @return {DexCandleChart} * @private */ _removeTradingView() { candlesService.unsubscribeBars(); try { if (this._chart) { this._chart.remove(); } } catch (e) { // Can't remove _chart } this._chart = null; return this; } /** * @private */ _refreshTradingView() { if (!this._chart) { return null; } const { up, down, volume0, volume1 } = themes.getCurrentCandleSColor(this.candle); const overrides = getOverrides(up, down); const studiesOverrides = getStudiesOverrides({ volume0, volume1 }); this._chart.applyOverrides(overrides); this._chart.applyStudiesOverrides(studiesOverrides); } /** * @return {DexCandleChart} * @private */ _createTradingView() { this.loadingTradingView = true; const { up, down, volume0, volume1 } = themes.getCurrentCandleSColor(this.candle); const themeConf = themes.getTradingViewConfig(this.theme); const overrides = { ...getOverrides(up, down), ...themeConf.OVERRIDES }; const studies_overrides = { ...getStudiesOverrides({ volume0, volume1 }), ...themeConf.STUDIES_OVERRIDES }; const toolbar_bg = themeConf.toolbarBg; const custom_css_url = themeConf.customCssUrl; this._chart = new TradingView.widget({ // debug: true, locale: DexCandleChart._remapLanguageCode(i18next.language), symbol: `${this._assetIdPair.amount}/${this._assetIdPair.price}`, interval: user.getSetting('lastInterval'), container_id: this.elementId, datafeed: candlesService, library_path: 'trading-view/', autosize: true, toolbar_bg, disabled_features: DISABLED_FEATURES, // enabled_features: ENABLED_FEATURES, overrides, studies_overrides, custom_css_url, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone }); this._chart.onChartReady(() => { if (this._changeTheme) { this._chart.applyOverrides(overrides); this._chart.applyStudiesOverrides(studies_overrides); } this._changeTheme = false; this.loadingTradingView = false; if (this._assetIdPairWasChanged) { this._setChartPair(); this._assetIdPairWasChanged = false; this._chartReady = true; } }); this._chart.options.datafeed.onLoadError = () => { this.notLoaded = true; }; return this; } /** * @private */ _setChartPair() { this._chart.symbolInterval(({ interval }) => { this._chart.setSymbol(`${this._assetIdPair.amount}/${this._assetIdPair.price}`, interval); }); } /** * @private */ _changeLangHandler() { return this._resetTradingView(); } static _remapLanguageCode(code) { switch (code) { case 'hi_IN': return 'en'; case 'zh_CN': return 'zh'; default: return code; } } } return new DexCandleChart(); }; controller.$inject = ['Base', 'candlesService', '$scope', 'themes', 'user']; controller.load = function () { const script = document.createElement('script'); script.src = '/trading-view/charting_library.min.js'; const promise = new Promise((resolve, reject) => { script.onload = resolve; script.onerror = reject; document.head.appendChild(script); }); controller.load = () => promise; return promise; }; angular.module('app.dex').component('wDexCandleChart', { bindings: {}, templateUrl: 'modules/dex/directives/dexCandleChart/dex-candle-chart.html', transclude: false, controller }); })();
src/modules/dex/directives/dexCandleChart/DexCandleChart.js
/* eslint-disable no-console */ (function () { 'use strict'; const DISABLED_FEATURES = [ 'header_screenshot', 'header_symbol_search', 'symbol_search_hot_key', 'display_market_status', 'control_bar', 'timeframes_toolbar', 'volume_force_overlay' ]; // TODO : added in version 1.12 // const ENABLED_FEATURES = [ // 'hide_left_toolbar_by_default' // ]; function getOverrides(candleUpColor, candleDownColor) { return { 'mainSeriesProperties.candleStyle.upColor': candleUpColor, 'mainSeriesProperties.candleStyle.downColor': candleDownColor, 'mainSeriesProperties.candleStyle.drawBorder': false, 'mainSeriesProperties.hollowCandleStyle.upColor': candleUpColor, 'mainSeriesProperties.hollowCandleStyle.downColor': candleDownColor, 'mainSeriesProperties.hollowCandleStyle.drawBorder': false, 'mainSeriesProperties.barStyle.upColor': candleUpColor, 'mainSeriesProperties.barStyle.downColor': candleDownColor, 'mainSeriesProperties.haStyle.upColor': candleUpColor, 'mainSeriesProperties.haStyle.downColor': candleDownColor, 'mainSeriesProperties.haStyle.drawBorder': false, 'mainSeriesProperties.lineStyle.color': candleUpColor, 'mainSeriesProperties.areaStyle.color1': candleUpColor, 'mainSeriesProperties.areaStyle.color2': candleUpColor, 'mainSeriesProperties.areaStyle.linecolor': candleUpColor, 'volumePaneSize': 'medium' }; } function getStudiesOverrides({ volume0, volume1 }) { return { 'volume.volume.color.0': volume0, 'volume.volume.color.1': volume1 }; } let counter = 0; /** * * @param {Base} Base * @param candlesService * @param {$rootScope.Scope} $scope * @param {app.themes} themes * @return {DexCandleChart} */ const controller = function (Base, candlesService, $scope, themes, user) { class DexCandleChart extends Base { constructor() { super(); /** * @type {string} */ this.elementId = `tradingview${counter++}`; /** * @type {boolean} */ this.notLoaded = false; /** * @type {TradingView} * @private */ this._chart = null; /** * @type {boolean} * @private */ this._chartReady = false; /** * @type {boolean} * @private */ this._assetIdPairWasChanged = false; /** * @type {boolean} * @private */ this._changeTheme = true; /** * @type {{price: string, amount: string}} */ this._assetIdPair = null; /** * @type {boolean} * @private */ this.loadingTradingView = true; /** * @type {string} * @private */ this.theme = user.getSetting('theme'); /** * @type {string} * @private */ this.candle = user.getSetting('candle'); this.observe('_assetIdPair', this._onChangeAssetPair); this.observe('theme', () => { this._changeTheme = true; this._resetTradingView(); }); this.observe('candle', this._refreshTradingView); this.syncSettings({ _assetIdPair: 'dex.assetIdPair' }); this.syncSettings({ theme: 'theme' }); this.syncSettings({ candle: 'candle' }); } $postLink() { controller.load() .then(() => { this._createTradingView(); this.listenEventEmitter(i18next, 'languageChanged', this._changeLangHandler.bind(this)); }, () => { console.warn('Error 403!'); this.notLoaded = true; }) .then(() => { $scope.$apply(); }); } $onDestroy() { super.$onDestroy(); if (!this.loadingTradingView) { user.setSetting('lastInterval', this._chart.symbolInterval().interval); } this._removeTradingView(); } /** * @private */ _onChangeAssetPair() { if (this._chartReady) { this._setChartPair(); } else { this._assetIdPairWasChanged = true; } } /** * @return {*} * @private */ _resetTradingView() { try { return this._removeTradingView() ._createTradingView(); } catch (e) { // Trading view not loaded } } /** * @return {DexCandleChart} * @private */ _removeTradingView() { candlesService.unsubscribeBars(); try { if (this._chart) { this._chart.remove(); } } catch (e) { // Can't remove _chart } this._chart = null; return this; } /** * @private */ _refreshTradingView() { if (!this._chart) { return null; } const { up, down, volume0, volume1 } = themes.getCurrentCandleSColor(this.candle); const overrides = getOverrides(up, down); const studiesOverrides = getStudiesOverrides({ volume0, volume1 }); this._chart.applyOverrides(overrides); this._chart.applyStudiesOverrides(studiesOverrides); } /** * @return {DexCandleChart} * @private */ _createTradingView() { this.loadingTradingView = true; const { up, down, volume0, volume1 } = themes.getCurrentCandleSColor(this.candle); const themeConf = themes.getTradingViewConfig(this.theme); const overrides = { ...getOverrides(up, down), ...themeConf.OVERRIDES }; const studies_overrides = { ...getStudiesOverrides({ volume0, volume1 }), ...themeConf.STUDIES_OVERRIDES }; const toolbar_bg = themeConf.toolbarBg; const custom_css_url = themeConf.customCssUrl; this._chart = new TradingView.widget({ // debug: true, locale: DexCandleChart._remapLanguageCode(i18next.language), symbol: `${this._assetIdPair.amount}/${this._assetIdPair.price}`, interval: user.getSetting('lastInterval'), container_id: this.elementId, datafeed: candlesService, library_path: 'trading-view/', autosize: true, toolbar_bg, disabled_features: DISABLED_FEATURES, // enabled_features: ENABLED_FEATURES, overrides, studies_overrides, custom_css_url, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone }); this._chart.onChartReady(() => { if (this._changeTheme) { this._chart.applyOverrides(overrides); this._chart.applyStudiesOverrides(studies_overrides); } this._changeTheme = false; this.loadingTradingView = false; if (this._assetIdPairWasChanged) { this._setChartPair(); this._assetIdPairWasChanged = false; this._chartReady = true; } }); this._chart.options.datafeed.onLoadError = () => { this.notLoaded = true; }; return this; } /** * @private */ _setChartPair() { this._chart.symbolInterval(({ interval }) => { this._chart.setSymbol(`${this._assetIdPair.amount}/${this._assetIdPair.price}`, interval); }); } /** * @private */ _changeLangHandler() { return this._resetTradingView(); } static _remapLanguageCode(code) { switch (code) { case 'hi': return 'en'; case 'nl': return 'nl_NL'; case 'zh-Hans-CN': return 'zh'; default: return code; } } } return new DexCandleChart(); }; controller.$inject = ['Base', 'candlesService', '$scope', 'themes', 'user']; controller.load = function () { const script = document.createElement('script'); script.src = '/trading-view/charting_library.min.js'; const promise = new Promise((resolve, reject) => { script.onload = resolve; script.onerror = reject; document.head.appendChild(script); }); controller.load = () => promise; return promise; }; angular.module('app.dex').component('wDexCandleChart', { bindings: {}, templateUrl: 'modules/dex/directives/dexCandleChart/dex-candle-chart.html', transclude: false, controller }); })();
CLIENT-1722: fix remap language
src/modules/dex/directives/dexCandleChart/DexCandleChart.js
CLIENT-1722: fix remap language
<ide><path>rc/modules/dex/directives/dexCandleChart/DexCandleChart.js <ide> * @private <ide> */ <ide> this.candle = user.getSetting('candle'); <del> <ide> this.observe('_assetIdPair', this._onChangeAssetPair); <ide> this.observe('theme', () => { <ide> this._changeTheme = true; <ide> <ide> static _remapLanguageCode(code) { <ide> switch (code) { <del> case 'hi': <add> case 'hi_IN': <ide> return 'en'; <del> case 'nl': <del> return 'nl_NL'; <del> case 'zh-Hans-CN': <add> case 'zh_CN': <ide> return 'zh'; <ide> default: <ide> return code;
Java
apache-2.0
3c1d3871a64dbb04daaa5301ac4e02aa165ef715
0
cloudsoft/brooklyn-tosca,SeaCloudsEU/brooklyn-tosca,cloudsoft/brooklyn-tosca,SeaCloudsEU/brooklyn-tosca,SeaCloudsEU/brooklyn-tosca,cloudsoft/brooklyn-tosca,kiuby88/brooklyn-tosca,kiuby88/brooklyn-tosca,kiuby88/brooklyn-tosca
package org.apache.brooklyn.tosca.a4c.brooklyn; import java.util.Map; import org.apache.brooklyn.api.catalog.BrooklynCatalog; import org.apache.brooklyn.api.catalog.CatalogItem; import org.apache.brooklyn.api.entity.Entity; import org.apache.brooklyn.api.entity.EntitySpec; import org.apache.brooklyn.api.mgmt.ManagementContext; import org.apache.brooklyn.config.ConfigKey; import org.apache.brooklyn.core.catalog.internal.CatalogUtils; import org.apache.brooklyn.entity.software.base.SoftwareProcess; import org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess; import org.apache.brooklyn.location.jclouds.JcloudsLocationConfig; import org.apache.brooklyn.util.collections.MutableMap; import org.apache.brooklyn.util.core.ResourceUtils; import org.apache.brooklyn.util.core.config.ConfigBag; import org.apache.brooklyn.util.core.flags.TypeCoercions; import org.apache.brooklyn.util.text.Strings; import org.apache.commons.lang3.StringUtils; import org.jclouds.compute.domain.OsFamily; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableList; import alien4cloud.model.components.AbstractPropertyValue; import alien4cloud.model.components.ImplementationArtifact; import alien4cloud.model.components.Interface; import alien4cloud.model.components.Operation; import alien4cloud.model.components.ScalarPropertyValue; import alien4cloud.model.topology.NodeTemplate; public class ToscaNodeToEntityConverter { private static final Logger log = LoggerFactory.getLogger(ToscaNodeToEntityConverter.class); private final ManagementContext mgnt; private NodeTemplate nodeTemplate; private String nodeId; private ToscaNodeToEntityConverter(ManagementContext mgmt) { this.mgnt = mgmt; } public static ToscaNodeToEntityConverter with(ManagementContext mgmt) { return new ToscaNodeToEntityConverter(mgmt); } public ToscaNodeToEntityConverter setNodeTemplate(NodeTemplate nodeTemplate) { this.nodeTemplate = nodeTemplate; return this; } public ToscaNodeToEntityConverter setNodeId(String nodeId) { this.nodeId = nodeId; return this; } public EntitySpec<? extends Entity> createSpec() { if (this.nodeTemplate == null) { throw new IllegalStateException("TOSCA node template is missing. You must specify it by using the method #setNodeTemplate(NodeTemplate nodeTemplate)"); } if (StringUtils.isEmpty(this.nodeId)) { throw new IllegalStateException("TOSCA node ID is missing. You must specify it by using the method #setNodeId(String nodeId)"); } EntitySpec<?> spec = null; CatalogItem catalogItem = CatalogUtils.getCatalogItemOptionalVersion(this.mgnt, this.nodeTemplate.getType()); if (catalogItem != null) { log.info("Found Brooklyn catalog item that match node type: " + this.nodeTemplate.getType()); spec = (EntitySpec<?>) this.mgnt.getCatalog().createSpec(catalogItem); } else { try { log.info("Found Brooklyn entity that match node type: " + this.nodeTemplate.getType()); spec = EntitySpec.create((Class<? extends Entity>) Class.forName(this.nodeTemplate.getType())); } catch (ClassNotFoundException e) { log.info("Cannot find any Brooklyn catalog item nor Brooklyn entities that match node type: " + this.nodeTemplate.getType() + ". Defaulting to a VanillaSoftwareProcess"); spec = EntitySpec.create(VanillaSoftwareProcess.class); } } // Applying name from the node template or its ID if (Strings.isNonBlank(this.nodeTemplate.getName())) { spec.displayName(this.nodeTemplate.getName()); } else { spec.displayName(this.nodeId); } // Add TOSCA node type as a property spec.configure("tosca.node.type", this.nodeTemplate.getType()); Map<String, AbstractPropertyValue> properties = this.nodeTemplate.getProperties(); // Applying provisioning properties ConfigBag prov = ConfigBag.newInstance(); prov.putIfNotNull(JcloudsLocationConfig.MIN_RAM, resolve(properties, "mem_size")); prov.putIfNotNull(JcloudsLocationConfig.MIN_DISK, resolve(properties, "disk_size")); prov.putIfNotNull(JcloudsLocationConfig.MIN_CORES, TypeCoercions.coerce(resolve(properties, "num_cpus"), Integer.class)); prov.putIfNotNull(JcloudsLocationConfig.OS_FAMILY, TypeCoercions.coerce(resolve(properties, "os_distribution"), OsFamily.class)); prov.putIfNotNull(JcloudsLocationConfig.OS_VERSION_REGEX, resolve(properties, "os_version")); // TODO: Mapping for "os_arch" and "os_type" are missing spec.configure(SoftwareProcess.PROVISIONING_PROPERTIES, prov.getAllConfig()); // Adding remaining TOSCA properties as EntitySpec properties for (Map.Entry<String, AbstractPropertyValue> property : properties.entrySet()) { if (property.getValue() instanceof ScalarPropertyValue) { spec.configure(property.getKey(), ((ScalarPropertyValue) property.getValue()).getValue()); } } // If the entity spec is of type VanillaSoftwareProcess, we assume that it's running. The operations should // then take care of setting up the correct scripts. if (spec.getType().isAssignableFrom(VanillaSoftwareProcess.class)) { spec.configure(VanillaSoftwareProcess.LAUNCH_COMMAND, "true"); spec.configure(VanillaSoftwareProcess.STOP_COMMAND, "true"); spec.configure(VanillaSoftwareProcess.CHECK_RUNNING_COMMAND, "true"); } // Applying operations final Map<String, Operation> operations = getInterfaceOperations(); if (!operations.isEmpty()) { if (!spec.getType().isAssignableFrom(VanillaSoftwareProcess.class)) { throw new IllegalStateException("Brooklyn entity: " + spec.getImplementation() + " does not support interface operations defined by node template" + this.nodeTemplate.getType()); } applyLifecycle(operations, "create", spec, VanillaSoftwareProcess.INSTALL_COMMAND); applyLifecycle(operations, "configure", spec, VanillaSoftwareProcess.CUSTOMIZE_COMMAND); applyLifecycle(operations, "start", spec, VanillaSoftwareProcess.LAUNCH_COMMAND); applyLifecycle(operations, "stop", spec, VanillaSoftwareProcess.STOP_COMMAND); if (!operations.isEmpty()) { log.warn("Could not translate some operations for " + this.nodeId + ": " + operations.keySet()); } } return spec; } protected Map<String, Operation> getInterfaceOperations() { final Map<String, Operation> operations = MutableMap.of(); if (this.nodeTemplate.getInterfaces() != null) { final ImmutableList<String> validInterfaceNames = ImmutableList.of("tosca.interfaces.node.lifecycle.Standard", "Standard", "standard"); final MutableMap<String, Interface> interfaces = MutableMap.copyOf(this.nodeTemplate.getInterfaces()); for (String validInterfaceName : validInterfaceNames) { Interface validInterface = interfaces.remove(validInterfaceName); if (validInterface != null) { operations.putAll(validInterface.getOperations()); if (!interfaces.isEmpty()) { log.warn("Could not translate some interfaces for " + this.nodeId + ": " + interfaces.keySet()); } break; } } } return operations; } protected void applyLifecycle(Map<String, Operation> ops, String opKey, EntitySpec<? extends Entity> spec, ConfigKey<String> cmdKey) { Operation op = ops.remove(opKey); if (op == null) { return; } ImplementationArtifact artifact = op.getImplementationArtifact(); if (artifact != null) { String ref = artifact.getArtifactRef(); if (ref != null) { // TODO get script/artifact relative to CSAR String script = new ResourceUtils(this).getResourceAsString(ref); String setScript = (String) spec.getConfig().get(cmdKey); if (Strings.isBlank(setScript) || setScript.trim().equals("true")) { setScript = script; } else { setScript += "\n"+script; } spec.configure(cmdKey, setScript); return; } log.warn("Unsupported operation implementation for " + opKey + ": " + artifact + " has no ref"); return; } log.warn("Unsupported operation implementation for " + opKey + ": " + artifact + " has no impl"); } public static String resolve(Map<String, AbstractPropertyValue> props, String... keys) { for (String key: keys) { AbstractPropertyValue v = props.remove(key); if (v == null) { continue; } if (v instanceof ScalarPropertyValue) { return ((ScalarPropertyValue)v).getValue(); } log.warn("Ignoring unsupported property value " + v); } return null; } }
src/main/javac/org/apache/brooklyn/tosca/a4c/brooklyn/ToscaNodeToEntityConverter.java
package org.apache.brooklyn.tosca.a4c.brooklyn; import java.util.Map; import org.apache.brooklyn.api.catalog.BrooklynCatalog; import org.apache.brooklyn.api.catalog.CatalogItem; import org.apache.brooklyn.api.entity.Entity; import org.apache.brooklyn.api.entity.EntitySpec; import org.apache.brooklyn.api.mgmt.ManagementContext; import org.apache.brooklyn.config.ConfigKey; import org.apache.brooklyn.core.catalog.internal.CatalogUtils; import org.apache.brooklyn.entity.software.base.SoftwareProcess; import org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess; import org.apache.brooklyn.location.jclouds.JcloudsLocationConfig; import org.apache.brooklyn.util.collections.MutableMap; import org.apache.brooklyn.util.core.ResourceUtils; import org.apache.brooklyn.util.core.config.ConfigBag; import org.apache.brooklyn.util.core.flags.TypeCoercions; import org.apache.brooklyn.util.text.Strings; import org.apache.commons.lang3.StringUtils; import org.jclouds.compute.domain.OsFamily; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import alien4cloud.model.components.AbstractPropertyValue; import alien4cloud.model.components.ImplementationArtifact; import alien4cloud.model.components.Interface; import alien4cloud.model.components.Operation; import alien4cloud.model.components.ScalarPropertyValue; import alien4cloud.model.topology.NodeTemplate; public class ToscaNodeToEntityConverter { private static final Logger log = LoggerFactory.getLogger(ToscaNodeToEntityConverter.class); private final ManagementContext mgnt; private NodeTemplate nodeTemplate; private String nodeId; private ToscaNodeToEntityConverter(ManagementContext mgmt) { this.mgnt = mgmt; } public static ToscaNodeToEntityConverter with(ManagementContext mgmt) { return new ToscaNodeToEntityConverter(mgmt); } public ToscaNodeToEntityConverter setNodeTemplate(NodeTemplate nodeTemplate) { this.nodeTemplate = nodeTemplate; return this; } public ToscaNodeToEntityConverter setNodeId(String nodeId) { this.nodeId = nodeId; return this; } public EntitySpec<? extends Entity> createSpec() { if (this.nodeTemplate == null) { throw new IllegalStateException("TOSCA node template is missing. You must specify it by using the method #setNodeTemplate(NodeTemplate nodeTemplate)"); } if (StringUtils.isEmpty(this.nodeId)) { throw new IllegalStateException("TOSCA node ID is missing. You must specify it by using the method #setNodeId(String nodeId)"); } EntitySpec<?> spec = null; CatalogItem<?, EntitySpec<?>> catalogItem = getEntityCatalogItem(); if (catalogItem != null) { log.info("Found Brooklyn catalog item that match node type: " + this.nodeTemplate.getType()); spec = (EntitySpec<?>) this.mgnt.getCatalog().createSpec((CatalogItem) catalogItem); } else { try { log.info("Found Brooklyn entity that match node type: " + this.nodeTemplate.getType()); spec = EntitySpec.create((Class<? extends Entity>) Class.forName(this.nodeTemplate.getType())); } catch (ClassNotFoundException e) { log.info("Cannot find any Brooklyn catalog item nor Brooklyn entities that match node type: " + this.nodeTemplate.getType() + ". Defaulting to a VanillaSoftwareProcess"); spec = EntitySpec.create(VanillaSoftwareProcess.class); } } // Applying name from the node template or its ID if (Strings.isNonBlank(this.nodeTemplate.getName())) { spec.displayName(this.nodeTemplate.getName()); } else { spec.displayName(this.nodeId); } // Add TOSCA node type as a property spec.configure("tosca.node.type", this.nodeTemplate.getType()); Map<String, AbstractPropertyValue> properties = this.nodeTemplate.getProperties(); // Applying provisioning properties ConfigBag prov = ConfigBag.newInstance(); prov.putIfNotNull(JcloudsLocationConfig.MIN_RAM, resolve(properties, "mem_size")); prov.putIfNotNull(JcloudsLocationConfig.MIN_DISK, resolve(properties, "disk_size")); prov.putIfNotNull(JcloudsLocationConfig.MIN_CORES, TypeCoercions.coerce(resolve(properties, "num_cpus"), Integer.class)); prov.putIfNotNull(JcloudsLocationConfig.OS_FAMILY, TypeCoercions.coerce(resolve(properties, "os_distribution"), OsFamily.class)); prov.putIfNotNull(JcloudsLocationConfig.OS_VERSION_REGEX, resolve(properties, "os_version")); // TODO: Mapping for "os_arch" and "os_type" are missing spec.configure(SoftwareProcess.PROVISIONING_PROPERTIES, prov.getAllConfig()); // Adding remaining TOSCA properties as EntitySpec properties for (Map.Entry<String, AbstractPropertyValue> property : properties.entrySet()) { if (property.getValue() instanceof ScalarPropertyValue) { spec.configure(property.getKey(), ((ScalarPropertyValue) property.getValue()).getValue()); } } // If the entity spec is of type VanillaSoftwareProcess, we assume that it's running. The operations should // then take care of setting up the correct scripts. if (spec.getType().isAssignableFrom(VanillaSoftwareProcess.class)) { spec.configure(VanillaSoftwareProcess.LAUNCH_COMMAND, "true"); spec.configure(VanillaSoftwareProcess.STOP_COMMAND, "true"); spec.configure(VanillaSoftwareProcess.CHECK_RUNNING_COMMAND, "true"); } // Applying operations final Map<String, Operation> operations = getInterfaceOperations(); if (!operations.isEmpty()) { if (!spec.getType().isAssignableFrom(VanillaSoftwareProcess.class)) { throw new IllegalStateException("Brooklyn entity: " + spec.getImplementation() + " does not support interface operations defined by node template" + this.nodeTemplate.getType()); } applyLifecycle(operations, "create", spec, VanillaSoftwareProcess.INSTALL_COMMAND); applyLifecycle(operations, "configure", spec, VanillaSoftwareProcess.CUSTOMIZE_COMMAND); applyLifecycle(operations, "start", spec, VanillaSoftwareProcess.LAUNCH_COMMAND); applyLifecycle(operations, "stop", spec, VanillaSoftwareProcess.STOP_COMMAND); if (!operations.isEmpty()) { log.warn("Could not translate some operations for " + this.nodeId + ": " + operations.keySet()); } } return spec; } protected CatalogItem<?, EntitySpec<?>> getEntityCatalogItem() { if (CatalogUtils.looksLikeVersionedId(this.nodeTemplate.getType())) { String id = CatalogUtils.getIdFromVersionedId(this.nodeTemplate.getType()); String version = CatalogUtils.getVersionFromVersionedId(this.nodeTemplate.getType()); return (CatalogItem<?, EntitySpec<?>>) this.mgnt.getCatalog().getCatalogItem(id, version); } else { return (CatalogItem<?, EntitySpec<?>>) this.mgnt.getCatalog().getCatalogItem(this.nodeTemplate.getType(), BrooklynCatalog.DEFAULT_VERSION); } } protected Map<String, Operation> getInterfaceOperations() { Map<String, Operation> operations = MutableMap.of(); // then get interface operations from node template if (this.nodeTemplate.getInterfaces() != null) { MutableMap<String, Interface> ifs = MutableMap.copyOf(this.nodeTemplate.getInterfaces()); Interface ifa = null; if (ifa == null) { ifa = ifs.remove("tosca.interfaces.node.lifecycle.Standard"); } if (ifa == null) { ifa = ifs.remove("standard"); } if (ifa == null) { ifs.remove("Standard"); } if (ifa!=null) { operations.putAll(ifa.getOperations()); } if (!ifs.isEmpty()) { log.warn("Could not translate some interfaces for " + this.nodeId + ": " + ifs.keySet()); } } return operations; } protected void applyLifecycle(Map<String, Operation> ops, String opKey, EntitySpec<? extends Entity> spec, ConfigKey<String> cmdKey) { Operation op = ops.remove(opKey); if (op == null) { return; } ImplementationArtifact artifact = op.getImplementationArtifact(); if (artifact != null) { String ref = artifact.getArtifactRef(); if (ref != null) { // TODO get script/artifact relative to CSAR String script = new ResourceUtils(this).getResourceAsString(ref); String setScript = (String) spec.getConfig().get(cmdKey); if (Strings.isBlank(setScript) || setScript.trim().equals("true")) { setScript = script; } else { setScript += "\n"+script; } spec.configure(cmdKey, setScript); return; } log.warn("Unsupported operation implementation for " + opKey + ": " + artifact + " has no ref"); return; } log.warn("Unsupported operation implementation for " + opKey + ": " + artifact + " has no impl"); } public static String resolve(Map<String, AbstractPropertyValue> props, String... keys) { for (String key: keys) { AbstractPropertyValue v = props.remove(key); if (v == null) { continue; } if (v instanceof ScalarPropertyValue) { return ((ScalarPropertyValue)v).getValue(); } log.warn("Ignoring unsupported property value " + v); } return null; } }
Addresses PR comments
src/main/javac/org/apache/brooklyn/tosca/a4c/brooklyn/ToscaNodeToEntityConverter.java
Addresses PR comments
<ide><path>rc/main/javac/org/apache/brooklyn/tosca/a4c/brooklyn/ToscaNodeToEntityConverter.java <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> <add>import com.google.common.collect.ImmutableList; <add> <ide> import alien4cloud.model.components.AbstractPropertyValue; <ide> import alien4cloud.model.components.ImplementationArtifact; <ide> import alien4cloud.model.components.Interface; <ide> <ide> EntitySpec<?> spec = null; <ide> <del> CatalogItem<?, EntitySpec<?>> catalogItem = getEntityCatalogItem(); <add> CatalogItem catalogItem = CatalogUtils.getCatalogItemOptionalVersion(this.mgnt, this.nodeTemplate.getType()); <ide> if (catalogItem != null) { <ide> log.info("Found Brooklyn catalog item that match node type: " + this.nodeTemplate.getType()); <del> spec = (EntitySpec<?>) this.mgnt.getCatalog().createSpec((CatalogItem) catalogItem); <add> spec = (EntitySpec<?>) this.mgnt.getCatalog().createSpec(catalogItem); <ide> } else { <ide> try { <ide> log.info("Found Brooklyn entity that match node type: " + this.nodeTemplate.getType()); <ide> return spec; <ide> } <ide> <del> protected CatalogItem<?, EntitySpec<?>> getEntityCatalogItem() { <del> if (CatalogUtils.looksLikeVersionedId(this.nodeTemplate.getType())) { <del> String id = CatalogUtils.getIdFromVersionedId(this.nodeTemplate.getType()); <del> String version = CatalogUtils.getVersionFromVersionedId(this.nodeTemplate.getType()); <del> return (CatalogItem<?, EntitySpec<?>>) this.mgnt.getCatalog().getCatalogItem(id, version); <del> } else { <del> return (CatalogItem<?, EntitySpec<?>>) this.mgnt.getCatalog().getCatalogItem(this.nodeTemplate.getType(), BrooklynCatalog.DEFAULT_VERSION); <del> } <del> } <del> <ide> protected Map<String, Operation> getInterfaceOperations() { <del> Map<String, Operation> operations = MutableMap.of(); <del> <del> // then get interface operations from node template <add> final Map<String, Operation> operations = MutableMap.of(); <add> <ide> if (this.nodeTemplate.getInterfaces() != null) { <del> MutableMap<String, Interface> ifs = MutableMap.copyOf(this.nodeTemplate.getInterfaces()); <del> Interface ifa = null; <del> if (ifa == null) { <del> ifa = ifs.remove("tosca.interfaces.node.lifecycle.Standard"); <del> } <del> if (ifa == null) { <del> ifa = ifs.remove("standard"); <del> } <del> if (ifa == null) { <del> ifs.remove("Standard"); <del> } <del> <del> if (ifa!=null) { <del> operations.putAll(ifa.getOperations()); <del> } <del> <del> if (!ifs.isEmpty()) { <del> log.warn("Could not translate some interfaces for " + this.nodeId + ": " + ifs.keySet()); <add> final ImmutableList<String> validInterfaceNames = ImmutableList.of("tosca.interfaces.node.lifecycle.Standard", "Standard", "standard"); <add> final MutableMap<String, Interface> interfaces = MutableMap.copyOf(this.nodeTemplate.getInterfaces()); <add> <add> for (String validInterfaceName : validInterfaceNames) { <add> Interface validInterface = interfaces.remove(validInterfaceName); <add> if (validInterface != null) { <add> operations.putAll(validInterface.getOperations()); <add> if (!interfaces.isEmpty()) { <add> log.warn("Could not translate some interfaces for " + this.nodeId + ": " + interfaces.keySet()); <add> } <add> break; <add> } <ide> } <ide> } <ide>
Java
mit
9fe501bcc32c53f92e6733a73dbcdd70e86f99d2
0
weisJ/darklaf,weisJ/darklaf,weisJ/darklaf,weisJ/darklaf
/* * MIT License * * Copyright (c) 2020-2022 Jannis Weis * * 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.github.weisj.darklaf.ui.tooltip; import java.awt.*; import java.util.Objects; import java.util.function.BiConsumer; import javax.swing.*; import javax.swing.border.Border; import com.github.weisj.darklaf.components.tooltip.ToolTipContext; import com.github.weisj.darklaf.components.tooltip.ToolTipStyle; import com.github.weisj.darklaf.ui.util.DarkUIUtil; import com.github.weisj.darklaf.ui.util.WindowUtil; import com.github.weisj.darklaf.util.Alignment; public final class ToolTipUtil { public static void applyContext(final JToolTip toolTip) { JComponent target = toolTip.getComponent(); if (target == null) return; ToolTipContext context = getToolTipContext(toolTip); if (context == null) return; context.setTarget(target); context.setToolTip(toolTip); Point p = MouseInfo.getPointerInfo().getLocation(); SwingUtilities.convertPointFromScreen(p, target); LocationResult pos = getBestPositionMatch(context, p); if (pos.point != null) { moveToolTip(toolTip, pos, target); } } private static LocationResult getBestPositionMatch(final ToolTipContext context, final Point p) { if (!context.isBestFit()) { return new LocationResult(context.getToolTipLocation(p, null), true); } Alignment original = context.getAlignment(); Alignment originalCenter = context.getCenterAlignment(); LayoutConstraints layoutConstraints = calculateLayoutConstraints(context, p); boolean isCenter = original == Alignment.CENTER; Alignment targetAlignment = isCenter ? originalCenter : original; if (context.isChooseBestInitialAlignment()) { targetAlignment = probeAlignment(context, layoutConstraints); } boolean centerVertically = targetAlignment.isHorizontal(); boolean centerHorizontally = targetAlignment.isVertical(); Alignment[] alignments = getAlignments(targetAlignment); Point pos; BiConsumer<ToolTipContext, Alignment> setter = isCenter ? ToolTipContext::setCenterAlignment : ToolTipContext::setAlignment; // Check if a position keeps the tooltip inside the window. pos = tryAlignments(alignments, context, p, layoutConstraints, setter, centerHorizontally, centerVertically); if (pos == null) { // Try again with screen bounds instead. layoutConstraints.windowBounds.setBounds(layoutConstraints.screenBoundary); pos = tryAlignments(alignments, context, p, layoutConstraints, setter, centerHorizontally, centerVertically); } LocationResult result; /* * At this point if the tooltip is still extending outside the screen boundary we surrender and * leave the tooltip as it was. */ if (pos == null) { context.setAlignment(Alignment.CENTER); context.setCenterAlignment(Alignment.CENTER); result = new LocationResult( context.getFallBackPositionProvider().calculateFallbackPosition(context), !context.getFallBackPositionProvider().providesAbsolutePosition()); } else { result = new LocationResult(pos, true); } context.updateToolTip(); context.setAlignment(original); context.setCenterAlignment(originalCenter); return result; } private static Alignment probeAlignment(final ToolTipContext context, final LayoutConstraints layoutConstraints) { JComponent target = context.getTarget(); if (target == null) return Alignment.SOUTH; Rectangle targetBounds = target.getBounds(); Point center = new Point(targetBounds.width / 2, targetBounds.height / 2); center = SwingUtilities.convertPoint(target, center, layoutConstraints.window); Rectangle windowBounds = layoutConstraints.windowBounds; if (center.y < windowBounds.height / 4) return Alignment.SOUTH; if (center.y > 3 * windowBounds.height / 4) return Alignment.NORTH; if (center.x - layoutConstraints.tooltipBounds.width / 2 < 0) return Alignment.EAST; if (center.x + layoutConstraints.tooltipBounds.width / 2 > windowBounds.width) return Alignment.WEST; return Alignment.SOUTH; } private static LayoutConstraints calculateLayoutConstraints(final ToolTipContext context, final Point p) { Window window = DarkUIUtil.getWindow(context.getTarget()); Rectangle screenBounds = DarkUIUtil.getScreenBounds(context.getTarget(), p); Rectangle windowBounds = window.getBounds(); JToolTip toolTip = context.getToolTip(); Rectangle tooltipBounds = new Rectangle(toolTip.getPreferredSize()); Border tooltipBorder = toolTip.getBorder(); Insets layoutInsets = tooltipBorder instanceof AlignableTooltipBorder ? ((AlignableTooltipBorder) tooltipBorder).getAlignmentInsets(toolTip) : new Insets(0, 0, 0, 0); return new LayoutConstraints(tooltipBounds, windowBounds, window, screenBounds, layoutInsets); } private static Point tryAlignments(final Alignment[] alignments, final ToolTipContext context, final Point p, final LayoutConstraints layoutConstraints, final BiConsumer<ToolTipContext, Alignment> setter, final boolean centerHorizontally, final boolean centerVertically) { Point pos = null; for (Alignment a : alignments) { if ((centerHorizontally || centerVertically) && a.isDiagonal()) { pos = tryPosition(a, context, p, layoutConstraints, setter, centerHorizontally, centerVertically); if (pos != null) break; } pos = tryPosition(a, context, p, layoutConstraints, setter, false, false); if (pos != null) break; } return pos; } private static Alignment[] getAlignments(final Alignment start) { /* * Example with start == NORTH: [NORTH, NORTH_WEST, NORTH_EAST, SOUTH, SOUTH_WEST, SOUTH_EAST, WEST, * EAST] */ Alignment opposite = start.opposite(); Alignment clockwise = start.clockwise(); Alignment anticlockwise = start.anticlockwise(); return new Alignment[] { start, anticlockwise, clockwise, opposite, opposite.clockwise(), opposite.anticlockwise(), anticlockwise.anticlockwise(), clockwise.clockwise(), }; } private static Point tryPosition(final Alignment a, final ToolTipContext context, final Point p, final LayoutConstraints layoutConstraints, final BiConsumer<ToolTipContext, Alignment> setter, final boolean centerHorizontally, final boolean centerVertically) { setter.accept(context, a); context.setCenterAlignment(a); context.updateToolTip(); Point pos = context.getToolTipLocation(p, null, centerHorizontally, centerVertically); Point screenPos = new Point(pos.x, pos.y); SwingUtilities.convertPointToScreen(screenPos, context.getTarget()); layoutConstraints.tooltipBounds.setLocation(screenPos); if (!fits(layoutConstraints)) pos = null; return pos; } private static boolean fits(final LayoutConstraints layoutConstraints) { final Rectangle testRectangle = layoutConstraints.testRectangle(); if (Objects.equals(layoutConstraints.windowBounds, layoutConstraints.screenBoundary)) { return SwingUtilities.isRectangleContainingRectangle(layoutConstraints.screenBoundary, testRectangle); } return SwingUtilities.isRectangleContainingRectangle(layoutConstraints.windowBounds, testRectangle) && SwingUtilities.isRectangleContainingRectangle(layoutConstraints.screenBoundary, testRectangle); } private static ToolTipContext getToolTipContext(final JToolTip tooltip) { Object context = tooltip.getClientProperty(DarkToolTipUI.KEY_CONTEXT); if (context instanceof ToolTipContext) { return (ToolTipContext) context; } context = tooltip.getComponent().getClientProperty(DarkToolTipUI.KEY_CONTEXT); if (context instanceof ToolTipContext) { return (ToolTipContext) context; } Object style = tooltip.getComponent().getClientProperty(DarkToolTipUI.KEY_STYLE); if (ToolTipStyle.BALLOON.equals(ToolTipStyle.parse(style))) { return ToolTipContext.getDefaultContext(); } return null; } public static void moveToolTip(final JToolTip toolTip, final LocationResult result, final JComponent target) { Window window = DarkUIUtil.getWindow(toolTip); if (window == null) return; if (result.isRelative) { SwingUtilities.convertPointToScreen(result.point, target); } WindowUtil.moveWindow(window, toolTip, result.point.x, result.point.y); } private static class LocationResult { private final Point point; private final boolean isRelative; private LocationResult(Point point, boolean isRelative) { this.point = point; this.isRelative = isRelative; } } private static final class LayoutConstraints { private final Rectangle tooltipBounds; private final Rectangle windowBounds; private final Window window; private final Rectangle screenBoundary; private final Insets layoutInsets; private LayoutConstraints(final Rectangle tooltipBounds, final Rectangle windowBounds, final Window window, final Rectangle screenBoundary, Insets layoutInsets) { this.tooltipBounds = tooltipBounds; this.windowBounds = windowBounds; this.window = window; this.screenBoundary = screenBoundary; this.layoutInsets = layoutInsets; } public Rectangle testRectangle() { return DarkUIUtil.applyInsets(new Rectangle(tooltipBounds), layoutInsets); } @Override public String toString() { return "LayoutConstraints{" + "tooltipBounds=" + tooltipBounds + ", layoutInsets=" + layoutInsets + ", screenBoundary=" + screenBoundary + ", windowBounds=" + windowBounds + ", window=" + window + '}'; } } }
core/src/main/java/com/github/weisj/darklaf/ui/tooltip/ToolTipUtil.java
/* * MIT License * * Copyright (c) 2020-2022 Jannis Weis * * 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.github.weisj.darklaf.ui.tooltip; import java.awt.*; import java.util.Objects; import java.util.function.BiConsumer; import javax.swing.*; import javax.swing.border.Border; import com.github.weisj.darklaf.components.tooltip.ToolTipContext; import com.github.weisj.darklaf.components.tooltip.ToolTipStyle; import com.github.weisj.darklaf.ui.util.DarkUIUtil; import com.github.weisj.darklaf.ui.util.WindowUtil; import com.github.weisj.darklaf.util.Alignment; public final class ToolTipUtil { public static void applyContext(final JToolTip toolTip) { JComponent target = toolTip.getComponent(); if (target == null) return; ToolTipContext context = getToolTipContext(toolTip); if (context == null) return; context.setTarget(target); context.setToolTip(toolTip); Point p = MouseInfo.getPointerInfo().getLocation(); SwingUtilities.convertPointFromScreen(p, target); LocationResult pos = getBestPositionMatch(context, p); if (pos.point != null) { moveToolTip(toolTip, pos, target); } } private static LocationResult getBestPositionMatch(final ToolTipContext context, final Point p) { if (!context.isBestFit()) { return new LocationResult(context.getToolTipLocation(p, null), true); } Alignment original = context.getAlignment(); Alignment originalCenter = context.getCenterAlignment(); LayoutConstraints layoutConstraints = calculateLayoutConstraints(context, p); boolean isCenter = original == Alignment.CENTER; Alignment targetAlignment = isCenter ? originalCenter : original; if (context.isChooseBestInitialAlignment()) { targetAlignment = probeAlignment(context, layoutConstraints); } boolean centerVertically = targetAlignment.isHorizontal(); boolean centerHorizontally = targetAlignment.isVertical(); Alignment[] alignments = getAlignments(targetAlignment); Point pos; BiConsumer<ToolTipContext, Alignment> setter = isCenter ? ToolTipContext::setCenterAlignment : ToolTipContext::setAlignment; // Check if a position keeps the tooltip inside the window. pos = tryAlignments(alignments, context, p, layoutConstraints, setter, centerHorizontally, centerVertically); if (pos == null) { // Try again with screen bounds instead. pos = tryAlignments(alignments, context, p, layoutConstraints, setter, centerHorizontally, centerVertically); } LocationResult result; /* * At this point if the tooltip is still extending outside the screen boundary we surrender and * leave the tooltip as it was. */ if (pos == null) { context.setAlignment(Alignment.CENTER); context.setCenterAlignment(Alignment.CENTER); result = new LocationResult( context.getFallBackPositionProvider().calculateFallbackPosition(context), !context.getFallBackPositionProvider().providesAbsolutePosition()); } else { result = new LocationResult(pos, true); } context.updateToolTip(); context.setAlignment(original); context.setCenterAlignment(originalCenter); return result; } private static Alignment probeAlignment(final ToolTipContext context, final LayoutConstraints layoutConstraints) { JComponent target = context.getTarget(); if (target == null) return Alignment.SOUTH; Rectangle targetBounds = target.getBounds(); Point center = new Point(targetBounds.width / 2, targetBounds.height / 2); center = SwingUtilities.convertPoint(target, center, layoutConstraints.window); Rectangle windowBounds = layoutConstraints.windowBounds; if (center.y < windowBounds.height / 4) return Alignment.SOUTH; if (center.y > 3 * windowBounds.height / 4) return Alignment.NORTH; if (center.x - layoutConstraints.tooltipBounds.width / 2 < 0) return Alignment.EAST; if (center.x + layoutConstraints.tooltipBounds.width / 2 > windowBounds.width) return Alignment.WEST; return Alignment.SOUTH; } private static LayoutConstraints calculateLayoutConstraints(final ToolTipContext context, final Point p) { Window window = DarkUIUtil.getWindow(context.getTarget()); Rectangle screenBounds = DarkUIUtil.getScreenBounds(context.getTarget(), p); Rectangle windowBounds = window.getBounds(); JToolTip toolTip = context.getToolTip(); Rectangle tooltipBounds = new Rectangle(toolTip.getPreferredSize()); Border tooltipBorder = toolTip.getBorder(); Insets layoutInsets = tooltipBorder instanceof AlignableTooltipBorder ? ((AlignableTooltipBorder) tooltipBorder).getAlignmentInsets(toolTip) : new Insets(0, 0, 0, 0); return new LayoutConstraints(tooltipBounds, windowBounds, window, screenBounds, layoutInsets); } private static Point tryAlignments(final Alignment[] alignments, final ToolTipContext context, final Point p, final LayoutConstraints layoutConstraints, final BiConsumer<ToolTipContext, Alignment> setter, final boolean centerHorizontally, final boolean centerVertically) { Point pos = null; for (Alignment a : alignments) { System.out.print(a + " => "); if ((centerHorizontally || centerVertically) && a.isDiagonal()) { pos = tryPosition(a, context, p, layoutConstraints, setter, centerHorizontally, centerVertically); if (pos != null) break; } pos = tryPosition(a, context, p, layoutConstraints, setter, false, false); System.out.println(pos); if (pos != null) break; } return pos; } private static Alignment[] getAlignments(final Alignment start) { /* * Example with start == NORTH: [NORTH, NORTH_WEST, NORTH_EAST, SOUTH, SOUTH_WEST, SOUTH_EAST, WEST, * EAST] */ Alignment opposite = start.opposite(); Alignment clockwise = start.clockwise(); Alignment anticlockwise = start.anticlockwise(); return new Alignment[] { start, anticlockwise, clockwise, opposite, opposite.clockwise(), opposite.anticlockwise(), anticlockwise.anticlockwise(), clockwise.clockwise(), }; } private static Point tryPosition(final Alignment a, final ToolTipContext context, final Point p, final LayoutConstraints layoutConstraints, final BiConsumer<ToolTipContext, Alignment> setter, final boolean centerHorizontally, final boolean centerVertically) { setter.accept(context, a); context.setCenterAlignment(a); context.updateToolTip(); Point pos = context.getToolTipLocation(p, null, centerHorizontally, centerVertically); Point screenPos = new Point(pos.x, pos.y); SwingUtilities.convertPointToScreen(screenPos, context.getTarget()); layoutConstraints.tooltipBounds.setLocation(screenPos); if (!fits(layoutConstraints)) pos = null; return pos; } private static boolean fits(final LayoutConstraints layoutConstraints) { final Rectangle testRectangle = layoutConstraints.testRectangle(); if (Objects.equals(layoutConstraints.windowBounds, layoutConstraints.screenBoundary)) { return SwingUtilities.isRectangleContainingRectangle(layoutConstraints.windowBounds, testRectangle); } return SwingUtilities.isRectangleContainingRectangle(layoutConstraints.windowBounds, testRectangle) && SwingUtilities.isRectangleContainingRectangle(layoutConstraints.screenBoundary, testRectangle); } private static ToolTipContext getToolTipContext(final JToolTip tooltip) { Object context = tooltip.getClientProperty(DarkToolTipUI.KEY_CONTEXT); if (context instanceof ToolTipContext) { return (ToolTipContext) context; } context = tooltip.getComponent().getClientProperty(DarkToolTipUI.KEY_CONTEXT); if (context instanceof ToolTipContext) { return (ToolTipContext) context; } Object style = tooltip.getComponent().getClientProperty(DarkToolTipUI.KEY_STYLE); if (ToolTipStyle.BALLOON.equals(ToolTipStyle.parse(style))) { return ToolTipContext.getDefaultContext(); } return null; } public static void moveToolTip(final JToolTip toolTip, final LocationResult result, final JComponent target) { Window window = DarkUIUtil.getWindow(toolTip); if (window == null) return; if (result.isRelative) { SwingUtilities.convertPointToScreen(result.point, target); } WindowUtil.moveWindow(window, toolTip, result.point.x, result.point.y); } private static class LocationResult { private final Point point; private final boolean isRelative; private LocationResult(Point point, boolean isRelative) { this.point = point; this.isRelative = isRelative; } } private static final class LayoutConstraints { private final Rectangle tooltipBounds; private final Rectangle windowBounds; private final Window window; private final Rectangle screenBoundary; private final Insets layoutInsets; private LayoutConstraints(final Rectangle tooltipBounds, final Rectangle windowBounds, final Window window, final Rectangle screenBoundary, Insets layoutInsets) { this.tooltipBounds = tooltipBounds; this.windowBounds = windowBounds; this.window = window; this.screenBoundary = screenBoundary; this.layoutInsets = layoutInsets; } public Rectangle testRectangle() { return DarkUIUtil.applyInsets(new Rectangle(tooltipBounds), layoutInsets); } @Override public String toString() { return "LayoutConstraints{" + "tooltipBounds=" + tooltipBounds + ", layoutInsets=" + layoutInsets + ", screenBoundary=" + screenBoundary + ", windowBounds=" + windowBounds + ", window=" + window + '}'; } } }
Actually try screen bounds instead of window bounds in second pass
core/src/main/java/com/github/weisj/darklaf/ui/tooltip/ToolTipUtil.java
Actually try screen bounds instead of window bounds in second pass
<ide><path>ore/src/main/java/com/github/weisj/darklaf/ui/tooltip/ToolTipUtil.java <ide> pos = tryAlignments(alignments, context, p, layoutConstraints, setter, centerHorizontally, centerVertically); <ide> if (pos == null) { <ide> // Try again with screen bounds instead. <add> layoutConstraints.windowBounds.setBounds(layoutConstraints.screenBoundary); <ide> pos = tryAlignments(alignments, context, p, layoutConstraints, setter, centerHorizontally, <ide> centerVertically); <ide> } <ide> <ide> LocationResult result; <del> <ide> /* <ide> * At this point if the tooltip is still extending outside the screen boundary we surrender and <ide> * leave the tooltip as it was. <ide> final boolean centerHorizontally, final boolean centerVertically) { <ide> Point pos = null; <ide> for (Alignment a : alignments) { <del> System.out.print(a + " => "); <ide> if ((centerHorizontally || centerVertically) && a.isDiagonal()) { <ide> pos = tryPosition(a, context, p, layoutConstraints, setter, centerHorizontally, <ide> centerVertically); <ide> if (pos != null) break; <ide> } <ide> pos = tryPosition(a, context, p, layoutConstraints, setter, false, false); <del> System.out.println(pos); <ide> if (pos != null) break; <ide> } <ide> return pos; <ide> final Rectangle testRectangle = layoutConstraints.testRectangle(); <ide> <ide> if (Objects.equals(layoutConstraints.windowBounds, layoutConstraints.screenBoundary)) { <del> return SwingUtilities.isRectangleContainingRectangle(layoutConstraints.windowBounds, testRectangle); <add> return SwingUtilities.isRectangleContainingRectangle(layoutConstraints.screenBoundary, testRectangle); <ide> } <ide> return SwingUtilities.isRectangleContainingRectangle(layoutConstraints.windowBounds, testRectangle) <ide> && SwingUtilities.isRectangleContainingRectangle(layoutConstraints.screenBoundary, testRectangle);
Java
apache-2.0
d2fff12e013964cc43707968735fd835936a8c9f
0
kimchy/compass,johnnywale/compass,johnnywale/compass,johnnywale/compass,kimchy/compass
/* * Copyright 2004-2006 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.compass.gps.device.hibernate.indexer; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.compass.core.CompassSession; import org.compass.gps.device.hibernate.HibernateGpsDevice; import org.compass.gps.device.hibernate.HibernateGpsDeviceException; import org.compass.gps.device.hibernate.entities.EntityInformation; import org.compass.gps.device.support.parallel.IndexEntity; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; /** * A Hibernate indexer uses Hibernate pagination using <code>setFirstResult</code> * and <code>setMaxResults</code>. * * @author kimchy */ public class PaginationHibernateIndexEntitiesIndexer implements HibernateIndexEntitiesIndexer { private static final Log log = LogFactory.getLog(PaginationHibernateIndexEntitiesIndexer.class); private HibernateGpsDevice device; public void setHibernateGpsDevice(HibernateGpsDevice device) { this.device = device; } public void performIndex(CompassSession session, IndexEntity[] entities) { for (int i = 0; i < entities.length; i++) { EntityInformation entityInfo = (EntityInformation) entities[i]; int fetchCount = device.getFetchCount(); int current = 0; while (true) { if (!device.isRunning()) { return; } Session hibernateSession = device.getSessionFactory().openSession(); Transaction hibernateTransaction = null; try { hibernateTransaction = hibernateSession.beginTransaction(); if (log.isDebugEnabled()) { log.debug(device.buildMessage("Indexing entity [" + entityInfo.getName() + "] range [" + current + "-" + (current + fetchCount) + "]")); } List values; Criteria criteria = entityInfo.getQueryProvider().createCriteria(hibernateSession, entityInfo); if (criteria != null) { values = criteria.list(); } else { Query query = entityInfo.getQueryProvider().createQuery(hibernateSession, entityInfo).setFirstResult(current).setMaxResults(fetchCount); values = query.list(); } for (Iterator it = values.iterator(); it.hasNext();) { session.create(it.next()); } session.evictAll(); hibernateTransaction.commit(); session.close(); current += fetchCount; if (values.size() < fetchCount) { break; } } catch (Exception e) { log.error(device.buildMessage("Failed to index the database"), e); if (hibernateTransaction != null) { try { hibernateTransaction.rollback(); } catch (Exception e1) { log.warn("Failed to rollback Hibernate", e1); } } if (!(e instanceof HibernateGpsDeviceException)) { throw new HibernateGpsDeviceException(device.buildMessage("Failed to index the database"), e); } throw (HibernateGpsDeviceException) e; } finally { hibernateSession.close(); } } } } }
src/main/src/org/compass/gps/device/hibernate/indexer/PaginationHibernateIndexEntitiesIndexer.java
/* * Copyright 2004-2006 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.compass.gps.device.hibernate.indexer; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.compass.core.CompassSession; import org.compass.gps.device.hibernate.HibernateGpsDevice; import org.compass.gps.device.hibernate.HibernateGpsDeviceException; import org.compass.gps.device.hibernate.entities.EntityInformation; import org.compass.gps.device.support.parallel.IndexEntity; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; /** * A Hibernate indexer uses Hibernate pagination using <code>setFirstResult</code> * and <code>setMaxResults</code>. * * @author kimchy */ public class PaginationHibernateIndexEntitiesIndexer implements HibernateIndexEntitiesIndexer { private static final Log log = LogFactory.getLog(PaginationHibernateIndexEntitiesIndexer.class); private HibernateGpsDevice device; public void setHibernateGpsDevice(HibernateGpsDevice device) { this.device = device; } public void performIndex(CompassSession session, IndexEntity[] entities) { for (int i = 0; i < entities.length; i++) { EntityInformation entityInfo = (EntityInformation) entities[i]; int fetchCount = device.getFetchCount(); int current = 0; while (true) { if (!device.isRunning()) { return; } Session hibernateSession = device.getSessionFactory().openSession(); Transaction hibernateTransaction = null; try { hibernateTransaction = hibernateSession.beginTransaction(); if (log.isDebugEnabled()) { log.debug(device.buildMessage("Indexing entity [" + entityInfo.getName() + "] range [" + current + "-" + (current + fetchCount) + "]")); } Query query = entityInfo.getQueryProvider().createQuery(hibernateSession, entityInfo).setFirstResult(current).setMaxResults(fetchCount); List values = query.list(); for (Iterator it = values.iterator(); it.hasNext();) { session.create(it.next()); } session.evictAll(); hibernateTransaction.commit(); session.close(); current += fetchCount; if (values.size() < fetchCount) { break; } } catch (Exception e) { log.error(device.buildMessage("Failed to index the database"), e); if (hibernateTransaction != null) { try { hibernateTransaction.rollback(); } catch (Exception e1) { log.warn("Failed to rollback Hibernate", e1); } } if (!(e instanceof HibernateGpsDeviceException)) { throw new HibernateGpsDeviceException(device.buildMessage("Failed to index the database"), e); } throw (HibernateGpsDeviceException) e; } finally { hibernateSession.close(); } } } } }
CMP-477 Improve ScrollableHibernateIndexEntitiesIndexer (use Hibernate Criteria)
src/main/src/org/compass/gps/device/hibernate/indexer/PaginationHibernateIndexEntitiesIndexer.java
CMP-477 Improve ScrollableHibernateIndexEntitiesIndexer (use Hibernate Criteria)
<ide><path>rc/main/src/org/compass/gps/device/hibernate/indexer/PaginationHibernateIndexEntitiesIndexer.java <ide> import org.compass.gps.device.hibernate.HibernateGpsDeviceException; <ide> import org.compass.gps.device.hibernate.entities.EntityInformation; <ide> import org.compass.gps.device.support.parallel.IndexEntity; <add>import org.hibernate.Criteria; <ide> import org.hibernate.Query; <ide> import org.hibernate.Session; <ide> import org.hibernate.Transaction; <ide> log.debug(device.buildMessage("Indexing entity [" + entityInfo.getName() + "] range [" <ide> + current + "-" + (current + fetchCount) + "]")); <ide> } <del> Query query = entityInfo.getQueryProvider().createQuery(hibernateSession, entityInfo).setFirstResult(current).setMaxResults(fetchCount); <del> List values = query.list(); <add> List values; <add> Criteria criteria = entityInfo.getQueryProvider().createCriteria(hibernateSession, entityInfo); <add> if (criteria != null) { <add> values = criteria.list(); <add> } else { <add> Query query = entityInfo.getQueryProvider().createQuery(hibernateSession, entityInfo).setFirstResult(current).setMaxResults(fetchCount); <add> values = query.list(); <add> } <ide> for (Iterator it = values.iterator(); it.hasNext();) { <ide> session.create(it.next()); <ide> }
JavaScript
agpl-3.0
29dcb53f6b5d75de988388450401ba44ce7dfee7
0
usu/ecamp3,ecamp/ecamp3,usu/ecamp3,ecamp/ecamp3,usu/ecamp3,ecamp/ecamp3,ecamp/ecamp3,usu/ecamp3
import { toTime, roundTimeUp, roundTimeDown } from '@/helpers/vCalendarDragAndDrop.js' /** * * @param ref(bool) enabled drag & drop is disabled if enabled=false * @param int threshold min. mouse movement needed to detect drag & drop * @returns */ export default function useDragAndDrop(enabled, createEntry) { /** * internal data (not exposed) */ // timestamp of mouse location when drag & drop event started let mouseStartTimestamp = null // temporary placeholder for new schedule entry, when created via drag & drop let newEntry = null // true if mousedown event was detected on an entry/event let entryWasClicked = false /** * internal methods */ const clear = () => { newEntry = null mouseStartTimestamp = null entryWasClicked = false } // this creates a placeholder for a new schedule entry and make it resizable const createNewEntry = (mouse) => { newEntry = { startTimestamp: roundTimeDown(mouse), endTimestamp: roundTimeDown(mouse), } } // resize placeholder entry const resizeEntry = (entry, mouse) => { const mouseRounded = roundTimeUp(mouse) const min = Math.min(mouseRounded, roundTimeDown(mouseStartTimestamp)) const max = Math.max(mouseRounded, roundTimeDown(mouseStartTimestamp)) entry.startTimestamp = min entry.endTimestamp = max } /** * exposed methods */ // triggered with MouseDown event on a calendar entry const entryMouseDown = ({ event: entry, timed, nativeEvent }) => { if (!enabled.value) { return } // cancel drag & drop if button is not left button if (nativeEvent.button !== 0) { return } if (entry && timed) { entryWasClicked = true } } // triggered with MouseDown event anywhere on the calendar (independent of clicking on entry or not) const timeMouseDown = (tms, nativeEvent) => { if (!enabled.value) { return } // cancel drag & drop if button is not left button if (nativeEvent.button !== 0) { return } if (!entryWasClicked) { // No entry is being dragged --> create a placeholder for a new schedule entry const mouseTime = toTime(tms) mouseStartTimestamp = mouseTime createNewEntry(mouseTime) } } // triggered when mouse is being moved in calendar (independent whether drag & drop is ongoing or not) const timeMouseMove = (tms) => { if (!enabled.value) { return } if (newEntry) { // resize placeholder const mouseTime = toTime(tms) resizeEntry(newEntry, mouseTime) createEntry(newEntry.startTimestamp, newEntry.endTimestamp, false) } } // triggered with MouseUp Event anywhere in the calendar const timeMouseUp = () => { if (!enabled.value) { return } if (newEntry && newEntry.endTimestamp - newEntry.startTimestamp > 0) { // placeholder for new schedule entry was created --> open dialog to create new activity createEntry(newEntry.startTimestamp, newEntry.endTimestamp, true) } clear() } // treat mouseleave as a mouseUp event (finish operation and save last known status) const nativeMouseLeave = () => { timeMouseUp() } return { vCalendarListeners: { 'mousedown:event': entryMouseDown, 'mousedown:time': timeMouseDown, 'mousemove:time': timeMouseMove, 'mouseup:time': timeMouseUp, }, nativeMouseLeave, } }
frontend/src/components/program/picasso/useDragAndDropNew.js
import { toTime, roundTimeUp, roundTimeDown } from '@/helpers/vCalendarDragAndDrop.js' /** * * @param ref(bool) enabled drag & drop is disabled if enabled=false * @param int threshold min. mouse movement needed to detect drag & drop * @returns */ export default function useDragAndDrop(enabled, createEntry) { /** * internal data (not exposed) */ // timestamp of mouse location when drag & drop event started let mouseStartTimestamp = null // temporary placeholder for new schedule entry, when created via drag & drop let newEntry = null // true if mousedown event was detected on an entry/event let entryWasClicked = false /** * internal methods */ const clear = () => { newEntry = null mouseStartTimestamp = null entryWasClicked = false } // this creates a placeholder for a new schedule entry and make it resizable const createNewEntry = (mouse) => { newEntry = { startTimestamp: roundTimeDown(mouse), endTimestamp: roundTimeDown(mouse) + 15, } } // resize placeholder entry const resizeEntry = (entry, mouse) => { const mouseRounded = roundTimeUp(mouse) const min = Math.min(mouseRounded, roundTimeDown(mouseStartTimestamp)) const max = Math.max(mouseRounded, roundTimeDown(mouseStartTimestamp)) entry.startTimestamp = min entry.endTimestamp = max } /** * exposed methods */ // triggered with MouseDown event on a calendar entry const entryMouseDown = ({ event: entry, timed, nativeEvent }) => { if (!enabled.value) { return } // cancel drag & drop if button is not left button if (nativeEvent.button !== 0) { return } if (entry && timed) { entryWasClicked = true } } // triggered with MouseDown event anywhere on the calendar (independent of clicking on entry or not) const timeMouseDown = (tms, nativeEvent) => { if (!enabled.value) { return } // cancel drag & drop if button is not left button if (nativeEvent.button !== 0) { return } if (!entryWasClicked) { // No entry is being dragged --> create a placeholder for a new schedule entry const mouseTime = toTime(tms) mouseStartTimestamp = mouseTime createNewEntry(mouseTime) } } // triggered when mouse is being moved in calendar (independent whether drag & drop is ongoing or not) const timeMouseMove = (tms) => { if (!enabled.value) { return } if (newEntry) { // resize placeholder const mouseTime = toTime(tms) resizeEntry(newEntry, mouseTime) createEntry(newEntry.startTimestamp, newEntry.endTimestamp, false) } } // triggered with MouseUp Event anywhere in the calendar const timeMouseUp = () => { if (!enabled.value) { return } if (newEntry) { // placeholder for new schedule entry was created --> open dialog to create new activity createEntry(newEntry.startTimestamp, newEntry.endTimestamp, true) } clear() } // treat mouseleave as a mouseUp event (finish operation and save last known status) const nativeMouseLeave = () => { timeMouseUp() } return { vCalendarListeners: { 'mousedown:event': entryMouseDown, 'mousedown:time': timeMouseDown, 'mousemove:time': timeMouseMove, 'mouseup:time': timeMouseUp, }, nativeMouseLeave, } }
drag drop: new scheduleEntry, don't trigger dialog with 0 length
frontend/src/components/program/picasso/useDragAndDropNew.js
drag drop: new scheduleEntry, don't trigger dialog with 0 length
<ide><path>rontend/src/components/program/picasso/useDragAndDropNew.js <ide> const createNewEntry = (mouse) => { <ide> newEntry = { <ide> startTimestamp: roundTimeDown(mouse), <del> endTimestamp: roundTimeDown(mouse) + 15, <add> endTimestamp: roundTimeDown(mouse), <ide> } <ide> } <ide> <ide> return <ide> } <ide> <del> if (newEntry) { <add> if (newEntry && newEntry.endTimestamp - newEntry.startTimestamp > 0) { <ide> // placeholder for new schedule entry was created --> open dialog to create new activity <ide> createEntry(newEntry.startTimestamp, newEntry.endTimestamp, true) <ide> }
Java
apache-2.0
9154df76164b7812246aa9da7c47e048d56d9dd7
0
bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud
package com.planet_ink.coffee_mud.Libraries; import com.planet_ink.coffee_web.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.AbilityMapper.AbilityMapping; import com.planet_ink.coffee_mud.Libraries.interfaces.AbilityParameters.AbilityParmEditor; import com.planet_ink.coffee_mud.core.exceptions.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.RawMaterial.Material; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.net.Socket; import java.util.*; /* Copyright 2008-2020 Bo Zimmerman 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. */ public class CMAbleParms extends StdLibrary implements AbilityParameters { @Override public String ID() { return "CMAbleParms"; } protected Map<String,AbilityParmEditor> DEFAULT_EDITORS = null; protected final static int[] ALL_BUCKET_MATERIAL_CHOICES = new int[]{RawMaterial.MATERIAL_CLOTH, RawMaterial.MATERIAL_METAL, RawMaterial.MATERIAL_LEATHER, RawMaterial.MATERIAL_LIQUID, RawMaterial.MATERIAL_WOODEN, RawMaterial.MATERIAL_PRECIOUS,RawMaterial.MATERIAL_VEGETATION, RawMaterial.MATERIAL_ROCK }; protected final static int[] ALLOWED_BUCKET_ACODES = new int[]{Ability.ACODE_CHANT,Ability.ACODE_SPELL,Ability.ACODE_PRAYER,Ability.ACODE_SONG,Ability.ACODE_SKILL, Ability.ACODE_THIEF_SKILL}; protected final static int[] ALLOWED_BUCKET_QUALITIES = new int[]{Ability.QUALITY_BENEFICIAL_OTHERS,Ability.QUALITY_BENEFICIAL_SELF,Ability.QUALITY_INDIFFERENT, Ability.QUALITY_OK_OTHERS,Ability.QUALITY_OK_SELF}; protected final static String[] ADJUSTER_TOKENS = new String[]{"+","-","="}; protected final static String[] RESISTER_IMMUNER_TOKENS = new String[]{"%",";"}; public CMAbleParms() { super(); } protected String parseLayers(final short[] layerAtt, final short[] clothingLayers, String misctype) { final int colon=misctype.indexOf(':'); if(colon>=0) { String layers=misctype.substring(0,colon).toUpperCase().trim(); misctype=misctype.substring(colon+1).trim(); if((layers.startsWith("MS"))||(layers.startsWith("SM"))) { layers=layers.substring(2); layerAtt[0]=Armor.LAYERMASK_MULTIWEAR|Armor.LAYERMASK_SEETHROUGH; } else if(layers.startsWith("M")) { layers=layers.substring(1); layerAtt[0]=Armor.LAYERMASK_MULTIWEAR; } else if(layers.startsWith("S")) { layers=layers.substring(1); layerAtt[0]=Armor.LAYERMASK_SEETHROUGH; } clothingLayers[0]=CMath.s_short(layers); } return misctype; } @Override public void parseWearLocation(final short[] layerAtt, final short[] layers, final long[] wornLoc, final boolean[] logicalAnd, final double[] hardBonus, String wearLocation) { if(layers != null) { layerAtt[0] = 0; layers[0] = 0; wearLocation=parseLayers(layerAtt,layers,wearLocation); } final double hardnessMultiplier = hardBonus[0]; wornLoc[0] = 0; hardBonus[0]=0.0; final Wearable.CODES codes = Wearable.CODES.instance(); for(int wo=1;wo<codes.total();wo++) { final String WO=codes.name(wo).toUpperCase(); if(wearLocation.equalsIgnoreCase(WO)) { hardBonus[0]+=codes.location_strength_points()[wo]; wornLoc[0]=CMath.pow(2,wo-1); logicalAnd[0]=false; } else if((wearLocation.toUpperCase().indexOf(WO+"||")>=0) ||(wearLocation.toUpperCase().endsWith("||"+WO))) { if(hardBonus[0]==0.0) hardBonus[0]+=codes.location_strength_points()[wo]; wornLoc[0]=wornLoc[0]|CMath.pow(2,wo-1); logicalAnd[0]=false; } else if((wearLocation.toUpperCase().indexOf(WO+"&&")>=0) ||(wearLocation.toUpperCase().endsWith("&&"+WO))) { hardBonus[0]+=codes.location_strength_points()[wo]; wornLoc[0]=wornLoc[0]|CMath.pow(2,wo-1); logicalAnd[0]=true; } } hardBonus[0]=(int)Math.round(hardBonus[0] * hardnessMultiplier); } public Vector<Object> parseRecipeFormatColumns(final String recipeFormat) { char C = '\0'; final StringBuffer currentColumn = new StringBuffer(""); Vector<String> currentColumns = null; final char[] recipeFmtC = recipeFormat.toCharArray(); final Vector<Object> columnsV = new Vector<Object>(); for(int c=0;c<=recipeFmtC.length;c++) { if(c==recipeFmtC.length) { break; } C = recipeFmtC[c]; if((C=='|') &&(c<(recipeFmtC.length-1)) &&(recipeFmtC[c+1]=='|') &&(currentColumn.length()>0)) { if(currentColumn.length()>0) { if(currentColumns == null) { currentColumns = new Vector<String>(); columnsV.addElement(currentColumns); } currentColumns.addElement(currentColumn.toString()); currentColumn.setLength(0); } c++; } else if(Character.isLetter(C)||Character.isDigit(C)||(C=='_')) currentColumn.append(C); else { if(currentColumn.length()>0) { if(currentColumns == null) { currentColumns = new Vector<String>(); columnsV.addElement(currentColumns); } currentColumns.addElement(currentColumn.toString()); currentColumn.setLength(0); } currentColumns = null; if((C=='.') &&(c<(recipeFmtC.length-2)) &&(recipeFmtC[c+1]=='.') &&(recipeFmtC[c+2]=='.')) { c+=2; columnsV.addElement("..."); } else if(columnsV.lastElement() instanceof String) columnsV.setElementAt(((String)columnsV.lastElement())+C,columnsV.size()-1); else columnsV.addElement(""+C); } } if(currentColumn.length()>0) { if(currentColumns == null) { currentColumns = new Vector<String>(); columnsV.addElement(currentColumns); } currentColumns.addElement(currentColumn.toString()); } if((currentColumns != null) && (currentColumns.size()==0)) columnsV.remove(currentColumns); return columnsV; } @Override public String makeRecipeFromItem(final ItemCraftor C, final Item I) throws CMException { final Vector<Object> columns = parseRecipeFormatColumns(C.parametersFormat()); final Map<String,AbilityParmEditor> editors = this.getEditors(); final StringBuilder recipe = new StringBuilder(""); for(int d=0;d<columns.size();d++) { if(columns.get(d) instanceof String) { final String name = (String)columns.get( d ); AbilityParmEditor A = editors.get(columns.get(d)); if((A==null)||(name.length()<3)) { recipe.append("\t"); continue; } if(A.appliesToClass(I)<0) A = editors.get("N_A"); if(A!=null) columns.set(d,A.ID()); } else if(columns.get(d) instanceof List) { AbilityParmEditor applicableA = null; final List<?> colV=(List<?>)columns.get(d); for(int c=0;c<colV.size();c++) { final Object o = colV.get(c); if (o instanceof List) continue; final String ID = (o instanceof String) ? (String)o : ((AbilityParmEditor)o).ID(); final AbilityParmEditor A = editors.get(ID); if(A==null) throw new CMException("Column name "+ID+" is not found."); if((applicableA==null) ||(A.appliesToClass(I) > applicableA.appliesToClass(I))) applicableA = A; } if((applicableA == null)||(applicableA.appliesToClass(I)<0)) applicableA = editors.get("N_A"); columns.set(d,applicableA.ID()); } else throw new CMException("Col name "+(columns.get(d))+" is not a String or List."); final AbilityParmEditor A = editors.get(columns.get(d)); if(A==null) throw new CMException("Editor name "+(columns.get(d))+" is not defined."); recipe.append(A.convertFromItem(C, I)); } return recipe.toString(); } @SuppressWarnings("unchecked") protected static int getClassFieldIndex(final DVector dataRow) { for(int d=0;d<dataRow.size();d++) { if(dataRow.elementAt(d,1) instanceof List) { final List<String> V=(List<String>)dataRow.elementAt(d,1); if(V.contains("ITEM_CLASS_ID")||V.contains("FOOD_DRINK")||V.contains("BUILDING_CODE")) return d; } else if(dataRow.elementAt(d,1) instanceof String) { final String s=(String)dataRow.elementAt(d,1); if(s.equalsIgnoreCase("ITEM_CLASS_ID")||s.equalsIgnoreCase("FOOD_DRINK")||s.equalsIgnoreCase("BUILDING_CODE")) return d; } } return -1; } @SuppressWarnings("unchecked") protected Object getSampleObject(final DVector dataRow) { boolean classIDRequired = false; String classID = null; final int fieldIndex = getClassFieldIndex(dataRow); for(int d=0;d<dataRow.size();d++) { if((dataRow.elementAt(d,1) instanceof List) &&(!classIDRequired) &&(((List<String>)dataRow.elementAt(d,1)).size()>1)) classIDRequired=true; } if(fieldIndex >=0) classID=(String)dataRow.elementAt(fieldIndex,2); if((classID!=null)&&(classID.length()>0)) { if(classID.equalsIgnoreCase("FOOD")) return CMClass.getItemPrototype("GenFood"); else if(classID.equalsIgnoreCase("SOAP")) return CMClass.getItemPrototype("GenItem"); else if(classID.equalsIgnoreCase("DRINK")) return CMClass.getItemPrototype("GenDrink"); else { final PhysicalAgent I=CMClass.getItemPrototype(classID); if(I==null) { final Pair<String[],String[]> codeFlags = getBuildingCodesNFlags(); if(CMParms.containsIgnoreCase(codeFlags.first, classID)) return classID.toUpperCase().trim(); } return I; } } if(classIDRequired) return null; return CMClass.getItemPrototype("StdItem"); } protected String stripData(final StringBuffer str, final String div) { final StringBuffer data = new StringBuffer(""); while(str.length()>0) { if(str.length() < div.length()) return null; for(int d=0;d<=div.length();d++) { if(d==div.length()) { str.delete(0,div.length()); return data.toString(); } else if(str.charAt(d)!=div.charAt(d)) break; } if(str.charAt(0)=='\n') { if(data.length()>0) return data.toString(); return null; } data.append(str.charAt(0)); str.delete(0,1); } if((div.charAt(0)=='\n') && (data.length()>0)) return data.toString(); return null; } @SuppressWarnings("unchecked") protected Vector<DVector> parseDataRows(final StringBuffer recipeData, final Vector<? extends Object> columnsV, final int numberOfDataColumns) throws CMException { StringBuffer str = new StringBuffer(recipeData.toString()); str = cleanDataRowEOLs(str); final Vector<DVector> rowsV = new Vector<DVector>(); DVector dataRow = new DVector(2); List<String> currCol = null; String lastDiv = null; int lastLen = str.length(); while(str.length() > 0) { lastLen = str.length(); for(int c = 0; c < columnsV.size(); c++) { String div = "\n"; currCol = null; if(columnsV.elementAt(c) instanceof String) stripData(str,(String)columnsV.elementAt(c)); else if(columnsV.elementAt(c) instanceof List) { currCol = (List<String>)columnsV.elementAt(c); if(c<columnsV.size()-1) { div = (String)columnsV.elementAt(c+1); c++; } } if((str.length()==0)&&(c<columnsV.size()-1)) break; if(!div.equals("...")) { lastDiv = div; String data = null; data = stripData(str,lastDiv); if(data == null) data = ""; dataRow.addElement(currCol,data); currCol = null; } else { final String data = stripData(str,lastDiv); if(data == null) break; dataRow.addElement(currCol,data); } } if(dataRow.size() != numberOfDataColumns) throw new CMException("Row "+(rowsV.size()+1)+" has "+dataRow.size()+"/"+numberOfDataColumns); rowsV.addElement(dataRow); dataRow = new DVector(2); if(str.length()==lastLen) throw new CMException("UNCHANGED: Row "+(rowsV.size()+1)+" has "+dataRow.size()+"/"+numberOfDataColumns); } if(str.length()<2) str.setLength(0); return rowsV; } protected boolean fixDataColumn(final DVector dataRow, final int rowShow) throws CMException { final Object classModelI = getSampleObject(dataRow); return fixDataColumn(dataRow,rowShow,classModelI); } @SuppressWarnings("unchecked") protected boolean fixDataColumn(final DVector dataRow, final int rowShow, final Object classModelI) throws CMException { final Map<String,AbilityParmEditor> editors = getEditors(); if(classModelI == null) { //Log.errOut("CMAbleParms","Data row "+rowShow+" discarded due to null/empty classID"); throw new CMException(L("Data row @x1 discarded due to null/empty classID",""+rowShow)); } for(int d=0;d<dataRow.size();d++) { final List<String> colV=(List<String>)dataRow.elementAt(d,1); if(colV.size()==1) { AbilityParmEditor A = editors.get(colV.get(0)); if((A == null)||(A.appliesToClass(classModelI)<0)) A = editors.get("N_A"); dataRow.setElementAt(d,1,A.ID()); } else { AbilityParmEditor applicableA = null; for(int c=0;c<colV.size();c++) { final AbilityParmEditor A = editors.get(colV.get(c)); if(A==null) throw new CMException(L("Col name @x1 is not defined.",""+(colV.get(c)))); if((applicableA==null) ||(A.appliesToClass(classModelI) > applicableA.appliesToClass(classModelI))) applicableA = A; } if((applicableA == null)||(applicableA.appliesToClass(classModelI)<0)) applicableA = editors.get("N_A"); dataRow.setElementAt(d,1,applicableA.ID()); } final AbilityParmEditor A = editors.get(dataRow.elementAt(d,1)); if(A==null) { if(classModelI instanceof CMObject) throw new CMException(L("Item id @x1 has no editor for @x2",((CMObject)classModelI).ID(),((String)dataRow.elementAt(d,1)))); else throw new CMException(L("Item id @x1 has no editor for @x2",classModelI+"",((String)dataRow.elementAt(d,1)))); //Log.errOut("CMAbleParms","Item id "+classModelI.ID()+" has no editor for "+((String)dataRow.elementAt(d,1))); //return false; } else if((rowShow>=0) &&(!A.confirmValue((String)dataRow.elementAt(d,2)))) { final String data = ((String)dataRow.elementAt(d,2)).replace('@', ' '); if(classModelI instanceof CMObject) throw new CMException(L("Item id @x1 has bad data '@x2' for column @x3 at row @x4",((CMObject)classModelI).ID(),data,((String)dataRow.elementAt(d,1)),""+rowShow)); else throw new CMException(L("Item id @x1 has bad data '@x2' for column @x3 at row @x4",""+classModelI,data,((String)dataRow.elementAt(d,1)),""+rowShow)); //Log.errOut("CMAbleParms","Item id "+classModelI.ID()+" has bad data '"+((String)dataRow.elementAt(d,2))+"' for column "+((String)dataRow.elementAt(d,1))+" at row "+rowShow); } } return true; } protected void fixDataColumns(final Vector<DVector> rowsV) throws CMException { DVector dataRow = new DVector(2); for(int r=0;r<rowsV.size();r++) { dataRow=rowsV.elementAt(r); if(!fixDataColumn(dataRow,r)) throw new CMException(L("Unknown error in row @x1",""+r)); /* catch(CMException e) { rowsV.removeElementAt(r); r--; } */ } } protected StringBuffer cleanDataRowEOLs(final StringBuffer str) { if(str.indexOf("\n")<0) return new StringBuffer(str.toString().replace('\r','\n')); for(int i=str.length()-1;i>=0;i--) { if(str.charAt(i)=='\r') str.delete(i,i+1); } return str; } @Override public void testRecipeParsing(final StringBuffer recipesString, final String recipeFormat) throws CMException { testRecipeParsing(recipesString,recipeFormat,null); } @Override public void testRecipeParsing(final String recipeFilename, final String recipeFormat, final boolean save) throws CMException { final StringBuffer str=new CMFile(Resources.buildResourcePath("skills")+recipeFilename,null,CMFile.FLAG_LOGERRORS).text(); testRecipeParsing(str,recipeFormat,save?recipeFilename:null); } @SuppressWarnings("unchecked") public void testRecipeParsing(final StringBuffer str, final String recipeFormat, final String saveRecipeFilename) throws CMException { final Vector<? extends Object> columnsV = parseRecipeFormatColumns(recipeFormat); int numberOfDataColumns = 0; for(int c = 0; c < columnsV.size(); c++) { if(columnsV.elementAt(c) instanceof List) numberOfDataColumns++; } final Vector<DVector> rowsV = parseDataRows(str,columnsV,numberOfDataColumns); final Vector<String> convertedColumnsV=(Vector<String>)columnsV; fixDataColumns(rowsV); final Map<String,AbilityParmEditor> editors = getEditors(); DVector editRow = null; final int[] showNumber = {0}; final int showFlag =-999; final MOB mob=CMClass.getFactoryMOB(); final Session fakeSession = (Session)CMClass.getCommon("FakeSession"); mob.setSession(fakeSession); fakeSession.setMob(mob); for(int r=0;r<rowsV.size();r++) { editRow = rowsV.elementAt(r); for(int a=0;a<editRow.size();a++) { final AbilityParmEditor A = editors.get(editRow.elementAt(a,1)); try { final String oldVal = (String)editRow.elementAt(a,2); fakeSession.getPreviousCMD().clear(); fakeSession.getPreviousCMD().addAll(new XVector<String>(A.fakeUserInput(oldVal))); final String newVal = A.commandLinePrompt(mob,oldVal,showNumber,showFlag); editRow.setElementAt(a,2,newVal); } catch (final Exception e) { } } } fakeSession.setMob(null); mob.destroy(); if(saveRecipeFilename!=null) resaveRecipeFile(mob,saveRecipeFilename,rowsV,convertedColumnsV,false); } protected void calculateRecipeCols(final int[] lengths, final String[] headers, final Vector<DVector> rowsV) { final Map<String,AbilityParmEditor> editors = getEditors(); DVector dataRow = null; final int numRows[]=new int[headers.length]; for(int r=0;r<rowsV.size();r++) { dataRow=rowsV.elementAt(r); for(int c=0;c<dataRow.size();c++) { final AbilityParmEditor A = editors.get(dataRow.elementAt(c,1)); try { int dataLen=((String)dataRow.elementAt(c, 2)).length(); if(dataLen > A.maxColWidth()) dataLen = A.maxColWidth(); if(dataLen < A.minColWidth()) dataLen = A.minColWidth(); lengths[c]+=dataLen; numRows[c]++; } catch(final Exception e) { } if(A==null) Log.errOut("CMAbleParms","Inexplicable lack of a column: "+((String)dataRow.elementAt(c,1))); else if(headers[c] == null) { headers[c] = A.colHeader(); } else if((!headers[c].startsWith("#"))&&(!headers[c].equalsIgnoreCase(A.colHeader()))) { headers[c]="#"+c; } } } for(int i=0;i<headers.length;i++) { if(numRows[i]>0) lengths[i] /= numRows[i]; if(headers[i]==null) headers[i]="*Add*"; } int currLenTotal = 0; for (final int length : lengths) currLenTotal+=length; int curCol = 0; while((currLenTotal+lengths.length)>72) { if(lengths[curCol]>1) { lengths[curCol]--; currLenTotal--; } curCol++; if(curCol >= lengths.length) curCol = 0; } while((currLenTotal+lengths.length)<72) { lengths[curCol]++; currLenTotal++; curCol++; if(curCol >= lengths.length) curCol = 0; } } @Override public AbilityRecipeData parseRecipe(final String recipeFilename, final String recipeFormat) { final AbilityRecipeDataImpl recipe = new AbilityRecipeDataImpl(recipeFilename, recipeFormat); return recipe; } @Override public StringBuffer getRecipeList(final CraftorAbility iA) { final AbilityRecipeData recipe = parseRecipe(iA.parametersFile(),iA.parametersFormat()); if(recipe.parseError() != null) return new StringBuffer("File: "+iA.parametersFile()+": "+recipe.parseError()); return getRecipeList(recipe); } private StringBuffer getRecipeList(final AbilityRecipeData recipe) { final StringBuffer list=new StringBuffer(""); DVector dataRow = null; list.append("### "); for(int l=0;l<recipe.columnLengths().length;l++) list.append(CMStrings.padRight(recipe.columnHeaders()[l],recipe.columnLengths()[l])+" "); list.append("\n\r"); for(int r=0;r<recipe.dataRows().size();r++) { dataRow=recipe.dataRows().get(r); list.append(CMStrings.padRight(""+(r+1),3)+" "); for(int c=0;c<dataRow.size();c++) list.append(CMStrings.padRight(CMStrings.limit((String)dataRow.elementAt(c,2),recipe.columnLengths()[c]),recipe.columnLengths()[c])+" "); list.append("\n\r"); } return list; } @Override @SuppressWarnings("unchecked") public void modifyRecipesList(final MOB mob, final String recipeFilename, final String recipeFormat) throws java.io.IOException { final Map<String,AbilityParmEditor> editors = getEditors(); final AbilityRecipeData recipe = parseRecipe(recipeFilename, recipeFormat); if(recipe.parseError() != null) { Log.errOut("CMAbleParms","File: "+recipeFilename+": "+recipe.parseError()); return; } while((mob.session()!=null)&&(!mob.session().isStopped())) { final StringBuffer list=getRecipeList(recipe); mob.tell(list.toString()); final String lineNum = mob.session().prompt(L("\n\rEnter a line to edit, A to add, or ENTER to exit: "),""); if(lineNum.trim().length()==0) break; DVector editRow = null; if(lineNum.equalsIgnoreCase("A")) { editRow = recipe.blankRow(); final int keyIndex = getClassFieldIndex(editRow); String classFieldData = null; if(keyIndex>=0) { final AbilityParmEditor A = editors.get(((List<String>)editRow.elementAt(keyIndex,1)).get(0)); if(A!=null) { classFieldData = A.commandLinePrompt(mob,(String)editRow.elementAt(keyIndex,2),new int[]{0},-999); if(!A.confirmValue(classFieldData)) { mob.tell(L("Invalid value. Aborted.")); continue; } } } editRow=recipe.newRow(classFieldData); if(editRow==null) continue; recipe.dataRows().add(editRow); } else if(CMath.isInteger(lineNum)) { final int line = CMath.s_int(lineNum); if((line<1)||(line>recipe.dataRows().size())) continue; editRow = recipe.dataRows().get(line-1); } else break; if(editRow != null) { int showFlag=-1; if(CMProps.getIntVar(CMProps.Int.EDITORTYPE)>0) showFlag=-999; boolean ok=false; while(!ok) { final int[] showNumber = {0}; final int keyIndex = getClassFieldIndex(editRow); for(int a=0;a<editRow.size();a++) { if(a!=keyIndex) { final AbilityParmEditor A = editors.get(editRow.elementAt(a,1)); final String newVal = A.commandLinePrompt(mob,(String)editRow.elementAt(a,2),showNumber,showFlag); editRow.setElementAt(a,2,newVal); } } if(showFlag<-900) { ok=true; break; } if(showFlag>0) { showFlag=-1; continue; } showFlag=CMath.s_int(mob.session().prompt(L("Edit which? "),"")); if(showFlag<=0) { showFlag=-1; ok=true; } } } } if((mob.session()!=null)&&(!mob.session().isStopped())) { final String prompt="Save to V)FS, F)ilesystem, or C)ancel (" + (recipe.wasVFS()?"V/f/c":"v/F/c")+"): "; final String choice=mob.session().choose(prompt,L("VFC"),recipe.wasVFS()?L("V"):L("F")); if(choice.equalsIgnoreCase("C")) mob.tell(L("Cancelled.")); else { final boolean saveToVFS = choice.equalsIgnoreCase("V"); resaveRecipeFile(mob, recipeFilename,recipe.dataRows(),recipe.columns(),saveToVFS); } } } @Override public void resaveRecipeFile(final MOB mob, final String recipeFilename, final List<DVector> rowsV, final List<? extends Object> columnsV, final boolean saveToVFS) { final StringBuffer saveBuf = new StringBuffer(""); for(int r=0;r<rowsV.size();r++) { final DVector dataRow = rowsV.get(r); int dataDex = 0; for(int c=0;c<columnsV.size();c++) { if(columnsV.get(c) instanceof String) saveBuf.append(columnsV.get(c)); else saveBuf.append(dataRow.elementAt(dataDex++,2)); } saveBuf.append("\n"); } CMFile file = new CMFile((saveToVFS?"::":"//")+Resources.buildResourcePath("skills")+recipeFilename,null,CMFile.FLAG_LOGERRORS); if(!file.canWrite()) Log.errOut("CMAbleParms","File: "+recipeFilename+" can not be written"); else if((!file.exists())||(!file.text().equals(saveBuf))) { file.saveText(saveBuf); if(!saveToVFS) { file = new CMFile("::"+Resources.buildResourcePath("skills")+recipeFilename,null,CMFile.FLAG_LOGERRORS); if((file.exists())&&(file.canWrite())) { file.saveText(saveBuf); } } if(mob != null) Log.sysOut("CMAbleParms","User: "+mob.Name()+" modified "+(saveToVFS?"VFS":"Local")+" file "+recipeFilename); Resources.removeResource("PARSED_RECIPE: "+recipeFilename); Resources.removeMultiLists(recipeFilename); } } protected static int getAppropriateResourceBucket(final Item I, final Object A) { final int myMaterial = ((I.material() & RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_MITHRIL) ? RawMaterial.MATERIAL_METAL : (I.material() & RawMaterial.MATERIAL_MASK); if(A instanceof Behavior) return CMLib.dice().pick( new int[]{RawMaterial.MATERIAL_LEATHER, RawMaterial.MATERIAL_VEGETATION}, myMaterial ); if(A instanceof Ability) { switch(((Ability)A).abilityCode() & Ability.ALL_ACODES) { case Ability.ACODE_CHANT: return CMLib.dice().pick( new int[]{RawMaterial.MATERIAL_VEGETATION, RawMaterial.MATERIAL_ROCK}, myMaterial ); case Ability.ACODE_SPELL: return CMLib.dice().pick( new int[]{RawMaterial.MATERIAL_WOODEN, RawMaterial.MATERIAL_PRECIOUS}, myMaterial ); case Ability.ACODE_PRAYER: return CMLib.dice().pick( new int[]{RawMaterial.MATERIAL_METAL, RawMaterial.MATERIAL_ROCK}, myMaterial ); case Ability.ACODE_SONG: return CMLib.dice().pick( new int[]{RawMaterial.MATERIAL_LIQUID, RawMaterial.MATERIAL_WOODEN}, myMaterial ); case Ability.ACODE_THIEF_SKILL: case Ability.ACODE_SKILL: return CMLib.dice().pick( new int[]{RawMaterial.MATERIAL_CLOTH, RawMaterial.MATERIAL_METAL}, myMaterial ); case Ability.ACODE_PROPERTY: if(A instanceof TriggeredAffect) return CMLib.dice().pick( new int[]{RawMaterial.MATERIAL_PRECIOUS, RawMaterial.MATERIAL_METAL}, myMaterial ); break; default: break; } } return CMLib.dice().pick( ALL_BUCKET_MATERIAL_CHOICES, myMaterial ); } protected static void addExtraMaterial(final Map<Integer,int[]> extraMatsM, final Item I, final Object A, double weight) { int times = 1; if(weight >= 1.0) { times = (int)Math.round(weight / 1.0); weight=.99; } final MaterialLibrary mats=CMLib.materials(); final int myBucket = getAppropriateResourceBucket(I,A); if(myBucket != RawMaterial.RESOURCE_NOTHING) { final PairList<Integer,Double> bucket = RawMaterial.CODES.instance().getValueSortedBucket(myBucket); Integer resourceCode = (bucket.size()==0) ? Integer.valueOf(CMLib.dice().pick( RawMaterial.CODES.ALL(), I.material() )) : bucket.get( (weight>=.99) ? bucket.size()-1 : 0 ).first; for (final Pair<Integer, Double> p : bucket) { if((weight <= p.second.doubleValue())&&(mats.isResourceCodeRoomMapped(p.first.intValue()))) { resourceCode = p.first; break; } } int tries=100; while((--tries>0)&&(!mats.isResourceCodeRoomMapped(resourceCode.intValue()))) resourceCode=bucket.get(CMLib.dice().roll(1, bucket.size(), -1)).first; resourceCode = Integer.valueOf( resourceCode.intValue() ); for(int x=0;x<times;x++) { final int[] amt = extraMatsM.get( resourceCode ); if(amt == null) extraMatsM.put( resourceCode, new int[]{1} ); else amt[0]++; } } } @SuppressWarnings("unchecked") protected static Pair<String[],String[]> getBuildingCodesNFlags() { Pair<String[],String[]> codesFlags = (Pair<String[],String[]>)Resources.getResource("BUILDING_SKILL_CODES_FLAGS"); if(codesFlags == null) { CraftorAbility A=(CraftorAbility)CMClass.getAbility("Masonry"); if(A==null) A=(CraftorAbility)CMClass.getAbility("Construction"); if(A==null) A=(CraftorAbility)CMClass.getAbility("Excavation"); if(A!=null) A.parametersFormat(); codesFlags = (Pair<String[],String[]>)Resources.getResource("BUILDING_SKILL_CODES_FLAGS"); } return codesFlags; } protected static void addExtraAbilityMaterial(final Map<Integer,int[]> extraMatsM, final Item I, final Ability A) { double level = CMLib.ableMapper().lowestQualifyingLevel( A.ID() ); if( level <= 0.0 ) { level = I.basePhyStats().level(); if( level <= 0.0 ) level = 1.0; addExtraMaterial(extraMatsM, I, A, CMath.div( level, CMProps.getIntVar( CMProps.Int.LASTPLAYERLEVEL ) )); } else { final double levelCap = CMLib.ableMapper().getCalculatedMedianLowestQualifyingLevel(); addExtraMaterial(extraMatsM, I, A, CMath.div(level , ( levelCap * 2.0))); } } public static Map<Integer,int[]> extraMaterial(final Item I) { final Map<Integer,int[]> extraMatsM=new TreeMap<Integer,int[]>(); /* * behaviors/properties of the item */ for(final Enumeration<Ability> a=I.effects(); a.hasMoreElements();) { final Ability A=a.nextElement(); if(A.isSavable()) { if((A.abilityCode() & Ability.ALL_ACODES) == Ability.ACODE_PROPERTY) { if(A instanceof AbilityContainer) { for(final Enumeration<Ability> a1=((AbilityContainer)A).allAbilities(); a1.hasMoreElements(); ) { addExtraAbilityMaterial(extraMatsM,I,a1.nextElement()); } } if(A instanceof TriggeredAffect) { if((A.flags() & Ability.FLAG_ADJUSTER) != 0) { int count = CMStrings.countSubstrings( new String[]{A.text()}, ADJUSTER_TOKENS ); if(count == 0) count = 1; for(int i=0;i<count;i++) addExtraAbilityMaterial(extraMatsM,I,A); } else if((A.flags() & (Ability.FLAG_RESISTER | Ability.FLAG_IMMUNER)) != 0) { int count = CMStrings.countSubstrings( new String[]{A.text()}, RESISTER_IMMUNER_TOKENS ); if(count == 0) count = 1; for(int i=0;i<count;i++) addExtraAbilityMaterial(extraMatsM,I,A); } } } else if((CMParms.indexOf(ALLOWED_BUCKET_ACODES, A.abilityCode() & Ability.ALL_ACODES ) >=0) &&(CMParms.indexOf( ALLOWED_BUCKET_QUALITIES, A.abstractQuality()) >=0 )) { addExtraAbilityMaterial(extraMatsM,I,A); } } } for(final Enumeration<Behavior> b=I.behaviors(); b.hasMoreElements();) { final Behavior B=b.nextElement(); if(B.isSavable()) { addExtraMaterial(extraMatsM, I, B, CMath.div( CMProps.getIntVar( CMProps.Int.LASTPLAYERLEVEL ), I.basePhyStats().level() )); } } return extraMatsM; } @Override public synchronized Map<String,AbilityParmEditor> getEditors() { if(DEFAULT_EDITORS != null) return DEFAULT_EDITORS; final Vector<AbilityParmEditorImpl> V=new XVector<AbilityParmEditorImpl>(new AbilityParmEditorImpl[] { new AbilityParmEditorImpl("SPELL_ID","The Spell ID",ParmType.CHOICES) { @Override public void createChoices() { createChoices(CMClass.abilities()); } @Override public String defaultValue() { return "Spell_ID"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Potion) return ((Potion)I).getSpellList(); else if((I instanceof Scroll) &&(I instanceof MiscMagic)) return ((Scroll)I).getSpellList(); return ""; } }, new AbilityParmEditorImpl("RESOURCE_NAME","Resource",ParmType.CHOICES) { @Override public void createChoices() { createChoices(RawMaterial.CODES.NAMES()); } @Override public String defaultValue() { return "IRON"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return RawMaterial.CODES.NAME(I.material()); } }, new AbilityParmEditorImpl("ITEM_NAME","Item Final Name",ParmType.STRING) { @Override public void createChoices() { } @Override public String defaultValue() { return "Item Name"; } @Override public int minColWidth() { return 10; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { final String oldName=I.Name(); if(I.material()==RawMaterial.RESOURCE_GLASS) return CMLib.english().removeArticleLead(oldName); String newName=oldName; final List<String> V=CMParms.parseSpaces(oldName,true); for(int i=0;i<V.size();i++) { final String s=V.get(i); final int code=RawMaterial.CODES.FIND_IgnoreCase(s); if((code>0)&&(code==I.material())) { V.set(i, "%"); if((i>0)&&(CMLib.english().isAnArticle(V.get(i-1)))) V.remove(i-1); newName=CMParms.combine(V); break; } } if(oldName.equals(newName)) { for(int i=0;i<V.size();i++) { final String s=V.get(i); final int code=RawMaterial.CODES.FIND_IgnoreCase(s); if(code>0) { V.set(i, "%"); if((i>0)&&(CMLib.english().isAnArticle(V.get(i-1)))) V.remove(i-1); newName=CMParms.combine(V); break; } } } if(newName.indexOf( '%' )<0) { for(int i=0;i<V.size()-1;i++) { if(CMLib.english().isAnArticle( V.get( i ) )) { if(i==0) V.set( i, "%" ); else V.add(i+1, "%"); break; } } newName=CMParms.combine( V ); } if(newName.indexOf( '%' )<0) { newName="% "+newName; } return newName; } }, new AbilityParmEditorImpl("STAIRS_DESC","Exit Desc",ParmType.STRING) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equals("STAIRS")) return 1; } return -1; } @Override public String defaultValue() { return "@x1stairs to the @x2 floor"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } }, new AbilityParmEditorImpl("BUILDING_NOUN","Building noun",ParmType.STRING) { @Override public void createChoices() { } @Override public String defaultValue() { return "thing"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } }, new AbilityParmEditorImpl("BUILDER_MASK","Builder Mask",ParmType.STRINGORNULL) { @Override public void createChoices() { } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } }, new AbilityParmEditorImpl("BUILDER_DESC","Info Description",ParmType.STRING) { @Override public void createChoices() { } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public int maxColWidth() { return 20; } }, new AbilityParmEditorImpl("RES_SUBTYPE","Sub-Type",ParmType.STRINGORNULL) { @Override public void createChoices() { } @Override public String defaultValue() { return ""; } @Override public int appliesToClass(final Object o) { if(o instanceof RawMaterial) return 5; return -1; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof RawMaterial) return ((RawMaterial)I).getSubType(); return ""; } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { return super.commandLinePrompt(mob, oldVal, showNumber, showFlag).toUpperCase().trim(); } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { return super.webValue(httpReq,parms,oldVal,fieldName).toUpperCase().trim(); } }, new AbilityParmEditorImpl("ITEM_LEVEL","Lvl",ParmType.NUMBER) { @Override public void createChoices() { } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if((I instanceof Weapon)||(I instanceof Armor)) { final int timsLevel = CMLib.itemBuilder().timsLevelCalculator(I); if((timsLevel > I.basePhyStats().level() ) && (timsLevel < CMProps.getIntVar(CMProps.Int.LASTPLAYERLEVEL))) return ""+timsLevel; } return ""+I.basePhyStats().level(); } }, new AbilityParmEditorImpl("BUILDING_GRID_SIZE","Grid Size",ParmType.NUMBER) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equals("ROOM")) return 1; } return -1; } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return "1"; } }, new AbilityParmEditorImpl("BUILD_TIME_TICKS","Time",ParmType.NUMBER) { @Override public void createChoices() { } @Override public String defaultValue() { return "20"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""+(10 + (I.basePhyStats().level()/2)); } }, new AbilityParmEditorImpl("FUTURE_USE","Future Use",ParmType.STRINGORNULL) { @Override public void createChoices() { } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return "1"; } }, new AbilityParmEditorImpl("AMOUNT_MATERIAL_REQUIRED","Amt",ParmType.NUMBER) { @Override public void createChoices() { } @Override public boolean confirmValue(final String oldVal) { return true; } @Override public String defaultValue() { return "10"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""+Math.round(CMath.mul(I.basePhyStats().weight(),(A!=null)?A.getItemWeightMultiplier(false):1.0)); } }, new AbilityParmEditorImpl("MATERIALS_REQUIRED","Amount/Cmp",ParmType.SPECIAL) { @Override public void createChoices() { } @Override public boolean confirmValue(final String oldVal) { return true; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { if(httpReq.isUrlParameter(fieldName+"_WHICH")) { final String which=httpReq.getUrlParameter(fieldName+"_WHICH"); if((which.trim().length()==0)||(which.trim().equalsIgnoreCase("AMOUNT"))) return httpReq.getUrlParameter(fieldName+"_AMOUNT"); if(which.trim().equalsIgnoreCase("COMPONENT")) return httpReq.getUrlParameter(fieldName+"_COMPONENT"); int x=1; final List<AbilityComponent> comps=new Vector<AbilityComponent>(); while(httpReq.isUrlParameter(fieldName+"_CUST_TYPE_"+x)) { String connector=httpReq.getUrlParameter(fieldName+"_CUST_CONN_"+x); final String amt=httpReq.getUrlParameter(fieldName+"_CUST_AMT_"+x); final String strVal=httpReq.getUrlParameter(fieldName+"_CUST_STR_"+x); final String loc=httpReq.getUrlParameter(fieldName+"_CUST_LOC_"+x); final String typ=httpReq.getUrlParameter(fieldName+"_CUST_TYPE_"+x); final String styp=httpReq.getUrlParameter(fieldName+"_CUST_STYPE_"+x); final String con=httpReq.getUrlParameter(fieldName+"_CUST_CON_"+x); if(connector==null) connector="AND"; if(connector.equalsIgnoreCase("DEL")||(connector.length()==0)) { x++; continue; } try { final AbilityComponent able=CMLib.ableComponents().createBlankAbilityComponent(); able.setConnector(AbilityComponent.CompConnector.valueOf(connector)); able.setAmount(CMath.s_int(amt)); able.setMask(""); able.setConsumed((con!=null) && con.equalsIgnoreCase("on")); able.setLocation(AbilityComponent.CompLocation.valueOf(loc)); able.setType(AbilityComponent.CompType.valueOf(typ), strVal, styp); comps.add(able); } catch(final Exception e) { } x++; } if(comps.size()>0) return CMLib.ableComponents().getAbilityComponentCodedString(comps); } return oldVal; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { int amt=(int)Math.round(CMath.mul(I.basePhyStats().weight()-1,(A!=null)?A.getItemWeightMultiplier(false):1.0)); if(amt<1) amt=1; final Map<Integer,int[]> extraMatsM = CMAbleParms.extraMaterial( I ); if((extraMatsM == null) || (extraMatsM.size()==0)) { return ""+amt; } final String subType = (I instanceof RawMaterial)?((RawMaterial)I).getSubType():""; final List<AbilityComponent> comps=new Vector<AbilityComponent>(); AbilityComponent able=CMLib.ableComponents().createBlankAbilityComponent(); able.setConnector(AbilityComponent.CompConnector.AND); able.setAmount(amt); able.setMask(""); able.setConsumed(true); able.setLocation(AbilityComponent.CompLocation.ONGROUND); able.setType(AbilityComponent.CompType.MATERIAL, Integer.valueOf(I.material() & RawMaterial.MATERIAL_MASK), subType); comps.add(able); for(final Integer resourceCode : extraMatsM.keySet()) { able=CMLib.ableComponents().createBlankAbilityComponent(); able.setConnector(AbilityComponent.CompConnector.AND); able.setAmount(extraMatsM.get(resourceCode)[0]); able.setMask(""); able.setConsumed(true); able.setLocation(AbilityComponent.CompLocation.ONGROUND); able.setType(AbilityComponent.CompType.RESOURCE, resourceCode, ""); comps.add(able); } return CMLib.ableComponents().getAbilityComponentCodedString(comps); } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { String value=webValue(httpReq,parms,oldVal,fieldName); if(value.endsWith("$")) value = value.substring(0,oldVal.length()-1); value = value.trim(); final String curWhich=httpReq.getUrlParameter(fieldName+"_WHICH"); int type=0; if("COMPONENT".equalsIgnoreCase(curWhich)) type=1; else if("EMBEDDED".equalsIgnoreCase(curWhich)) type=2; else if("AMOUNT".equalsIgnoreCase(curWhich)) type=0; else if(CMLib.ableComponents().getAbilityComponentMap().containsKey(value.toUpperCase().trim())) type=1; else if(value.startsWith("(")) type=2; else type=0; List<AbilityComponent> comps=null; if(type==2) { final Hashtable<String,List<AbilityComponent>> H=new Hashtable<String,List<AbilityComponent>>(); final String s="ID="+value; CMLib.ableComponents().addAbilityComponent(s, H); comps=H.get("ID"); } if(comps==null) comps=new ArrayList<AbilityComponent>(1); final StringBuffer str = new StringBuffer("<FONT SIZE=-1>"); str.append("<INPUT TYPE=RADIO NAME="+fieldName+"_WHICH "+(type==0?"CHECKED ":"")+"VALUE=\"AMOUNT\">"); str.append("\n\rAmount: <INPUT TYPE=TEXT SIZE=3 NAME="+fieldName+"_AMOUNT VALUE=\""+(type!=0?"":value)+"\" ONKEYDOWN=\"document.RESOURCES."+fieldName+"_WHICH[0].checked=true;\">"); str.append("\n\r<BR>"); str.append("<INPUT TYPE=RADIO NAME="+fieldName+"_WHICH "+(type==1?"CHECKED ":"")+"VALUE=\"COMPONENT\">"); str.append(L("\n\rSkill Components:")); str.append("\n\r<SELECT NAME="+fieldName+"_COMPONENT ONCHANGE=\"document.RESOURCES."+fieldName+"_WHICH[1].checked=true;\">"); str.append("<OPTION VALUE=\"0\""); if((type!=1)||(value.length()==0)||(value.equalsIgnoreCase("0"))) str.append(" SELECTED"); str.append(">&nbsp;"); for(final String S : CMLib.ableComponents().getAbilityComponentMap().keySet()) { str.append("<OPTION VALUE=\""+S+"\""); if((type==1)&&(value.equalsIgnoreCase(S))) str.append(" SELECTED"); str.append(">"+S); } str.append("</SELECT>"); str.append("\n\r<BR>"); str.append("<INPUT TYPE=RADIO NAME="+fieldName+"_WHICH "+(type==2?"CHECKED ":"")+"VALUE=\"EMBEDDED\">"); str.append("\n\rCustom:"); str.append("\n\r<BR>"); AbilityComponent comp; for(int i=0;i<=comps.size();i++) { comp=(i<comps.size())?comps.get(i):null; if(i>0) { str.append("\n\r<SELECT NAME="+fieldName+"_CUST_CONN_"+(i+1)+" ONCHANGE=\"document.RESOURCES."+fieldName+"_WHICH[2].checked=true;\">"); if(comp!=null) str.append("<OPTION VALUE=\"DEL\">DEL"); else if(type==2) str.append("<OPTION VALUE=\"\" SELECTED>"); for(final AbilityComponent.CompConnector conector : AbilityComponent.CompConnector.values()) { str.append("<OPTION VALUE=\""+conector.toString()+"\" "); if((type==2)&&(comp!=null)&&(conector==comp.getConnector())) str.append("SELECTED "); str.append(">"+CMStrings.capitalizeAndLower(conector.toString())); } str.append("</SELECT>"); } str.append("\n\rAmt: <INPUT TYPE=TEXT SIZE=2 NAME="+fieldName+"_CUST_AMT_"+(i+1)+" VALUE=\""+(((type!=2)||(comp==null))?"":Integer.toString(comp.getAmount()))+"\" ONKEYDOWN=\"document.RESOURCES."+fieldName+"_WHICH[2].checked=true;\">"); str.append("\n\r<SELECT NAME="+fieldName+"_CUST_TYPE_"+(i+1)+" ONCHANGE=\"document.RESOURCES."+fieldName+"_WHICH[2].checked=true; ReShow();\">"); final AbilityComponent.CompType compType=(comp!=null)?comp.getType():AbilityComponent.CompType.STRING; final String subType=(comp != null)?comp.getSubType():""; for(final AbilityComponent.CompType conn : AbilityComponent.CompType.values()) { str.append("<OPTION VALUE=\""+conn.toString()+"\" "); if(conn==compType) str.append("SELECTED "); str.append(">"+CMStrings.capitalizeAndLower(conn.toString())); } str.append("</SELECT>"); if(compType==AbilityComponent.CompType.STRING) str.append("\n\r<INPUT TYPE=TEXT SIZE=10 NAME="+fieldName+"_CUST_STR_"+(i+1)+" VALUE=\""+(((type!=2)||(comp==null))?"":comp.getStringType())+"\" ONKEYDOWN=\"document.RESOURCES."+fieldName+"_WHICH[2].checked=true;\">"); else { str.append("\n\r<SELECT NAME="+fieldName+"_CUST_STR_"+(i+1)+" ONCHANGE=\"document.RESOURCES."+fieldName+"_WHICH[2].checked=true;\">"); if(compType==AbilityComponent.CompType.MATERIAL) { final RawMaterial.Material[] M=RawMaterial.Material.values(); Arrays.sort(M,new Comparator<RawMaterial.Material>() { @Override public int compare(final Material o1, final Material o2) { return o1.name().compareToIgnoreCase(o2.name()); } }); for(final RawMaterial.Material m : M) { str.append("<OPTION VALUE="+m.mask()); if((type==2)&&(comp!=null)&&(m.mask()==comp.getLongType())) str.append(" SELECTED"); str.append(">"+m.noun()); } } else if(compType==AbilityComponent.CompType.RESOURCE) { final List<Pair<String,Integer>> L=new Vector<Pair<String,Integer>>(); for(int x=0;x<RawMaterial.CODES.TOTAL();x++) L.add(new Pair<String,Integer>(RawMaterial.CODES.NAME(x),Integer.valueOf(RawMaterial.CODES.GET(x)))); Collections.sort(L,new Comparator<Pair<String,Integer>>() { @Override public int compare(final Pair<String, Integer> o1, final Pair<String, Integer> o2) { return o1.first.compareToIgnoreCase(o2.first); } }); for(final Pair<String,Integer> p : L) { str.append("<OPTION VALUE="+p.second); if((type==2)&&(comp!=null)&&(p.second.longValue()==comp.getLongType())) str.append(" SELECTED"); str.append(">"+p.first); } } str.append("</SELECT>"); str.append(" <INPUT TYPE=TEXT SIZE=2 NAME="+fieldName+"_CUST_STYPE_"+(i+1)+" VALUE=\""+subType+"\">"); } str.append("\n\r<SELECT NAME="+fieldName+"_CUST_LOC_"+(i+1)+" ONCHANGE=\"document.RESOURCES."+fieldName+"_WHICH[2].checked=true;\">"); for(final AbilityComponent.CompLocation conn : AbilityComponent.CompLocation.values()) { str.append("<OPTION VALUE=\""+conn.toString()+"\" "); if((type==2)&&(comp!=null)&&(conn==comp.getLocation())) str.append("SELECTED "); str.append(">"+CMStrings.capitalizeAndLower(conn.toString())); } str.append("</SELECT>"); str.append("\n\rConsumed:<INPUT TYPE=CHECKBOX NAME="+fieldName+"_CUST_CON_"+(i+1)+" "+((type!=2)||(comp==null)||(!comp.isConsumed())?"":"CHECKED")+" ONCLICK=\"document.RESOURCES."+fieldName+"_WHICH[2].checked=true;\">"); if(i<comps.size()) str.append("\n\r<BR>\n\r"); else str.append("\n\r<a href=\"javascript:ReShow();\">&lt;*&gt;</a>\n\r"); } str.append("<BR>"); str.append("</FONT>"); return str.toString(); } @Override public String[] fakeUserInput(final String oldVal) { return new String[] { oldVal }; } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { ++showNumber[0]; String str = oldVal; while(!mob.session().isStopped()) { final String help="<AMOUNT>" +"\n\rSkill Component: "+CMParms.toListString(CMLib.ableComponents().getAbilityComponentMap().keySet()) +"\n\rCustom Component: ([DISPOSITION]:[FATE]:[AMOUNT]:[COMPONENT ID]:[MASK]) && ..."; str=CMLib.genEd().prompt(mob,oldVal,showNumber[0],showFlag,prompt(),true,help).trim(); if(str.equals(oldVal)) return oldVal; if(CMath.isInteger(str)) return Integer.toString(CMath.s_int(str)); if(CMLib.ableComponents().getAbilityComponentMap().containsKey(str.toUpperCase().trim())) return str.toUpperCase().trim(); String error=null; if(str.trim().startsWith("(")) { error=CMLib.ableComponents().addAbilityComponent("ID="+str, new Hashtable<String,List<AbilityComponent>>()); if(error==null) return str; } mob.session().println(L("'@x1' is not an amount of material, a component key, or custom component list@x2. Please use ? for help.",str,(error==null?"":"("+error+")"))); } return str; } @Override public String defaultValue() { return "1"; } }, new AbilityParmEditorImpl("OPTIONAL_AMOUNT_REQUIRED","Amt",ParmType.NUMBER) { @Override public void createChoices() { } @Override public boolean confirmValue(final String oldVal) { return true; } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } }, new AbilityParmEditorImpl("ITEM_BASE_VALUE","Value",ParmType.NUMBER) { @Override public void createChoices() { } @Override public String defaultValue() { return "5"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""+I.baseGoldValue(); } }, new AbilityParmEditorImpl("ROOM_CLASS_ID","Class ID",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equalsIgnoreCase("ROOM") ||chk.equalsIgnoreCase("EXCAVATE")) return 1; } return -1; } @Override public void createChoices() { final Vector<Environmental> V = new Vector<Environmental>(); V.addAll(new XVector<Room>(CMClass.locales())); createChoices(V); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return "Plains"; } }, new AbilityParmEditorImpl("ALLITEM_CLASS_ID","Class ID",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equalsIgnoreCase("ITEM")) return 1; } return -1; } @Override public void createChoices() { final XVector<Environmental> V = new XVector<Environmental>(); V.addAll(CMClass.basicItems()); V.addAll(CMClass.weapons()); V.addAll(CMClass.tech()); V.addAll(CMClass.armor()); V.addAll(CMClass.miscMagic()); V.addAll(CMClass.clanItems()); for(int i=V.size()-1;i<=0;i--) { if(V.get(i) instanceof CMObjectWrapper) V.remove(i); } createChoices(V); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return "StdItem"; } }, new AbilityParmEditorImpl("ROOM_CLASS_ID_OR_NONE","Class ID",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equalsIgnoreCase("DEMOLISH") ||chk.equalsIgnoreCase("STAIRS")) return 1; } return -1; } @Override public void createChoices() { final Vector<Object> V = new Vector<Object>(); V.add(""); V.addAll(new XVector<Room>(CMClass.locales())); createChoices(V); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return ""; } }, new AbilityParmEditorImpl("EXIT_CLASS_ID","Class ID",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equalsIgnoreCase("DOOR")) return 1; } return -1; } @Override public void createChoices() { final Vector<Environmental> V = new Vector<Environmental>(); V.addAll(new XVector<Exit>(CMClass.exits())); final Vector<CMObject> V2=new Vector<CMObject>(); Environmental I; for(final Enumeration<Environmental> e=V.elements();e.hasMoreElements();) { I=e.nextElement(); if(I.isGeneric()) V2.addElement(I); } createChoices(V2); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return "GenExit"; } }, new AbilityParmEditorImpl("ITEM_CLASS_ID","Class ID",ParmType.CHOICES) { @Override public void createChoices() { final List<Item> V = new ArrayList<Item>(); V.addAll(new XVector<ClanItem>(CMClass.clanItems())); V.addAll(new XVector<Armor>(CMClass.armor())); V.addAll(new XVector<Item>(CMClass.basicItems())); V.addAll(new XVector<MiscMagic>(CMClass.miscMagic())); V.addAll(new XVector<Technical>(CMClass.tech())); V.addAll(new XVector<Weapon>(CMClass.weapons())); final List<Item> V2=new ArrayList<Item>(); Item I; for(final Iterator<Item> e=V.iterator();e.hasNext();) { I=e.next(); if(I.isGeneric() || I.ID().equalsIgnoreCase("StdDeckOfCards")) V2.add(I); } for(int i=V.size()-1;i<=0;i--) { if(V.get(i) instanceof CMObjectWrapper) V.remove(i); } createChoices(V2); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I.isGeneric()) return I.ID(); if(I instanceof Weapon) return "GenWeapon"; if(I instanceof Armor) return "GenArmor"; if(I instanceof Rideable) return "GenRideable"; return "GenItem"; } @Override public String defaultValue() { return "GenItem"; } }, new AbilityParmEditorImpl("CODED_WEAR_LOCATION","Wear Locs",ParmType.SPECIAL) { @Override public int appliesToClass(final Object o) { if(o instanceof FalseLimb) return -1; return ((o instanceof Armor) || (o instanceof MusicalInstrument)) ? 2 : -1; } @Override public void createChoices() { } @Override public boolean confirmValue(final String oldVal) { return oldVal.trim().length() > 0; } @Override public String defaultValue() { return "NECK"; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final short[] layerAtt = new short[1]; final short[] layers = new short[1]; final long[] wornLoc = new long[1]; final boolean[] logicalAnd = new boolean[1]; final double[] hardBonus=new double[1]; CMLib.ableParms().parseWearLocation(layerAtt,layers,wornLoc,logicalAnd,hardBonus,oldVal); if(httpReq.isUrlParameter(fieldName+"_WORNDATA")) { wornLoc[0]=CMath.s_long(httpReq.getUrlParameter(fieldName+"_WORNDATA")); for(int i=1;;i++) if(httpReq.isUrlParameter(fieldName+"_WORNDATA"+(Integer.toString(i)))) wornLoc[0]=wornLoc[0]|CMath.s_long(httpReq.getUrlParameter(fieldName+"_WORNDATA"+(Integer.toString(i)))); else break; logicalAnd[0] = httpReq.getUrlParameter(fieldName+"_ISTWOHANDED").equalsIgnoreCase("on"); layers[0] = CMath.s_short(httpReq.getUrlParameter(fieldName+"_LAYER")); layerAtt[0] = 0; if((httpReq.isUrlParameter(fieldName+"_SEETHRU")) &&(httpReq.getUrlParameter(fieldName+"_SEETHRU").equalsIgnoreCase("on"))) layerAtt[0] |= Armor.LAYERMASK_SEETHROUGH; if((httpReq.isUrlParameter(fieldName+"_MULTIWEAR")) &&(httpReq.getUrlParameter(fieldName+"_MULTIWEAR").equalsIgnoreCase("on"))) layerAtt[0] |= Armor.LAYERMASK_MULTIWEAR; } return reconvert(layerAtt,layers,wornLoc,logicalAnd,hardBonus); } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String value = webValue(httpReq,parms,oldVal,fieldName); final short[] layerAtt = new short[1]; final short[] layers = new short[1]; final long[] wornLoc = new long[1]; final boolean[] logicalAnd = new boolean[1]; final double[] hardBonus=new double[1]; CMLib.ableParms().parseWearLocation(layerAtt,layers,wornLoc,logicalAnd,hardBonus,value); final StringBuffer str = new StringBuffer(""); str.append("\n\r<SELECT NAME="+fieldName+"_WORNDATA MULTIPLE>"); final Wearable.CODES codes = Wearable.CODES.instance(); for(int i=1;i<codes.total();i++) { final String climstr=codes.name(i); final int mask=(int)CMath.pow(2,i-1); str.append("<OPTION VALUE="+mask); if((wornLoc[0]&mask)>0) str.append(" SELECTED"); str.append(">"+climstr); } str.append("</SELECT>"); str.append("<BR>\n\r<INPUT TYPE=RADIO NAME="+fieldName+"_ISTWOHANDED value=\"on\" "+(logicalAnd[0]?"CHECKED":"")+">Is worn on All above Locations."); str.append("<BR>\n\r<INPUT TYPE=RADIO NAME="+fieldName+"_ISTWOHANDED value=\"\" "+(logicalAnd[0]?"":"CHECKED")+">Is worn on ANY of the above Locations."); str.append("<BR>\n\rLayer: <INPUT TYPE=TEXT NAME="+fieldName+"_LAYER SIZE=5 VALUE=\""+layers[0]+"\">"); final boolean seeThru = CMath.bset(layerAtt[0],Armor.LAYERMASK_SEETHROUGH); final boolean multiWear = CMath.bset(layerAtt[0],Armor.LAYERMASK_MULTIWEAR); str.append("&nbsp;&nbsp;\n\r<INPUT TYPE=CHECKBOX NAME="+fieldName+"_SEETHRU value=\"on\" "+(seeThru?"CHECKED":"")+">Is see-through."); str.append("&nbsp;&nbsp;\n\r<INPUT TYPE=CHECKBOX NAME="+fieldName+"_MULTIWEAR value=\"on\" "+(multiWear?"CHECKED":"")+">Is multi-wear."); return str.toString(); } public String reconvert(final short[] layerAtt, final short[] layers, final long[] wornLoc, final boolean[] logicalAnd, final double[] hardBonus) { final StringBuffer newVal = new StringBuffer(""); if((layerAtt[0]!=0)||(layers[0]!=0)) { if(CMath.bset(layerAtt[0],Armor.LAYERMASK_MULTIWEAR)) newVal.append('M'); if(CMath.bset(layerAtt[0],Armor.LAYERMASK_SEETHROUGH)) newVal.append('S'); newVal.append(layers[0]); newVal.append(':'); } boolean needLink=false; final Wearable.CODES codes = Wearable.CODES.instance(); for(int wo=1;wo<codes.total();wo++) { if(CMath.bset(wornLoc[0],CMath.pow(2,wo-1))) { if(needLink) newVal.append(logicalAnd[0]?"&&":"||"); needLink = true; newVal.append(codes.name(wo).toUpperCase()); } } return newVal.toString(); } @Override public String convertFromItem(final ItemCraftor C, final Item I) { if(!(I instanceof Armor)) return "HELD"; final Armor A=(Armor)I; final boolean[] logicalAnd=new boolean[]{I.rawLogicalAnd()}; final long[] wornLoc=new long[]{I.rawProperLocationBitmap()}; final double[] hardBonus=new double[]{0.0}; final short[] layerAtt=new short[]{A.getLayerAttributes()}; final short[] layers=new short[]{A.getClothingLayer()}; return reconvert(layerAtt,layers,wornLoc,logicalAnd,hardBonus); } @Override public String[] fakeUserInput(final String oldVal) { final ArrayList<String> V = new ArrayList<String>(); final short[] layerAtt = new short[1]; final short[] layers = new short[1]; final long[] wornLoc = new long[1]; final boolean[] logicalAnd = new boolean[1]; final double[] hardBonus=new double[1]; CMLib.ableParms().parseWearLocation(layerAtt,layers,wornLoc,logicalAnd,hardBonus,oldVal); V.add(""+layers[0]); if(CMath.bset(layerAtt[0],Armor.LAYERMASK_SEETHROUGH)) V.add("Y"); else V.add("N"); if(CMath.bset(layerAtt[0],Armor.LAYERMASK_MULTIWEAR)) V.add("Y"); else V.add("N"); V.add("1"); V.add("1"); final Wearable.CODES codes = Wearable.CODES.instance(); for(int i=0;i<codes.total();i++) { if(CMath.bset(wornLoc[0],codes.get(i))) { V.add(""+(i+2)); V.add(""+(i+2)); } } V.add("0"); return CMParms.toStringArray(V); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { final short[] layerAtt = new short[1]; final short[] layers = new short[1]; final long[] wornLoc = new long[1]; final boolean[] logicalAnd = new boolean[1]; final double[] hardBonus=new double[1]; CMLib.ableParms().parseWearLocation(layerAtt,layers,wornLoc,logicalAnd,hardBonus,oldVal); CMLib.genEd().wornLayer(mob,layerAtt,layers,++showNumber[0],showFlag); CMLib.genEd().wornLocation(mob,wornLoc,logicalAnd,++showNumber[0],showFlag); return reconvert(layerAtt,layers,wornLoc,logicalAnd,hardBonus); } }, new AbilityParmEditorImpl("PAGES_CHARS","Max Pgs/Chrs.",ParmType.SPECIAL) { @Override public int appliesToClass(final Object o) { return (o instanceof Book) ? 1 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "1/0"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Book) return ""+((Book)I).getMaxPages()+"/"+((Book)I).getMaxCharsPerPage(); return "1/0"; } @Override public boolean confirmValue(final String oldVal) { return oldVal.trim().length() > 0; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { int maxPages=1; int maxCharsPage=0; if(oldVal.length()>0) { final int x=oldVal.indexOf('/'); if(x>0) { maxPages=CMath.s_int(oldVal.substring(0,x)); maxCharsPage=CMath.s_int(oldVal.substring(x+1)); } } if(httpReq.isUrlParameter(fieldName+"_MAXPAGES")) maxPages = CMath.s_int(httpReq.getUrlParameter(fieldName+"_MAXPAGES")); if(httpReq.isUrlParameter(fieldName+"_MAXCHARSPAGE")) maxCharsPage = CMath.s_int(httpReq.getUrlParameter(fieldName+"_MAXCHARSPAGE")); return ""+maxPages+"/"+maxCharsPage; } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String value = webValue(httpReq, parms, oldVal, fieldName); final StringBuffer str = new StringBuffer(""); str.append("<TABLE WIDTH=100% BORDER=\"1\" CELLSPACING=0 CELLPADDING=0><TR>"); final String[] vals = this.fakeUserInput(value); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("Max Pages")+"</FONT></TD>"); str.append("<TD WIDTH=25%><INPUT TYPE=TEXT SIZE=5 NAME="+fieldName+"_MAXPAGES VALUE=\""+vals[0]+"\">"); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("Max Chars Page")+"</FONT></TD>"); str.append("<TD WIDTH=25%><INPUT TYPE=TEXT SIZE=5 NAME="+fieldName+"_MAXCHARSPAGE VALUE=\""+vals[1]+"\">"); str.append("</TD>"); str.append("</TR></TABLE>"); return str.toString(); } @Override public String[] fakeUserInput(final String oldVal) { final ArrayList<String> V = new ArrayList<String>(); int maxPages=1; int maxCharsPage=0; if(oldVal.length()>0) { final int x=oldVal.indexOf('/'); if(x>0) { maxPages=CMath.s_int(oldVal.substring(0,x)); maxCharsPage=CMath.s_int(oldVal.substring(x+1)); } } V.add(""+maxPages); V.add(""+maxCharsPage); return CMParms.toStringArray(V); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { final String[] input=this.fakeUserInput(oldVal); int maxPages=CMath.s_int(input[0]); int maxCharsPage=CMath.s_int(input[1]); maxPages = CMLib.genEd().prompt(mob, maxPages, ++showNumber[0], showFlag, L("Max Pages"), null); maxCharsPage = CMLib.genEd().prompt(mob, maxCharsPage, ++showNumber[0], showFlag, L("Max Chars/Page"), null); return maxPages+"/"+maxCharsPage; } }, new AbilityParmEditorImpl("RIDE_OVERRIDE_STRS","Ride Strings",ParmType.SPECIAL) { @Override public int appliesToClass(final Object o) { return (o instanceof Rideable) ? 1 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Rideable) { final Rideable R=(Rideable)I; final StringBuilder str=new StringBuilder(""); //STATESTR,STATESUBJSTR,RIDERSTR,MOUNTSTR,DISMOUNTSTR,PUTSTR str.append(R.getStateString().replace(';', ',')).append(';'); str.append(R.getStateStringSubject().replace(';', ',')).append(';'); str.append(R.getRideString().replace(';', ',')).append(';'); str.append(R.getMountString().replace(';', ',')).append(';'); str.append(R.getDismountString().replace(';', ',')).append(';'); str.append(R.getPutString().replace(';', ',')); if(str.length()==5) return ""; return str.toString(); } return ""; } @Override public boolean confirmValue(final String oldVal) { return true; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String[] finput = this.fakeUserInput(oldVal); String stateStr=finput[0]; String stateSubjectStr=finput[1]; String riderStr=finput[2]; String mountStr=finput[3]; String dismountStr=finput[4]; String putStr=finput[5]; if(httpReq.isUrlParameter(fieldName+"_RSTATESTR")) stateStr = httpReq.getUrlParameter(fieldName+"_RSTATESTR"); if(httpReq.isUrlParameter(fieldName+"_RSTATESUBJSTR")) stateSubjectStr = httpReq.getUrlParameter(fieldName+"_RSTATESUBJSTR"); if(httpReq.isUrlParameter(fieldName+"_RRIDERSTR")) riderStr = httpReq.getUrlParameter(fieldName+"_RRIDERSTR"); if(httpReq.isUrlParameter(fieldName+"_RMOUNTSTR")) mountStr = httpReq.getUrlParameter(fieldName+"_RMOUNTSTR"); if(httpReq.isUrlParameter(fieldName+"_RDISMOUNTSTR")) dismountStr = httpReq.getUrlParameter(fieldName+"_RDISMOUNTSTR"); if(httpReq.isUrlParameter(fieldName+"_RPUTSTR")) putStr = httpReq.getUrlParameter(fieldName+"_RPUTSTR"); final StringBuilder str=new StringBuilder(""); str.append(stateStr.replace(';', ',')).append(';'); str.append(stateSubjectStr.replace(';', ',')).append(';'); str.append(riderStr.replace(';', ',')).append(';'); str.append(mountStr.replace(';', ',')).append(';'); str.append(dismountStr.replace(';', ',')).append(';'); str.append(putStr.replace(';', ',')); if(str.length()==5) return ""; return str.toString(); } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String value = webValue(httpReq, parms, oldVal, fieldName); final StringBuffer str = new StringBuffer(""); str.append("<TABLE WIDTH=100% BORDER=\"1\" CELLSPACING=0 CELLPADDING=0>"); final String[] vals = this.fakeUserInput(value); str.append("<TR>"); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("State")+"</FONT></TD>"); str.append("<TD><INPUT TYPE=TEXT SIZE=50 NAME="+fieldName+"_RSTATESTR VALUE=\""+vals[0]+"\">"); str.append("</TR>"); str.append("<TR>"); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("State Subj.")+"</FONT></TD>"); str.append("<TD><INPUT TYPE=TEXT SIZE=50 NAME="+fieldName+"_RSTATESUBJSTR VALUE=\""+vals[1]+"\">"); str.append("</TR>"); str.append("<TR>"); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("Rider")+"</FONT></TD>"); str.append("<TD><INPUT TYPE=TEXT SIZE=50 NAME="+fieldName+"_RRIDERSTR VALUE=\""+vals[2]+"\">"); str.append("</TR>"); str.append("<TR>"); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("Mount")+"</FONT></TD>"); str.append("<TD><INPUT TYPE=TEXT SIZE=50 NAME="+fieldName+"_RMOUNTSTR VALUE=\""+vals[3]+"\">"); str.append("</TR>"); str.append("<TR>"); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("Dismount")+"</FONT></TD>"); str.append("<TD><INPUT TYPE=TEXT SIZE=50 NAME="+fieldName+"_RDISMOUNTSTR VALUE=\""+vals[4]+"\">"); str.append("</TR>"); str.append("<TR>"); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("Put")+"</FONT></TD>"); str.append("<TD><INPUT TYPE=TEXT SIZE=50 NAME="+fieldName+"_RPUTSTR VALUE=\""+vals[5]+"\">"); str.append("</TR>"); str.append("</TABLE>"); return str.toString(); } @Override public String[] fakeUserInput(final String oldVal) { final ArrayList<String> V = new ArrayList<String>(); String stateStr=""; String stateSubjectStr=""; String riderStr=""; String mountStr=""; String dismountStr=""; String putStr=""; if(oldVal.length()>0) { final List<String> lst=CMParms.parseSemicolons(oldVal.trim(),false); if(lst.size()>0) stateStr=lst.get(0).replace(';',','); if(lst.size()>1) stateSubjectStr=lst.get(1).replace(';',','); if(lst.size()>2) riderStr=lst.get(2).replace(';',','); if(lst.size()>3) mountStr=lst.get(3).replace(';',','); if(lst.size()>4) dismountStr=lst.get(4).replace(';',','); if(lst.size()>5) putStr=lst.get(5).replace(';',','); } V.add(stateStr); V.add(stateSubjectStr); V.add(riderStr); V.add(mountStr); V.add(dismountStr); V.add(putStr); return CMParms.toStringArray(V); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { final String[] finput = this.fakeUserInput(oldVal); String stateStr=finput[0]; String stateSubjectStr=finput[1]; String riderStr=finput[2]; String mountStr=finput[3]; String dismountStr=finput[4]; String putStr=finput[5]; stateStr = CMLib.genEd().prompt(mob, stateStr, ++showNumber[0], showFlag, L("State Str"), true); stateSubjectStr = CMLib.genEd().prompt(mob, stateSubjectStr, ++showNumber[0], showFlag, L("State Subject"), true); riderStr = CMLib.genEd().prompt(mob, riderStr, ++showNumber[0], showFlag, L("Ride Str"), true); mountStr = CMLib.genEd().prompt(mob, mountStr, ++showNumber[0], showFlag, L("Mount Str"), true); dismountStr = CMLib.genEd().prompt(mob, dismountStr, ++showNumber[0], showFlag, L("Dismount Str"), true); putStr = CMLib.genEd().prompt(mob, putStr, ++showNumber[0], showFlag, L("Put Str"), true); final StringBuilder str=new StringBuilder(""); str.append(stateStr.replace(';', ',')).append(';'); str.append(stateSubjectStr.replace(';', ',')).append(';'); str.append(riderStr.replace(';', ',')).append(';'); str.append(mountStr.replace(';', ',')).append(';'); str.append(dismountStr.replace(';', ',')).append(';'); str.append(putStr.replace(';', ',')); if(str.length()==5) return ""; return str.toString(); } }, new AbilityParmEditorImpl("CONTAINER_CAPACITY","Cap.",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return (o instanceof Container) ? 1 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "20"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Container) return ""+((Container)I).capacity(); return "0"; } }, new AbilityParmEditorImpl("BASE_ARMOR_AMOUNT","Arm.",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return (o instanceof Armor) ? 2 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""+I.basePhyStats().armor(); } }, new AbilityParmEditorImpl("CONTAINER_TYPE","Con.",ParmType.MULTICHOICES) { @Override public void createChoices() { createBinaryChoices(Container.CONTAIN_DESCS); } @Override public int appliesToClass(final Object o) { return (o instanceof Container) ? 1 : -1; } @Override public String defaultValue() { return "0"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof Container)) return ""; final Container C=(Container)I; final StringBuilder str=new StringBuilder(""); for(int i=1;i<Container.CONTAIN_DESCS.length;i++) { if(CMath.isSet(C.containTypes(), i-1)) { if(str.length()>0) str.append("|"); str.append(Container.CONTAIN_DESCS[i]); } } return str.toString(); } }, new AbilityParmEditorImpl("CONTAINER_TYPE_OR_LIDLOCK","Con.",ParmType.SPECIAL) { @Override public void createChoices() { super.choices = new PairVector<String,String>(); for(final String s : Container.CONTAIN_DESCS) choices().add(s.toUpperCase().trim(),s); choices().add("LID","Lid"); choices().add("LOCK","Lock"); } @Override public int appliesToClass(final Object o) { return (o instanceof Container) ? 1 : -1; } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { final StringBuilder str=new StringBuilder(""); if(I instanceof Container) { final Container C=(Container)I; if(C.hasALock()) str.append("LOCK"); if(str.length()>0) str.append("|"); if(C.hasADoor()) str.append("LID"); if(str.length()>0) str.append("|"); for(int i=1;i<Container.CONTAIN_DESCS.length;i++) { if(CMath.isSet(C.containTypes(), i-1)) { if(str.length()>0) str.append("|"); str.append(Container.CONTAIN_DESCS[i]); } } } return str.toString(); } @Override public String[] fakeUserInput(final String oldVal) { if(oldVal.trim().length()==0) return new String[]{"NULL"}; return CMParms.parseAny(oldVal,'|',true).toArray(new String[0]); } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String webValue = httpReq.getUrlParameter(fieldName); if(webValue == null) return oldVal; String id=""; int index=0; final StringBuilder str=new StringBuilder(""); for(;httpReq.isUrlParameter(fieldName+id);id=""+(++index)) { final String newVal = httpReq.getUrlParameter(fieldName+id); if((newVal!=null)&&(newVal.length()>0)&&(choices().containsFirst(newVal))) str.append(newVal).append("|"); } return str.toString(); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { return CMLib.genEd().promptMultiSelectList(mob,oldVal,"|",++showNumber[0],showFlag,prompt(),choices(),false); } @Override public boolean confirmValue(final String oldVal) { final List<String> webVals=CMParms.parseAny(oldVal.toUpperCase().trim(), "|", true); for(final String s : webVals) { if(!choices().containsFirst(s)) return false; } return true; } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String webValue = webValue(httpReq,parms,oldVal,fieldName); final List<String> webVals=CMParms.parseAny(webValue.toUpperCase().trim(), "|", true); String onChange = null; onChange = " MULTIPLE "; if(!parms.containsKey("NOSELECT")) onChange+= "ONCHANGE=\"MultiSelect(this);\""; final StringBuilder str=new StringBuilder(""); str.append("\n\r<SELECT NAME="+fieldName+onChange+">"); for(int i=0;i<choices().size();i++) { final String option = (choices().get(i).first); str.append("<OPTION VALUE=\""+option+"\" "); if(webVals.contains(option)) str.append("SELECTED"); str.append(">"+(choices().get(i).second)); } return str.toString()+"</SELECT>"; } }, new AbilityParmEditorImpl("CODED_SPELL_LIST","Spell Affects",ParmType.SPECIAL) { @Override public void createChoices() { } @Override public int maxColWidth() { return 20; } @Override public boolean confirmValue(String oldVal) { if(oldVal.length()==0) return true; if(oldVal.charAt(0)=='*') oldVal = oldVal.substring(1); final int x=oldVal.indexOf('('); int y=oldVal.indexOf(';'); if((x<y)&&(x>0)) y=x; if(y<0) return CMClass.getAbility(oldVal)!=null; return CMClass.getAbility(oldVal.substring(0,y))!=null; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return CMLib.coffeeMaker().getCodedSpellsOrBehaviors(I); } @Override public String defaultValue() { return ""; } public String rebuild(final List<CMObject> spells) throws CMException { final StringBuffer newVal = new StringBuffer(""); if(spells.size()==1) { newVal.append("*" + spells.get(0).ID() + ";"); if(spells.get(0) instanceof Ability) newVal.append(((Ability)spells.get(0)).text()); else if(spells.get(0) instanceof Behavior) newVal.append(((Behavior)spells.get(0)).getParms()); } else { if(spells.size()>1) { for(int s=0;s<spells.size();s++) { final String txt; if(spells.get(s) instanceof Ability) txt=((Ability)spells.get(s)).text(); else if(spells.get(s) instanceof Behavior) txt=((Behavior)spells.get(s)).getParms(); else txt=""; if(txt.length()>0) { if((txt.indexOf(';')>=0) ||(CMClass.getAbility(txt.trim())!=null) ||(CMClass.getBehavior(txt.trim())!=null)) throw new CMException("You may not have more than one spell when one of the spells parameters is a spell id or a ; character."); } newVal.append(spells.get(s).ID()); if(txt.length()>0) newVal.append(";" + txt); if(s<(spells.size()-1)) newVal.append(";"); } } } return newVal.toString(); } @Override public String[] fakeUserInput(final String oldVal) { final Vector<String> V = new Vector<String>(); final Vector<String> V2 = new Vector<String>(); final List<CMObject> spells=CMLib.coffeeMaker().getCodedSpellsOrBehaviors(oldVal); for(int s=0;s<spells.size();s++) { final CMObject O = spells.get(s); V.addElement(O.ID()); V2.addElement(O.ID()); if(O instanceof Ability) V2.addElement(((Ability)O).text()); else if(O instanceof Behavior) V2.addElement(((Behavior)O).getParms()); else V2.add(""); } V.addAll(V2); V.addElement(""); return CMParms.toStringArray(V); } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { List<CMObject> spells=null; if(httpReq.isUrlParameter(fieldName+"_AFFECT1")) { spells = new Vector<CMObject>(); int num=1; String behav=httpReq.getUrlParameter(fieldName+"_AFFECT"+num); String theparm=httpReq.getUrlParameter(fieldName+"_ADATA"+num); while((behav!=null)&&(theparm!=null)) { if(behav.length()>0) { final Ability A=CMClass.getAbility(behav); if(A!=null) { if(theparm.trim().length()>0) A.setMiscText(theparm); spells.add(A); } else { final Behavior B=CMClass.getBehavior(behav); if(B!=null) { if(theparm.trim().length()>0) B.setParms(theparm); spells.add(B); } } } num++; behav=httpReq.getUrlParameter(fieldName+"_AFFECT"+num); theparm=httpReq.getUrlParameter(fieldName+"_ADATA"+num); } } else spells = CMLib.coffeeMaker().getCodedSpellsOrBehaviors(oldVal); try { return rebuild(spells); } catch(final Exception e) { return oldVal; } } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final List<CMObject> spells=CMLib.coffeeMaker().getCodedSpellsOrBehaviors(webValue(httpReq,parms,oldVal,fieldName)); final StringBuffer str = new StringBuffer(""); str.append("<TABLE WIDTH=100% BORDER=\"1\" CELLSPACING=0 CELLPADDING=0>"); for(int i=0;i<spells.size();i++) { final CMObject A=spells.get(i); str.append("<TR><TD WIDTH=50%>"); str.append("\n\r<SELECT ONCHANGE=\"EditAffect(this);\" NAME="+fieldName+"_AFFECT"+(i+1)+">"); str.append("<OPTION VALUE=\"\">Delete!"); str.append("<OPTION VALUE=\""+A.ID()+"\" SELECTED>"+A.ID()); str.append("</SELECT>"); str.append("</TD><TD WIDTH=50%>"); final String parmstr=(A instanceof Ability)?((Ability)A).text():((Behavior)A).getParms(); final String theparm=CMStrings.replaceAll(parmstr,"\"","&quot;"); str.append("\n\r<INPUT TYPE=TEXT SIZE=30 NAME="+fieldName+"_ADATA"+(i+1)+" VALUE=\""+theparm+"\">"); str.append("</TD></TR>"); } str.append("<TR><TD WIDTH=50%>"); str.append("\n\r<SELECT ONCHANGE=\"AddAffect(this);\" NAME="+fieldName+"_AFFECT"+(spells.size()+1)+">"); str.append("<OPTION SELECTED VALUE=\"\">Select an Effect/Behav"); for(final Enumeration<Ability> a=CMClass.abilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A.classificationCode()&Ability.ALL_DOMAINS)==Ability.DOMAIN_ARCHON) continue; final String cnam=A.ID(); str.append("<OPTION VALUE=\""+cnam+"\">"+cnam); } for(final Enumeration<Behavior> b=CMClass.behaviors();b.hasMoreElements();) { final Behavior B=b.nextElement(); final String cnam=B.ID(); str.append("<OPTION VALUE=\""+cnam+"\">"+cnam); } str.append("</SELECT>"); str.append("</TD><TD WIDTH=50%>"); str.append("\n\r<INPUT TYPE=TEXT SIZE=30 NAME="+fieldName+"_ADATA"+(spells.size()+1)+" VALUE=\"\">"); str.append("</TD></TR>"); str.append("</TABLE>"); return str.toString(); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { final List<CMObject> spells=CMLib.coffeeMaker().getCodedSpellsOrBehaviors(oldVal); final StringBuffer rawCheck = new StringBuffer(""); for(int s=0;s<spells.size();s++) { rawCheck.append(spells.get(s).ID()).append(";"); if(spells.get(s) instanceof Ability) rawCheck.append(((Ability)spells.get(s)).text()).append(";"); else if(spells.get(s) instanceof Behavior) rawCheck.append(((Behavior)spells.get(s)).getParms()).append(";"); } boolean okToProceed = true; ++showNumber[0]; String newVal = null; while(okToProceed) { okToProceed = false; CMLib.genEd().spellsOrBehavs(mob,spells,showNumber[0],showFlag,true); final StringBuffer sameCheck = new StringBuffer(""); for(int s=0;s<spells.size();s++) { sameCheck.append(spells.get(s).ID()).append(';'); if(spells.get(s) instanceof Ability) sameCheck.append(((Ability)spells.get(s)).text()).append(";"); else if(spells.get(s) instanceof Behavior) sameCheck.append(((Behavior)spells.get(s)).getParms()).append(";"); } if(sameCheck.toString().equals(rawCheck.toString())) return oldVal; try { newVal = rebuild(spells); } catch(final CMException e) { mob.tell(e.getMessage()); okToProceed = true; break; } } return (newVal==null)?oldVal:newVal.toString(); } }, new AbilityParmEditorImpl("BUILDING_FLAGS","Flags",ParmType.SPECIAL) { @Override public void createChoices() { } @Override public boolean confirmValue(final String oldVal) { if(oldVal.trim().length()==0) return true; final Pair<String[],String[]> codesFlags = CMAbleParms.getBuildingCodesNFlags(); final String[] names = CMParms.parseSpaces(oldVal, true).toArray(new String[0]); for(final String name : names) { if(!CMParms.containsIgnoreCase(codesFlags.second, name)) return false; } return true; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return ""; } @Override public String[] fakeUserInput(final String oldVal) { return CMParms.parseSpaces(oldVal, true).toArray(new String[0]); } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String webValue = httpReq.getUrlParameter(fieldName); if(webValue == null) return oldVal; final StringBuilder s=new StringBuilder(""); String id=""; int index=0; final Pair<String[],String[]> codesFlags = CMAbleParms.getBuildingCodesNFlags(); for(;httpReq.isUrlParameter(fieldName+id);id=""+(++index)) { final String newVal = httpReq.getUrlParameter(fieldName+id); if(CMParms.containsIgnoreCase(codesFlags.second, newVal.toUpperCase().trim())) s.append(" ").append(newVal.toUpperCase().trim()); } return s.toString().trim(); } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final StringBuffer str = new StringBuffer(""); final String webValue = webValue(httpReq,parms,oldVal,fieldName); String onChange = null; onChange = " MULTIPLE "; if(!parms.containsKey("NOSELECT")) onChange+= "ONCHANGE=\"MultiSelect(this);\""; final Pair<String[],String[]> codesFlags = CMAbleParms.getBuildingCodesNFlags(); final String[] fakeValues = this.fakeUserInput(webValue); str.append("\n\r<SELECT NAME="+fieldName+onChange+">"); for(int i=0;i<codesFlags.second.length;i++) { final String option = (codesFlags.second[i]); str.append("<OPTION VALUE=\""+option+"\" "); if(CMParms.containsIgnoreCase(fakeValues, option)) str.append("SELECTED"); str.append(">"+option); } return str.toString()+"</SELECT>"; } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { final Pair<String[],String[]> codesFlags = CMAbleParms.getBuildingCodesNFlags(); final String help=CMParms.combineWith(Arrays.asList(codesFlags.second), ','); final String newVal = CMLib.genEd().prompt(mob, oldVal, ++showNumber[0], showFlag, L("Flags"), true, help); String[] newVals; if(newVal.indexOf(',')>0) newVals = CMParms.parseCommas(newVal.toUpperCase().trim(), true).toArray(new String[0]); else if(newVal.indexOf(';')>0) newVals = CMParms.parseSemicolons(newVal.toUpperCase().trim(), true).toArray(new String[0]); else newVals = CMParms.parse(newVal.toUpperCase().trim()).toArray(new String[0]); final StringBuilder finalVal = new StringBuilder(""); for(int i=0;i<newVals.length;i++) { if(CMParms.containsIgnoreCase(codesFlags.second, newVals[i])) finalVal.append(" ").append(newVals[i]); } return finalVal.toString().toUpperCase().trim(); } }, new AbilityParmEditorImpl("EXIT_NAMES","Exit Words",ParmType.SPECIAL) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equalsIgnoreCase("DOOR")) return 1; } return -1; } @Override public boolean confirmValue(final String oldVal) { if(oldVal.trim().length()==0) return true; final String[] names = CMParms.parseAny(oldVal.trim(), '|', true).toArray(new String[0]); if(names.length > 5) return false; return true; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return "door|open|close|A closed door.|An open doorway."; } @Override public String[] fakeUserInput(final String oldVal) { final Vector<String> V = new Vector<String>(); V.addAll(CMParms.parseAny(oldVal.trim(), '|', true)); while(V.size()<5) V.add(""); return CMParms.toStringArray(V); } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { if(httpReq.isUrlParameter(fieldName+"_W1")) { final StringBuilder str=new StringBuilder(""); str.append(httpReq.getUrlParameter(fieldName+"_W1")).append("|"); str.append(httpReq.getUrlParameter(fieldName+"_W2")).append("|"); str.append(httpReq.getUrlParameter(fieldName+"_W3")).append("|"); str.append(httpReq.getUrlParameter(fieldName+"_W4")).append("|"); str.append(httpReq.getUrlParameter(fieldName+"_W5")); String s=str.toString(); while(s.endsWith("|")) s=s.substring(0,s.length()-1); return s; } else { return oldVal; } } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final StringBuffer str = new StringBuffer(""); str.append("<TABLE WIDTH=100% BORDER=\"1\" CELLSPACING=0 CELLPADDING=0>"); final String[] vals = this.fakeUserInput(oldVal); final String[] keys = new String[]{"Noun","Open","Close","Closed Display","Open Display"}; for(int i=0;i<keys.length;i++) { str.append("<TR><TD WIDTH=30%><FONT COLOR=WHITE>"+L(keys[i])+"</FONT></TD>"); str.append("<TD><INPUT TYPE=TEXT SIZE=30 NAME="+fieldName+"_W"+(i+1)+" VALUE=\""+vals[i]+"\">"); str.append("</TD></TR>"); } str.append("</TABLE>"); return str.toString(); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { final String[] vals = this.fakeUserInput(oldVal); final StringBuilder newVal = new StringBuilder(""); newVal.append(CMLib.genEd().prompt(mob, vals[0], ++showNumber[0], showFlag, L("Exit Noun"), true)).append("|"); newVal.append(CMLib.genEd().prompt(mob, vals[1], ++showNumber[0], showFlag, L("Open Verb"), true)).append("|"); newVal.append(CMLib.genEd().prompt(mob, vals[2], ++showNumber[0], showFlag, L("Close Verb"), true)).append("|"); newVal.append(CMLib.genEd().prompt(mob, vals[3], ++showNumber[0], showFlag, L("Opened Text"), true)).append("|"); newVal.append(CMLib.genEd().prompt(mob, vals[4], ++showNumber[0], showFlag, L("Closed Text"), true)); String s=newVal.toString(); while(s.endsWith("|")) s=s.substring(0,s.length()-1); return s; } }, new AbilityParmEditorImpl("PCODED_SPELL_LIST","Spell Affects",ParmType.SPECIAL) { @Override public void createChoices() { } @Override public int maxColWidth() { return 20; } @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equalsIgnoreCase("WALL") ||chk.equalsIgnoreCase("DEMOLISH") ||chk.equalsIgnoreCase("TITLE") ||chk.equalsIgnoreCase("DESC")) return -1; final Pair<String[],String[]> codeFlags = CMAbleParms.getBuildingCodesNFlags(); if(CMParms.contains(codeFlags.first, chk)) return 1; } return -1; } @Override public boolean confirmValue(final String oldVal) { if(oldVal.trim().length()==0) return true; final String[] spells = CMParms.parseAny(oldVal.trim(), ')', true).toArray(new String[0]); for(String spell : spells) { final int x=spell.indexOf('('); if(x>0) spell=spell.substring(0,x); if(spell.trim().length()==0) continue; if((CMClass.getAbility(spell)==null)&&(CMClass.getBehavior(spell)==null)) return false; } return true; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return ""; } public String rebuild(final List<CMObject> spells) throws CMException { final StringBuffer newVal = new StringBuffer(""); for(int s=0;s<spells.size();s++) { final String txt; if(spells.get(s) instanceof Ability) txt = ((Ability)spells.get(s)).text().trim(); else if(spells.get(s) instanceof Behavior) txt = ((Behavior)spells.get(s)).getParms().trim(); else continue; newVal.append(spells.get(s).ID()).append("(").append(txt).append(")"); } return newVal.toString(); } @Override public String[] fakeUserInput(final String oldVal) { final Vector<String> V = new Vector<String>(); final String[] spells = CMParms.parseAny(oldVal.trim(), ')', true).toArray(new String[0]); for(String spell : spells) { final int x=spell.indexOf('('); String parms=""; if(x>0) { parms=spell.substring(x+1).trim(); spell=spell.substring(0,x); } if(spell.trim().length()==0) continue; if((CMClass.getAbility(spell)!=null) ||(CMClass.getBehavior(spell)!=null)) { V.add(spell); V.add(parms); } } return CMParms.toStringArray(V); } public List<CMObject> getCodedSpells(final String oldVal) { final String[] spellStrs = this.fakeUserInput(oldVal); final List<CMObject> spells=new ArrayList<CMObject>(spellStrs.length/2); for(int s=0;s<spellStrs.length;s+=2) { final Ability A=CMClass.getAbility(spellStrs[s]); if(A!=null) { if(spellStrs[s+1].length()>0) A.setMiscText(spellStrs[s+1]); spells.add(A); } else { final Behavior B=CMClass.getBehavior(spellStrs[s]); if(spellStrs[s+1].length()>0) B.setParms(spellStrs[s+1]); spells.add(B); } } return spells; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { List<CMObject> spells=null; if(httpReq.isUrlParameter(fieldName+"_AFFECT1")) { spells = new Vector<CMObject>(); int num=1; String behav=httpReq.getUrlParameter(fieldName+"_AFFECT"+num); String theparm=httpReq.getUrlParameter(fieldName+"_ADATA"+num); while((behav!=null)&&(theparm!=null)) { if(behav.length()>0) { final Ability A=CMClass.getAbility(behav); if(A!=null) { if(theparm.trim().length()>0) A.setMiscText(theparm); spells.add(A); } else { final Behavior B=CMClass.getBehavior(behav); if(theparm.trim().length()>0) B.setParms(theparm); spells.add(B); } } num++; behav=httpReq.getUrlParameter(fieldName+"_AFFECT"+num); theparm=httpReq.getUrlParameter(fieldName+"_ADATA"+num); } } else { spells = getCodedSpells(oldVal); } try { return rebuild(spells); } catch(final Exception e) { return oldVal; } } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final List<CMObject> spells=getCodedSpells(webValue(httpReq,parms,oldVal,fieldName)); final StringBuffer str = new StringBuffer(""); str.append("<TABLE WIDTH=100% BORDER=\"1\" CELLSPACING=0 CELLPADDING=0>"); for(int i=0;i<spells.size();i++) { final CMObject A=spells.get(i); str.append("<TR><TD WIDTH=50%>"); str.append("\n\r<SELECT ONCHANGE=\"EditAffect(this);\" NAME="+fieldName+"_AFFECT"+(i+1)+">"); str.append("<OPTION VALUE=\"\">Delete!"); str.append("<OPTION VALUE=\""+A.ID()+"\" SELECTED>"+A.ID()); str.append("</SELECT>"); str.append("</TD><TD WIDTH=50%>"); final String theparm; if(A instanceof Ability) theparm=CMStrings.replaceAll(((Ability)A).text(),"\"","&quot;"); else if(A instanceof Behavior) theparm=CMStrings.replaceAll(((Behavior)A).getParms(),"\"","&quot;"); else continue; str.append("\n\r<INPUT TYPE=TEXT SIZE=30 NAME="+fieldName+"_ADATA"+(i+1)+" VALUE=\""+theparm+"\">"); str.append("</TD></TR>"); } str.append("<TR><TD WIDTH=50%>"); str.append("\n\r<SELECT ONCHANGE=\"AddAffect(this);\" NAME="+fieldName+"_AFFECT"+(spells.size()+1)+">"); str.append("<OPTION SELECTED VALUE=\"\">Select Effect/Behavior"); for(final Enumeration<Ability> a=CMClass.abilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A.classificationCode()&Ability.ALL_DOMAINS)==Ability.DOMAIN_ARCHON) continue; final String cnam=A.ID(); str.append("<OPTION VALUE=\""+cnam+"\">"+cnam); } for(final Enumeration<Behavior> a=CMClass.behaviors();a.hasMoreElements();) { final Behavior A=a.nextElement(); final String cnam=A.ID(); str.append("<OPTION VALUE=\""+cnam+"\">"+cnam); } str.append("</SELECT>"); str.append("</TD><TD WIDTH=50%>"); str.append("\n\r<INPUT TYPE=TEXT SIZE=30 NAME="+fieldName+"_ADATA"+(spells.size()+1)+" VALUE=\"\">"); str.append("</TD></TR>"); str.append("</TABLE>"); return str.toString(); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { final List<CMObject> spells=getCodedSpells(oldVal); final StringBuffer rawCheck = new StringBuffer(""); for(int s=0;s<spells.size();s++) { rawCheck.append(spells.get(s).ID()).append(";"); if(spells.get(s) instanceof Ability) rawCheck.append(((Ability)spells.get(s)).text()).append(";"); else if(spells.get(s) instanceof Behavior) rawCheck.append(((Behavior)spells.get(s)).getParms()).append(";"); else rawCheck.append(";"); } boolean okToProceed = true; ++showNumber[0]; String newVal = null; while(okToProceed) { okToProceed = false; CMLib.genEd().spellsOrBehaviors(mob,spells,showNumber[0],showFlag,true); final StringBuffer sameCheck = new StringBuffer(""); for(int s=0;s<spells.size();s++) { if(spells.get(s) instanceof Ability) rawCheck.append(((Ability)spells.get(s)).text()).append(";"); else if(spells.get(s) instanceof Behavior) rawCheck.append(((Behavior)spells.get(s)).getParms()).append(";"); else rawCheck.append(";"); } if(sameCheck.toString().equals(rawCheck.toString())) return oldVal; try { newVal = rebuild(spells); } catch(final CMException e) { mob.tell(e.getMessage()); okToProceed = true; break; } } return (newVal==null)?oldVal:newVal.toString(); } }, new AbilityParmEditorImpl("BASE_DAMAGE","Dmg.",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return (o instanceof Weapon) ? 2 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Weapon) return ""+((Weapon)I).basePhyStats().damage(); return "0"; } }, new AbilityParmEditorImpl("LID_LOCK","Lid.",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof Container) ? 1 : -1; } @Override public void createChoices() { createChoices(new String[] { "", "LID", "LOCK" }); } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof Container)) return ""; final Container C=(Container)I; if(C.hasALock()) return "LOCK"; if(C.hasADoor()) return "LID"; return ""; } }, new AbilityParmEditorImpl("BUILDING_CODE","Code",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return 1; } @Override public void createChoices() { createChoices(getBuildingCodesNFlags().first); } @Override public String defaultValue() { return "TITLE"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return "TITLE"; } }, new AbilityParmEditorImpl("STATUE","Statue",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return ((!(o instanceof Armor)) && (!(o instanceof Container)) && (!(o instanceof Drink))) ? 1 : -1; } @Override public void createChoices() { createChoices(new String[] { "", "STATUE" }); } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Weapon) return ""; if(I instanceof Armor) return ""; if(I instanceof Ammunition) return ""; final int x=I.Name().lastIndexOf(" of "); if(x<0) return ""; final String ender=I.Name(); if(!I.displayText().endsWith(ender+" is here")) return ""; if(!I.description().startsWith(ender+". ")) return ""; return "STATUE"; } }, new AbilityParmEditorImpl("RIDE_BASIS","Ride",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof Rideable) ? 3 : -1; } @Override public void createChoices() { createChoices(new String[] { "", "CHAIR", "TABLE", "LADDER", "ENTER", "BED" }); } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof Rideable)) return ""; switch(((Rideable)I).rideBasis()) { case Rideable.RIDEABLE_SIT: return "SIT"; case Rideable.RIDEABLE_TABLE: return "TABLE"; case Rideable.RIDEABLE_LADDER: return "LADDER"; case Rideable.RIDEABLE_ENTERIN: return "ENTER"; case Rideable.RIDEABLE_SLEEP: return "BED"; default: return ""; } } }, new AbilityParmEditorImpl("LIQUID_CAPACITY","Liq.",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return (o instanceof Drink) ? 4 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "25"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof Drink)) return ""; return ""+((Drink)I).liquidHeld(); } }, new AbilityParmEditorImpl("MAX_WAND_USES","Max.",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return (o instanceof Wand) ? 5 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "25"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof Wand)) return ""; return ""+((Wand)I).maxUses(); } }, new AbilityParmEditorImpl("WAND_TYPE","MagicT",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof Wand) ? 2 : -1; } @Override public int minColWidth() { return 3; } @Override public boolean confirmValue(final String oldVal) { if(oldVal==null) return false; if(oldVal.length()==0) return true; return super.confirmValue(oldVal); } @Override public String[] fakeUserInput(final String oldVal) { if((oldVal==null) || (oldVal.length()==0)) return new String[] { "ANY" }; return new String[] { oldVal }; } @Override public void createChoices() { choices = new PairVector<String,String>(); choices.add("ANY", "Any"); for(final String[] set : Wand.WandUsage.WAND_OPTIONS) choices.add(set[0], CMStrings.capitalizeAllFirstLettersAndLower(set[1])); } @Override public String defaultValue() { return "ANY"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Wand) { final int ofType=((Wand)I).getEnchantType(); if((ofType<0)||(ofType>Ability.ACODE_DESCS_.length)) return "ANY"; return Ability.ACODE_DESCS_[ofType]; } return "ANY"; } }, new AbilityParmEditorImpl("DICE_SIDES","Dice.",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { if(o instanceof CMObject) { if(((CMObject)o).ID().endsWith("Dice")) return 1; } return -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "6"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""+I.basePhyStats().ability(); } }, new AbilityParmEditorImpl("WEAPON_CLASS","WClas",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof Weapon) ? 2 : -1; } @Override public void createChoices() { createChoices(Weapon.CLASS_DESCS); } @Override public String defaultValue() { return "BLUNT"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Weapon) return Weapon.CLASS_DESCS[((Weapon)I).weaponClassification()]; return "0"; } }, new AbilityParmEditorImpl("SMOKE_FLAG","Smoke",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof Light) ? 5 : -1; } @Override public void createChoices() { createChoices(new String[] { "", "SMOKE" }); } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof Light)) return ""; if((I instanceof Container) &&(((Light)I).getDuration() > 199) &&(((Container)I).capacity()==0)) return "SMOKE"; return ""; } }, new AbilityParmEditorImpl("WEAPON_HANDS_REQUIRED","Hand",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return (o instanceof Weapon) ? 2 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Weapon) return ((Weapon)I).rawLogicalAnd()?"2":"1"; return ""; } }, new AbilityParmEditorImpl("KEY_VALUE_PARMS","Keys",ParmType.STRINGORNULL) { @Override public int appliesToClass(final Object o) { return 1; } @Override public void createChoices() { } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { // how would I even start.... return ""; } }, new AbilityParmEditorImpl("LIGHT_DURATION","Dur.",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return (o instanceof Light) ? 5 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "10"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Light) return ""+((Light)I).getDuration(); return ""; } }, new AbilityParmEditorImpl("CLAN_ITEM_CODENUMBER","Typ.",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof ClanItem) ? 10 : -1; } @Override public void createChoices() { createNumberedChoices(ClanItem.ClanItemType.ALL); } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof ClanItem) return ""+((ClanItem)I).getClanItemType().ordinal(); return ""; } }, new AbilityParmEditorImpl("CLAN_EXPERIENCE_COST_AMOUNT","Exp",ParmType.NUMBER) { @Override public void createChoices() { } @Override public String defaultValue() { return "100"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof ClanItem)) return "100"; if(I.getClass().getName().toString().indexOf("Flag")>0) return "2500"; if(I.getClass().getName().toString().indexOf("ClanItem")>0) return "1000"; if(I.getClass().getName().toString().indexOf("GenClanSpecialItem")>0) return "500"; return "100"; } }, new AbilityParmEditorImpl("CLAN_AREA_FLAG","Area",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return o.getClass().getName().toString().indexOf("LawBook") > 0 ? 5 : -1; } @Override public void createChoices() { createChoices(new String[] { "", "AREA" }); } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return (I.getClass().getName().toString().indexOf("LawBook")>0)?"AREA":""; } }, new AbilityParmEditorImpl("READABLE_TEXT","Read",ParmType.STRINGORNULL) { @Override public void createChoices() { } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(CMLib.flags().isReadable(I)) return I.readableText(); return ""; } }, new AbilityParmEditorImpl("REQUIRED_COMMON_SKILL_ID","Common Skill",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof ClanItem) ? 5 : -1; } @Override public void createChoices() { final Vector<Object> V = new Vector<Object>(); Ability A = null; for(final Enumeration<Ability> e=CMClass.abilities();e.hasMoreElements();) { A=e.nextElement(); if((A.classificationCode() & Ability.ALL_ACODES) == Ability.ACODE_COMMON_SKILL) V.addElement(A); } V.addElement(""); createChoices(V); } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I.getClass().getName().toString().indexOf("LawBook")>0) return ""; if(I instanceof ClanItem) return ((ClanItem)I).readableText(); return ""; } }, new AbilityParmEditorImpl("FOOD_DRINK","ETyp",ParmType.CHOICES) { @Override public void createChoices() { createChoices(new String[] { "", "FOOD", "DRINK", "SOAP", "GenPerfume" }); } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { final String str=(I.name()+" "+I.displayText()+" "+I.description()).toUpperCase(); if(str.startsWith("SOAP ") || str.endsWith(" SOAP") || (str.indexOf("SOAP")>0)) return "SOAP"; if(I instanceof Perfume) return "PERFUME"; if(I instanceof Food) return "FOOD"; if(I instanceof Drink) return "DRINK"; return ""; } }, new AbilityParmEditorImpl("SMELL_LIST","Smells",ParmType.STRING) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { return (o instanceof Perfume) ? 5 : -1; } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Perfume) return ((Perfume)I).getSmellList(); return ""; } }, new AbilityParmEditorImpl("RESOURCE_OR_KEYWORD","Resc/Itm",ParmType.SPECIAL) { @Override public void createChoices() { } @Override public boolean confirmValue(final String oldVal) { return true; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { if(httpReq.isUrlParameter(fieldName+"_WHICH")) { final String which=httpReq.getUrlParameter(fieldName+"_WHICH"); if(which.trim().length()>0) return httpReq.getUrlParameter(fieldName+"_RESOURCE"); return httpReq.getUrlParameter(fieldName+"_WORD"); } return oldVal; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { String value=webValue(httpReq,parms,oldVal,fieldName); if(value.endsWith("$")) value = value.substring(0,oldVal.length()-1); value = value.trim(); final StringBuffer str = new StringBuffer(""); str.append("\n\r<INPUT TYPE=RADIO NAME="+fieldName+"_WHICH "); final boolean rsc=(value.trim().length()==0)||(RawMaterial.CODES.FIND_IgnoreCase(value)>=0); if(rsc) str.append("CHECKED "); str.append("VALUE=\"RESOURCE\">"); str.append("\n\r<SELECT NAME="+fieldName+"_RESOURCE>"); final String[] Ss=RawMaterial.CODES.NAMES().clone(); Arrays.sort(Ss); for(final String S : Ss) { final String VALUE = S.equals("NOTHING")?"":S; str.append("<OPTION VALUE=\""+VALUE+"\""); if(rsc&&(value.equalsIgnoreCase(VALUE))) str.append(" SELECTED"); str.append(">"+CMStrings.capitalizeAndLower(S)); } str.append("</SELECT>"); str.append("<BR>"); str.append("\n\r<INPUT TYPE=RADIO NAME="+fieldName+"_WHICH "); if(!rsc) str.append("CHECKED "); str.append("VALUE=\"\">"); str.append("\n\r<INPUT TYPE=TEXT NAME="+fieldName+"_WORD VALUE=\""+(rsc?"":value)+"\">"); return str.toString(); } @Override public String[] fakeUserInput(final String oldVal) { return new String[] { oldVal }; } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { ++showNumber[0]; boolean proceed = true; String str = oldVal; while(proceed&&(!mob.session().isStopped())) { proceed = false; str=CMLib.genEd().prompt(mob,oldVal,showNumber[0],showFlag,prompt(),true,CMParms.toListString(RawMaterial.CODES.NAMES())).trim(); if(str.equals(oldVal)) return oldVal; final int r=RawMaterial.CODES.FIND_IgnoreCase(str); if(r==0) str=""; else if(r>0) str=RawMaterial.CODES.NAME(r); if(str.equals(oldVal)) return oldVal; if(str.length()==0) return ""; final boolean isResource = CMParms.contains(RawMaterial.CODES.NAMES(),str); if((!isResource)&&(mob.session()!=null)&&(!mob.session().isStopped())) if(!mob.session().confirm(L("You`ve entered a non-resource item keyword '@x1', ok (Y/n)?",str),"Y")) proceed = true; } return str; } @Override public String defaultValue() { return ""; } }, new AbilityParmEditorImpl("RESOURCE_NAME_OR_HERB_NAME","Resrc/Herb",ParmType.SPECIAL) { @Override public void createChoices() { } @Override public boolean confirmValue(final String oldVal) { if(oldVal.trim().length()==0) return true; if(!oldVal.endsWith("$")) { return CMParms.contains(RawMaterial.CODES.NAMES(),oldVal); } return true; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String[] fakeUserInput(final String oldVal) { if(oldVal.endsWith("$")) return new String[]{oldVal.substring(0,oldVal.length()-1)}; return new String[]{oldVal}; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, String oldVal, final String fieldName) { final AbilityParmEditor A = CMLib.ableParms().getEditors().get("RESOURCE_OR_KEYWORD"); if(oldVal.endsWith("$")) oldVal = oldVal.substring(0,oldVal.length()-1); final String value = A.webValue(httpReq,parms,oldVal,fieldName); final int r=RawMaterial.CODES.FIND_IgnoreCase(value); if(r>=0) return RawMaterial.CODES.NAME(r); return (value.trim().length()==0)?"":(value+"$"); } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final AbilityParmEditor A = CMLib.ableParms().getEditors().get("RESOURCE_OR_KEYWORD"); return A.webField(httpReq,parms,oldVal,fieldName); } @Override public String webTableField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal) { if(oldVal.endsWith("$")) return oldVal.substring(0,oldVal.length()-1); return oldVal; } @Override public String commandLinePrompt(final MOB mob, String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { ++showNumber[0]; boolean proceed = true; String str = oldVal; final String orig = oldVal; while(proceed&&(!mob.session().isStopped())) { proceed = false; if(oldVal.trim().endsWith("$")) oldVal=oldVal.trim().substring(0,oldVal.trim().length()-1); str=CMLib.genEd().prompt(mob,oldVal,showNumber[0],showFlag,prompt(),true,CMParms.toListString(RawMaterial.CODES.NAMES())).trim(); if(str.equals(orig)) return orig; final int r=RawMaterial.CODES.FIND_IgnoreCase(str); if(r==0) str=""; else if(r>0) str=RawMaterial.CODES.NAME(r); if(str.equals(orig)) return orig; if(str.length()==0) return ""; final boolean isResource = CMParms.contains(RawMaterial.CODES.NAMES(),str); if((!isResource)&&(mob.session()!=null)&&(!mob.session().isStopped())) { if(!mob.session().confirm(L("You`ve entered a non-resource item keyword '@x1', ok (Y/n)?",str),"Y")) proceed = true; else str=str+"$"; } } return str; } @Override public String defaultValue() { return ""; } }, new AbilityParmEditorImpl("AMMO_TYPE","Ammo",ParmType.STRING) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { return ((o instanceof AmmunitionWeapon) || (o instanceof Ammunition)) ? 2 : -1; } @Override public String defaultValue() { return "arrows"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Ammunition) return ""+((Ammunition)I).ammunitionType(); if((I instanceof AmmunitionWeapon)&&(((AmmunitionWeapon)I).requiresAmmunition())) return ""+((AmmunitionWeapon)I).ammunitionType(); return ""; } }, new AbilityParmEditorImpl("AMMO_CAPACITY","Ammo#",ParmType.NUMBER) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { return ((o instanceof AmmunitionWeapon) || (o instanceof Ammunition)) ? 2 : -1; } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Ammunition) return ""+((Ammunition)I).ammunitionRemaining(); if((I instanceof AmmunitionWeapon)&&(((AmmunitionWeapon)I).requiresAmmunition())) return ""+((AmmunitionWeapon)I).ammunitionCapacity(); return ""; } }, new AbilityParmEditorImpl("MAXIMUM_RANGE","Max",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return ((o instanceof Weapon) && (!(o instanceof Ammunition))) ? 2 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "5"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Weapon) return ""+((Weapon)I).getRanges()[1]; else if(I instanceof Ammunition) return ""+I.maxRange(); return ""; } }, new AbilityParmEditorImpl("RESOURCE_OR_MATERIAL","Rsc/ Mat",ParmType.CHOICES) { @Override public void createChoices() { final XVector<String> V=new XVector<String>(RawMaterial.CODES.NAMES()); Collections.sort(V); final XVector<String> V2=new XVector<String>(RawMaterial.Material.names()); Collections.sort(V2); V.addAll(V2); createChoices(V); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(CMStrings.containsWordIgnoreCase(I.Name(),"rice")) return "RICE"; if(I.material() == RawMaterial.RESOURCE_PAPER) return "WOOD"; return RawMaterial.CODES.NAME(I.material()); } @Override public String defaultValue() { return "IRON"; } }, new AbilityParmEditorImpl("REQ_RESOURCE_OR_MATERIAL","Rsc/ Mat",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { if(o instanceof RawMaterial) return 1; return -1; } @Override public void createChoices() { final XVector<String> V=new XVector<String>(RawMaterial.CODES.NAMES()); Collections.sort(V); final XVector<String> V2=new XVector<String>(RawMaterial.Material.names()); Collections.sort(V2); V.addAll(V2); createChoices(V); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(CMStrings.containsWordIgnoreCase(I.Name(),"rice")) return "RICE"; if(I.material() == RawMaterial.RESOURCE_PAPER) return "WOOD"; return RawMaterial.CODES.NAME(I.material()); } @Override public String defaultValue() { return "IRON"; } }, new AbilityParmEditorImpl("OPTIONAL_RESOURCE_OR_MATERIAL","Rsc/ Mat",ParmType.CHOICES) { @Override public void createChoices() { final XVector<String> V=new XVector<String>(RawMaterial.CODES.NAMES()); Collections.sort(V); final XVector<String> V2=new XVector<String>(RawMaterial.Material.names()); Collections.sort(V2); V.addAll(V2); V.addElement(""); createChoices(V); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return ""; } }, new AbilityParmEditorImpl("OPTIONAL_RESOURCE_OR_MATERIAL_AMT","Rsc Amt",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { if(o instanceof Wand) return 1; return ((o instanceof Weapon) && (!(o instanceof Ammunition))) ? 2 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return ""; } @Override public boolean confirmValue(final String oldVal) { if(oldVal.trim().length()==0) return true; return CMath.isInteger(oldVal); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I==null) return ""; final List<String> words=CMParms.parse(I.name()); for(int i=words.size()-1;i>=0;i--) { final String s=words.get(i); final int y=s.indexOf('-'); if(y>=0) { words.add(s.substring(0, y)); words.add(s.substring(0, y+1)); } } for(final String word : words) { if(word.length()>0) { final int rsc=RawMaterial.CODES.FIND_IgnoreCase(word); if((rsc > 0)&&(rsc != I.material())) { if(I.basePhyStats().level()>80) return ""+4; if(I.basePhyStats().level()>40) return ""+2; return ""+1; } } } return ""; } }, new AbilityParmEditorImpl("OPTIONAL_BUILDING_RESOURCE_OR_MATERIAL","Rsc/ Mat",ParmType.CHOICES) { @Override public void createChoices() { final XVector<String> V=new XVector<String>(RawMaterial.CODES.NAMES()); Collections.sort(V); final XVector<String> V2=new XVector<String>(RawMaterial.Material.names()); Collections.sort(V2); V.addAll(V2); V.addElement("VALUE"); V.addElement("MONEY"); V.addElement(""); createChoices(V); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { final List<String> words=CMParms.parse(I.name()); for(int i=words.size()-1;i>=0;i--) { final String s=words.get(i); final int y=s.indexOf('-'); if(y>=0) { words.add(s.substring(0, y)); words.add(s.substring(0, y+1)); } } for(final String word : words) { if(word.length()>0) { final int rsc=RawMaterial.CODES.FIND_IgnoreCase(word); if((rsc > 0)&&(rsc != I.material())) return RawMaterial.CODES.NAME(rsc); } } return ""; } @Override public String defaultValue() { return ""; } }, new AbilityParmEditorImpl("HERB_NAME","Herb Final Name",ParmType.STRING) { @Override public void createChoices() { } @Override public String defaultValue() { return "Herb Name"; } @Override public int minColWidth() { return 10; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I.material()==RawMaterial.RESOURCE_HERBS) return CMStrings.lastWordIn(I.Name()); return ""; } }, new AbilityParmEditorImpl("FLOWER_NAME","Flower Final Name",ParmType.STRING) { @Override public void createChoices() { } @Override public String defaultValue() { return "Flower Name"; } @Override public int minColWidth() { return 10; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I.material()==RawMaterial.RESOURCE_FLOWERS) return CMStrings.lastWordIn(I.Name()); return ""; } }, new AbilityParmEditorImpl("RIDE_CAPACITY","Ridrs",ParmType.NUMBER) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { return (o instanceof Rideable) ? 3 : -1; } @Override public String defaultValue() { return "2"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Rideable) return ""+((Rideable)I).riderCapacity(); return "0"; } }, new AbilityParmEditorImpl("METAL_OR_WOOD","Metal",ParmType.CHOICES) { @Override public void createChoices() { createChoices(new String[] { "METAL", "WOOD" }); } @Override public String defaultValue() { return "METAL"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { switch(I.material()&RawMaterial.MATERIAL_MASK) { case RawMaterial.MATERIAL_METAL: case RawMaterial.MATERIAL_MITHRIL: return "METAL"; case RawMaterial.MATERIAL_WOODEN: return "WOOD"; } return ""; // absolutely no way to determine } }, new AbilityParmEditorImpl("OPTIONAL_RACE_ID","Race",ParmType.SPECIAL) { @Override public void createChoices() { createChoices(CMClass.races()); choices().add("",""); for(int x=0;x<choices().size();x++) choices().get(x).first = choices().get(x).first.toUpperCase(); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; // absolutely no way to determine } @Override public String defaultValue() { return ""; } @Override public boolean confirmValue(final String oldVal) { if(oldVal.trim().length()==0) return true; final Vector<String> parsedVals = CMParms.parse(oldVal.toUpperCase()); for(int v=0;v<parsedVals.size();v++) { if(CMClass.getRace(parsedVals.elementAt(v))==null) return false; } return true; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { Vector<String> raceIDs=null; if(httpReq.isUrlParameter(fieldName+"_RACE")) { String id=""; raceIDs=new Vector<String>(); for(int i=0;httpReq.isUrlParameter(fieldName+"_RACE"+id);id=""+(++i)) raceIDs.addElement(httpReq.getUrlParameter(fieldName+"_RACE"+id).toUpperCase().trim()); } else raceIDs = CMParms.parse(oldVal.toUpperCase().trim()); return CMParms.combine(raceIDs,0); } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final Vector<String> raceIDs=CMParms.parse(webValue(httpReq,parms,oldVal,fieldName).toUpperCase()); final StringBuffer str = new StringBuffer(""); str.append("\n\r<SELECT NAME="+fieldName+"_RACE MULTIPLE>"); str.append("<OPTION VALUE=\"\" "+((raceIDs.size()==0)?"SELECTED":"")+">"); for(final Enumeration<Race> e=CMClass.races();e.hasMoreElements();) { final Race R=e.nextElement(); str.append("<OPTION VALUE=\""+R.ID()+"\" "+((raceIDs.contains(R.ID().toUpperCase()))?"SELECTED":"")+">"+R.name()); } str.append("</SELECT>"); return str.toString(); } @Override public String[] fakeUserInput(final String oldVal) { final Vector<String> parsedVals = CMParms.parse(oldVal.toUpperCase()); if(parsedVals.size()==0) return new String[]{""}; final Vector<String> races = new Vector<String>(); for(int p=0;p<parsedVals.size();p++) { final Race R=CMClass.getRace(parsedVals.elementAt(p)); races.addElement(R.name()); } for(int p=0;p<parsedVals.size();p++) { final Race R=CMClass.getRace(parsedVals.elementAt(p)); races.addElement(R.name()); } races.addElement(""); return CMParms.toStringArray(races); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { if((showFlag>0)&&(showFlag!=showNumber[0])) return oldVal; String behave="NO"; String newVal = oldVal; while((mob.session()!=null)&&(!mob.session().isStopped())&&(behave.length()>0)) { mob.tell(showNumber+". "+prompt()+": '"+newVal+"'."); if((showFlag!=showNumber[0])&&(showFlag>-999)) return newVal; final Vector<String> parsedVals = CMParms.parse(newVal.toUpperCase()); behave=mob.session().prompt(L("Enter a race to add/remove (?)\n\r:"),""); if(behave.length()>0) { if(behave.equalsIgnoreCase("?")) mob.tell(CMLib.lister().reallyList(mob,CMClass.races(),-1).toString()); else { final Race R=CMClass.getRace(behave); if(R!=null) { if(parsedVals.contains(R.ID().toUpperCase())) { mob.tell(L("'@x1' removed.",behave)); parsedVals.remove(R.ID().toUpperCase().trim()); newVal = CMParms.combine(parsedVals,0); } else { mob.tell(L("@x1 added.",R.ID())); parsedVals.addElement(R.ID().toUpperCase()); newVal = CMParms.combine(parsedVals,0); } } else { mob.tell(L("'@x1' is not a recognized race. Try '?'.",behave)); } } } else { if(oldVal.equalsIgnoreCase(newVal)) mob.tell(L("(no change)")); } } return newVal; } }, new AbilityParmEditorImpl("INSTRUMENT_TYPE","Instrmnt",ParmType.CHOICES) { @Override public void createChoices() { createChoices(MusicalInstrument.InstrumentType.valueNames()); } @Override public int appliesToClass(final Object o) { return (o instanceof MusicalInstrument) ? 5 : -1; } @Override public String defaultValue() { return "DRUMS"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof MusicalInstrument) return ((MusicalInstrument)I).getInstrumentTypeName(); return "0"; } }, new AbilityParmEditorImpl("STONE_FLAG","Stone",ParmType.CHOICES) { @Override public void createChoices() { createChoices(new String[] { "", "STONE" }); } @Override public int appliesToClass(final Object o) { return (o instanceof RawMaterial) ? 5 : -1; } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I.material()==RawMaterial.RESOURCE_STONE) return "STONE"; return ""; } }, new AbilityParmEditorImpl("POSE_NAME","Pose Word",ParmType.ONEWORD) { @Override public void createChoices() { } @Override public String defaultValue() { return "New Post"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } }, new AbilityParmEditorImpl("POSE_DESCRIPTION","Pose Description",ParmType.STRING) { @Override public void createChoices() { } @Override public String defaultValue() { return "<S-NAME> is standing here."; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof DeadBody)) return ""; String pose=I.displayText(); pose=CMStrings.replaceAll(pose,I.name(),"<S-NAME>"); pose=CMStrings.replaceWord(pose,"himself"," <S-HIM-HERSELF>"); pose=CMStrings.replaceWord(pose,"herself"," <S-HIM-HERSELF>"); pose=CMStrings.replaceWord(pose,"his"," <S-HIS-HER>"); pose=CMStrings.replaceWord(pose,"her"," <S-HIS-HER>"); pose=CMStrings.replaceWord(pose,"him"," <S-HIM-HER>"); pose=CMStrings.replaceWord(pose,"her"," <S-HIM-HER>"); return pose; } }, new AbilityParmEditorImpl("WOOD_METAL_CLOTH","",ParmType.CHOICES) { @Override public void createChoices() { createChoices(new String[] { "WOOD", "METAL", "CLOTH" }); } @Override public String defaultValue() { return "WOOD"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { switch(I.material()&RawMaterial.MATERIAL_MASK) { case RawMaterial.MATERIAL_CLOTH: return "CLOTH"; case RawMaterial.MATERIAL_METAL: return "METAL"; case RawMaterial.MATERIAL_MITHRIL: return "METAL"; case RawMaterial.MATERIAL_WOODEN: return "WOOD"; default: return ""; } } }, new AbilityParmEditorImpl("WEAPON_TYPE","W.Type",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof Weapon) ? 2 : -1; } @Override public void createChoices() { createChoices(Weapon.TYPE_DESCS); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return (I instanceof Weapon) ? Weapon.TYPE_DESCS[((Weapon) I).weaponDamageType()] : ""; } @Override public String defaultValue() { return "BASHING"; } }, new AbilityParmEditorImpl("ATTACK_MODIFICATION","Att.",ParmType.NUMBER) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { return (o instanceof Weapon) ? 2 : -1; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return "" + ((I instanceof Weapon) ? ((Weapon) I).basePhyStats().attackAdjustment() : 0); } @Override public String defaultValue() { return "0"; } }, new AbilityParmEditorImpl("N_A","N/A",ParmType.STRING) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { return -1; } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public boolean confirmValue(final String oldVal) { return oldVal.trim().length() == 0 || oldVal.equals("0") || oldVal.equals("NA") || oldVal.equals("-"); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { return ""; } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String, String> parms, final String oldVal, final String fieldName) { return ""; } }, new AbilityParmEditorImpl("RESOURCE_NAME_AMOUNT_MATERIAL_REQUIRED","Resrc/Amt",ParmType.SPECIAL) { @Override public void createChoices() { createChoices(RawMaterial.CODES.NAMES()); choices().add("",""); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { int amt=(int)Math.round(CMath.mul(I.basePhyStats().weight()-1,(A!=null)?A.getItemWeightMultiplier(false):1.0)); if(amt<1) amt=1; return RawMaterial.CODES.NAME(I.material())+"/"+amt; } @Override public String defaultValue() { return ""; } @Override public int appliesToClass(final Object o) { return 0; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { if(httpReq.isUrlParameter(fieldName+"_RESOURCE")) { final String rsc=httpReq.getUrlParameter(fieldName+"_RESOURCE"); final String amt=httpReq.getUrlParameter(fieldName+"_AMOUNT"); if((rsc.trim().length()==0)||(rsc.equalsIgnoreCase("NOTHING"))||(CMath.s_int(amt)<=0)) return ""; return rsc+"/"+amt; } return oldVal; } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String value=webValue(httpReq,parms,oldVal,fieldName); String rsc = ""; int amt = 0; final int x=value.indexOf('/'); if(x>0) { rsc = value.substring(0,x); amt = CMath.s_int(value.substring(x+1)); } final StringBuffer str=new StringBuffer(""); str.append("\n\r<SELECT NAME="+fieldName+"_RESOURCE MULTIPLE>"); final String[] Ss=RawMaterial.CODES.NAMES().clone(); Arrays.sort(Ss); for(final String S : Ss) { str.append("<OPTION VALUE=\""+S+"\" " +((S.equalsIgnoreCase(rsc))?"SELECTED":"")+">" +CMStrings.capitalizeAndLower(S)); } str.append("</SELECT>"); str.append("&nbsp;&nbsp;Amount: "); str.append("<INPUT TYPE=TEXT NAME="+fieldName+"_AMOUNT VALUE="+amt+">"); return str.toString(); } @Override public boolean confirmValue(String oldVal) { if(oldVal.trim().length()==0) return true; oldVal=oldVal.trim(); final int x=oldVal.indexOf('/'); if(x<0) return false; if(!CMStrings.contains(choices().toArrayFirst(new String[0]),oldVal.substring(0,x))) return false; if(!CMath.isInteger(oldVal.substring(x+1))) return false; return true; } @Override public String[] fakeUserInput(final String oldVal) { final int x=oldVal.indexOf('/'); if(x<=0) return new String[]{""}; return new String[]{oldVal.substring(0,x),oldVal.substring(x+1)}; } @Override public String commandLinePrompt(final MOB mob, String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { oldVal=oldVal.trim(); final int x=oldVal.indexOf('/'); String oldRsc = ""; int oldAmt = 0; if(x>0) { oldRsc = oldVal.substring(0,x); oldAmt = CMath.s_int(oldVal.substring(x)); } oldRsc = CMLib.genEd().prompt(mob,oldRsc,++showNumber[0],showFlag,prompt(),choices()); if(oldRsc.length()>0) return oldRsc+"/"+CMLib.genEd().prompt(mob,oldAmt,++showNumber[0],showFlag,prompt()); return ""; } }, }); DEFAULT_EDITORS = new Hashtable<String,AbilityParmEditor>(); for(int v=0;v<V.size();v++) { final AbilityParmEditor A = V.elementAt(v); DEFAULT_EDITORS.put(A.ID(),A); } return DEFAULT_EDITORS; } protected class AbilityRecipeDataImpl implements AbilityRecipeData { private String recipeFilename; private String recipeFormat; private Vector<Object> columns; private Vector<DVector> dataRows; private int numberOfDataColumns; public String[] columnHeaders; public int[] columnLengths; public int classFieldIndex; private String parseError = null; private boolean wasVFS = false; public AbilityRecipeDataImpl(final String recipeFilename, final String recipeFormat) { this.recipeFilename = recipeFilename; this.recipeFormat = recipeFormat; if(recipeFilename.trim().length()==0) { parseError = "No file"; return; } final CMFile F = new CMFile(Resources.buildResourcePath("skills")+recipeFilename,null,CMFile.FLAG_LOGERRORS); wasVFS=F.isVFSFile(); final StringBuffer str=F.text(); columns = parseRecipeFormatColumns(recipeFormat); numberOfDataColumns = 0; for(int c = 0; c < columns.size(); c++) { if(columns.elementAt(c) instanceof List) numberOfDataColumns++; } dataRows = null; try { dataRows = parseDataRows(str,columns,numberOfDataColumns); final DVector editRow = new DVector(2); for(int c=0;c<columns().size();c++) { if(columns().elementAt(c) instanceof List) editRow.addElement(columns().elementAt(c),""); } if(editRow.size()==0) { //classFieldIndex = CMAbleParms.getClassFieldIndex(dataRow); } else classFieldIndex = CMAbleParms.getClassFieldIndex(editRow); fixDataColumns(dataRows); } catch(final CMException e) { parseError = e.getMessage(); return; } columnLengths = new int[numberOfDataColumns]; columnHeaders = new String[numberOfDataColumns]; calculateRecipeCols(columnLengths,columnHeaders,dataRows); } @Override public boolean wasVFS() { return wasVFS; } @Override public DVector newRow(final String classFieldData) { final DVector editRow = blankRow(); final int keyIndex =classFieldIndex; if((keyIndex>=0)&&(classFieldData!=null)) { editRow.setElementAt(keyIndex,2,classFieldData); } try { fixDataColumn(editRow,-1); } catch (final CMException cme) { return null; } for(int i=0;i<editRow.size();i++) { if(i!=keyIndex) { final AbilityParmEditor A = getEditors().get(editRow.elementAt(i,1)); editRow.setElementAt(i,2,A.defaultValue()); } } return editRow; } @Override public DVector blankRow() { final DVector editRow = new DVector(2); for(int c=0;c<columns().size();c++) { if(columns().elementAt(c) instanceof List) editRow.addElement(columns().elementAt(c),""); } return editRow; } @Override public int getClassFieldIndex() { return classFieldIndex; } @Override public String recipeFilename() { return recipeFilename; } @Override public String recipeFormat() { return recipeFormat; } @Override public Vector<DVector> dataRows() { return dataRows; } @Override public Vector<? extends Object> columns() { return columns; } @Override public int[] columnLengths() { return columnLengths; } @Override public String[] columnHeaders() { return columnHeaders; } @Override public int numberOfDataColumns() { return numberOfDataColumns; } @Override public String parseError() { return parseError; } } protected abstract class AbilityParmEditorImpl implements AbilityParmEditor { private final String ID; private final ParmType fieldType; private String prompt = null; private String header = null; protected PairList<String, String> choices = null; public AbilityParmEditorImpl(final String fieldName, final String shortHeader, final ParmType type) { ID=fieldName; fieldType = type; header = shortHeader; prompt = CMStrings.capitalizeAndLower(CMStrings.replaceAll(ID,"_"," ")); createChoices(); } @Override public String ID() { return ID; } @Override public ParmType parmType() { return fieldType; } @Override public String prompt() { return prompt; } @Override public String colHeader() { return header; } @Override public int maxColWidth() { return Integer.MAX_VALUE; } @Override public int minColWidth() { return 0; } @Override public boolean confirmValue(final String oldVal) { final boolean spaceOK = fieldType != ParmType.ONEWORD; boolean emptyOK = false; switch(fieldType) { case STRINGORNULL: emptyOK = true; //$FALL-THROUGH$ case ONEWORD: case STRING: { if((!spaceOK) && (oldVal.indexOf(' ') >= 0)) return false; return (emptyOK)||(oldVal.trim().length()>0); } case NUMBER: return CMath.isInteger(oldVal); case CHOICES: if(!CMStrings.contains(choices.toArrayFirst(new String[0]),oldVal)) return CMStrings.contains(choices.toArrayFirst(new String[0]),oldVal.toUpperCase().trim()); return true; case MULTICHOICES: return CMath.isInteger(oldVal)||choices().containsFirst(oldVal); case SPECIAL: break; } return false; } @Override public String[] fakeUserInput(final String oldVal) { boolean emptyOK = false; switch(fieldType) { case STRINGORNULL: emptyOK = true; //$FALL-THROUGH$ case ONEWORD: case STRING: { if(emptyOK && (oldVal.trim().length()==0)) return new String[]{"NULL"}; return new String[]{oldVal}; } case NUMBER: return new String[]{oldVal}; case CHOICES: { if(oldVal.trim().length()==0) return new String[]{"NULL"}; final Vector<String> V = new XVector<String>(choices.toArrayFirst(new String[0])); for(int v=0;v<V.size();v++) { if(oldVal.equalsIgnoreCase(V.elementAt(v))) return new String[]{choices.get(v).second}; } return new String[]{oldVal}; } case MULTICHOICES: if(oldVal.trim().length()==0) return new String[]{"NULL"}; if(!CMath.isInteger(oldVal)) { final Vector<String> V = new XVector<String>(choices.toArrayFirst(new String[0])); for(int v=0;v<V.size();v++) { if(oldVal.equalsIgnoreCase(V.elementAt(v))) return new String[]{choices.get(v).second,""}; } } else { final Vector<String> V = new Vector<String>(); for(int c=0;c<choices.size();c++) { if(CMath.bset(CMath.s_int(oldVal),CMath.s_int(choices.get(c).first))) { V.addElement(choices.get(c).second); V.addElement(choices.get(c).second); } } if(V.size()>0) { V.addElement(""); return CMParms.toStringArray(V); } } return new String[]{"NULL"}; case SPECIAL: break; } return new String[]{}; } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { String str = null; boolean emptyOK = false; final boolean spaceOK = fieldType != ParmType.ONEWORD; switch(fieldType) { case STRINGORNULL: emptyOK = true; //$FALL-THROUGH$ case ONEWORD: case STRING: { ++showNumber[0]; boolean proceed = true; while(proceed&&(!mob.session().isStopped())) { str = CMLib.genEd().prompt(mob,oldVal,showNumber[0],showFlag,prompt(),emptyOK).trim(); if((!spaceOK) && (str.indexOf(' ') >= 0)) mob.tell(L("Spaces are not allowed here.")); else proceed=false; } break; } case NUMBER: { final String newStr=CMLib.genEd().prompt(mob,oldVal,++showNumber[0],showFlag,prompt(),true); if(newStr.trim().length()==0) str=""; else str = Integer.toString(CMath.s_int(newStr)); break; } case CHOICES: str = CMLib.genEd().promptMultiOrExtra(mob,oldVal,++showNumber[0],showFlag,prompt(),choices); break; case MULTICHOICES: str = CMLib.genEd().promptMultiOrExtra(mob,oldVal,++showNumber[0],showFlag,prompt(),choices); if(CMath.isInteger(str)) str = Integer.toString(CMath.s_int(str)); break; case SPECIAL: break; } return str; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String webValue = httpReq.getUrlParameter(fieldName); switch(fieldType) { case ONEWORD: case STRINGORNULL: case STRING: case NUMBER: return (webValue == null)?oldVal:webValue; case MULTICHOICES: { if(webValue == null) return oldVal; String id=""; long num=0; int index=0; for(;httpReq.isUrlParameter(fieldName+id);id=""+(++index)) { final String newVal = httpReq.getUrlParameter(fieldName+id); if(CMath.s_long(newVal)<=0) return newVal; num |= CMath.s_long(newVal); } return ""+num; } case CHOICES: return (webValue == null)?oldVal:webValue; case SPECIAL: break; } return ""; } @Override public String webTableField(final HTTPRequest httpReq, final java.util.Map<String, String> parms, final String oldVal) { return oldVal; } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { int textSize = 50; final String webValue = webValue(httpReq,parms,oldVal,fieldName); String onChange = null; final Vector<String> choiceValues = new Vector<String>(); switch(fieldType) { case ONEWORD: textSize = 10; //$FALL-THROUGH$ case STRINGORNULL: case STRING: return "\n\r<INPUT TYPE=TEXT NAME=" + fieldName + " SIZE=" + textSize + " VALUE=\"" + webValue + "\">"; case NUMBER: return "\n\r<INPUT TYPE=TEXT NAME=" + fieldName + " SIZE=10 VALUE=\"" + webValue + "\">"; case MULTICHOICES: { onChange = " MULTIPLE "; if(!parms.containsKey("NOSELECT")) onChange+= "ONCHANGE=\"MultiSelect(this);\""; if(CMath.isInteger(webValue)) { final int bits = CMath.s_int(webValue); for(int i=0;i<choices.size();i++) { final int bitVal =CMath.s_int(choices.get(i).first); if((bitVal>0)&&(CMath.bset(bits,bitVal))) choiceValues.addElement(choices.get(i).first); } } } //$FALL-THROUGH$ case CHOICES: { if(choiceValues.size()==0) choiceValues.addElement(webValue); if((onChange == null)&&(!parms.containsKey("NOSELECT"))) onChange = " ONCHANGE=\"Select(this);\""; else if(onChange==null) onChange=""; final StringBuffer str= new StringBuffer(""); str.append("\n\r<SELECT NAME="+fieldName+onChange+">"); for(int i=0;i<choices.size();i++) { final String option = (choices.get(i).first); str.append("<OPTION VALUE=\""+option+"\" "); for(int c=0;c<choiceValues.size();c++) { if(option.equalsIgnoreCase(choiceValues.elementAt(c))) str.append("SELECTED"); } str.append(">"+(choices.get(i).second)); } return str.toString()+"</SELECT>"; } case SPECIAL: break; } return ""; } public abstract void createChoices(); @Override public PairList<String,String> createChoices(final Enumeration<? extends Object> e) { if(choices != null) return choices; choices = new PairVector<String,String>(); Object o = null; for(;e.hasMoreElements();) { o = e.nextElement(); if(o instanceof String) choices.add((String)o,CMStrings.capitalizeAndLower((String)o)); else if(o instanceof Ability) choices.add(((Ability)o).ID(),((Ability)o).name()); else if(o instanceof Race) choices.add(((Race)o).ID(),((Race)o).name()); else if(o instanceof Environmental) choices.add(((Environmental)o).ID(),((Environmental)o).ID()); } return choices; } @SuppressWarnings("unchecked") @Override public PairList<String,String> createChoices(final List<? extends Object> V) { return createChoices(new IteratorEnumeration<Object>((Iterator<Object>)V.iterator())); } @Override public PairList<String,String> createChoices(final String[] S) { final XVector<String> X=new XVector<String>(S); Collections.sort(X); return createChoices(X.elements()); } public PairList<String,String> createBinaryChoices(final String[] S) { if(choices != null) return choices; choices = createChoices(new XVector<String>(S).elements()); for(int i=0;i<choices.size();i++) { if(i==0) choices.get(i).first =Integer.toString(0); else choices.get(i).first = Integer.toString(1<<(i-1)); } return choices; } public PairList<String,String> createNumberedChoices(final String[] S) { if(choices != null) return choices; choices = createChoices(new XVector<String>(S).elements()); for(int i=0;i<choices.size();i++) choices.get(i).first = Integer.toString(i); return choices; } @Override public PairList<String, String> choices() { return choices; } @Override public int appliesToClass(final Object o) { return 0; } } }
com/planet_ink/coffee_mud/Libraries/CMAbleParms.java
package com.planet_ink.coffee_mud.Libraries; import com.planet_ink.coffee_web.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.AbilityMapper.AbilityMapping; import com.planet_ink.coffee_mud.Libraries.interfaces.AbilityParameters.AbilityParmEditor; import com.planet_ink.coffee_mud.core.exceptions.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.RawMaterial.Material; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.net.Socket; import java.util.*; /* Copyright 2008-2020 Bo Zimmerman 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. */ public class CMAbleParms extends StdLibrary implements AbilityParameters { @Override public String ID() { return "CMAbleParms"; } protected Map<String,AbilityParmEditor> DEFAULT_EDITORS = null; protected final static int[] ALL_BUCKET_MATERIAL_CHOICES = new int[]{RawMaterial.MATERIAL_CLOTH, RawMaterial.MATERIAL_METAL, RawMaterial.MATERIAL_LEATHER, RawMaterial.MATERIAL_LIQUID, RawMaterial.MATERIAL_WOODEN, RawMaterial.MATERIAL_PRECIOUS,RawMaterial.MATERIAL_VEGETATION, RawMaterial.MATERIAL_ROCK }; protected final static int[] ALLOWED_BUCKET_ACODES = new int[]{Ability.ACODE_CHANT,Ability.ACODE_SPELL,Ability.ACODE_PRAYER,Ability.ACODE_SONG,Ability.ACODE_SKILL, Ability.ACODE_THIEF_SKILL}; protected final static int[] ALLOWED_BUCKET_QUALITIES = new int[]{Ability.QUALITY_BENEFICIAL_OTHERS,Ability.QUALITY_BENEFICIAL_SELF,Ability.QUALITY_INDIFFERENT, Ability.QUALITY_OK_OTHERS,Ability.QUALITY_OK_SELF}; protected final static String[] ADJUSTER_TOKENS = new String[]{"+","-","="}; protected final static String[] RESISTER_IMMUNER_TOKENS = new String[]{"%",";"}; public CMAbleParms() { super(); } protected String parseLayers(final short[] layerAtt, final short[] clothingLayers, String misctype) { final int colon=misctype.indexOf(':'); if(colon>=0) { String layers=misctype.substring(0,colon).toUpperCase().trim(); misctype=misctype.substring(colon+1).trim(); if((layers.startsWith("MS"))||(layers.startsWith("SM"))) { layers=layers.substring(2); layerAtt[0]=Armor.LAYERMASK_MULTIWEAR|Armor.LAYERMASK_SEETHROUGH; } else if(layers.startsWith("M")) { layers=layers.substring(1); layerAtt[0]=Armor.LAYERMASK_MULTIWEAR; } else if(layers.startsWith("S")) { layers=layers.substring(1); layerAtt[0]=Armor.LAYERMASK_SEETHROUGH; } clothingLayers[0]=CMath.s_short(layers); } return misctype; } @Override public void parseWearLocation(final short[] layerAtt, final short[] layers, final long[] wornLoc, final boolean[] logicalAnd, final double[] hardBonus, String wearLocation) { if(layers != null) { layerAtt[0] = 0; layers[0] = 0; wearLocation=parseLayers(layerAtt,layers,wearLocation); } final double hardnessMultiplier = hardBonus[0]; wornLoc[0] = 0; hardBonus[0]=0.0; final Wearable.CODES codes = Wearable.CODES.instance(); for(int wo=1;wo<codes.total();wo++) { final String WO=codes.name(wo).toUpperCase(); if(wearLocation.equalsIgnoreCase(WO)) { hardBonus[0]+=codes.location_strength_points()[wo]; wornLoc[0]=CMath.pow(2,wo-1); logicalAnd[0]=false; } else if((wearLocation.toUpperCase().indexOf(WO+"||")>=0) ||(wearLocation.toUpperCase().endsWith("||"+WO))) { if(hardBonus[0]==0.0) hardBonus[0]+=codes.location_strength_points()[wo]; wornLoc[0]=wornLoc[0]|CMath.pow(2,wo-1); logicalAnd[0]=false; } else if((wearLocation.toUpperCase().indexOf(WO+"&&")>=0) ||(wearLocation.toUpperCase().endsWith("&&"+WO))) { hardBonus[0]+=codes.location_strength_points()[wo]; wornLoc[0]=wornLoc[0]|CMath.pow(2,wo-1); logicalAnd[0]=true; } } hardBonus[0]=(int)Math.round(hardBonus[0] * hardnessMultiplier); } public Vector<Object> parseRecipeFormatColumns(final String recipeFormat) { char C = '\0'; final StringBuffer currentColumn = new StringBuffer(""); Vector<String> currentColumns = null; final char[] recipeFmtC = recipeFormat.toCharArray(); final Vector<Object> columnsV = new Vector<Object>(); for(int c=0;c<=recipeFmtC.length;c++) { if(c==recipeFmtC.length) { break; } C = recipeFmtC[c]; if((C=='|') &&(c<(recipeFmtC.length-1)) &&(recipeFmtC[c+1]=='|') &&(currentColumn.length()>0)) { if(currentColumn.length()>0) { if(currentColumns == null) { currentColumns = new Vector<String>(); columnsV.addElement(currentColumns); } currentColumns.addElement(currentColumn.toString()); currentColumn.setLength(0); } c++; } else if(Character.isLetter(C)||Character.isDigit(C)||(C=='_')) currentColumn.append(C); else { if(currentColumn.length()>0) { if(currentColumns == null) { currentColumns = new Vector<String>(); columnsV.addElement(currentColumns); } currentColumns.addElement(currentColumn.toString()); currentColumn.setLength(0); } currentColumns = null; if((C=='.') &&(c<(recipeFmtC.length-2)) &&(recipeFmtC[c+1]=='.') &&(recipeFmtC[c+2]=='.')) { c+=2; columnsV.addElement("..."); } else if(columnsV.lastElement() instanceof String) columnsV.setElementAt(((String)columnsV.lastElement())+C,columnsV.size()-1); else columnsV.addElement(""+C); } } if(currentColumn.length()>0) { if(currentColumns == null) { currentColumns = new Vector<String>(); columnsV.addElement(currentColumns); } currentColumns.addElement(currentColumn.toString()); } if((currentColumns != null) && (currentColumns.size()==0)) columnsV.remove(currentColumns); return columnsV; } @Override public String makeRecipeFromItem(final ItemCraftor C, final Item I) throws CMException { final Vector<Object> columns = parseRecipeFormatColumns(C.parametersFormat()); final Map<String,AbilityParmEditor> editors = this.getEditors(); final StringBuilder recipe = new StringBuilder(""); for(int d=0;d<columns.size();d++) { if(columns.get(d) instanceof String) { final String name = (String)columns.get( d ); AbilityParmEditor A = editors.get(columns.get(d)); if((A==null)||(name.length()<3)) { recipe.append("\t"); continue; } if(A.appliesToClass(I)<0) A = editors.get("N_A"); if(A!=null) columns.set(d,A.ID()); } else if(columns.get(d) instanceof List) { AbilityParmEditor applicableA = null; final List<?> colV=(List<?>)columns.get(d); for(int c=0;c<colV.size();c++) { final Object o = colV.get(c); if (o instanceof List) continue; final String ID = (o instanceof String) ? (String)o : ((AbilityParmEditor)o).ID(); final AbilityParmEditor A = editors.get(ID); if(A==null) throw new CMException("Column name "+ID+" is not found."); if((applicableA==null) ||(A.appliesToClass(I) > applicableA.appliesToClass(I))) applicableA = A; } if((applicableA == null)||(applicableA.appliesToClass(I)<0)) applicableA = editors.get("N_A"); columns.set(d,applicableA.ID()); } else throw new CMException("Col name "+(columns.get(d))+" is not a String or List."); final AbilityParmEditor A = editors.get(columns.get(d)); if(A==null) throw new CMException("Editor name "+(columns.get(d))+" is not defined."); recipe.append(A.convertFromItem(C, I)); } return recipe.toString(); } @SuppressWarnings("unchecked") protected static int getClassFieldIndex(final DVector dataRow) { for(int d=0;d<dataRow.size();d++) { if(dataRow.elementAt(d,1) instanceof List) { final List<String> V=(List<String>)dataRow.elementAt(d,1); if(V.contains("ITEM_CLASS_ID")||V.contains("FOOD_DRINK")||V.contains("BUILDING_CODE")) return d; } else if(dataRow.elementAt(d,1) instanceof String) { final String s=(String)dataRow.elementAt(d,1); if(s.equalsIgnoreCase("ITEM_CLASS_ID")||s.equalsIgnoreCase("FOOD_DRINK")||s.equalsIgnoreCase("BUILDING_CODE")) return d; } } return -1; } @SuppressWarnings("unchecked") protected Object getSampleObject(final DVector dataRow) { boolean classIDRequired = false; String classID = null; final int fieldIndex = getClassFieldIndex(dataRow); for(int d=0;d<dataRow.size();d++) { if((dataRow.elementAt(d,1) instanceof List) &&(!classIDRequired) &&(((List<String>)dataRow.elementAt(d,1)).size()>1)) classIDRequired=true; } if(fieldIndex >=0) classID=(String)dataRow.elementAt(fieldIndex,2); if((classID!=null)&&(classID.length()>0)) { if(classID.equalsIgnoreCase("FOOD")) return CMClass.getItemPrototype("GenFood"); else if(classID.equalsIgnoreCase("SOAP")) return CMClass.getItemPrototype("GenItem"); else if(classID.equalsIgnoreCase("DRINK")) return CMClass.getItemPrototype("GenDrink"); else { final PhysicalAgent I=CMClass.getItemPrototype(classID); if(I==null) { final Pair<String[],String[]> codeFlags = getBuildingCodesNFlags(); if(CMParms.containsIgnoreCase(codeFlags.first, classID)) return classID.toUpperCase().trim(); } return I; } } if(classIDRequired) return null; return CMClass.getItemPrototype("StdItem"); } protected String stripData(final StringBuffer str, final String div) { final StringBuffer data = new StringBuffer(""); while(str.length()>0) { if(str.length() < div.length()) return null; for(int d=0;d<=div.length();d++) { if(d==div.length()) { str.delete(0,div.length()); return data.toString(); } else if(str.charAt(d)!=div.charAt(d)) break; } if(str.charAt(0)=='\n') { if(data.length()>0) return data.toString(); return null; } data.append(str.charAt(0)); str.delete(0,1); } if((div.charAt(0)=='\n') && (data.length()>0)) return data.toString(); return null; } @SuppressWarnings("unchecked") protected Vector<DVector> parseDataRows(final StringBuffer recipeData, final Vector<? extends Object> columnsV, final int numberOfDataColumns) throws CMException { StringBuffer str = new StringBuffer(recipeData.toString()); str = cleanDataRowEOLs(str); final Vector<DVector> rowsV = new Vector<DVector>(); DVector dataRow = new DVector(2); List<String> currCol = null; String lastDiv = null; int lastLen = str.length(); while(str.length() > 0) { lastLen = str.length(); for(int c = 0; c < columnsV.size(); c++) { String div = "\n"; currCol = null; if(columnsV.elementAt(c) instanceof String) stripData(str,(String)columnsV.elementAt(c)); else if(columnsV.elementAt(c) instanceof List) { currCol = (List<String>)columnsV.elementAt(c); if(c<columnsV.size()-1) { div = (String)columnsV.elementAt(c+1); c++; } } if((str.length()==0)&&(c<columnsV.size()-1)) break; if(!div.equals("...")) { lastDiv = div; String data = null; data = stripData(str,lastDiv); if(data == null) data = ""; dataRow.addElement(currCol,data); currCol = null; } else { final String data = stripData(str,lastDiv); if(data == null) break; dataRow.addElement(currCol,data); } } if(dataRow.size() != numberOfDataColumns) throw new CMException("Row "+(rowsV.size()+1)+" has "+dataRow.size()+"/"+numberOfDataColumns); rowsV.addElement(dataRow); dataRow = new DVector(2); if(str.length()==lastLen) throw new CMException("UNCHANGED: Row "+(rowsV.size()+1)+" has "+dataRow.size()+"/"+numberOfDataColumns); } if(str.length()<2) str.setLength(0); return rowsV; } protected boolean fixDataColumn(final DVector dataRow, final int rowShow) throws CMException { final Object classModelI = getSampleObject(dataRow); return fixDataColumn(dataRow,rowShow,classModelI); } @SuppressWarnings("unchecked") protected boolean fixDataColumn(final DVector dataRow, final int rowShow, final Object classModelI) throws CMException { final Map<String,AbilityParmEditor> editors = getEditors(); if(classModelI == null) { //Log.errOut("CMAbleParms","Data row "+rowShow+" discarded due to null/empty classID"); throw new CMException(L("Data row @x1 discarded due to null/empty classID",""+rowShow)); } for(int d=0;d<dataRow.size();d++) { final List<String> colV=(List<String>)dataRow.elementAt(d,1); if(colV.size()==1) { AbilityParmEditor A = editors.get(colV.get(0)); if((A == null)||(A.appliesToClass(classModelI)<0)) A = editors.get("N_A"); dataRow.setElementAt(d,1,A.ID()); } else { AbilityParmEditor applicableA = null; for(int c=0;c<colV.size();c++) { final AbilityParmEditor A = editors.get(colV.get(c)); if(A==null) throw new CMException(L("Col name @x1 is not defined.",""+(colV.get(c)))); if((applicableA==null) ||(A.appliesToClass(classModelI) > applicableA.appliesToClass(classModelI))) applicableA = A; } if((applicableA == null)||(applicableA.appliesToClass(classModelI)<0)) applicableA = editors.get("N_A"); dataRow.setElementAt(d,1,applicableA.ID()); } final AbilityParmEditor A = editors.get(dataRow.elementAt(d,1)); if(A==null) { if(classModelI instanceof CMObject) throw new CMException(L("Item id @x1 has no editor for @x2",((CMObject)classModelI).ID(),((String)dataRow.elementAt(d,1)))); else throw new CMException(L("Item id @x1 has no editor for @x2",classModelI+"",((String)dataRow.elementAt(d,1)))); //Log.errOut("CMAbleParms","Item id "+classModelI.ID()+" has no editor for "+((String)dataRow.elementAt(d,1))); //return false; } else if((rowShow>=0) &&(!A.confirmValue((String)dataRow.elementAt(d,2)))) { final String data = ((String)dataRow.elementAt(d,2)).replace('@', ' '); if(classModelI instanceof CMObject) throw new CMException(L("Item id @x1 has bad data '@x2' for column @x3 at row @x4",((CMObject)classModelI).ID(),data,((String)dataRow.elementAt(d,1)),""+rowShow)); else throw new CMException(L("Item id @x1 has bad data '@x2' for column @x3 at row @x4",""+classModelI,data,((String)dataRow.elementAt(d,1)),""+rowShow)); //Log.errOut("CMAbleParms","Item id "+classModelI.ID()+" has bad data '"+((String)dataRow.elementAt(d,2))+"' for column "+((String)dataRow.elementAt(d,1))+" at row "+rowShow); } } return true; } protected void fixDataColumns(final Vector<DVector> rowsV) throws CMException { DVector dataRow = new DVector(2); for(int r=0;r<rowsV.size();r++) { dataRow=rowsV.elementAt(r); if(!fixDataColumn(dataRow,r)) throw new CMException(L("Unknown error in row @x1",""+r)); /* catch(CMException e) { rowsV.removeElementAt(r); r--; } */ } } protected StringBuffer cleanDataRowEOLs(final StringBuffer str) { if(str.indexOf("\n")<0) return new StringBuffer(str.toString().replace('\r','\n')); for(int i=str.length()-1;i>=0;i--) { if(str.charAt(i)=='\r') str.delete(i,i+1); } return str; } @Override public void testRecipeParsing(final StringBuffer recipesString, final String recipeFormat) throws CMException { testRecipeParsing(recipesString,recipeFormat,null); } @Override public void testRecipeParsing(final String recipeFilename, final String recipeFormat, final boolean save) throws CMException { final StringBuffer str=new CMFile(Resources.buildResourcePath("skills")+recipeFilename,null,CMFile.FLAG_LOGERRORS).text(); testRecipeParsing(str,recipeFormat,save?recipeFilename:null); } @SuppressWarnings("unchecked") public void testRecipeParsing(final StringBuffer str, final String recipeFormat, final String saveRecipeFilename) throws CMException { final Vector<? extends Object> columnsV = parseRecipeFormatColumns(recipeFormat); int numberOfDataColumns = 0; for(int c = 0; c < columnsV.size(); c++) { if(columnsV.elementAt(c) instanceof List) numberOfDataColumns++; } final Vector<DVector> rowsV = parseDataRows(str,columnsV,numberOfDataColumns); final Vector<String> convertedColumnsV=(Vector<String>)columnsV; fixDataColumns(rowsV); final Map<String,AbilityParmEditor> editors = getEditors(); DVector editRow = null; final int[] showNumber = {0}; final int showFlag =-999; final MOB mob=CMClass.getFactoryMOB(); final Session fakeSession = (Session)CMClass.getCommon("FakeSession"); mob.setSession(fakeSession); fakeSession.setMob(mob); for(int r=0;r<rowsV.size();r++) { editRow = rowsV.elementAt(r); for(int a=0;a<editRow.size();a++) { final AbilityParmEditor A = editors.get(editRow.elementAt(a,1)); try { final String oldVal = (String)editRow.elementAt(a,2); fakeSession.getPreviousCMD().clear(); fakeSession.getPreviousCMD().addAll(new XVector<String>(A.fakeUserInput(oldVal))); final String newVal = A.commandLinePrompt(mob,oldVal,showNumber,showFlag); editRow.setElementAt(a,2,newVal); } catch (final Exception e) { } } } fakeSession.setMob(null); mob.destroy(); if(saveRecipeFilename!=null) resaveRecipeFile(mob,saveRecipeFilename,rowsV,convertedColumnsV,false); } protected void calculateRecipeCols(final int[] lengths, final String[] headers, final Vector<DVector> rowsV) { final Map<String,AbilityParmEditor> editors = getEditors(); DVector dataRow = null; final int numRows[]=new int[headers.length]; for(int r=0;r<rowsV.size();r++) { dataRow=rowsV.elementAt(r); for(int c=0;c<dataRow.size();c++) { final AbilityParmEditor A = editors.get(dataRow.elementAt(c,1)); try { int dataLen=((String)dataRow.elementAt(c, 2)).length(); if(dataLen > A.maxColWidth()) dataLen = A.maxColWidth(); if(dataLen < A.minColWidth()) dataLen = A.minColWidth(); lengths[c]+=dataLen; numRows[c]++; } catch(final Exception e) { } if(A==null) Log.errOut("CMAbleParms","Inexplicable lack of a column: "+((String)dataRow.elementAt(c,1))); else if(headers[c] == null) { headers[c] = A.colHeader(); } else if((!headers[c].startsWith("#"))&&(!headers[c].equalsIgnoreCase(A.colHeader()))) { headers[c]="#"+c; } } } for(int i=0;i<headers.length;i++) { if(numRows[i]>0) lengths[i] /= numRows[i]; if(headers[i]==null) headers[i]="*Add*"; } int currLenTotal = 0; for (final int length : lengths) currLenTotal+=length; int curCol = 0; while((currLenTotal+lengths.length)>72) { if(lengths[curCol]>1) { lengths[curCol]--; currLenTotal--; } curCol++; if(curCol >= lengths.length) curCol = 0; } while((currLenTotal+lengths.length)<72) { lengths[curCol]++; currLenTotal++; curCol++; if(curCol >= lengths.length) curCol = 0; } } @Override public AbilityRecipeData parseRecipe(final String recipeFilename, final String recipeFormat) { final AbilityRecipeDataImpl recipe = new AbilityRecipeDataImpl(recipeFilename, recipeFormat); return recipe; } @Override public StringBuffer getRecipeList(final CraftorAbility iA) { final AbilityRecipeData recipe = parseRecipe(iA.parametersFile(),iA.parametersFormat()); if(recipe.parseError() != null) return new StringBuffer("File: "+iA.parametersFile()+": "+recipe.parseError()); return getRecipeList(recipe); } private StringBuffer getRecipeList(final AbilityRecipeData recipe) { final StringBuffer list=new StringBuffer(""); DVector dataRow = null; list.append("### "); for(int l=0;l<recipe.columnLengths().length;l++) list.append(CMStrings.padRight(recipe.columnHeaders()[l],recipe.columnLengths()[l])+" "); list.append("\n\r"); for(int r=0;r<recipe.dataRows().size();r++) { dataRow=recipe.dataRows().get(r); list.append(CMStrings.padRight(""+(r+1),3)+" "); for(int c=0;c<dataRow.size();c++) list.append(CMStrings.padRight(CMStrings.limit((String)dataRow.elementAt(c,2),recipe.columnLengths()[c]),recipe.columnLengths()[c])+" "); list.append("\n\r"); } return list; } @Override @SuppressWarnings("unchecked") public void modifyRecipesList(final MOB mob, final String recipeFilename, final String recipeFormat) throws java.io.IOException { final Map<String,AbilityParmEditor> editors = getEditors(); final AbilityRecipeData recipe = parseRecipe(recipeFilename, recipeFormat); if(recipe.parseError() != null) { Log.errOut("CMAbleParms","File: "+recipeFilename+": "+recipe.parseError()); return; } while((mob.session()!=null)&&(!mob.session().isStopped())) { final StringBuffer list=getRecipeList(recipe); mob.tell(list.toString()); final String lineNum = mob.session().prompt(L("\n\rEnter a line to edit, A to add, or ENTER to exit: "),""); if(lineNum.trim().length()==0) break; DVector editRow = null; if(lineNum.equalsIgnoreCase("A")) { editRow = recipe.blankRow(); final int keyIndex = getClassFieldIndex(editRow); String classFieldData = null; if(keyIndex>=0) { final AbilityParmEditor A = editors.get(((List<String>)editRow.elementAt(keyIndex,1)).get(0)); if(A!=null) { classFieldData = A.commandLinePrompt(mob,(String)editRow.elementAt(keyIndex,2),new int[]{0},-999); if(!A.confirmValue(classFieldData)) { mob.tell(L("Invalid value. Aborted.")); continue; } } } editRow=recipe.newRow(classFieldData); if(editRow==null) continue; recipe.dataRows().add(editRow); } else if(CMath.isInteger(lineNum)) { final int line = CMath.s_int(lineNum); if((line<1)||(line>recipe.dataRows().size())) continue; editRow = recipe.dataRows().get(line-1); } else break; if(editRow != null) { int showFlag=-1; if(CMProps.getIntVar(CMProps.Int.EDITORTYPE)>0) showFlag=-999; boolean ok=false; while(!ok) { final int[] showNumber = {0}; final int keyIndex = getClassFieldIndex(editRow); for(int a=0;a<editRow.size();a++) { if(a!=keyIndex) { final AbilityParmEditor A = editors.get(editRow.elementAt(a,1)); final String newVal = A.commandLinePrompt(mob,(String)editRow.elementAt(a,2),showNumber,showFlag); editRow.setElementAt(a,2,newVal); } } if(showFlag<-900) { ok=true; break; } if(showFlag>0) { showFlag=-1; continue; } showFlag=CMath.s_int(mob.session().prompt(L("Edit which? "),"")); if(showFlag<=0) { showFlag=-1; ok=true; } } } } if((mob.session()!=null)&&(!mob.session().isStopped())) { final String prompt="Save to V)FS, F)ilesystem, or C)ancel (" + (recipe.wasVFS()?"V/f/c":"v/F/c")+"): "; final String choice=mob.session().choose(prompt,L("VFC"),recipe.wasVFS()?L("V"):L("F")); if(choice.equalsIgnoreCase("C")) mob.tell(L("Cancelled.")); else { final boolean saveToVFS = choice.equalsIgnoreCase("V"); resaveRecipeFile(mob, recipeFilename,recipe.dataRows(),recipe.columns(),saveToVFS); } } } @Override public void resaveRecipeFile(final MOB mob, final String recipeFilename, final List<DVector> rowsV, final List<? extends Object> columnsV, final boolean saveToVFS) { final StringBuffer saveBuf = new StringBuffer(""); for(int r=0;r<rowsV.size();r++) { final DVector dataRow = rowsV.get(r); int dataDex = 0; for(int c=0;c<columnsV.size();c++) { if(columnsV.get(c) instanceof String) saveBuf.append(columnsV.get(c)); else saveBuf.append(dataRow.elementAt(dataDex++,2)); } saveBuf.append("\n"); } CMFile file = new CMFile((saveToVFS?"::":"//")+Resources.buildResourcePath("skills")+recipeFilename,null,CMFile.FLAG_LOGERRORS); if(!file.canWrite()) Log.errOut("CMAbleParms","File: "+recipeFilename+" can not be written"); else if((!file.exists())||(!file.text().equals(saveBuf))) { file.saveText(saveBuf); if(!saveToVFS) { file = new CMFile("::"+Resources.buildResourcePath("skills")+recipeFilename,null,CMFile.FLAG_LOGERRORS); if((file.exists())&&(file.canWrite())) { file.saveText(saveBuf); } } if(mob != null) Log.sysOut("CMAbleParms","User: "+mob.Name()+" modified "+(saveToVFS?"VFS":"Local")+" file "+recipeFilename); Resources.removeResource("PARSED_RECIPE: "+recipeFilename); Resources.removeMultiLists(recipeFilename); } } protected static int getAppropriateResourceBucket(final Item I, final Object A) { final int myMaterial = ((I.material() & RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_MITHRIL) ? RawMaterial.MATERIAL_METAL : (I.material() & RawMaterial.MATERIAL_MASK); if(A instanceof Behavior) return CMLib.dice().pick( new int[]{RawMaterial.MATERIAL_LEATHER, RawMaterial.MATERIAL_VEGETATION}, myMaterial ); if(A instanceof Ability) { switch(((Ability)A).abilityCode() & Ability.ALL_ACODES) { case Ability.ACODE_CHANT: return CMLib.dice().pick( new int[]{RawMaterial.MATERIAL_VEGETATION, RawMaterial.MATERIAL_ROCK}, myMaterial ); case Ability.ACODE_SPELL: return CMLib.dice().pick( new int[]{RawMaterial.MATERIAL_WOODEN, RawMaterial.MATERIAL_PRECIOUS}, myMaterial ); case Ability.ACODE_PRAYER: return CMLib.dice().pick( new int[]{RawMaterial.MATERIAL_METAL, RawMaterial.MATERIAL_ROCK}, myMaterial ); case Ability.ACODE_SONG: return CMLib.dice().pick( new int[]{RawMaterial.MATERIAL_LIQUID, RawMaterial.MATERIAL_WOODEN}, myMaterial ); case Ability.ACODE_THIEF_SKILL: case Ability.ACODE_SKILL: return CMLib.dice().pick( new int[]{RawMaterial.MATERIAL_CLOTH, RawMaterial.MATERIAL_METAL}, myMaterial ); case Ability.ACODE_PROPERTY: if(A instanceof TriggeredAffect) return CMLib.dice().pick( new int[]{RawMaterial.MATERIAL_PRECIOUS, RawMaterial.MATERIAL_METAL}, myMaterial ); break; default: break; } } return CMLib.dice().pick( ALL_BUCKET_MATERIAL_CHOICES, myMaterial ); } protected static void addExtraMaterial(final Map<Integer,int[]> extraMatsM, final Item I, final Object A, double weight) { int times = 1; if(weight >= 1.0) { times = (int)Math.round(weight / 1.0); weight=.99; } final MaterialLibrary mats=CMLib.materials(); final int myBucket = getAppropriateResourceBucket(I,A); if(myBucket != RawMaterial.RESOURCE_NOTHING) { final PairList<Integer,Double> bucket = RawMaterial.CODES.instance().getValueSortedBucket(myBucket); Integer resourceCode = (bucket.size()==0) ? Integer.valueOf(CMLib.dice().pick( RawMaterial.CODES.ALL(), I.material() )) : bucket.get( (weight>=.99) ? bucket.size()-1 : 0 ).first; for (final Pair<Integer, Double> p : bucket) { if((weight <= p.second.doubleValue())&&(mats.isResourceCodeRoomMapped(p.first.intValue()))) { resourceCode = p.first; break; } } int tries=100; while((--tries>0)&&(!mats.isResourceCodeRoomMapped(resourceCode.intValue()))) resourceCode=bucket.get(CMLib.dice().roll(1, bucket.size(), -1)).first; resourceCode = Integer.valueOf( resourceCode.intValue() ); for(int x=0;x<times;x++) { final int[] amt = extraMatsM.get( resourceCode ); if(amt == null) extraMatsM.put( resourceCode, new int[]{1} ); else amt[0]++; } } } @SuppressWarnings("unchecked") protected static Pair<String[],String[]> getBuildingCodesNFlags() { Pair<String[],String[]> codesFlags = (Pair<String[],String[]>)Resources.getResource("BUILDING_SKILL_CODES_FLAGS"); if(codesFlags == null) { CraftorAbility A=(CraftorAbility)CMClass.getAbility("Masonry"); if(A==null) A=(CraftorAbility)CMClass.getAbility("Construction"); if(A==null) A=(CraftorAbility)CMClass.getAbility("Excavation"); if(A!=null) A.parametersFormat(); codesFlags = (Pair<String[],String[]>)Resources.getResource("BUILDING_SKILL_CODES_FLAGS"); } return codesFlags; } protected static void addExtraAbilityMaterial(final Map<Integer,int[]> extraMatsM, final Item I, final Ability A) { double level = CMLib.ableMapper().lowestQualifyingLevel( A.ID() ); if( level <= 0.0 ) { level = I.basePhyStats().level(); if( level <= 0.0 ) level = 1.0; addExtraMaterial(extraMatsM, I, A, CMath.div( level, CMProps.getIntVar( CMProps.Int.LASTPLAYERLEVEL ) )); } else { final double levelCap = CMLib.ableMapper().getCalculatedMedianLowestQualifyingLevel(); addExtraMaterial(extraMatsM, I, A, CMath.div(level , ( levelCap * 2.0))); } } public static Map<Integer,int[]> extraMaterial(final Item I) { final Map<Integer,int[]> extraMatsM=new TreeMap<Integer,int[]>(); /* * behaviors/properties of the item */ for(final Enumeration<Ability> a=I.effects(); a.hasMoreElements();) { final Ability A=a.nextElement(); if(A.isSavable()) { if((A.abilityCode() & Ability.ALL_ACODES) == Ability.ACODE_PROPERTY) { if(A instanceof AbilityContainer) { for(final Enumeration<Ability> a1=((AbilityContainer)A).allAbilities(); a1.hasMoreElements(); ) { addExtraAbilityMaterial(extraMatsM,I,a1.nextElement()); } } if(A instanceof TriggeredAffect) { if((A.flags() & Ability.FLAG_ADJUSTER) != 0) { int count = CMStrings.countSubstrings( new String[]{A.text()}, ADJUSTER_TOKENS ); if(count == 0) count = 1; for(int i=0;i<count;i++) addExtraAbilityMaterial(extraMatsM,I,A); } else if((A.flags() & (Ability.FLAG_RESISTER | Ability.FLAG_IMMUNER)) != 0) { int count = CMStrings.countSubstrings( new String[]{A.text()}, RESISTER_IMMUNER_TOKENS ); if(count == 0) count = 1; for(int i=0;i<count;i++) addExtraAbilityMaterial(extraMatsM,I,A); } } } else if((CMParms.indexOf(ALLOWED_BUCKET_ACODES, A.abilityCode() & Ability.ALL_ACODES ) >=0) &&(CMParms.indexOf( ALLOWED_BUCKET_QUALITIES, A.abstractQuality()) >=0 )) { addExtraAbilityMaterial(extraMatsM,I,A); } } } for(final Enumeration<Behavior> b=I.behaviors(); b.hasMoreElements();) { final Behavior B=b.nextElement(); if(B.isSavable()) { addExtraMaterial(extraMatsM, I, B, CMath.div( CMProps.getIntVar( CMProps.Int.LASTPLAYERLEVEL ), I.basePhyStats().level() )); } } return extraMatsM; } @Override public synchronized Map<String,AbilityParmEditor> getEditors() { if(DEFAULT_EDITORS != null) return DEFAULT_EDITORS; final Vector<AbilityParmEditorImpl> V=new XVector<AbilityParmEditorImpl>(new AbilityParmEditorImpl[] { new AbilityParmEditorImpl("SPELL_ID","The Spell ID",ParmType.CHOICES) { @Override public void createChoices() { createChoices(CMClass.abilities()); } @Override public String defaultValue() { return "Spell_ID"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Potion) return ((Potion)I).getSpellList(); else if((I instanceof Scroll) &&(I instanceof MiscMagic)) return ((Scroll)I).getSpellList(); return ""; } }, new AbilityParmEditorImpl("RESOURCE_NAME","Resource",ParmType.CHOICES) { @Override public void createChoices() { createChoices(RawMaterial.CODES.NAMES()); } @Override public String defaultValue() { return "IRON"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return RawMaterial.CODES.NAME(I.material()); } }, new AbilityParmEditorImpl("ITEM_NAME","Item Final Name",ParmType.STRING) { @Override public void createChoices() { } @Override public String defaultValue() { return "Item Name"; } @Override public int minColWidth() { return 10; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { final String oldName=I.Name(); if(I.material()==RawMaterial.RESOURCE_GLASS) return CMLib.english().removeArticleLead(oldName); String newName=oldName; final List<String> V=CMParms.parseSpaces(oldName,true); for(int i=0;i<V.size();i++) { final String s=V.get(i); final int code=RawMaterial.CODES.FIND_IgnoreCase(s); if((code>0)&&(code==I.material())) { V.set(i, "%"); if((i>0)&&(CMLib.english().isAnArticle(V.get(i-1)))) V.remove(i-1); newName=CMParms.combine(V); break; } } if(oldName.equals(newName)) { for(int i=0;i<V.size();i++) { final String s=V.get(i); final int code=RawMaterial.CODES.FIND_IgnoreCase(s); if(code>0) { V.set(i, "%"); if((i>0)&&(CMLib.english().isAnArticle(V.get(i-1)))) V.remove(i-1); newName=CMParms.combine(V); break; } } } if(newName.indexOf( '%' )<0) { for(int i=0;i<V.size()-1;i++) { if(CMLib.english().isAnArticle( V.get( i ) )) { if(i==0) V.set( i, "%" ); else V.add(i+1, "%"); break; } } newName=CMParms.combine( V ); } if(newName.indexOf( '%' )<0) { newName="% "+newName; } return newName; } }, new AbilityParmEditorImpl("STAIRS_DESC","Exit Desc",ParmType.STRING) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equals("STAIRS")) return 1; } return -1; } @Override public String defaultValue() { return "@x1stairs to the @x2 floor"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } }, new AbilityParmEditorImpl("BUILDING_NOUN","Building noun",ParmType.STRING) { @Override public void createChoices() { } @Override public String defaultValue() { return "thing"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } }, new AbilityParmEditorImpl("BUILDER_MASK","Builder Mask",ParmType.STRINGORNULL) { @Override public void createChoices() { } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } }, new AbilityParmEditorImpl("BUILDER_DESC","Info Description",ParmType.STRING) { @Override public void createChoices() { } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public int maxColWidth() { return 20; } }, new AbilityParmEditorImpl("RES_SUBTYPE","Sub-Type",ParmType.STRINGORNULL) { @Override public void createChoices() { } @Override public String defaultValue() { return ""; } @Override public int appliesToClass(final Object o) { if(o instanceof RawMaterial) return 5; return -1; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof RawMaterial) return ((RawMaterial)I).getSubType(); return ""; } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { return super.commandLinePrompt(mob, oldVal, showNumber, showFlag).toUpperCase().trim(); } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { return super.webValue(httpReq,parms,oldVal,fieldName).toUpperCase().trim(); } }, new AbilityParmEditorImpl("ITEM_LEVEL","Lvl",ParmType.NUMBER) { @Override public void createChoices() { } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if((I instanceof Weapon)||(I instanceof Armor)) { final int timsLevel = CMLib.itemBuilder().timsLevelCalculator(I); if((timsLevel > I.basePhyStats().level() ) && (timsLevel < CMProps.getIntVar(CMProps.Int.LASTPLAYERLEVEL))) return ""+timsLevel; } return ""+I.basePhyStats().level(); } }, new AbilityParmEditorImpl("BUILDING_GRID_SIZE","Grid Size",ParmType.NUMBER) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equals("ROOM")) return 1; } return -1; } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return "1"; } }, new AbilityParmEditorImpl("BUILD_TIME_TICKS","Time",ParmType.NUMBER) { @Override public void createChoices() { } @Override public String defaultValue() { return "20"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""+(10 + (I.basePhyStats().level()/2)); } }, new AbilityParmEditorImpl("FUTURE_USE","Future Use",ParmType.STRINGORNULL) { @Override public void createChoices() { } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return "1"; } }, new AbilityParmEditorImpl("AMOUNT_MATERIAL_REQUIRED","Amt",ParmType.NUMBER) { @Override public void createChoices() { } @Override public boolean confirmValue(final String oldVal) { return true; } @Override public String defaultValue() { return "10"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""+Math.round(CMath.mul(I.basePhyStats().weight(),(A!=null)?A.getItemWeightMultiplier(false):1.0)); } }, new AbilityParmEditorImpl("MATERIALS_REQUIRED","Amount/Cmp",ParmType.SPECIAL) { @Override public void createChoices() { } @Override public boolean confirmValue(final String oldVal) { return true; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { if(httpReq.isUrlParameter(fieldName+"_WHICH")) { final String which=httpReq.getUrlParameter(fieldName+"_WHICH"); if((which.trim().length()==0)||(which.trim().equalsIgnoreCase("AMOUNT"))) return httpReq.getUrlParameter(fieldName+"_AMOUNT"); if(which.trim().equalsIgnoreCase("COMPONENT")) return httpReq.getUrlParameter(fieldName+"_COMPONENT"); int x=1; final List<AbilityComponent> comps=new Vector<AbilityComponent>(); while(httpReq.isUrlParameter(fieldName+"_CUST_TYPE_"+x)) { String connector=httpReq.getUrlParameter(fieldName+"_CUST_CONN_"+x); final String amt=httpReq.getUrlParameter(fieldName+"_CUST_AMT_"+x); final String strVal=httpReq.getUrlParameter(fieldName+"_CUST_STR_"+x); final String loc=httpReq.getUrlParameter(fieldName+"_CUST_LOC_"+x); final String typ=httpReq.getUrlParameter(fieldName+"_CUST_TYPE_"+x); final String styp=httpReq.getUrlParameter(fieldName+"_CUST_STYPE_"+x); final String con=httpReq.getUrlParameter(fieldName+"_CUST_CON_"+x); if(connector==null) connector="AND"; if(connector.equalsIgnoreCase("DEL")||(connector.length()==0)) { x++; continue; } try { final AbilityComponent able=CMLib.ableComponents().createBlankAbilityComponent(); able.setConnector(AbilityComponent.CompConnector.valueOf(connector)); able.setAmount(CMath.s_int(amt)); able.setMask(""); able.setConsumed((con!=null) && con.equalsIgnoreCase("on")); able.setLocation(AbilityComponent.CompLocation.valueOf(loc)); able.setType(AbilityComponent.CompType.valueOf(typ), strVal, styp); comps.add(able); } catch(final Exception e) { } x++; } if(comps.size()>0) return CMLib.ableComponents().getAbilityComponentCodedString(comps); } return oldVal; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { int amt=(int)Math.round(CMath.mul(I.basePhyStats().weight()-1,(A!=null)?A.getItemWeightMultiplier(false):1.0)); if(amt<1) amt=1; final Map<Integer,int[]> extraMatsM = CMAbleParms.extraMaterial( I ); if((extraMatsM == null) || (extraMatsM.size()==0)) { return ""+amt; } final String subType = (I instanceof RawMaterial)?((RawMaterial)I).getSubType():""; final List<AbilityComponent> comps=new Vector<AbilityComponent>(); AbilityComponent able=CMLib.ableComponents().createBlankAbilityComponent(); able.setConnector(AbilityComponent.CompConnector.AND); able.setAmount(amt); able.setMask(""); able.setConsumed(true); able.setLocation(AbilityComponent.CompLocation.ONGROUND); able.setType(AbilityComponent.CompType.MATERIAL, Integer.valueOf(I.material() & RawMaterial.MATERIAL_MASK), subType); comps.add(able); for(final Integer resourceCode : extraMatsM.keySet()) { able=CMLib.ableComponents().createBlankAbilityComponent(); able.setConnector(AbilityComponent.CompConnector.AND); able.setAmount(extraMatsM.get(resourceCode)[0]); able.setMask(""); able.setConsumed(true); able.setLocation(AbilityComponent.CompLocation.ONGROUND); able.setType(AbilityComponent.CompType.RESOURCE, resourceCode, ""); comps.add(able); } return CMLib.ableComponents().getAbilityComponentCodedString(comps); } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { String value=webValue(httpReq,parms,oldVal,fieldName); if(value.endsWith("$")) value = value.substring(0,oldVal.length()-1); value = value.trim(); final String curWhich=httpReq.getUrlParameter(fieldName+"_WHICH"); int type=0; if("COMPONENT".equalsIgnoreCase(curWhich)) type=1; else if("EMBEDDED".equalsIgnoreCase(curWhich)) type=2; else if("AMOUNT".equalsIgnoreCase(curWhich)) type=0; else if(CMLib.ableComponents().getAbilityComponentMap().containsKey(value.toUpperCase().trim())) type=1; else if(value.startsWith("(")) type=2; else type=0; List<AbilityComponent> comps=null; if(type==2) { final Hashtable<String,List<AbilityComponent>> H=new Hashtable<String,List<AbilityComponent>>(); final String s="ID="+value; CMLib.ableComponents().addAbilityComponent(s, H); comps=H.get("ID"); } if(comps==null) comps=new ArrayList<AbilityComponent>(1); final StringBuffer str = new StringBuffer("<FONT SIZE=-1>"); str.append("<INPUT TYPE=RADIO NAME="+fieldName+"_WHICH "+(type==0?"CHECKED ":"")+"VALUE=\"AMOUNT\">"); str.append("\n\rAmount: <INPUT TYPE=TEXT SIZE=3 NAME="+fieldName+"_AMOUNT VALUE=\""+(type!=0?"":value)+"\" ONKEYDOWN=\"document.RESOURCES."+fieldName+"_WHICH[0].checked=true;\">"); str.append("\n\r<BR>"); str.append("<INPUT TYPE=RADIO NAME="+fieldName+"_WHICH "+(type==1?"CHECKED ":"")+"VALUE=\"COMPONENT\">"); str.append(L("\n\rSkill Components:")); str.append("\n\r<SELECT NAME="+fieldName+"_COMPONENT ONCHANGE=\"document.RESOURCES."+fieldName+"_WHICH[1].checked=true;\">"); str.append("<OPTION VALUE=\"0\""); if((type!=1)||(value.length()==0)||(value.equalsIgnoreCase("0"))) str.append(" SELECTED"); str.append(">&nbsp;"); for(final String S : CMLib.ableComponents().getAbilityComponentMap().keySet()) { str.append("<OPTION VALUE=\""+S+"\""); if((type==1)&&(value.equalsIgnoreCase(S))) str.append(" SELECTED"); str.append(">"+S); } str.append("</SELECT>"); str.append("\n\r<BR>"); str.append("<INPUT TYPE=RADIO NAME="+fieldName+"_WHICH "+(type==2?"CHECKED ":"")+"VALUE=\"EMBEDDED\">"); str.append("\n\rCustom:"); str.append("\n\r<BR>"); AbilityComponent comp; for(int i=0;i<=comps.size();i++) { comp=(i<comps.size())?comps.get(i):null; if(i>0) { str.append("\n\r<SELECT NAME="+fieldName+"_CUST_CONN_"+(i+1)+" ONCHANGE=\"document.RESOURCES."+fieldName+"_WHICH[2].checked=true;\">"); if(comp!=null) str.append("<OPTION VALUE=\"DEL\">DEL"); else if(type==2) str.append("<OPTION VALUE=\"\" SELECTED>"); for(final AbilityComponent.CompConnector conector : AbilityComponent.CompConnector.values()) { str.append("<OPTION VALUE=\""+conector.toString()+"\" "); if((type==2)&&(comp!=null)&&(conector==comp.getConnector())) str.append("SELECTED "); str.append(">"+CMStrings.capitalizeAndLower(conector.toString())); } str.append("</SELECT>"); } str.append("\n\rAmt: <INPUT TYPE=TEXT SIZE=2 NAME="+fieldName+"_CUST_AMT_"+(i+1)+" VALUE=\""+(((type!=2)||(comp==null))?"":Integer.toString(comp.getAmount()))+"\" ONKEYDOWN=\"document.RESOURCES."+fieldName+"_WHICH[2].checked=true;\">"); str.append("\n\r<SELECT NAME="+fieldName+"_CUST_TYPE_"+(i+1)+" ONCHANGE=\"document.RESOURCES."+fieldName+"_WHICH[2].checked=true; ReShow();\">"); final AbilityComponent.CompType compType=(comp!=null)?comp.getType():AbilityComponent.CompType.STRING; final String subType=(comp != null)?comp.getSubType():""; for(final AbilityComponent.CompType conn : AbilityComponent.CompType.values()) { str.append("<OPTION VALUE=\""+conn.toString()+"\" "); if(conn==compType) str.append("SELECTED "); str.append(">"+CMStrings.capitalizeAndLower(conn.toString())); } str.append("</SELECT>"); if(compType==AbilityComponent.CompType.STRING) str.append("\n\r<INPUT TYPE=TEXT SIZE=10 NAME="+fieldName+"_CUST_STR_"+(i+1)+" VALUE=\""+(((type!=2)||(comp==null))?"":comp.getStringType())+"\" ONKEYDOWN=\"document.RESOURCES."+fieldName+"_WHICH[2].checked=true;\">"); else { str.append("\n\r<SELECT NAME="+fieldName+"_CUST_STR_"+(i+1)+" ONCHANGE=\"document.RESOURCES."+fieldName+"_WHICH[2].checked=true;\">"); if(compType==AbilityComponent.CompType.MATERIAL) { final RawMaterial.Material[] M=RawMaterial.Material.values(); Arrays.sort(M,new Comparator<RawMaterial.Material>() { @Override public int compare(final Material o1, final Material o2) { return o1.name().compareToIgnoreCase(o2.name()); } }); for(final RawMaterial.Material m : M) { str.append("<OPTION VALUE="+m.mask()); if((type==2)&&(comp!=null)&&(m.mask()==comp.getLongType())) str.append(" SELECTED"); str.append(">"+m.noun()); } } else if(compType==AbilityComponent.CompType.RESOURCE) { final List<Pair<String,Integer>> L=new Vector<Pair<String,Integer>>(); for(int x=0;x<RawMaterial.CODES.TOTAL();x++) L.add(new Pair<String,Integer>(RawMaterial.CODES.NAME(x),Integer.valueOf(RawMaterial.CODES.GET(x)))); Collections.sort(L,new Comparator<Pair<String,Integer>>() { @Override public int compare(final Pair<String, Integer> o1, final Pair<String, Integer> o2) { return o1.first.compareToIgnoreCase(o2.first); } }); for(final Pair<String,Integer> p : L) { str.append("<OPTION VALUE="+p.second); if((type==2)&&(comp!=null)&&(p.second.longValue()==comp.getLongType())) str.append(" SELECTED"); str.append(">"+p.first); } } str.append("</SELECT>"); str.append(" <INPUT TYPE=TEXT SIZE=2 NAME="+fieldName+"_CUST_STYPE_"+(i+1)+" VALUE=\""+subType+"\">"); } str.append("\n\r<SELECT NAME="+fieldName+"_CUST_LOC_"+(i+1)+" ONCHANGE=\"document.RESOURCES."+fieldName+"_WHICH[2].checked=true;\">"); for(final AbilityComponent.CompLocation conn : AbilityComponent.CompLocation.values()) { str.append("<OPTION VALUE=\""+conn.toString()+"\" "); if((type==2)&&(comp!=null)&&(conn==comp.getLocation())) str.append("SELECTED "); str.append(">"+CMStrings.capitalizeAndLower(conn.toString())); } str.append("</SELECT>"); str.append("\n\rConsumed:<INPUT TYPE=CHECKBOX NAME="+fieldName+"_CUST_CON_"+(i+1)+" "+((type!=2)||(comp==null)||(!comp.isConsumed())?"":"CHECKED")+" ONCLICK=\"document.RESOURCES."+fieldName+"_WHICH[2].checked=true;\">"); if(i<comps.size()) str.append("\n\r<BR>\n\r"); else str.append("\n\r<a href=\"javascript:ReShow();\">&lt;*&gt;</a>\n\r"); } str.append("<BR>"); str.append("</FONT>"); return str.toString(); } @Override public String[] fakeUserInput(final String oldVal) { return new String[] { oldVal }; } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { ++showNumber[0]; String str = oldVal; while(!mob.session().isStopped()) { final String help="<AMOUNT>" +"\n\rSkill Component: "+CMParms.toListString(CMLib.ableComponents().getAbilityComponentMap().keySet()) +"\n\rCustom Component: ([DISPOSITION]:[FATE]:[AMOUNT]:[COMPONENT ID]:[MASK]) && ..."; str=CMLib.genEd().prompt(mob,oldVal,showNumber[0],showFlag,prompt(),true,help).trim(); if(str.equals(oldVal)) return oldVal; if(CMath.isInteger(str)) return Integer.toString(CMath.s_int(str)); if(CMLib.ableComponents().getAbilityComponentMap().containsKey(str.toUpperCase().trim())) return str.toUpperCase().trim(); String error=null; if(str.trim().startsWith("(")) { error=CMLib.ableComponents().addAbilityComponent("ID="+str, new Hashtable<String,List<AbilityComponent>>()); if(error==null) return str; } mob.session().println(L("'@x1' is not an amount of material, a component key, or custom component list@x2. Please use ? for help.",str,(error==null?"":"("+error+")"))); } return str; } @Override public String defaultValue() { return "1"; } }, new AbilityParmEditorImpl("OPTIONAL_AMOUNT_REQUIRED","Amt",ParmType.NUMBER) { @Override public void createChoices() { } @Override public boolean confirmValue(final String oldVal) { return true; } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } }, new AbilityParmEditorImpl("ITEM_BASE_VALUE","Value",ParmType.NUMBER) { @Override public void createChoices() { } @Override public String defaultValue() { return "5"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""+I.baseGoldValue(); } }, new AbilityParmEditorImpl("ROOM_CLASS_ID","Class ID",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equalsIgnoreCase("ROOM") ||chk.equalsIgnoreCase("EXCAVATE")) return 1; } return -1; } @Override public void createChoices() { final Vector<Environmental> V = new Vector<Environmental>(); V.addAll(new XVector<Room>(CMClass.locales())); createChoices(V); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return "Plains"; } }, new AbilityParmEditorImpl("ALLITEM_CLASS_ID","Class ID",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equalsIgnoreCase("ITEM")) return 1; } return -1; } @Override public void createChoices() { final XVector<Environmental> V = new XVector<Environmental>(); V.addAll(CMClass.basicItems()); V.addAll(CMClass.weapons()); V.addAll(CMClass.tech()); V.addAll(CMClass.armor()); V.addAll(CMClass.miscMagic()); V.addAll(CMClass.clanItems()); for(int i=V.size()-1;i<=0;i--) { if(V.get(i) instanceof CMObjectWrapper) V.remove(i); } createChoices(V); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return "StdItem"; } }, new AbilityParmEditorImpl("ROOM_CLASS_ID_OR_NONE","Class ID",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equalsIgnoreCase("DEMOLISH") ||chk.equalsIgnoreCase("STAIRS")) return 1; } return -1; } @Override public void createChoices() { final Vector<Object> V = new Vector<Object>(); V.add(""); V.addAll(new XVector<Room>(CMClass.locales())); createChoices(V); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return ""; } }, new AbilityParmEditorImpl("EXIT_CLASS_ID","Class ID",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equalsIgnoreCase("DOOR")) return 1; } return -1; } @Override public void createChoices() { final Vector<Environmental> V = new Vector<Environmental>(); V.addAll(new XVector<Exit>(CMClass.exits())); final Vector<CMObject> V2=new Vector<CMObject>(); Environmental I; for(final Enumeration<Environmental> e=V.elements();e.hasMoreElements();) { I=e.nextElement(); if(I.isGeneric()) V2.addElement(I); } createChoices(V2); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return "GenExit"; } }, new AbilityParmEditorImpl("ITEM_CLASS_ID","Class ID",ParmType.CHOICES) { @Override public void createChoices() { final List<Item> V = new ArrayList<Item>(); V.addAll(new XVector<ClanItem>(CMClass.clanItems())); V.addAll(new XVector<Armor>(CMClass.armor())); V.addAll(new XVector<Item>(CMClass.basicItems())); V.addAll(new XVector<MiscMagic>(CMClass.miscMagic())); V.addAll(new XVector<Technical>(CMClass.tech())); V.addAll(new XVector<Weapon>(CMClass.weapons())); final List<Item> V2=new ArrayList<Item>(); Item I; for(final Iterator<Item> e=V.iterator();e.hasNext();) { I=e.next(); if(I.isGeneric() || I.ID().equalsIgnoreCase("StdDeckOfCards")) V2.add(I); } for(int i=V.size()-1;i<=0;i--) { if(V.get(i) instanceof CMObjectWrapper) V.remove(i); } createChoices(V2); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I.isGeneric()) return I.ID(); if(I instanceof Weapon) return "GenWeapon"; if(I instanceof Armor) return "GenArmor"; if(I instanceof Rideable) return "GenRideable"; return "GenItem"; } @Override public String defaultValue() { return "GenItem"; } }, new AbilityParmEditorImpl("CODED_WEAR_LOCATION","Wear Locs",ParmType.SPECIAL) { @Override public int appliesToClass(final Object o) { if(o instanceof FalseLimb) return -1; return ((o instanceof Armor) || (o instanceof MusicalInstrument)) ? 2 : -1; } @Override public void createChoices() { } @Override public boolean confirmValue(final String oldVal) { return oldVal.trim().length() > 0; } @Override public String defaultValue() { return "NECK"; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final short[] layerAtt = new short[1]; final short[] layers = new short[1]; final long[] wornLoc = new long[1]; final boolean[] logicalAnd = new boolean[1]; final double[] hardBonus=new double[1]; CMLib.ableParms().parseWearLocation(layerAtt,layers,wornLoc,logicalAnd,hardBonus,oldVal); if(httpReq.isUrlParameter(fieldName+"_WORNDATA")) { wornLoc[0]=CMath.s_long(httpReq.getUrlParameter(fieldName+"_WORNDATA")); for(int i=1;;i++) if(httpReq.isUrlParameter(fieldName+"_WORNDATA"+(Integer.toString(i)))) wornLoc[0]=wornLoc[0]|CMath.s_long(httpReq.getUrlParameter(fieldName+"_WORNDATA"+(Integer.toString(i)))); else break; logicalAnd[0] = httpReq.getUrlParameter(fieldName+"_ISTWOHANDED").equalsIgnoreCase("on"); layers[0] = CMath.s_short(httpReq.getUrlParameter(fieldName+"_LAYER")); layerAtt[0] = 0; if((httpReq.isUrlParameter(fieldName+"_SEETHRU")) &&(httpReq.getUrlParameter(fieldName+"_SEETHRU").equalsIgnoreCase("on"))) layerAtt[0] |= Armor.LAYERMASK_SEETHROUGH; if((httpReq.isUrlParameter(fieldName+"_MULTIWEAR")) &&(httpReq.getUrlParameter(fieldName+"_MULTIWEAR").equalsIgnoreCase("on"))) layerAtt[0] |= Armor.LAYERMASK_MULTIWEAR; } return reconvert(layerAtt,layers,wornLoc,logicalAnd,hardBonus); } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String value = webValue(httpReq,parms,oldVal,fieldName); final short[] layerAtt = new short[1]; final short[] layers = new short[1]; final long[] wornLoc = new long[1]; final boolean[] logicalAnd = new boolean[1]; final double[] hardBonus=new double[1]; CMLib.ableParms().parseWearLocation(layerAtt,layers,wornLoc,logicalAnd,hardBonus,value); final StringBuffer str = new StringBuffer(""); str.append("\n\r<SELECT NAME="+fieldName+"_WORNDATA MULTIPLE>"); final Wearable.CODES codes = Wearable.CODES.instance(); for(int i=1;i<codes.total();i++) { final String climstr=codes.name(i); final int mask=(int)CMath.pow(2,i-1); str.append("<OPTION VALUE="+mask); if((wornLoc[0]&mask)>0) str.append(" SELECTED"); str.append(">"+climstr); } str.append("</SELECT>"); str.append("<BR>\n\r<INPUT TYPE=RADIO NAME="+fieldName+"_ISTWOHANDED value=\"on\" "+(logicalAnd[0]?"CHECKED":"")+">Is worn on All above Locations."); str.append("<BR>\n\r<INPUT TYPE=RADIO NAME="+fieldName+"_ISTWOHANDED value=\"\" "+(logicalAnd[0]?"":"CHECKED")+">Is worn on ANY of the above Locations."); str.append("<BR>\n\rLayer: <INPUT TYPE=TEXT NAME="+fieldName+"_LAYER SIZE=5 VALUE=\""+layers[0]+"\">"); final boolean seeThru = CMath.bset(layerAtt[0],Armor.LAYERMASK_SEETHROUGH); final boolean multiWear = CMath.bset(layerAtt[0],Armor.LAYERMASK_MULTIWEAR); str.append("&nbsp;&nbsp;\n\r<INPUT TYPE=CHECKBOX NAME="+fieldName+"_SEETHRU value=\"on\" "+(seeThru?"CHECKED":"")+">Is see-through."); str.append("&nbsp;&nbsp;\n\r<INPUT TYPE=CHECKBOX NAME="+fieldName+"_MULTIWEAR value=\"on\" "+(multiWear?"CHECKED":"")+">Is multi-wear."); return str.toString(); } public String reconvert(final short[] layerAtt, final short[] layers, final long[] wornLoc, final boolean[] logicalAnd, final double[] hardBonus) { final StringBuffer newVal = new StringBuffer(""); if((layerAtt[0]!=0)||(layers[0]!=0)) { if(CMath.bset(layerAtt[0],Armor.LAYERMASK_MULTIWEAR)) newVal.append('M'); if(CMath.bset(layerAtt[0],Armor.LAYERMASK_SEETHROUGH)) newVal.append('S'); newVal.append(layers[0]); newVal.append(':'); } boolean needLink=false; final Wearable.CODES codes = Wearable.CODES.instance(); for(int wo=1;wo<codes.total();wo++) { if(CMath.bset(wornLoc[0],CMath.pow(2,wo-1))) { if(needLink) newVal.append(logicalAnd[0]?"&&":"||"); needLink = true; newVal.append(codes.name(wo).toUpperCase()); } } return newVal.toString(); } @Override public String convertFromItem(final ItemCraftor C, final Item I) { if(!(I instanceof Armor)) return "HELD"; final Armor A=(Armor)I; final boolean[] logicalAnd=new boolean[]{I.rawLogicalAnd()}; final long[] wornLoc=new long[]{I.rawProperLocationBitmap()}; final double[] hardBonus=new double[]{0.0}; final short[] layerAtt=new short[]{A.getLayerAttributes()}; final short[] layers=new short[]{A.getClothingLayer()}; return reconvert(layerAtt,layers,wornLoc,logicalAnd,hardBonus); } @Override public String[] fakeUserInput(final String oldVal) { final ArrayList<String> V = new ArrayList<String>(); final short[] layerAtt = new short[1]; final short[] layers = new short[1]; final long[] wornLoc = new long[1]; final boolean[] logicalAnd = new boolean[1]; final double[] hardBonus=new double[1]; CMLib.ableParms().parseWearLocation(layerAtt,layers,wornLoc,logicalAnd,hardBonus,oldVal); V.add(""+layers[0]); if(CMath.bset(layerAtt[0],Armor.LAYERMASK_SEETHROUGH)) V.add("Y"); else V.add("N"); if(CMath.bset(layerAtt[0],Armor.LAYERMASK_MULTIWEAR)) V.add("Y"); else V.add("N"); V.add("1"); V.add("1"); final Wearable.CODES codes = Wearable.CODES.instance(); for(int i=0;i<codes.total();i++) { if(CMath.bset(wornLoc[0],codes.get(i))) { V.add(""+(i+2)); V.add(""+(i+2)); } } V.add("0"); return CMParms.toStringArray(V); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { final short[] layerAtt = new short[1]; final short[] layers = new short[1]; final long[] wornLoc = new long[1]; final boolean[] logicalAnd = new boolean[1]; final double[] hardBonus=new double[1]; CMLib.ableParms().parseWearLocation(layerAtt,layers,wornLoc,logicalAnd,hardBonus,oldVal); CMLib.genEd().wornLayer(mob,layerAtt,layers,++showNumber[0],showFlag); CMLib.genEd().wornLocation(mob,wornLoc,logicalAnd,++showNumber[0],showFlag); return reconvert(layerAtt,layers,wornLoc,logicalAnd,hardBonus); } }, new AbilityParmEditorImpl("PAGES_CHARS","Max Pgs/Chrs.",ParmType.SPECIAL) { @Override public int appliesToClass(final Object o) { return (o instanceof Book) ? 1 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "1/0"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Book) return ""+((Book)I).getMaxPages()+"/"+((Book)I).getMaxCharsPerPage(); return "1/0"; } @Override public boolean confirmValue(final String oldVal) { return oldVal.trim().length() > 0; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { int maxPages=1; int maxCharsPage=0; if(oldVal.length()>0) { final int x=oldVal.indexOf('/'); if(x>0) { maxPages=CMath.s_int(oldVal.substring(0,x)); maxCharsPage=CMath.s_int(oldVal.substring(x+1)); } } if(httpReq.isUrlParameter(fieldName+"_MAXPAGES")) maxPages = CMath.s_int(httpReq.getUrlParameter(fieldName+"_MAXPAGES")); if(httpReq.isUrlParameter(fieldName+"_MAXCHARSPAGE")) maxCharsPage = CMath.s_int(httpReq.getUrlParameter(fieldName+"_MAXCHARSPAGE")); return ""+maxPages+"/"+maxCharsPage; } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String value = webValue(httpReq, parms, oldVal, fieldName); final StringBuffer str = new StringBuffer(""); str.append("<TABLE WIDTH=100% BORDER=\"1\" CELLSPACING=0 CELLPADDING=0><TR>"); final String[] vals = this.fakeUserInput(value); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("Max Pages")+"</FONT></TD>"); str.append("<TD WIDTH=25%><INPUT TYPE=TEXT SIZE=5 NAME="+fieldName+"_MAXPAGES VALUE=\""+vals[0]+"\">"); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("Max Chars Page")+"</FONT></TD>"); str.append("<TD WIDTH=25%><INPUT TYPE=TEXT SIZE=5 NAME="+fieldName+"_MAXCHARSPAGE VALUE=\""+vals[1]+"\">"); str.append("</TD>"); str.append("</TR></TABLE>"); return str.toString(); } @Override public String[] fakeUserInput(final String oldVal) { final ArrayList<String> V = new ArrayList<String>(); int maxPages=1; int maxCharsPage=0; if(oldVal.length()>0) { final int x=oldVal.indexOf('/'); if(x>0) { maxPages=CMath.s_int(oldVal.substring(0,x)); maxCharsPage=CMath.s_int(oldVal.substring(x+1)); } } V.add(""+maxPages); V.add(""+maxCharsPage); return CMParms.toStringArray(V); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { final String[] input=this.fakeUserInput(oldVal); int maxPages=CMath.s_int(input[0]); int maxCharsPage=CMath.s_int(input[1]); maxPages = CMLib.genEd().prompt(mob, maxPages, ++showNumber[0], showFlag, L("Max Pages"), null); maxCharsPage = CMLib.genEd().prompt(mob, maxCharsPage, ++showNumber[0], showFlag, L("Max Chars/Page"), null); return maxPages+"/"+maxCharsPage; } }, new AbilityParmEditorImpl("RIDE_OVERRIDE_STRS","Ride Strings",ParmType.SPECIAL) { @Override public int appliesToClass(final Object o) { return (o instanceof Rideable) ? 1 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Rideable) { final Rideable R=(Rideable)I; final StringBuilder str=new StringBuilder(""); //STATESTR,STATESUBJSTR,RIDERSTR,MOUNTSTR,DISMOUNTSTR,PUTSTR str.append(R.getStateString().replace(';', ',')).append(';'); str.append(R.getStateStringSubject().replace(';', ',')).append(';'); str.append(R.getRideString().replace(';', ',')).append(';'); str.append(R.getMountString().replace(';', ',')).append(';'); str.append(R.getDismountString().replace(';', ',')).append(';'); str.append(R.getPutString().replace(';', ',')); if(str.length()==5) return ""; return str.toString(); } return ""; } @Override public boolean confirmValue(final String oldVal) { return true; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String[] finput = this.fakeUserInput(oldVal); String stateStr=finput[0]; String stateSubjectStr=finput[1]; String riderStr=finput[2]; String mountStr=finput[3]; String dismountStr=finput[4]; String putStr=finput[5]; if(httpReq.isUrlParameter(fieldName+"_RSTATESTR")) stateStr = httpReq.getUrlParameter(fieldName+"_RSTATESTR"); if(httpReq.isUrlParameter(fieldName+"_RSTATESUBJSTR")) stateSubjectStr = httpReq.getUrlParameter(fieldName+"_RSTATESUBJSTR"); if(httpReq.isUrlParameter(fieldName+"_RRIDERSTR")) riderStr = httpReq.getUrlParameter(fieldName+"_RRIDERSTR"); if(httpReq.isUrlParameter(fieldName+"_RMOUNTSTR")) mountStr = httpReq.getUrlParameter(fieldName+"_RMOUNTSTR"); if(httpReq.isUrlParameter(fieldName+"_RDISMOUNTSTR")) dismountStr = httpReq.getUrlParameter(fieldName+"_RDISMOUNTSTR"); if(httpReq.isUrlParameter(fieldName+"_RPUTSTR")) putStr = httpReq.getUrlParameter(fieldName+"_RPUTSTR"); final StringBuilder str=new StringBuilder(""); str.append(stateStr.replace(';', ',')).append(';'); str.append(stateSubjectStr.replace(';', ',')).append(';'); str.append(riderStr.replace(';', ',')).append(';'); str.append(mountStr.replace(';', ',')).append(';'); str.append(dismountStr.replace(';', ',')).append(';'); str.append(putStr.replace(';', ',')); if(str.length()==5) return ""; return str.toString(); } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String value = webValue(httpReq, parms, oldVal, fieldName); final StringBuffer str = new StringBuffer(""); str.append("<TABLE WIDTH=100% BORDER=\"1\" CELLSPACING=0 CELLPADDING=0>"); final String[] vals = this.fakeUserInput(value); str.append("<TR>"); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("State")+"</FONT></TD>"); str.append("<TD><INPUT TYPE=TEXT SIZE=50 NAME="+fieldName+"_RSTATESTR VALUE=\""+vals[0]+"\">"); str.append("</TR>"); str.append("<TR>"); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("State Subj.")+"</FONT></TD>"); str.append("<TD><INPUT TYPE=TEXT SIZE=50 NAME="+fieldName+"_RSTATESUBJSTR VALUE=\""+vals[1]+"\">"); str.append("</TR>"); str.append("<TR>"); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("Rider")+"</FONT></TD>"); str.append("<TD><INPUT TYPE=TEXT SIZE=50 NAME="+fieldName+"_RRIDERSTR VALUE=\""+vals[2]+"\">"); str.append("</TR>"); str.append("<TR>"); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("Mount")+"</FONT></TD>"); str.append("<TD><INPUT TYPE=TEXT SIZE=50 NAME="+fieldName+"_RMOUNTSTR VALUE=\""+vals[3]+"\">"); str.append("</TR>"); str.append("<TR>"); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("Dismount")+"</FONT></TD>"); str.append("<TD><INPUT TYPE=TEXT SIZE=50 NAME="+fieldName+"_RDISMOUNTSTR VALUE=\""+vals[4]+"\">"); str.append("</TR>"); str.append("<TR>"); str.append("<TD WIDTH=25%><FONT COLOR=WHITE>"+L("Put")+"</FONT></TD>"); str.append("<TD><INPUT TYPE=TEXT SIZE=50 NAME="+fieldName+"_RPUTSTR VALUE=\""+vals[5]+"\">"); str.append("</TR>"); str.append("</TABLE>"); return str.toString(); } @Override public String[] fakeUserInput(final String oldVal) { final ArrayList<String> V = new ArrayList<String>(); String stateStr=""; String stateSubjectStr=""; String riderStr=""; String mountStr=""; String dismountStr=""; String putStr=""; if(oldVal.length()>0) { final List<String> lst=CMParms.parseSemicolons(oldVal.trim(),false); if(lst.size()>0) stateStr=lst.get(0).replace(';',','); if(lst.size()>1) stateSubjectStr=lst.get(1).replace(';',','); if(lst.size()>2) riderStr=lst.get(2).replace(';',','); if(lst.size()>3) mountStr=lst.get(3).replace(';',','); if(lst.size()>4) dismountStr=lst.get(4).replace(';',','); if(lst.size()>5) putStr=lst.get(5).replace(';',','); } V.add(stateStr); V.add(stateSubjectStr); V.add(riderStr); V.add(mountStr); V.add(dismountStr); V.add(putStr); return CMParms.toStringArray(V); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { final String[] finput = this.fakeUserInput(oldVal); String stateStr=finput[0]; String stateSubjectStr=finput[1]; String riderStr=finput[2]; String mountStr=finput[3]; String dismountStr=finput[4]; String putStr=finput[5]; stateStr = CMLib.genEd().prompt(mob, stateStr, ++showNumber[0], showFlag, L("State Str"), true); stateSubjectStr = CMLib.genEd().prompt(mob, stateSubjectStr, ++showNumber[0], showFlag, L("State Subject"), true); riderStr = CMLib.genEd().prompt(mob, riderStr, ++showNumber[0], showFlag, L("Ride Str"), true); mountStr = CMLib.genEd().prompt(mob, mountStr, ++showNumber[0], showFlag, L("Mount Str"), true); dismountStr = CMLib.genEd().prompt(mob, dismountStr, ++showNumber[0], showFlag, L("Dismount Str"), true); putStr = CMLib.genEd().prompt(mob, putStr, ++showNumber[0], showFlag, L("Put Str"), true); final StringBuilder str=new StringBuilder(""); str.append(stateStr.replace(';', ',')).append(';'); str.append(stateSubjectStr.replace(';', ',')).append(';'); str.append(riderStr.replace(';', ',')).append(';'); str.append(mountStr.replace(';', ',')).append(';'); str.append(dismountStr.replace(';', ',')).append(';'); str.append(putStr.replace(';', ',')); if(str.length()==5) return ""; return str.toString(); } }, new AbilityParmEditorImpl("CONTAINER_CAPACITY","Cap.",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return (o instanceof Container) ? 1 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "20"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Container) return ""+((Container)I).capacity(); return "0"; } }, new AbilityParmEditorImpl("BASE_ARMOR_AMOUNT","Arm.",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return (o instanceof Armor) ? 2 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""+I.basePhyStats().armor(); } }, new AbilityParmEditorImpl("CONTAINER_TYPE","Con.",ParmType.MULTICHOICES) { @Override public void createChoices() { createBinaryChoices(Container.CONTAIN_DESCS); } @Override public int appliesToClass(final Object o) { return (o instanceof Container) ? 1 : -1; } @Override public String defaultValue() { return "0"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof Container)) return ""; final Container C=(Container)I; final StringBuilder str=new StringBuilder(""); for(int i=1;i<Container.CONTAIN_DESCS.length;i++) { if(CMath.isSet(C.containTypes(), i-1)) { if(str.length()>0) str.append("|"); str.append(Container.CONTAIN_DESCS[i]); } } return str.toString(); } }, new AbilityParmEditorImpl("CONTAINER_TYPE_OR_LIDLOCK","Con.",ParmType.SPECIAL) { @Override public void createChoices() { super.choices = new PairVector<String,String>(); for(final String s : Container.CONTAIN_DESCS) choices().add(s.toUpperCase().trim(),s); choices().add("LID","Lid"); choices().add("LOCK","Lock"); } @Override public int appliesToClass(final Object o) { return (o instanceof Container) ? 1 : -1; } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { final StringBuilder str=new StringBuilder(""); if(I instanceof Container) { final Container C=(Container)I; if(C.hasALock()) str.append("LOCK"); if(str.length()>0) str.append("|"); if(C.hasADoor()) str.append("LID"); if(str.length()>0) str.append("|"); for(int i=1;i<Container.CONTAIN_DESCS.length;i++) { if(CMath.isSet(C.containTypes(), i-1)) { if(str.length()>0) str.append("|"); str.append(Container.CONTAIN_DESCS[i]); } } } return str.toString(); } @Override public String[] fakeUserInput(final String oldVal) { if(oldVal.trim().length()==0) return new String[]{"NULL"}; return CMParms.parseAny(oldVal,'|',true).toArray(new String[0]); } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String webValue = httpReq.getUrlParameter(fieldName); if(webValue == null) return oldVal; String id=""; int index=0; final StringBuilder str=new StringBuilder(""); for(;httpReq.isUrlParameter(fieldName+id);id=""+(++index)) { final String newVal = httpReq.getUrlParameter(fieldName+id); if((newVal!=null)&&(newVal.length()>0)&&(choices().containsFirst(newVal))) str.append(newVal).append("|"); } return str.toString(); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { return CMLib.genEd().promptMultiSelectList(mob,oldVal,"|",++showNumber[0],showFlag,prompt(),choices(),false); } @Override public boolean confirmValue(final String oldVal) { final List<String> webVals=CMParms.parseAny(oldVal.toUpperCase().trim(), "|", true); for(final String s : webVals) { if(!choices().containsFirst(s)) return false; } return true; } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String webValue = webValue(httpReq,parms,oldVal,fieldName); final List<String> webVals=CMParms.parseAny(webValue.toUpperCase().trim(), "|", true); String onChange = null; onChange = " MULTIPLE "; if(!parms.containsKey("NOSELECT")) onChange+= "ONCHANGE=\"MultiSelect(this);\""; final StringBuilder str=new StringBuilder(""); str.append("\n\r<SELECT NAME="+fieldName+onChange+">"); for(int i=0;i<choices().size();i++) { final String option = (choices().get(i).first); str.append("<OPTION VALUE=\""+option+"\" "); if(webVals.contains(option)) str.append("SELECTED"); str.append(">"+(choices().get(i).second)); } return str.toString()+"</SELECT>"; } }, new AbilityParmEditorImpl("CODED_SPELL_LIST","Spell Affects",ParmType.SPECIAL) { @Override public void createChoices() { } @Override public int maxColWidth() { return 20; } @Override public boolean confirmValue(String oldVal) { if(oldVal.length()==0) return true; if(oldVal.charAt(0)=='*') oldVal = oldVal.substring(1); final int x=oldVal.indexOf('('); int y=oldVal.indexOf(';'); if((x<y)&&(x>0)) y=x; if(y<0) return CMClass.getAbility(oldVal)!=null; return CMClass.getAbility(oldVal.substring(0,y))!=null; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return CMLib.coffeeMaker().getCodedSpellsOrBehaviors(I); } @Override public String defaultValue() { return ""; } public String rebuild(final List<CMObject> spells) throws CMException { final StringBuffer newVal = new StringBuffer(""); if(spells.size()==1) { newVal.append("*" + spells.get(0).ID() + ";"); if(spells.get(0) instanceof Ability) newVal.append(((Ability)spells.get(0)).text()); else if(spells.get(0) instanceof Behavior) newVal.append(((Behavior)spells.get(0)).getParms()); } else { if(spells.size()>1) { for(int s=0;s<spells.size();s++) { final String txt; if(spells.get(s) instanceof Ability) txt=((Ability)spells.get(s)).text(); else if(spells.get(s) instanceof Behavior) txt=((Behavior)spells.get(s)).getParms(); else txt=""; if(txt.length()>0) { if((txt.indexOf(';')>=0) ||(CMClass.getAbility(txt.trim())!=null) ||(CMClass.getBehavior(txt.trim())!=null)) throw new CMException("You may not have more than one spell when one of the spells parameters is a spell id or a ; character."); } newVal.append(spells.get(s).ID()); if(txt.length()>0) newVal.append(";" + txt); if(s<(spells.size()-1)) newVal.append(";"); } } } return newVal.toString(); } @Override public String[] fakeUserInput(final String oldVal) { final Vector<String> V = new Vector<String>(); final Vector<String> V2 = new Vector<String>(); final List<CMObject> spells=CMLib.coffeeMaker().getCodedSpellsOrBehaviors(oldVal); for(int s=0;s<spells.size();s++) { final CMObject O = spells.get(s); V.addElement(O.ID()); V2.addElement(O.ID()); if(O instanceof Ability) V2.addElement(((Ability)O).text()); else if(O instanceof Behavior) V2.addElement(((Behavior)O).getParms()); else V2.add(""); } V.addAll(V2); V.addElement(""); return CMParms.toStringArray(V); } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { List<CMObject> spells=null; if(httpReq.isUrlParameter(fieldName+"_AFFECT1")) { spells = new Vector<CMObject>(); int num=1; String behav=httpReq.getUrlParameter(fieldName+"_AFFECT"+num); String theparm=httpReq.getUrlParameter(fieldName+"_ADATA"+num); while((behav!=null)&&(theparm!=null)) { if(behav.length()>0) { final Ability A=CMClass.getAbility(behav); if(A!=null) { if(theparm.trim().length()>0) A.setMiscText(theparm); spells.add(A); } else { final Behavior B=CMClass.getBehavior(behav); if(B!=null) { if(theparm.trim().length()>0) B.setParms(theparm); spells.add(B); } } } num++; behav=httpReq.getUrlParameter(fieldName+"_AFFECT"+num); theparm=httpReq.getUrlParameter(fieldName+"_ADATA"+num); } } else spells = CMLib.coffeeMaker().getCodedSpellsOrBehaviors(oldVal); try { return rebuild(spells); } catch(final Exception e) { return oldVal; } } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final List<CMObject> spells=CMLib.coffeeMaker().getCodedSpellsOrBehaviors(webValue(httpReq,parms,oldVal,fieldName)); final StringBuffer str = new StringBuffer(""); str.append("<TABLE WIDTH=100% BORDER=\"1\" CELLSPACING=0 CELLPADDING=0>"); for(int i=0;i<spells.size();i++) { final CMObject A=spells.get(i); str.append("<TR><TD WIDTH=50%>"); str.append("\n\r<SELECT ONCHANGE=\"EditAffect(this);\" NAME="+fieldName+"_AFFECT"+(i+1)+">"); str.append("<OPTION VALUE=\"\">Delete!"); str.append("<OPTION VALUE=\""+A.ID()+"\" SELECTED>"+A.ID()); str.append("</SELECT>"); str.append("</TD><TD WIDTH=50%>"); final String parmstr=(A instanceof Ability)?((Ability)A).text():((Behavior)A).getParms(); final String theparm=CMStrings.replaceAll(parmstr,"\"","&quot;"); str.append("\n\r<INPUT TYPE=TEXT SIZE=30 NAME="+fieldName+"_ADATA"+(i+1)+" VALUE=\""+theparm+"\">"); str.append("</TD></TR>"); } str.append("<TR><TD WIDTH=50%>"); str.append("\n\r<SELECT ONCHANGE=\"AddAffect(this);\" NAME="+fieldName+"_AFFECT"+(spells.size()+1)+">"); str.append("<OPTION SELECTED VALUE=\"\">Select an Effect/Behav"); for(final Enumeration<Ability> a=CMClass.abilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A.classificationCode()&Ability.ALL_DOMAINS)==Ability.DOMAIN_ARCHON) continue; final String cnam=A.ID(); str.append("<OPTION VALUE=\""+cnam+"\">"+cnam); } for(final Enumeration<Behavior> b=CMClass.behaviors();b.hasMoreElements();) { final Behavior B=b.nextElement(); final String cnam=B.ID(); str.append("<OPTION VALUE=\""+cnam+"\">"+cnam); } str.append("</SELECT>"); str.append("</TD><TD WIDTH=50%>"); str.append("\n\r<INPUT TYPE=TEXT SIZE=30 NAME="+fieldName+"_ADATA"+(spells.size()+1)+" VALUE=\"\">"); str.append("</TD></TR>"); str.append("</TABLE>"); return str.toString(); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { final List<CMObject> spells=CMLib.coffeeMaker().getCodedSpellsOrBehaviors(oldVal); final StringBuffer rawCheck = new StringBuffer(""); for(int s=0;s<spells.size();s++) { rawCheck.append(spells.get(s).ID()).append(";"); if(spells.get(s) instanceof Ability) rawCheck.append(((Ability)spells.get(s)).text()).append(";"); else if(spells.get(s) instanceof Behavior) rawCheck.append(((Behavior)spells.get(s)).getParms()).append(";"); } boolean okToProceed = true; ++showNumber[0]; String newVal = null; while(okToProceed) { okToProceed = false; CMLib.genEd().spellsOrBehavs(mob,spells,showNumber[0],showFlag,true); final StringBuffer sameCheck = new StringBuffer(""); for(int s=0;s<spells.size();s++) { sameCheck.append(spells.get(s).ID()).append(';'); if(spells.get(s) instanceof Ability) sameCheck.append(((Ability)spells.get(s)).text()).append(";"); else if(spells.get(s) instanceof Behavior) sameCheck.append(((Behavior)spells.get(s)).getParms()).append(";"); } if(sameCheck.toString().equals(rawCheck.toString())) return oldVal; try { newVal = rebuild(spells); } catch(final CMException e) { mob.tell(e.getMessage()); okToProceed = true; break; } } return (newVal==null)?oldVal:newVal.toString(); } }, new AbilityParmEditorImpl("BUILDING_FLAGS","Flags",ParmType.SPECIAL) { @Override public void createChoices() { } @Override public boolean confirmValue(final String oldVal) { if(oldVal.trim().length()==0) return true; final Pair<String[],String[]> codesFlags = CMAbleParms.getBuildingCodesNFlags(); final String[] names = CMParms.parseSpaces(oldVal, true).toArray(new String[0]); for(final String name : names) { if(!CMParms.containsIgnoreCase(codesFlags.second, name)) return false; } return true; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return ""; } @Override public String[] fakeUserInput(final String oldVal) { return CMParms.parseSpaces(oldVal, true).toArray(new String[0]); } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String webValue = httpReq.getUrlParameter(fieldName); if(webValue == null) return oldVal; final StringBuilder s=new StringBuilder(""); String id=""; int index=0; final Pair<String[],String[]> codesFlags = CMAbleParms.getBuildingCodesNFlags(); for(;httpReq.isUrlParameter(fieldName+id);id=""+(++index)) { final String newVal = httpReq.getUrlParameter(fieldName+id); if(CMParms.containsIgnoreCase(codesFlags.second, newVal.toUpperCase().trim())) s.append(" ").append(newVal.toUpperCase().trim()); } return s.toString().trim(); } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final StringBuffer str = new StringBuffer(""); final String webValue = webValue(httpReq,parms,oldVal,fieldName); String onChange = null; onChange = " MULTIPLE "; if(!parms.containsKey("NOSELECT")) onChange+= "ONCHANGE=\"MultiSelect(this);\""; final Pair<String[],String[]> codesFlags = CMAbleParms.getBuildingCodesNFlags(); final String[] fakeValues = this.fakeUserInput(webValue); str.append("\n\r<SELECT NAME="+fieldName+onChange+">"); for(int i=0;i<codesFlags.second.length;i++) { final String option = (codesFlags.second[i]); str.append("<OPTION VALUE=\""+option+"\" "); if(CMParms.containsIgnoreCase(fakeValues, option)) str.append("SELECTED"); str.append(">"+option); } return str.toString()+"</SELECT>"; } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { final Pair<String[],String[]> codesFlags = CMAbleParms.getBuildingCodesNFlags(); final String help=CMParms.combineWith(Arrays.asList(codesFlags.second), ','); final String newVal = CMLib.genEd().prompt(mob, oldVal, ++showNumber[0], showFlag, L("Flags"), true, help); String[] newVals; if(newVal.indexOf(',')>0) newVals = CMParms.parseCommas(newVal.toUpperCase().trim(), true).toArray(new String[0]); else if(newVal.indexOf(';')>0) newVals = CMParms.parseSemicolons(newVal.toUpperCase().trim(), true).toArray(new String[0]); else newVals = CMParms.parse(newVal.toUpperCase().trim()).toArray(new String[0]); final StringBuilder finalVal = new StringBuilder(""); for(int i=0;i<newVals.length;i++) { if(CMParms.containsIgnoreCase(codesFlags.second, newVals[i])) finalVal.append(" ").append(newVals[i]); } return finalVal.toString().toUpperCase().trim(); } }, new AbilityParmEditorImpl("EXIT_NAMES","Exit Words",ParmType.SPECIAL) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equalsIgnoreCase("DOOR")) return 1; } return -1; } @Override public boolean confirmValue(final String oldVal) { if(oldVal.trim().length()==0) return true; final String[] names = CMParms.parseAny(oldVal.trim(), '|', true).toArray(new String[0]); if(names.length > 5) return false; return true; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return "door|open|close|A closed door.|An open doorway."; } @Override public String[] fakeUserInput(final String oldVal) { final Vector<String> V = new Vector<String>(); V.addAll(CMParms.parseAny(oldVal.trim(), '|', true)); while(V.size()<5) V.add(""); return CMParms.toStringArray(V); } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { if(httpReq.isUrlParameter(fieldName+"_W1")) { final StringBuilder str=new StringBuilder(""); str.append(httpReq.getUrlParameter(fieldName+"_W1")).append("|"); str.append(httpReq.getUrlParameter(fieldName+"_W2")).append("|"); str.append(httpReq.getUrlParameter(fieldName+"_W3")).append("|"); str.append(httpReq.getUrlParameter(fieldName+"_W4")).append("|"); str.append(httpReq.getUrlParameter(fieldName+"_W5")); String s=str.toString(); while(s.endsWith("|")) s=s.substring(0,s.length()-1); return s; } else { return oldVal; } } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final StringBuffer str = new StringBuffer(""); str.append("<TABLE WIDTH=100% BORDER=\"1\" CELLSPACING=0 CELLPADDING=0>"); final String[] vals = this.fakeUserInput(oldVal); final String[] keys = new String[]{"Noun","Open","Close","Closed Display","Open Display"}; for(int i=0;i<keys.length;i++) { str.append("<TR><TD WIDTH=30%><FONT COLOR=WHITE>"+L(keys[i])+"</FONT></TD>"); str.append("<TD><INPUT TYPE=TEXT SIZE=30 NAME="+fieldName+"_W"+(i+1)+" VALUE=\""+vals[i]+"\">"); str.append("</TD></TR>"); } str.append("</TABLE>"); return str.toString(); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { final String[] vals = this.fakeUserInput(oldVal); final StringBuilder newVal = new StringBuilder(""); newVal.append(CMLib.genEd().prompt(mob, vals[0], ++showNumber[0], showFlag, L("Exit Noun"), true)).append("|"); newVal.append(CMLib.genEd().prompt(mob, vals[1], ++showNumber[0], showFlag, L("Open Verb"), true)).append("|"); newVal.append(CMLib.genEd().prompt(mob, vals[2], ++showNumber[0], showFlag, L("Close Verb"), true)).append("|"); newVal.append(CMLib.genEd().prompt(mob, vals[3], ++showNumber[0], showFlag, L("Opened Text"), true)).append("|"); newVal.append(CMLib.genEd().prompt(mob, vals[4], ++showNumber[0], showFlag, L("Closed Text"), true)); String s=newVal.toString(); while(s.endsWith("|")) s=s.substring(0,s.length()-1); return s; } }, new AbilityParmEditorImpl("PCODED_SPELL_LIST","Spell Affects",ParmType.SPECIAL) { @Override public void createChoices() { } @Override public int maxColWidth() { return 20; } @Override public int appliesToClass(final Object o) { if(o instanceof String) { final String chk=((String)o).toUpperCase(); if(chk.equalsIgnoreCase("WALL") ||chk.equalsIgnoreCase("DEMOLISH") ||chk.equalsIgnoreCase("TITLE") ||chk.equalsIgnoreCase("DESC")) return -1; final Pair<String[],String[]> codeFlags = CMAbleParms.getBuildingCodesNFlags(); if(CMParms.contains(codeFlags.first, chk)) return 1; } return -1; } @Override public boolean confirmValue(final String oldVal) { if(oldVal.trim().length()==0) return true; final String[] spells = CMParms.parseAny(oldVal.trim(), ')', true).toArray(new String[0]); for(String spell : spells) { final int x=spell.indexOf('('); if(x>0) spell=spell.substring(0,x); if(spell.trim().length()==0) continue; if((CMClass.getAbility(spell)==null)&&(CMClass.getBehavior(spell)==null)) return false; } return true; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return ""; } public String rebuild(final List<CMObject> spells) throws CMException { final StringBuffer newVal = new StringBuffer(""); for(int s=0;s<spells.size();s++) { final String txt; if(spells.get(s) instanceof Ability) txt = ((Ability)spells.get(s)).text().trim(); else if(spells.get(s) instanceof Behavior) txt = ((Behavior)spells.get(s)).getParms().trim(); else continue; newVal.append(spells.get(s).ID()).append("(").append(txt).append(")"); } return newVal.toString(); } @Override public String[] fakeUserInput(final String oldVal) { final Vector<String> V = new Vector<String>(); final String[] spells = CMParms.parseAny(oldVal.trim(), ')', true).toArray(new String[0]); for(String spell : spells) { final int x=spell.indexOf('('); String parms=""; if(x>0) { parms=spell.substring(x+1).trim(); spell=spell.substring(0,x); } if(spell.trim().length()==0) continue; if((CMClass.getAbility(spell)!=null) ||(CMClass.getBehavior(spell)!=null)) { V.add(spell); V.add(parms); } } return CMParms.toStringArray(V); } public List<CMObject> getCodedSpells(final String oldVal) { final String[] spellStrs = this.fakeUserInput(oldVal); final List<CMObject> spells=new ArrayList<CMObject>(spellStrs.length/2); for(int s=0;s<spellStrs.length;s+=2) { final Ability A=CMClass.getAbility(spellStrs[s]); if(A!=null) { if(spellStrs[s+1].length()>0) A.setMiscText(spellStrs[s+1]); spells.add(A); } else { final Behavior B=CMClass.getBehavior(spellStrs[s]); if(spellStrs[s+1].length()>0) B.setParms(spellStrs[s+1]); spells.add(B); } } return spells; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { List<CMObject> spells=null; if(httpReq.isUrlParameter(fieldName+"_AFFECT1")) { spells = new Vector<CMObject>(); int num=1; String behav=httpReq.getUrlParameter(fieldName+"_AFFECT"+num); String theparm=httpReq.getUrlParameter(fieldName+"_ADATA"+num); while((behav!=null)&&(theparm!=null)) { if(behav.length()>0) { final Ability A=CMClass.getAbility(behav); if(A!=null) { if(theparm.trim().length()>0) A.setMiscText(theparm); spells.add(A); } else { final Behavior B=CMClass.getBehavior(behav); if(theparm.trim().length()>0) B.setParms(theparm); spells.add(B); } } num++; behav=httpReq.getUrlParameter(fieldName+"_AFFECT"+num); theparm=httpReq.getUrlParameter(fieldName+"_ADATA"+num); } } else { spells = getCodedSpells(oldVal); } try { return rebuild(spells); } catch(final Exception e) { return oldVal; } } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final List<CMObject> spells=getCodedSpells(webValue(httpReq,parms,oldVal,fieldName)); final StringBuffer str = new StringBuffer(""); str.append("<TABLE WIDTH=100% BORDER=\"1\" CELLSPACING=0 CELLPADDING=0>"); for(int i=0;i<spells.size();i++) { final CMObject A=spells.get(i); str.append("<TR><TD WIDTH=50%>"); str.append("\n\r<SELECT ONCHANGE=\"EditAffect(this);\" NAME="+fieldName+"_AFFECT"+(i+1)+">"); str.append("<OPTION VALUE=\"\">Delete!"); str.append("<OPTION VALUE=\""+A.ID()+"\" SELECTED>"+A.ID()); str.append("</SELECT>"); str.append("</TD><TD WIDTH=50%>"); final String theparm; if(A instanceof Ability) theparm=CMStrings.replaceAll(((Ability)A).text(),"\"","&quot;"); else if(A instanceof Behavior) theparm=CMStrings.replaceAll(((Behavior)A).getParms(),"\"","&quot;"); else continue; str.append("\n\r<INPUT TYPE=TEXT SIZE=30 NAME="+fieldName+"_ADATA"+(i+1)+" VALUE=\""+theparm+"\">"); str.append("</TD></TR>"); } str.append("<TR><TD WIDTH=50%>"); str.append("\n\r<SELECT ONCHANGE=\"AddAffect(this);\" NAME="+fieldName+"_AFFECT"+(spells.size()+1)+">"); str.append("<OPTION SELECTED VALUE=\"\">Select Effect/Behavior"); for(final Enumeration<Ability> a=CMClass.abilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A.classificationCode()&Ability.ALL_DOMAINS)==Ability.DOMAIN_ARCHON) continue; final String cnam=A.ID(); str.append("<OPTION VALUE=\""+cnam+"\">"+cnam); } for(final Enumeration<Behavior> a=CMClass.behaviors();a.hasMoreElements();) { final Behavior A=a.nextElement(); final String cnam=A.ID(); str.append("<OPTION VALUE=\""+cnam+"\">"+cnam); } str.append("</SELECT>"); str.append("</TD><TD WIDTH=50%>"); str.append("\n\r<INPUT TYPE=TEXT SIZE=30 NAME="+fieldName+"_ADATA"+(spells.size()+1)+" VALUE=\"\">"); str.append("</TD></TR>"); str.append("</TABLE>"); return str.toString(); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { final List<CMObject> spells=getCodedSpells(oldVal); final StringBuffer rawCheck = new StringBuffer(""); for(int s=0;s<spells.size();s++) { rawCheck.append(spells.get(s).ID()).append(";"); if(spells.get(s) instanceof Ability) rawCheck.append(((Ability)spells.get(s)).text()).append(";"); else if(spells.get(s) instanceof Behavior) rawCheck.append(((Behavior)spells.get(s)).getParms()).append(";"); else rawCheck.append(";"); } boolean okToProceed = true; ++showNumber[0]; String newVal = null; while(okToProceed) { okToProceed = false; CMLib.genEd().spellsOrBehaviors(mob,spells,showNumber[0],showFlag,true); final StringBuffer sameCheck = new StringBuffer(""); for(int s=0;s<spells.size();s++) { if(spells.get(s) instanceof Ability) rawCheck.append(((Ability)spells.get(s)).text()).append(";"); else if(spells.get(s) instanceof Behavior) rawCheck.append(((Behavior)spells.get(s)).getParms()).append(";"); else rawCheck.append(";"); } if(sameCheck.toString().equals(rawCheck.toString())) return oldVal; try { newVal = rebuild(spells); } catch(final CMException e) { mob.tell(e.getMessage()); okToProceed = true; break; } } return (newVal==null)?oldVal:newVal.toString(); } }, new AbilityParmEditorImpl("BASE_DAMAGE","Dmg.",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return (o instanceof Weapon) ? 2 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Weapon) return ""+((Weapon)I).basePhyStats().damage(); return "0"; } }, new AbilityParmEditorImpl("LID_LOCK","Lid.",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof Container) ? 1 : -1; } @Override public void createChoices() { createChoices(new String[] { "", "LID", "LOCK" }); } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof Container)) return ""; final Container C=(Container)I; if(C.hasALock()) return "LOCK"; if(C.hasADoor()) return "LID"; return ""; } }, new AbilityParmEditorImpl("BUILDING_CODE","Code",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return 1; } @Override public void createChoices() { createChoices(getBuildingCodesNFlags().first); } @Override public String defaultValue() { return "TITLE"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return "TITLE"; } }, new AbilityParmEditorImpl("STATUE","Statue",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return ((!(o instanceof Armor)) && (!(o instanceof Container)) && (!(o instanceof Drink))) ? 1 : -1; } @Override public void createChoices() { createChoices(new String[] { "", "STATUE" }); } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Weapon) return ""; if(I instanceof Armor) return ""; if(I instanceof Ammunition) return ""; final int x=I.Name().lastIndexOf(" of "); if(x<0) return ""; final String ender=I.Name(); if(!I.displayText().endsWith(ender+" is here")) return ""; if(!I.description().startsWith(ender+". ")) return ""; return "STATUE"; } }, new AbilityParmEditorImpl("RIDE_BASIS","Ride",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof Rideable) ? 3 : -1; } @Override public void createChoices() { createChoices(new String[] { "", "CHAIR", "TABLE", "LADDER", "ENTER", "BED" }); } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof Rideable)) return ""; switch(((Rideable)I).rideBasis()) { case Rideable.RIDEABLE_SIT: return "SIT"; case Rideable.RIDEABLE_TABLE: return "TABLE"; case Rideable.RIDEABLE_LADDER: return "LADDER"; case Rideable.RIDEABLE_ENTERIN: return "ENTER"; case Rideable.RIDEABLE_SLEEP: return "BED"; default: return ""; } } }, new AbilityParmEditorImpl("LIQUID_CAPACITY","Liq.",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return (o instanceof Drink) ? 4 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "25"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof Drink)) return ""; return ""+((Drink)I).liquidHeld(); } }, new AbilityParmEditorImpl("MAX_WAND_USES","Max.",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return (o instanceof Wand) ? 5 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "25"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof Wand)) return ""; return ""+((Wand)I).maxUses(); } }, new AbilityParmEditorImpl("WAND_TYPE","MagicT",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof Wand) ? 2 : -1; } @Override public int minColWidth() { return 3; } @Override public boolean confirmValue(final String oldVal) { if(oldVal==null) return false; if(oldVal.length()==0) return true; return super.confirmValue(oldVal); } @Override public String[] fakeUserInput(final String oldVal) { if((oldVal==null) || (oldVal.length()==0)) return new String[] { "ANY" }; return new String[] { oldVal }; } @Override public void createChoices() { choices = new PairVector<String,String>(); choices.add("ANY", "Any"); for(final String[] set : Wand.WandUsage.WAND_OPTIONS) choices.add(set[0], CMStrings.capitalizeAllFirstLettersAndLower(set[1])); } @Override public String defaultValue() { return "ANY"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Wand) { final int ofType=((Wand)I).getEnchantType(); if((ofType<0)||(ofType>Ability.ACODE_DESCS_.length)) return "ANY"; return Ability.ACODE_DESCS_[ofType]; } return "ANY"; } }, new AbilityParmEditorImpl("DICE_SIDES","Dice.",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { if(o instanceof CMObject) { if(((CMObject)o).ID().endsWith("Dice")) return 1; } return -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "6"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""+I.basePhyStats().ability(); } }, new AbilityParmEditorImpl("WEAPON_CLASS","WClas",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof Weapon) ? 2 : -1; } @Override public void createChoices() { createChoices(Weapon.CLASS_DESCS); } @Override public String defaultValue() { return "BLUNT"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Weapon) return Weapon.CLASS_DESCS[((Weapon)I).weaponClassification()]; return "0"; } }, new AbilityParmEditorImpl("SMOKE_FLAG","Smoke",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof Light) ? 5 : -1; } @Override public void createChoices() { createChoices(new String[] { "", "SMOKE" }); } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof Light)) return ""; if((I instanceof Container) &&(((Light)I).getDuration() > 199) &&(((Container)I).capacity()==0)) return "SMOKE"; return ""; } }, new AbilityParmEditorImpl("WEAPON_HANDS_REQUIRED","Hand",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return (o instanceof Weapon) ? 2 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Weapon) return ((Weapon)I).rawLogicalAnd()?"2":"1"; return ""; } }, new AbilityParmEditorImpl("KEY_VALUE_PARMS","Keys",ParmType.STRINGORNULL) { @Override public int appliesToClass(final Object o) { return 1; } @Override public void createChoices() { } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { // how would I even start.... return ""; } }, new AbilityParmEditorImpl("LIGHT_DURATION","Dur.",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return (o instanceof Light) ? 5 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "10"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Light) return ""+((Light)I).getDuration(); return ""; } }, new AbilityParmEditorImpl("CLAN_ITEM_CODENUMBER","Typ.",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof ClanItem) ? 10 : -1; } @Override public void createChoices() { createNumberedChoices(ClanItem.ClanItemType.ALL); } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof ClanItem) return ""+((ClanItem)I).getClanItemType().ordinal(); return ""; } }, new AbilityParmEditorImpl("CLAN_EXPERIENCE_COST_AMOUNT","Exp",ParmType.NUMBER) { @Override public void createChoices() { } @Override public String defaultValue() { return "100"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof ClanItem)) return "100"; if(I.getClass().getName().toString().indexOf("Flag")>0) return "2500"; if(I.getClass().getName().toString().indexOf("ClanItem")>0) return "1000"; if(I.getClass().getName().toString().indexOf("GenClanSpecialItem")>0) return "500"; return "100"; } }, new AbilityParmEditorImpl("CLAN_AREA_FLAG","Area",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return o.getClass().getName().toString().indexOf("LawBook") > 0 ? 5 : -1; } @Override public void createChoices() { createChoices(new String[] { "", "AREA" }); } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return (I.getClass().getName().toString().indexOf("LawBook")>0)?"AREA":""; } }, new AbilityParmEditorImpl("READABLE_TEXT","Read",ParmType.STRINGORNULL) { @Override public void createChoices() { } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(CMLib.flags().isReadable(I)) return I.readableText(); return ""; } }, new AbilityParmEditorImpl("REQUIRED_COMMON_SKILL_ID","Common Skill",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof ClanItem) ? 5 : -1; } @Override public void createChoices() { final Vector<Object> V = new Vector<Object>(); Ability A = null; for(final Enumeration<Ability> e=CMClass.abilities();e.hasMoreElements();) { A=e.nextElement(); if((A.classificationCode() & Ability.ALL_ACODES) == Ability.ACODE_COMMON_SKILL) V.addElement(A); } V.addElement(""); createChoices(V); } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I.getClass().getName().toString().indexOf("LawBook")>0) return ""; if(I instanceof ClanItem) return ((ClanItem)I).readableText(); return ""; } }, new AbilityParmEditorImpl("FOOD_DRINK","ETyp",ParmType.CHOICES) { @Override public void createChoices() { createChoices(new String[] { "", "FOOD", "DRINK", "SOAP", "GenPerfume" }); } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { final String str=(I.name()+" "+I.displayText()+" "+I.description()).toUpperCase(); if(str.startsWith("SOAP ") || str.endsWith(" SOAP") || (str.indexOf("SOAP")>0)) return "SOAP"; if(I instanceof Perfume) return "PERFUME"; if(I instanceof Food) return "FOOD"; if(I instanceof Drink) return "DRINK"; return ""; } }, new AbilityParmEditorImpl("SMELL_LIST","Smells",ParmType.STRING) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { return (o instanceof Perfume) ? 5 : -1; } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Perfume) return ((Perfume)I).getSmellList(); return ""; } }, new AbilityParmEditorImpl("RESOURCE_OR_KEYWORD","Resc/Itm",ParmType.SPECIAL) { @Override public void createChoices() { } @Override public boolean confirmValue(final String oldVal) { return true; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { if(httpReq.isUrlParameter(fieldName+"_WHICH")) { final String which=httpReq.getUrlParameter(fieldName+"_WHICH"); if(which.trim().length()>0) return httpReq.getUrlParameter(fieldName+"_RESOURCE"); return httpReq.getUrlParameter(fieldName+"_WORD"); } return oldVal; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { String value=webValue(httpReq,parms,oldVal,fieldName); if(value.endsWith("$")) value = value.substring(0,oldVal.length()-1); value = value.trim(); final StringBuffer str = new StringBuffer(""); str.append("\n\r<INPUT TYPE=RADIO NAME="+fieldName+"_WHICH "); final boolean rsc=(value.trim().length()==0)||(RawMaterial.CODES.FIND_IgnoreCase(value)>=0); if(rsc) str.append("CHECKED "); str.append("VALUE=\"RESOURCE\">"); str.append("\n\r<SELECT NAME="+fieldName+"_RESOURCE>"); final String[] Ss=RawMaterial.CODES.NAMES().clone(); Arrays.sort(Ss); for(final String S : Ss) { final String VALUE = S.equals("NOTHING")?"":S; str.append("<OPTION VALUE=\""+VALUE+"\""); if(rsc&&(value.equalsIgnoreCase(VALUE))) str.append(" SELECTED"); str.append(">"+CMStrings.capitalizeAndLower(S)); } str.append("</SELECT>"); str.append("<BR>"); str.append("\n\r<INPUT TYPE=RADIO NAME="+fieldName+"_WHICH "); if(!rsc) str.append("CHECKED "); str.append("VALUE=\"\">"); str.append("\n\r<INPUT TYPE=TEXT NAME="+fieldName+"_WORD VALUE=\""+(rsc?"":value)+"\">"); return str.toString(); } @Override public String[] fakeUserInput(final String oldVal) { return new String[] { oldVal }; } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { ++showNumber[0]; boolean proceed = true; String str = oldVal; while(proceed&&(!mob.session().isStopped())) { proceed = false; str=CMLib.genEd().prompt(mob,oldVal,showNumber[0],showFlag,prompt(),true,CMParms.toListString(RawMaterial.CODES.NAMES())).trim(); if(str.equals(oldVal)) return oldVal; final int r=RawMaterial.CODES.FIND_IgnoreCase(str); if(r==0) str=""; else if(r>0) str=RawMaterial.CODES.NAME(r); if(str.equals(oldVal)) return oldVal; if(str.length()==0) return ""; final boolean isResource = CMParms.contains(RawMaterial.CODES.NAMES(),str); if((!isResource)&&(mob.session()!=null)&&(!mob.session().isStopped())) if(!mob.session().confirm(L("You`ve entered a non-resource item keyword '@x1', ok (Y/n)?",str),"Y")) proceed = true; } return str; } @Override public String defaultValue() { return ""; } }, new AbilityParmEditorImpl("RESOURCE_NAME_OR_HERB_NAME","Resrc/Herb",ParmType.SPECIAL) { @Override public void createChoices() { } @Override public boolean confirmValue(final String oldVal) { if(oldVal.trim().length()==0) return true; if(!oldVal.endsWith("$")) { return CMParms.contains(RawMaterial.CODES.NAMES(),oldVal); } return true; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String[] fakeUserInput(final String oldVal) { if(oldVal.endsWith("$")) return new String[]{oldVal.substring(0,oldVal.length()-1)}; return new String[]{oldVal}; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, String oldVal, final String fieldName) { final AbilityParmEditor A = CMLib.ableParms().getEditors().get("RESOURCE_OR_KEYWORD"); if(oldVal.endsWith("$")) oldVal = oldVal.substring(0,oldVal.length()-1); final String value = A.webValue(httpReq,parms,oldVal,fieldName); final int r=RawMaterial.CODES.FIND_IgnoreCase(value); if(r>=0) return RawMaterial.CODES.NAME(r); return (value.trim().length()==0)?"":(value+"$"); } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final AbilityParmEditor A = CMLib.ableParms().getEditors().get("RESOURCE_OR_KEYWORD"); return A.webField(httpReq,parms,oldVal,fieldName); } @Override public String webTableField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal) { if(oldVal.endsWith("$")) return oldVal.substring(0,oldVal.length()-1); return oldVal; } @Override public String commandLinePrompt(final MOB mob, String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { ++showNumber[0]; boolean proceed = true; String str = oldVal; final String orig = oldVal; while(proceed&&(!mob.session().isStopped())) { proceed = false; if(oldVal.trim().endsWith("$")) oldVal=oldVal.trim().substring(0,oldVal.trim().length()-1); str=CMLib.genEd().prompt(mob,oldVal,showNumber[0],showFlag,prompt(),true,CMParms.toListString(RawMaterial.CODES.NAMES())).trim(); if(str.equals(orig)) return orig; final int r=RawMaterial.CODES.FIND_IgnoreCase(str); if(r==0) str=""; else if(r>0) str=RawMaterial.CODES.NAME(r); if(str.equals(orig)) return orig; if(str.length()==0) return ""; final boolean isResource = CMParms.contains(RawMaterial.CODES.NAMES(),str); if((!isResource)&&(mob.session()!=null)&&(!mob.session().isStopped())) { if(!mob.session().confirm(L("You`ve entered a non-resource item keyword '@x1', ok (Y/n)?",str),"Y")) proceed = true; else str=str+"$"; } } return str; } @Override public String defaultValue() { return ""; } }, new AbilityParmEditorImpl("AMMO_TYPE","Ammo",ParmType.STRING) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { return ((o instanceof Weapon) || (o instanceof Ammunition)) ? 2 : -1; } @Override public String defaultValue() { return "arrows"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Ammunition) return ""+((Ammunition)I).ammunitionType(); return ""; } }, new AbilityParmEditorImpl("AMMO_CAPACITY","Ammo#",ParmType.NUMBER) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { return ((o instanceof Weapon) || (o instanceof Ammunition)) ? 2 : -1; } @Override public String defaultValue() { return "1"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Ammunition) return ""+((Ammunition)I).ammunitionRemaining(); if((I instanceof AmmunitionWeapon)&&(((AmmunitionWeapon)I).requiresAmmunition())) return ""+((AmmunitionWeapon)I).ammunitionCapacity(); return ""; } }, new AbilityParmEditorImpl("MAXIMUM_RANGE","Max",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { return ((o instanceof Weapon) && (!(o instanceof Ammunition))) ? 2 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return "5"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Weapon) return ""+((Weapon)I).getRanges()[1]; else if(I instanceof Ammunition) return ""+I.maxRange(); return ""; } }, new AbilityParmEditorImpl("RESOURCE_OR_MATERIAL","Rsc/ Mat",ParmType.CHOICES) { @Override public void createChoices() { final XVector<String> V=new XVector<String>(RawMaterial.CODES.NAMES()); Collections.sort(V); final XVector<String> V2=new XVector<String>(RawMaterial.Material.names()); Collections.sort(V2); V.addAll(V2); createChoices(V); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(CMStrings.containsWordIgnoreCase(I.Name(),"rice")) return "RICE"; if(I.material() == RawMaterial.RESOURCE_PAPER) return "WOOD"; return RawMaterial.CODES.NAME(I.material()); } @Override public String defaultValue() { return "IRON"; } }, new AbilityParmEditorImpl("REQ_RESOURCE_OR_MATERIAL","Rsc/ Mat",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { if(o instanceof RawMaterial) return 1; return -1; } @Override public void createChoices() { final XVector<String> V=new XVector<String>(RawMaterial.CODES.NAMES()); Collections.sort(V); final XVector<String> V2=new XVector<String>(RawMaterial.Material.names()); Collections.sort(V2); V.addAll(V2); createChoices(V); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(CMStrings.containsWordIgnoreCase(I.Name(),"rice")) return "RICE"; if(I.material() == RawMaterial.RESOURCE_PAPER) return "WOOD"; return RawMaterial.CODES.NAME(I.material()); } @Override public String defaultValue() { return "IRON"; } }, new AbilityParmEditorImpl("OPTIONAL_RESOURCE_OR_MATERIAL","Rsc/ Mat",ParmType.CHOICES) { @Override public void createChoices() { final XVector<String> V=new XVector<String>(RawMaterial.CODES.NAMES()); Collections.sort(V); final XVector<String> V2=new XVector<String>(RawMaterial.Material.names()); Collections.sort(V2); V.addAll(V2); V.addElement(""); createChoices(V); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public String defaultValue() { return ""; } }, new AbilityParmEditorImpl("OPTIONAL_RESOURCE_OR_MATERIAL_AMT","Rsc Amt",ParmType.NUMBER) { @Override public int appliesToClass(final Object o) { if(o instanceof Wand) return 1; return ((o instanceof Weapon) && (!(o instanceof Ammunition))) ? 2 : -1; } @Override public void createChoices() { } @Override public String defaultValue() { return ""; } @Override public boolean confirmValue(final String oldVal) { if(oldVal.trim().length()==0) return true; return CMath.isInteger(oldVal); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I==null) return ""; final List<String> words=CMParms.parse(I.name()); for(int i=words.size()-1;i>=0;i--) { final String s=words.get(i); final int y=s.indexOf('-'); if(y>=0) { words.add(s.substring(0, y)); words.add(s.substring(0, y+1)); } } for(final String word : words) { if(word.length()>0) { final int rsc=RawMaterial.CODES.FIND_IgnoreCase(word); if((rsc > 0)&&(rsc != I.material())) { if(I.basePhyStats().level()>80) return ""+4; if(I.basePhyStats().level()>40) return ""+2; return ""+1; } } } return ""; } }, new AbilityParmEditorImpl("OPTIONAL_BUILDING_RESOURCE_OR_MATERIAL","Rsc/ Mat",ParmType.CHOICES) { @Override public void createChoices() { final XVector<String> V=new XVector<String>(RawMaterial.CODES.NAMES()); Collections.sort(V); final XVector<String> V2=new XVector<String>(RawMaterial.Material.names()); Collections.sort(V2); V.addAll(V2); V.addElement("VALUE"); V.addElement("MONEY"); V.addElement(""); createChoices(V); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { final List<String> words=CMParms.parse(I.name()); for(int i=words.size()-1;i>=0;i--) { final String s=words.get(i); final int y=s.indexOf('-'); if(y>=0) { words.add(s.substring(0, y)); words.add(s.substring(0, y+1)); } } for(final String word : words) { if(word.length()>0) { final int rsc=RawMaterial.CODES.FIND_IgnoreCase(word); if((rsc > 0)&&(rsc != I.material())) return RawMaterial.CODES.NAME(rsc); } } return ""; } @Override public String defaultValue() { return ""; } }, new AbilityParmEditorImpl("HERB_NAME","Herb Final Name",ParmType.STRING) { @Override public void createChoices() { } @Override public String defaultValue() { return "Herb Name"; } @Override public int minColWidth() { return 10; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I.material()==RawMaterial.RESOURCE_HERBS) return CMStrings.lastWordIn(I.Name()); return ""; } }, new AbilityParmEditorImpl("FLOWER_NAME","Flower Final Name",ParmType.STRING) { @Override public void createChoices() { } @Override public String defaultValue() { return "Flower Name"; } @Override public int minColWidth() { return 10; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I.material()==RawMaterial.RESOURCE_FLOWERS) return CMStrings.lastWordIn(I.Name()); return ""; } }, new AbilityParmEditorImpl("RIDE_CAPACITY","Ridrs",ParmType.NUMBER) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { return (o instanceof Rideable) ? 3 : -1; } @Override public String defaultValue() { return "2"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof Rideable) return ""+((Rideable)I).riderCapacity(); return "0"; } }, new AbilityParmEditorImpl("METAL_OR_WOOD","Metal",ParmType.CHOICES) { @Override public void createChoices() { createChoices(new String[] { "METAL", "WOOD" }); } @Override public String defaultValue() { return "METAL"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { switch(I.material()&RawMaterial.MATERIAL_MASK) { case RawMaterial.MATERIAL_METAL: case RawMaterial.MATERIAL_MITHRIL: return "METAL"; case RawMaterial.MATERIAL_WOODEN: return "WOOD"; } return ""; // absolutely no way to determine } }, new AbilityParmEditorImpl("OPTIONAL_RACE_ID","Race",ParmType.SPECIAL) { @Override public void createChoices() { createChoices(CMClass.races()); choices().add("",""); for(int x=0;x<choices().size();x++) choices().get(x).first = choices().get(x).first.toUpperCase(); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; // absolutely no way to determine } @Override public String defaultValue() { return ""; } @Override public boolean confirmValue(final String oldVal) { if(oldVal.trim().length()==0) return true; final Vector<String> parsedVals = CMParms.parse(oldVal.toUpperCase()); for(int v=0;v<parsedVals.size();v++) { if(CMClass.getRace(parsedVals.elementAt(v))==null) return false; } return true; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { Vector<String> raceIDs=null; if(httpReq.isUrlParameter(fieldName+"_RACE")) { String id=""; raceIDs=new Vector<String>(); for(int i=0;httpReq.isUrlParameter(fieldName+"_RACE"+id);id=""+(++i)) raceIDs.addElement(httpReq.getUrlParameter(fieldName+"_RACE"+id).toUpperCase().trim()); } else raceIDs = CMParms.parse(oldVal.toUpperCase().trim()); return CMParms.combine(raceIDs,0); } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final Vector<String> raceIDs=CMParms.parse(webValue(httpReq,parms,oldVal,fieldName).toUpperCase()); final StringBuffer str = new StringBuffer(""); str.append("\n\r<SELECT NAME="+fieldName+"_RACE MULTIPLE>"); str.append("<OPTION VALUE=\"\" "+((raceIDs.size()==0)?"SELECTED":"")+">"); for(final Enumeration<Race> e=CMClass.races();e.hasMoreElements();) { final Race R=e.nextElement(); str.append("<OPTION VALUE=\""+R.ID()+"\" "+((raceIDs.contains(R.ID().toUpperCase()))?"SELECTED":"")+">"+R.name()); } str.append("</SELECT>"); return str.toString(); } @Override public String[] fakeUserInput(final String oldVal) { final Vector<String> parsedVals = CMParms.parse(oldVal.toUpperCase()); if(parsedVals.size()==0) return new String[]{""}; final Vector<String> races = new Vector<String>(); for(int p=0;p<parsedVals.size();p++) { final Race R=CMClass.getRace(parsedVals.elementAt(p)); races.addElement(R.name()); } for(int p=0;p<parsedVals.size();p++) { final Race R=CMClass.getRace(parsedVals.elementAt(p)); races.addElement(R.name()); } races.addElement(""); return CMParms.toStringArray(races); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { if((showFlag>0)&&(showFlag!=showNumber[0])) return oldVal; String behave="NO"; String newVal = oldVal; while((mob.session()!=null)&&(!mob.session().isStopped())&&(behave.length()>0)) { mob.tell(showNumber+". "+prompt()+": '"+newVal+"'."); if((showFlag!=showNumber[0])&&(showFlag>-999)) return newVal; final Vector<String> parsedVals = CMParms.parse(newVal.toUpperCase()); behave=mob.session().prompt(L("Enter a race to add/remove (?)\n\r:"),""); if(behave.length()>0) { if(behave.equalsIgnoreCase("?")) mob.tell(CMLib.lister().reallyList(mob,CMClass.races(),-1).toString()); else { final Race R=CMClass.getRace(behave); if(R!=null) { if(parsedVals.contains(R.ID().toUpperCase())) { mob.tell(L("'@x1' removed.",behave)); parsedVals.remove(R.ID().toUpperCase().trim()); newVal = CMParms.combine(parsedVals,0); } else { mob.tell(L("@x1 added.",R.ID())); parsedVals.addElement(R.ID().toUpperCase()); newVal = CMParms.combine(parsedVals,0); } } else { mob.tell(L("'@x1' is not a recognized race. Try '?'.",behave)); } } } else { if(oldVal.equalsIgnoreCase(newVal)) mob.tell(L("(no change)")); } } return newVal; } }, new AbilityParmEditorImpl("INSTRUMENT_TYPE","Instrmnt",ParmType.CHOICES) { @Override public void createChoices() { createChoices(MusicalInstrument.InstrumentType.valueNames()); } @Override public int appliesToClass(final Object o) { return (o instanceof MusicalInstrument) ? 5 : -1; } @Override public String defaultValue() { return "DRUMS"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I instanceof MusicalInstrument) return ((MusicalInstrument)I).getInstrumentTypeName(); return "0"; } }, new AbilityParmEditorImpl("STONE_FLAG","Stone",ParmType.CHOICES) { @Override public void createChoices() { createChoices(new String[] { "", "STONE" }); } @Override public int appliesToClass(final Object o) { return (o instanceof RawMaterial) ? 5 : -1; } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(I.material()==RawMaterial.RESOURCE_STONE) return "STONE"; return ""; } }, new AbilityParmEditorImpl("POSE_NAME","Pose Word",ParmType.ONEWORD) { @Override public void createChoices() { } @Override public String defaultValue() { return "New Post"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } }, new AbilityParmEditorImpl("POSE_DESCRIPTION","Pose Description",ParmType.STRING) { @Override public void createChoices() { } @Override public String defaultValue() { return "<S-NAME> is standing here."; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { if(!(I instanceof DeadBody)) return ""; String pose=I.displayText(); pose=CMStrings.replaceAll(pose,I.name(),"<S-NAME>"); pose=CMStrings.replaceWord(pose,"himself"," <S-HIM-HERSELF>"); pose=CMStrings.replaceWord(pose,"herself"," <S-HIM-HERSELF>"); pose=CMStrings.replaceWord(pose,"his"," <S-HIS-HER>"); pose=CMStrings.replaceWord(pose,"her"," <S-HIS-HER>"); pose=CMStrings.replaceWord(pose,"him"," <S-HIM-HER>"); pose=CMStrings.replaceWord(pose,"her"," <S-HIM-HER>"); return pose; } }, new AbilityParmEditorImpl("WOOD_METAL_CLOTH","",ParmType.CHOICES) { @Override public void createChoices() { createChoices(new String[] { "WOOD", "METAL", "CLOTH" }); } @Override public String defaultValue() { return "WOOD"; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { switch(I.material()&RawMaterial.MATERIAL_MASK) { case RawMaterial.MATERIAL_CLOTH: return "CLOTH"; case RawMaterial.MATERIAL_METAL: return "METAL"; case RawMaterial.MATERIAL_MITHRIL: return "METAL"; case RawMaterial.MATERIAL_WOODEN: return "WOOD"; default: return ""; } } }, new AbilityParmEditorImpl("WEAPON_TYPE","W.Type",ParmType.CHOICES) { @Override public int appliesToClass(final Object o) { return (o instanceof Weapon) ? 2 : -1; } @Override public void createChoices() { createChoices(Weapon.TYPE_DESCS); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return (I instanceof Weapon) ? Weapon.TYPE_DESCS[((Weapon) I).weaponDamageType()] : ""; } @Override public String defaultValue() { return "BASHING"; } }, new AbilityParmEditorImpl("ATTACK_MODIFICATION","Att.",ParmType.NUMBER) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { return (o instanceof Weapon) ? 2 : -1; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return "" + ((I instanceof Weapon) ? ((Weapon) I).basePhyStats().attackAdjustment() : 0); } @Override public String defaultValue() { return "0"; } }, new AbilityParmEditorImpl("N_A","N/A",ParmType.STRING) { @Override public void createChoices() { } @Override public int appliesToClass(final Object o) { return -1; } @Override public String defaultValue() { return ""; } @Override public String convertFromItem(final ItemCraftor A, final Item I) { return ""; } @Override public boolean confirmValue(final String oldVal) { return oldVal.trim().length() == 0 || oldVal.equals("0") || oldVal.equals("NA") || oldVal.equals("-"); } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { return ""; } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String, String> parms, final String oldVal, final String fieldName) { return ""; } }, new AbilityParmEditorImpl("RESOURCE_NAME_AMOUNT_MATERIAL_REQUIRED","Resrc/Amt",ParmType.SPECIAL) { @Override public void createChoices() { createChoices(RawMaterial.CODES.NAMES()); choices().add("",""); } @Override public String convertFromItem(final ItemCraftor A, final Item I) { int amt=(int)Math.round(CMath.mul(I.basePhyStats().weight()-1,(A!=null)?A.getItemWeightMultiplier(false):1.0)); if(amt<1) amt=1; return RawMaterial.CODES.NAME(I.material())+"/"+amt; } @Override public String defaultValue() { return ""; } @Override public int appliesToClass(final Object o) { return 0; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { if(httpReq.isUrlParameter(fieldName+"_RESOURCE")) { final String rsc=httpReq.getUrlParameter(fieldName+"_RESOURCE"); final String amt=httpReq.getUrlParameter(fieldName+"_AMOUNT"); if((rsc.trim().length()==0)||(rsc.equalsIgnoreCase("NOTHING"))||(CMath.s_int(amt)<=0)) return ""; return rsc+"/"+amt; } return oldVal; } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String value=webValue(httpReq,parms,oldVal,fieldName); String rsc = ""; int amt = 0; final int x=value.indexOf('/'); if(x>0) { rsc = value.substring(0,x); amt = CMath.s_int(value.substring(x+1)); } final StringBuffer str=new StringBuffer(""); str.append("\n\r<SELECT NAME="+fieldName+"_RESOURCE MULTIPLE>"); final String[] Ss=RawMaterial.CODES.NAMES().clone(); Arrays.sort(Ss); for(final String S : Ss) { str.append("<OPTION VALUE=\""+S+"\" " +((S.equalsIgnoreCase(rsc))?"SELECTED":"")+">" +CMStrings.capitalizeAndLower(S)); } str.append("</SELECT>"); str.append("&nbsp;&nbsp;Amount: "); str.append("<INPUT TYPE=TEXT NAME="+fieldName+"_AMOUNT VALUE="+amt+">"); return str.toString(); } @Override public boolean confirmValue(String oldVal) { if(oldVal.trim().length()==0) return true; oldVal=oldVal.trim(); final int x=oldVal.indexOf('/'); if(x<0) return false; if(!CMStrings.contains(choices().toArrayFirst(new String[0]),oldVal.substring(0,x))) return false; if(!CMath.isInteger(oldVal.substring(x+1))) return false; return true; } @Override public String[] fakeUserInput(final String oldVal) { final int x=oldVal.indexOf('/'); if(x<=0) return new String[]{""}; return new String[]{oldVal.substring(0,x),oldVal.substring(x+1)}; } @Override public String commandLinePrompt(final MOB mob, String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { oldVal=oldVal.trim(); final int x=oldVal.indexOf('/'); String oldRsc = ""; int oldAmt = 0; if(x>0) { oldRsc = oldVal.substring(0,x); oldAmt = CMath.s_int(oldVal.substring(x)); } oldRsc = CMLib.genEd().prompt(mob,oldRsc,++showNumber[0],showFlag,prompt(),choices()); if(oldRsc.length()>0) return oldRsc+"/"+CMLib.genEd().prompt(mob,oldAmt,++showNumber[0],showFlag,prompt()); return ""; } }, }); DEFAULT_EDITORS = new Hashtable<String,AbilityParmEditor>(); for(int v=0;v<V.size();v++) { final AbilityParmEditor A = V.elementAt(v); DEFAULT_EDITORS.put(A.ID(),A); } return DEFAULT_EDITORS; } protected class AbilityRecipeDataImpl implements AbilityRecipeData { private String recipeFilename; private String recipeFormat; private Vector<Object> columns; private Vector<DVector> dataRows; private int numberOfDataColumns; public String[] columnHeaders; public int[] columnLengths; public int classFieldIndex; private String parseError = null; private boolean wasVFS = false; public AbilityRecipeDataImpl(final String recipeFilename, final String recipeFormat) { this.recipeFilename = recipeFilename; this.recipeFormat = recipeFormat; if(recipeFilename.trim().length()==0) { parseError = "No file"; return; } final CMFile F = new CMFile(Resources.buildResourcePath("skills")+recipeFilename,null,CMFile.FLAG_LOGERRORS); wasVFS=F.isVFSFile(); final StringBuffer str=F.text(); columns = parseRecipeFormatColumns(recipeFormat); numberOfDataColumns = 0; for(int c = 0; c < columns.size(); c++) { if(columns.elementAt(c) instanceof List) numberOfDataColumns++; } dataRows = null; try { dataRows = parseDataRows(str,columns,numberOfDataColumns); final DVector editRow = new DVector(2); for(int c=0;c<columns().size();c++) { if(columns().elementAt(c) instanceof List) editRow.addElement(columns().elementAt(c),""); } if(editRow.size()==0) { //classFieldIndex = CMAbleParms.getClassFieldIndex(dataRow); } else classFieldIndex = CMAbleParms.getClassFieldIndex(editRow); fixDataColumns(dataRows); } catch(final CMException e) { parseError = e.getMessage(); return; } columnLengths = new int[numberOfDataColumns]; columnHeaders = new String[numberOfDataColumns]; calculateRecipeCols(columnLengths,columnHeaders,dataRows); } @Override public boolean wasVFS() { return wasVFS; } @Override public DVector newRow(final String classFieldData) { final DVector editRow = blankRow(); final int keyIndex =classFieldIndex; if((keyIndex>=0)&&(classFieldData!=null)) { editRow.setElementAt(keyIndex,2,classFieldData); } try { fixDataColumn(editRow,-1); } catch (final CMException cme) { return null; } for(int i=0;i<editRow.size();i++) { if(i!=keyIndex) { final AbilityParmEditor A = getEditors().get(editRow.elementAt(i,1)); editRow.setElementAt(i,2,A.defaultValue()); } } return editRow; } @Override public DVector blankRow() { final DVector editRow = new DVector(2); for(int c=0;c<columns().size();c++) { if(columns().elementAt(c) instanceof List) editRow.addElement(columns().elementAt(c),""); } return editRow; } @Override public int getClassFieldIndex() { return classFieldIndex; } @Override public String recipeFilename() { return recipeFilename; } @Override public String recipeFormat() { return recipeFormat; } @Override public Vector<DVector> dataRows() { return dataRows; } @Override public Vector<? extends Object> columns() { return columns; } @Override public int[] columnLengths() { return columnLengths; } @Override public String[] columnHeaders() { return columnHeaders; } @Override public int numberOfDataColumns() { return numberOfDataColumns; } @Override public String parseError() { return parseError; } } protected abstract class AbilityParmEditorImpl implements AbilityParmEditor { private final String ID; private final ParmType fieldType; private String prompt = null; private String header = null; protected PairList<String, String> choices = null; public AbilityParmEditorImpl(final String fieldName, final String shortHeader, final ParmType type) { ID=fieldName; fieldType = type; header = shortHeader; prompt = CMStrings.capitalizeAndLower(CMStrings.replaceAll(ID,"_"," ")); createChoices(); } @Override public String ID() { return ID; } @Override public ParmType parmType() { return fieldType; } @Override public String prompt() { return prompt; } @Override public String colHeader() { return header; } @Override public int maxColWidth() { return Integer.MAX_VALUE; } @Override public int minColWidth() { return 0; } @Override public boolean confirmValue(final String oldVal) { final boolean spaceOK = fieldType != ParmType.ONEWORD; boolean emptyOK = false; switch(fieldType) { case STRINGORNULL: emptyOK = true; //$FALL-THROUGH$ case ONEWORD: case STRING: { if((!spaceOK) && (oldVal.indexOf(' ') >= 0)) return false; return (emptyOK)||(oldVal.trim().length()>0); } case NUMBER: return CMath.isInteger(oldVal); case CHOICES: if(!CMStrings.contains(choices.toArrayFirst(new String[0]),oldVal)) return CMStrings.contains(choices.toArrayFirst(new String[0]),oldVal.toUpperCase().trim()); return true; case MULTICHOICES: return CMath.isInteger(oldVal)||choices().containsFirst(oldVal); case SPECIAL: break; } return false; } @Override public String[] fakeUserInput(final String oldVal) { boolean emptyOK = false; switch(fieldType) { case STRINGORNULL: emptyOK = true; //$FALL-THROUGH$ case ONEWORD: case STRING: { if(emptyOK && (oldVal.trim().length()==0)) return new String[]{"NULL"}; return new String[]{oldVal}; } case NUMBER: return new String[]{oldVal}; case CHOICES: { if(oldVal.trim().length()==0) return new String[]{"NULL"}; final Vector<String> V = new XVector<String>(choices.toArrayFirst(new String[0])); for(int v=0;v<V.size();v++) { if(oldVal.equalsIgnoreCase(V.elementAt(v))) return new String[]{choices.get(v).second}; } return new String[]{oldVal}; } case MULTICHOICES: if(oldVal.trim().length()==0) return new String[]{"NULL"}; if(!CMath.isInteger(oldVal)) { final Vector<String> V = new XVector<String>(choices.toArrayFirst(new String[0])); for(int v=0;v<V.size();v++) { if(oldVal.equalsIgnoreCase(V.elementAt(v))) return new String[]{choices.get(v).second,""}; } } else { final Vector<String> V = new Vector<String>(); for(int c=0;c<choices.size();c++) { if(CMath.bset(CMath.s_int(oldVal),CMath.s_int(choices.get(c).first))) { V.addElement(choices.get(c).second); V.addElement(choices.get(c).second); } } if(V.size()>0) { V.addElement(""); return CMParms.toStringArray(V); } } return new String[]{"NULL"}; case SPECIAL: break; } return new String[]{}; } @Override public String commandLinePrompt(final MOB mob, final String oldVal, final int[] showNumber, final int showFlag) throws java.io.IOException { String str = null; boolean emptyOK = false; final boolean spaceOK = fieldType != ParmType.ONEWORD; switch(fieldType) { case STRINGORNULL: emptyOK = true; //$FALL-THROUGH$ case ONEWORD: case STRING: { ++showNumber[0]; boolean proceed = true; while(proceed&&(!mob.session().isStopped())) { str = CMLib.genEd().prompt(mob,oldVal,showNumber[0],showFlag,prompt(),emptyOK).trim(); if((!spaceOK) && (str.indexOf(' ') >= 0)) mob.tell(L("Spaces are not allowed here.")); else proceed=false; } break; } case NUMBER: { final String newStr=CMLib.genEd().prompt(mob,oldVal,++showNumber[0],showFlag,prompt(),true); if(newStr.trim().length()==0) str=""; else str = Integer.toString(CMath.s_int(newStr)); break; } case CHOICES: str = CMLib.genEd().promptMultiOrExtra(mob,oldVal,++showNumber[0],showFlag,prompt(),choices); break; case MULTICHOICES: str = CMLib.genEd().promptMultiOrExtra(mob,oldVal,++showNumber[0],showFlag,prompt(),choices); if(CMath.isInteger(str)) str = Integer.toString(CMath.s_int(str)); break; case SPECIAL: break; } return str; } @Override public String webValue(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { final String webValue = httpReq.getUrlParameter(fieldName); switch(fieldType) { case ONEWORD: case STRINGORNULL: case STRING: case NUMBER: return (webValue == null)?oldVal:webValue; case MULTICHOICES: { if(webValue == null) return oldVal; String id=""; long num=0; int index=0; for(;httpReq.isUrlParameter(fieldName+id);id=""+(++index)) { final String newVal = httpReq.getUrlParameter(fieldName+id); if(CMath.s_long(newVal)<=0) return newVal; num |= CMath.s_long(newVal); } return ""+num; } case CHOICES: return (webValue == null)?oldVal:webValue; case SPECIAL: break; } return ""; } @Override public String webTableField(final HTTPRequest httpReq, final java.util.Map<String, String> parms, final String oldVal) { return oldVal; } @Override public String webField(final HTTPRequest httpReq, final java.util.Map<String,String> parms, final String oldVal, final String fieldName) { int textSize = 50; final String webValue = webValue(httpReq,parms,oldVal,fieldName); String onChange = null; final Vector<String> choiceValues = new Vector<String>(); switch(fieldType) { case ONEWORD: textSize = 10; //$FALL-THROUGH$ case STRINGORNULL: case STRING: return "\n\r<INPUT TYPE=TEXT NAME=" + fieldName + " SIZE=" + textSize + " VALUE=\"" + webValue + "\">"; case NUMBER: return "\n\r<INPUT TYPE=TEXT NAME=" + fieldName + " SIZE=10 VALUE=\"" + webValue + "\">"; case MULTICHOICES: { onChange = " MULTIPLE "; if(!parms.containsKey("NOSELECT")) onChange+= "ONCHANGE=\"MultiSelect(this);\""; if(CMath.isInteger(webValue)) { final int bits = CMath.s_int(webValue); for(int i=0;i<choices.size();i++) { final int bitVal =CMath.s_int(choices.get(i).first); if((bitVal>0)&&(CMath.bset(bits,bitVal))) choiceValues.addElement(choices.get(i).first); } } } //$FALL-THROUGH$ case CHOICES: { if(choiceValues.size()==0) choiceValues.addElement(webValue); if((onChange == null)&&(!parms.containsKey("NOSELECT"))) onChange = " ONCHANGE=\"Select(this);\""; else if(onChange==null) onChange=""; final StringBuffer str= new StringBuffer(""); str.append("\n\r<SELECT NAME="+fieldName+onChange+">"); for(int i=0;i<choices.size();i++) { final String option = (choices.get(i).first); str.append("<OPTION VALUE=\""+option+"\" "); for(int c=0;c<choiceValues.size();c++) { if(option.equalsIgnoreCase(choiceValues.elementAt(c))) str.append("SELECTED"); } str.append(">"+(choices.get(i).second)); } return str.toString()+"</SELECT>"; } case SPECIAL: break; } return ""; } public abstract void createChoices(); @Override public PairList<String,String> createChoices(final Enumeration<? extends Object> e) { if(choices != null) return choices; choices = new PairVector<String,String>(); Object o = null; for(;e.hasMoreElements();) { o = e.nextElement(); if(o instanceof String) choices.add((String)o,CMStrings.capitalizeAndLower((String)o)); else if(o instanceof Ability) choices.add(((Ability)o).ID(),((Ability)o).name()); else if(o instanceof Race) choices.add(((Race)o).ID(),((Race)o).name()); else if(o instanceof Environmental) choices.add(((Environmental)o).ID(),((Environmental)o).ID()); } return choices; } @SuppressWarnings("unchecked") @Override public PairList<String,String> createChoices(final List<? extends Object> V) { return createChoices(new IteratorEnumeration<Object>((Iterator<Object>)V.iterator())); } @Override public PairList<String,String> createChoices(final String[] S) { final XVector<String> X=new XVector<String>(S); Collections.sort(X); return createChoices(X.elements()); } public PairList<String,String> createBinaryChoices(final String[] S) { if(choices != null) return choices; choices = createChoices(new XVector<String>(S).elements()); for(int i=0;i<choices.size();i++) { if(i==0) choices.get(i).first =Integer.toString(0); else choices.get(i).first = Integer.toString(1<<(i-1)); } return choices; } public PairList<String,String> createNumberedChoices(final String[] S) { if(choices != null) return choices; choices = createChoices(new XVector<String>(S).elements()); for(int i=0;i<choices.size();i++) choices.get(i).first = Integer.toString(i); return choices; } @Override public PairList<String, String> choices() { return choices; } @Override public int appliesToClass(final Object o) { return 0; } } }
Fix for learning ammunition based weapons. git-svn-id: 0cdf8356e41b2d8ccbb41bb76c82068fe80b2514@19656 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/Libraries/CMAbleParms.java
Fix for learning ammunition based weapons.
<ide><path>om/planet_ink/coffee_mud/Libraries/CMAbleParms.java <ide> @Override <ide> public int appliesToClass(final Object o) <ide> { <del> return ((o instanceof Weapon) || (o instanceof Ammunition)) ? 2 : -1; <add> return ((o instanceof AmmunitionWeapon) || (o instanceof Ammunition)) ? 2 : -1; <ide> } <ide> <ide> @Override <ide> { <ide> if(I instanceof Ammunition) <ide> return ""+((Ammunition)I).ammunitionType(); <add> if((I instanceof AmmunitionWeapon)&&(((AmmunitionWeapon)I).requiresAmmunition())) <add> return ""+((AmmunitionWeapon)I).ammunitionType(); <ide> return ""; <ide> } <ide> }, <ide> @Override <ide> public int appliesToClass(final Object o) <ide> { <del> return ((o instanceof Weapon) || (o instanceof Ammunition)) ? 2 : -1; <add> return ((o instanceof AmmunitionWeapon) || (o instanceof Ammunition)) ? 2 : -1; <ide> } <ide> <ide> @Override
Java
apache-2.0
dc2425081469377276f5cd6605267e66f28a7335
0
gro-gg/latex-maven-plugin
package org.codehaus.mojo.latex; /* * Copyright 2010 INRIA / CITI Laboratory / Amazones Research Team. * * 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. * */ import static java.lang.String.format; import static org.apache.commons.exec.CommandLine.parse; import static org.apache.commons.io.FileUtils.copyDirectory; import static org.apache.commons.io.FileUtils.copyFile; import static org.apache.commons.io.FileUtils.iterateFiles; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.io.FileUtils; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; /** * LaTeX documents building goal. * * @author Julien Ponge * @goal latex * @phase compile */ public final class LaTeXMojo extends AbstractMojo { /** * The documents root. * * @parameter expression="${latex.docsRoot}" default-value="src/main/latex" * @required */ private File docsRoot; /** * Common files directory inside the documents root (the only directory to be skipped). * * @parameter expression="${latex.commonsDirName}" default-value="common" * @required */ private String commonsDirName; /** * The Maven build directory. * * @parameter expression="${project.build.directory}" * @required * @readonly */ private File buildDir; /** * The LaTeX builds directory. * * @parameter expression="${project.latex.build.directory}" default-value="${project.build.directory}/latex" * @required */ private File latexBuildDir; /** * Path to the LaTeX binaries installation. * * @parameter expression="${latex.binariesPath}" default-value="" */ private String binariesPath; /** * Indicates whether to run 'makeglossaries' or not. * * @parameter expression="${latex.makeGlossaries}" default-value="false" */ private boolean makeGlossaries; public void execute() throws MojoExecutionException, MojoFailureException { try { final File[] docDirs = getDocDirs(); final File[] buildDirs = prepareLaTeXBuildDirectories( docDirs ); buildDocuments( buildDirs ); } catch ( final IOException e ) { getLog().error( e ); throw new MojoFailureException( e.getMessage() ); } } private File[] prepareLaTeXBuildDirectories( final File[] docDirs ) throws IOException { final File[] buildDirs = new File[docDirs.length]; final File commonsDir = new File( docsRoot, commonsDirName ); for ( int i = 0; i < docDirs.length; i++ ) { final File dir = docDirs[i]; final File target = new File( latexBuildDir, docDirs[i].getName() ); buildDirs[i] = target; copyDirectory( dir, target ); if ( commonsDir.exists() ) { copyDirectory( commonsDir, target ); } @SuppressWarnings( "unchecked" ) final Iterator<File> iterator = iterateFiles( target, new String[]{ ".svn" }, true ); while ( iterator.hasNext() ) { FileUtils.deleteDirectory( (File) iterator.next() ); } } return buildDirs; } private File[] getDocDirs() { return docsRoot.listFiles( createCommonsDirNameFilter() ); } private FileFilter createCommonsDirNameFilter() { return new FileFilter() { public boolean accept( final File pathname ) { return pathname.isDirectory() && !( pathname.getName().equals( commonsDirName ) ) && !( pathname.isHidden() ); } }; } private void buildDocuments( final File[] buildDirs ) throws IOException, MojoFailureException { for ( final File dir : buildDirs ) { final File texFile = new File( dir, dir.getName() + ".tex" ); final File pdfFile = new File( dir, dir.getName() + ".pdf" ); if ( requiresBuilding(dir, pdfFile) ) { final CommandLine pdfLaTeX = createPdfLaTeXCommandLine( texFile ); executeBibtexIfNecessary( pdfLaTeX, dir ); executeMakeGlossariesIfNecessary( dir ); execute( pdfLaTeX, dir ); execute( pdfLaTeX, dir ); copyPdfFileToBuildDir( pdfFile, dir ); } else { if ( getLog().isInfoEnabled() ) { getLog().info( format( "Skipping: no LaTeX changes detected in %s", dir.getCanonicalPath() ) ); } } } } private boolean requiresBuilding( final File dir, final File pdfFile ) { @SuppressWarnings( "unchecked" ) final Collection<File> texFiles = FileUtils.listFiles( dir, new String[]{ ".tex", ".bib" }, true ); if ( pdfFileDoesNotExist( pdfFile ) ) { return true; } for ( final File texFile : texFiles ) { if ( FileUtils.isFileNewer( texFile, pdfFile ) ) { return true; } } return false; } private static boolean pdfFileDoesNotExist( final File pdfFile ) { return !pdfFile.exists(); } private CommandLine createPdfLaTeXCommandLine( final File texFile ) { return createCommandLine( "pdflatex", "-shell-escape", "--halt-on-error", texFile.getAbsolutePath() ); } private CommandLine createCommandLine( final String commandName, final String ... arguments ) { CommandLine result = parse( executablePath( commandName ) ); for ( final String argument : arguments ) { result = result.addArgument( argument ); } logDebugMessageIfEnabled( format( "%s: %s", commandName, result ) ); return result; } private String executablePath( final String executable ) { if ( binariesPath == null ) { return executable; } return new StringBuilder().append( binariesPath ).append( File.separator ).append( executable ).toString(); } private void logDebugMessageIfEnabled( final String debugMessage ) { if ( getLog().isDebugEnabled() ) { getLog().debug( debugMessage ); } } private void executeBibtexIfNecessary( final CommandLine pdfLaTeX, final File dir ) throws MojoFailureException, IOException { final File bibFile = new File( dir, format( "%s.bib", dir.getName() ) ); if ( bibFile.exists() ) { execute( pdfLaTeX, dir ); final CommandLine bibTeX = createCommandLine( "bibtex", dir.getName() ); execute( bibTeX, dir ); } } private void execute( final CommandLine commandLine, final File dir ) throws IOException, MojoFailureException { final DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory( dir ); if ( executor.execute( commandLine ) != 0 ) { throw new MojoFailureException( "Error code returned for: " + commandLine.toString() ); } } private void executeMakeGlossariesIfNecessary( final File dir ) throws MojoFailureException, IOException { if ( makeGlossaries ) { if (containsDirectoryAuxFile(dir)) { final CommandLine makeglossaries = createCommandLine("makeglossaries", dir.getName()); execute(makeglossaries, dir); } } } private boolean containsDirectoryAuxFile(File dir) { File[] matchingFiles = dir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".aux"); } }); return matchingFiles.length > 0; } private void copyPdfFileToBuildDir( final File pdfFile, final File dir ) throws IOException { final File destFile = new File( buildDir, pdfFile.getName() ); copyFile( pdfFile, destFile ); } }
src/main/java/org/codehaus/mojo/latex/LaTeXMojo.java
package org.codehaus.mojo.latex; /* * Copyright 2010 INRIA / CITI Laboratory / Amazones Research Team. * * 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. * */ import static java.lang.String.format; import static org.apache.commons.exec.CommandLine.parse; import static org.apache.commons.io.FileUtils.copyDirectory; import static org.apache.commons.io.FileUtils.copyFile; import static org.apache.commons.io.FileUtils.iterateFiles; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.io.FileUtils; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; /** * LaTeX documents building goal. * * @author Julien Ponge * @goal latex * @phase compile */ public final class LaTeXMojo extends AbstractMojo { /** * The documents root. * * @parameter expression="${latex.docsRoot}" default-value="src/main/latex" * @required */ private File docsRoot; /** * Common files directory inside the documents root (the only directory to be skipped). * * @parameter expression="${latex.commonsDirName}" default-value="common" * @required */ private String commonsDirName; /** * The Maven build directory. * * @parameter expression="${project.build.directory}" * @required * @readonly */ private File buildDir; /** * The LaTeX builds directory. * * @parameter expression="${project.latex.build.directory}" default-value="${project.build.directory}/latex" * @required */ private File latexBuildDir; /** * Path to the LaTeX binaries installation. * * @parameter expression="${latex.binariesPath}" default-value="" */ private String binariesPath; /** * Indicates whether to run 'makeglossaries' or not. * * @parameter expression="${latex.makeGlossaries}" default-value="false" */ private boolean makeGlossaries; public void execute() throws MojoExecutionException, MojoFailureException { try { final File[] docDirs = getDocDirs(); final File[] buildDirs = prepareLaTeXBuildDirectories( docDirs ); buildDocuments( buildDirs ); } catch ( final IOException e ) { getLog().error( e ); throw new MojoFailureException( e.getMessage() ); } } private File[] prepareLaTeXBuildDirectories( final File[] docDirs ) throws IOException { final File[] buildDirs = new File[docDirs.length]; final File commonsDir = new File( docsRoot, commonsDirName ); for ( int i = 0; i < docDirs.length; i++ ) { final File dir = docDirs[i]; final File target = new File( latexBuildDir, docDirs[i].getName() ); buildDirs[i] = target; copyDirectory( dir, target ); if ( commonsDir.exists() ) { copyDirectory( commonsDir, target ); } @SuppressWarnings( "unchecked" ) final Iterator<File> iterator = iterateFiles( target, new String[]{ ".svn" }, true ); while ( iterator.hasNext() ) { FileUtils.deleteDirectory( (File) iterator.next() ); } } return buildDirs; } private File[] getDocDirs() { return docsRoot.listFiles( createCommonsDirNameFilter() ); } private FileFilter createCommonsDirNameFilter() { return new FileFilter() { public boolean accept( final File pathname ) { return pathname.isDirectory() && !( pathname.getName().equals( commonsDirName ) ) && !( pathname.isHidden() ); } }; } private void buildDocuments( final File[] buildDirs ) throws IOException, MojoFailureException { for ( final File dir : buildDirs ) { final File texFile = new File( dir, dir.getName() + ".tex" ); final File pdfFile = new File( dir, dir.getName() + ".pdf" ); if ( requiresBuilding(dir, pdfFile) ) { final CommandLine pdfLaTeX = createPdfLaTeXCommandLine( texFile ); executeBibtexIfNecessary( pdfLaTeX, dir ); executeMakeGlossariesIfNecessary( dir ); execute( pdfLaTeX, dir ); execute( pdfLaTeX, dir ); copyPdfFileToBuildDir( pdfFile, dir ); } else { if ( getLog().isInfoEnabled() ) { getLog().info( format( "Skipping: no LaTeX changes detected in %s", dir.getCanonicalPath() ) ); } } } } private boolean requiresBuilding( final File dir, final File pdfFile ) { @SuppressWarnings( "unchecked" ) final Collection<File> texFiles = FileUtils.listFiles( dir, new String[]{ ".tex", ".bib" }, true ); if ( pdfFileDoesNotExist( pdfFile ) ) { return true; } for ( final File texFile : texFiles ) { if ( FileUtils.isFileNewer( texFile, pdfFile ) ) { return true; } } return false; } private static boolean pdfFileDoesNotExist( final File pdfFile ) { return !pdfFile.exists(); } private CommandLine createPdfLaTeXCommandLine( final File texFile ) { return createCommandLine( "pdflatex", "-shell-escape", "--halt-on-error", texFile.getAbsolutePath() ); } private CommandLine createCommandLine( final String commandName, final String ... arguments ) { CommandLine result = parse( executablePath( commandName ) ); for ( final String argument : arguments ) { result = result.addArgument( argument ); } logDebugMessageIfEnabled( format( "%s: %s", commandName, result ) ); return result; } private String executablePath( final String executable ) { if ( binariesPath == null ) { return executable; } return new StringBuilder().append( binariesPath ).append( File.separator ).append( executable ).toString(); } private void logDebugMessageIfEnabled( final String debugMessage ) { if ( getLog().isDebugEnabled() ) { getLog().debug( debugMessage ); } } private void executeBibtexIfNecessary( final CommandLine pdfLaTeX, final File dir ) throws MojoFailureException, IOException { final File bibFile = new File( dir, format( "%s.bib", dir.getName() ) ); if ( bibFile.exists() ) { execute( pdfLaTeX, dir ); final CommandLine bibTeX = createCommandLine( "bibtex", dir.getName() ); execute( bibTeX, dir ); } } private void execute( final CommandLine commandLine, final File dir ) throws IOException, MojoFailureException { final DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory( dir ); if ( executor.execute( commandLine ) != 0 ) { throw new MojoFailureException( "Error code returned for: " + commandLine.toString() ); } } private void executeMakeGlossariesIfNecessary( final File dir ) throws MojoFailureException, IOException { if ( makeGlossaries ) { final CommandLine makeglossaries = createCommandLine( "makeglossaries", dir.getName() ); execute( makeglossaries, dir ); } } private void copyPdfFileToBuildDir( final File pdfFile, final File dir ) throws IOException { final File destFile = new File( buildDir, pdfFile.getName() ); copyFile( pdfFile, destFile ); } }
only make glossaries if the target directory contains a *.aux file
src/main/java/org/codehaus/mojo/latex/LaTeXMojo.java
only make glossaries if the target directory contains a *.aux file
<ide><path>rc/main/java/org/codehaus/mojo/latex/LaTeXMojo.java <ide> <ide> import java.io.File; <ide> import java.io.FileFilter; <add>import java.io.FilenameFilter; <ide> import java.io.IOException; <ide> import java.util.Collection; <ide> import java.util.Iterator; <ide> <ide> /** <ide> * Indicates whether to run 'makeglossaries' or not. <del> * <add> * <ide> * @parameter expression="${latex.makeGlossaries}" default-value="false" <ide> */ <ide> private boolean makeGlossaries; <ide> { <ide> final File[] buildDirs = new File[docDirs.length]; <ide> final File commonsDir = new File( docsRoot, commonsDirName ); <del> <add> <ide> for ( int i = 0; i < docDirs.length; i++ ) <ide> { <ide> final File dir = docDirs[i]; <ide> final File target = new File( latexBuildDir, docDirs[i].getName() ); <ide> buildDirs[i] = target; <del> <add> <ide> copyDirectory( dir, target ); <ide> if ( commonsDir.exists() ) <ide> { <ide> copyDirectory( commonsDir, target ); <ide> } <del> <add> <ide> @SuppressWarnings( "unchecked" ) <ide> final Iterator<File> iterator = iterateFiles( target, new String[]{ ".svn" }, true ); <ide> while ( iterator.hasNext() ) <ide> { <ide> FileUtils.deleteDirectory( (File) iterator.next() ); <ide> } <del> <del> } <del> <add> <add> } <add> <ide> return buildDirs; <ide> } <ide> <ide> { <ide> public boolean accept( final File pathname ) <ide> { <del> return pathname.isDirectory() <add> return pathname.isDirectory() <ide> && !( pathname.getName().equals( commonsDirName ) ) <ide> && !( pathname.isHidden() ); <ide> } <ide> { <ide> if ( makeGlossaries ) <ide> { <del> final CommandLine makeglossaries = createCommandLine( "makeglossaries", dir.getName() ); <del> execute( makeglossaries, dir ); <del> } <add> if (containsDirectoryAuxFile(dir)) { <add> final CommandLine makeglossaries = createCommandLine("makeglossaries", dir.getName()); <add> execute(makeglossaries, dir); <add> } <add> } <add> } <add> <add> private boolean containsDirectoryAuxFile(File dir) { <add> File[] matchingFiles = dir.listFiles(new FilenameFilter() { <add> public boolean accept(File dir, String name) { <add> return name.endsWith(".aux"); <add> } <add> }); <add> return matchingFiles.length > 0; <ide> } <ide> <ide> private void copyPdfFileToBuildDir( final File pdfFile, final File dir ) throws IOException {
Java
mit
eff95bc582dc63722cfdad9db7bfeee3ecd6d384
0
chr-krenn/chr-krenn-fhj-ws2017-sd17-pse,chr-krenn/chr-krenn-fhj-ws2017-sd17-pse
package org.se.lab.web; import org.apache.log4j.Logger; import org.primefaces.event.FileUploadEvent; import org.primefaces.model.DefaultStreamedContent; import org.primefaces.model.StreamedContent; import org.primefaces.model.UploadedFile; import org.se.lab.db.data.Community; import org.se.lab.db.data.User; import org.se.lab.db.data.UserProfile; import org.se.lab.service.UserService; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.faces.context.FacesContext; import javax.faces.context.Flash; import javax.inject.Inject; import javax.inject.Named; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; @Named @RequestScoped public class UserDataBean implements Serializable { private static final long serialVersionUID = 1L; private final static Logger LOG = Logger.getLogger(UserDataBean.class); Flash flash; FacesContext context; private StreamedContent photo; @Inject private UserService service; private User user; private User loggedInUser; private UserProfile userProfile; private List<User> contacts = new ArrayList<User>(); private String errorMsg = ""; private List<Community> communities = new ArrayList<Community>(); private String id = ""; private String hideAddRemove = ""; private String fromHeader = ""; private int userId = 0; private boolean isContactAddable = false; private boolean ownProfile = false; private boolean isAdmin = false; private String visibility; @PostConstruct public void init() { context = FacesContext.getCurrentInstance(); Map<String, Object> session = context.getExternalContext().getSessionMap(); if (session.size() != 0 && session.get("user") != null) { flash = FacesContext.getCurrentInstance().getExternalContext().getFlash(); id = context.getExternalContext().getRequestParameterMap().get("userid"); handleButton(session); userId = (int) session.get("user"); String userProfId = String.valueOf(context.getExternalContext().getFlash().get("uid")); String fromHeaderCheck = String.valueOf(context.getExternalContext().getFlash().get("fromHeader")); if (fromHeaderCheck != null && fromHeaderCheck.equals("1")) { userProfId = null; } //Wr befinden uns auf einem Profil eines anderen Users if (userProfId != null && !userProfId.equals("null")) { setContactAddable(true); /* TODO userProfId might be "null" or NaN */ user = getUser(Integer.parseInt(userProfId)); //Holen des eingeloggten Users try { loggedInUser = service.findById(userId); List<User> usersList = service.getContactsOfUser(loggedInUser); for (User u : usersList) { //Wenn sich der User des aktuell angezeigten Profils in der Kontaktliste befindet wird der removeBtn angezeigt if (u.getId() == user.getId()) { setContactAddable(false); } } } catch (Exception e) { errorMsg = "Can't load your profile without errors! - pls contact the admin or try later"; LOG.error(errorMsg); setErrorMsg(errorMsg); } } else { user = getUser(userId); loggedInUser = user; } try { loadContactsCommunitiesAndUserprofile(); validateUserPriviles(loggedInUser); } catch (Exception e) { errorMsg = "Can't load your profile without errors! - pls contact the admin or try later"; LOG.error(errorMsg); setErrorMsg(errorMsg); } } else { /* * If session is null - redirect to login page! * */ try { context.getExternalContext().redirect("/pse/index.xhtml"); } catch (IOException e) { LOG.error("Can't redirect to /pse/index.xhtml"); //e.printStackTrace(); } } setErrorMsg(""); } private void loadContactsCommunitiesAndUserprofile() { try { contacts = service.getContactsOfUser(user); communities = user.getCommunities(); userProfile = service.getUserProfilById(user.getId()); } catch (Exception e) { errorMsg = "Can't load your profile without errors! - pls contact the admin or try later"; LOG.error(errorMsg); setErrorMsg(errorMsg); } } private void handleButton(Map<String, Object> session) { if (id == null) { id = String.valueOf(flash.get("uid")); } if (id != null) { flash.put("uid", id); if (id.equals(String.valueOf(session.get("user")))) { setOwnProfile(true); } else { setOwnProfile(false); } } hideAddRemove = context.getExternalContext().getRequestParameterMap().get("hideAddRemove"); fromHeader = context.getExternalContext().getRequestParameterMap().get("fromHeader"); flash.put("uid", id); flash.put("hideAddRemove", hideAddRemove); flash.put("fromHeader", fromHeader); String hideAddRemoveCheck = String.valueOf(context.getExternalContext().getFlash().get("hideAddRemove")); //Hide Buttons for own profile if ("1".equals(hideAddRemoveCheck)) { setOwnProfile(true); } } public void addContact() { String contactName = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("contactName"); System.out.println("LoggedInAdd " + loggedInUser.getId()); System.out.println("addContact: " + contactName); LOG.info("contactName " + contactName); LOG.info("u " + loggedInUser.getId()); LOG.info("userid " + userId); service.addContact(loggedInUser, contactName); setContactAddable(false); } public void removeContact() { String contactName = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("contactName"); System.out.println("LoggedInRemove " + loggedInUser.getId()); System.out.println("RemoveContact: " + contactName); LOG.info("contactName " + contactName); LOG.info("u " + loggedInUser.getId()); LOG.info("userid " + userId); service.removeContact(loggedInUser, contactName); setContactAddable(true); } public StreamedContent getImage() { //todo maybe need to load from db if (user.getUserProfile().getPicture() != null) { return new DefaultStreamedContent(new ByteArrayInputStream(user.getUserProfile().getPicture())); } return null; } public void uploadPicture(FileUploadEvent event) { UploadedFile uploadedFile = event.getFile(); UserProfile userProfile = user.getUserProfile(); userProfile.setPicture(uploadedFile.getContents()); service.addPictureToProfile(userProfile); } public boolean isImageExists() { if(user != null) { return user.getUserProfile().getPicture() != null; } else { return false; } } private void validateUserPriviles(User u) { try { this.isAdmin = service.hasUserTheRole(UserService.ROLE.ADMIN, u); } catch (Exception e) { errorMsg = "Can't load your profile without errors! - pls contact the admin or try later"; LOG.error(errorMsg); setErrorMsg(errorMsg); } } private boolean hasUserPrivilege(UserService.ROLE role) { try { return service.hasUserTheRole(role, user); } catch (Exception e) { errorMsg = String.format("Can't check privilege of user: %s", user.getUsername()); LOG.error(errorMsg); setErrorMsg(errorMsg); return false; } } public User getUser(int id) { return service.findById(id); } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public StreamedContent getPhoto() { return photo; } public void setPhoto(StreamedContent photo) { this.photo = photo; } public List<User> getContacts() { return contacts; } public void setContacts(List<User> contacts) { this.contacts = contacts; } public List<Community> getCommunities() { return communities; } public void setCommunities(List<Community> communities) { this.communities = communities; } public UserProfile getUserProfile() { return userProfile; } public void setUserProfile(UserProfile info) { this.userProfile = info; } public String redirect() { return "/profile.xhtml?faces-redirect=true"; } public boolean isContactAddable() { return isContactAddable; } public void setContactAddable(boolean contactAddable) { this.isContactAddable = contactAddable; } public boolean isAdmin() { return isAdmin; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } public boolean isOwnProfile() { return ownProfile; } public void setOwnProfile(boolean ownProfile) { this.ownProfile = ownProfile; } public User getLoggedInUser() { return loggedInUser; } public String setMessageVisibility(String visibility) { return visibility; } public String getVisibility() { return visibility; } public void setVisibility(String visibility) { if(visibility==null) this.visibility = "default"; this.visibility = visibility; } private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); } }
src/main/java/org/se/lab/web/UserDataBean.java
package org.se.lab.web; import org.apache.log4j.Logger; import org.primefaces.event.FileUploadEvent; import org.primefaces.model.DefaultStreamedContent; import org.primefaces.model.StreamedContent; import org.primefaces.model.UploadedFile; import org.se.lab.db.data.Community; import org.se.lab.db.data.User; import org.se.lab.db.data.UserProfile; import org.se.lab.service.UserService; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.faces.context.FacesContext; import javax.faces.context.Flash; import javax.inject.Inject; import javax.inject.Named; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; @Named @RequestScoped public class UserDataBean implements Serializable { private static final long serialVersionUID = 1L; private final static Logger LOG = Logger.getLogger(UserDataBean.class); Flash flash; FacesContext context; private StreamedContent photo; @Inject private UserService service; private User user; private User loggedInUser; private UserProfile userProfile; private List<User> contacts = new ArrayList<User>(); private String errorMsg = ""; private List<Community> communities = new ArrayList<Community>(); private String id = ""; private String hideAddRemove = ""; private String fromHeader = ""; private int userId = 0; private boolean isContactAddable = false; private boolean ownProfile = false; private boolean isAdmin = false; private String visibility; @PostConstruct public void init() { context = FacesContext.getCurrentInstance(); Map<String, Object> session = context.getExternalContext().getSessionMap(); if (session.size() != 0 && session.get("user") != null) { flash = FacesContext.getCurrentInstance().getExternalContext().getFlash(); id = context.getExternalContext().getRequestParameterMap().get("userid"); handleButton(session); userId = (int) session.get("user"); String userProfId = String.valueOf(context.getExternalContext().getFlash().get("uid")); String fromHeaderCheck = String.valueOf(context.getExternalContext().getFlash().get("fromHeader")); if (fromHeaderCheck != null && fromHeaderCheck.equals("1")) { userProfId = null; } //Wr befinden uns auf einem Profil eines anderen Users if (userProfId != null && !userProfId.equals("null")) { setContactAddable(true); /* TODO userProfId might be "null" or NaN */ user = getUser(Integer.parseInt(userProfId)); //Holen des eingeloggten Users try { loggedInUser = service.findById(userId); List<User> usersList = service.getContactsOfUser(loggedInUser); for (User u : usersList) { //Wenn sich der User des aktuell angezeigten Profils in der Kontaktliste befindet wird der removeBtn angezeigt if (u.getId() == user.getId()) { setContactAddable(false); } } } catch (Exception e) { errorMsg = "Can't load your profile without errors! - pls contact the admin or try later"; LOG.error(errorMsg); setErrorMsg(errorMsg); } } else { user = getUser(userId); loggedInUser = user; } try { loadContactsCommunitiesAndUserprofile(); validateUserPriviles(loggedInUser); } catch (Exception e) { errorMsg = "Can't load your profile without errors! - pls contact the admin or try later"; LOG.error(errorMsg); setErrorMsg(errorMsg); } } else { /* * If session is null - redirect to login page! * */ try { context.getExternalContext().redirect("/pse/index.xhtml"); } catch (IOException e) { LOG.error("Can't redirect to /pse/index.xhtml"); //e.printStackTrace(); } } setErrorMsg(""); } private void loadContactsCommunitiesAndUserprofile() { try { contacts = service.getContactsOfUser(user); communities = user.getCommunities(); userProfile = service.getUserProfilById(user.getId()); } catch (Exception e) { errorMsg = "Can't load your profile without errors! - pls contact the admin or try later"; LOG.error(errorMsg); setErrorMsg(errorMsg); } } private void handleButton(Map<String, Object> session) { if (id == null) { id = String.valueOf(flash.get("uid")); } if (id != null) { flash.put("uid", id); if (id.equals(String.valueOf(session.get("user")))) { setOwnProfile(true); } else { setOwnProfile(false); } } hideAddRemove = context.getExternalContext().getRequestParameterMap().get("hideAddRemove"); fromHeader = context.getExternalContext().getRequestParameterMap().get("fromHeader"); flash.put("uid", id); flash.put("hideAddRemove", hideAddRemove); flash.put("fromHeader", fromHeader); String hideAddRemoveCheck = String.valueOf(context.getExternalContext().getFlash().get("hideAddRemove")); //Hide Buttons for own profile if ("1".equals(hideAddRemoveCheck)) { setOwnProfile(true); } } public void addContact() { String contactName = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("contactName"); System.out.println("LoggedInAdd " + loggedInUser.getId()); System.out.println("addContact: " + contactName); LOG.info("contactName " + contactName); LOG.info("u " + loggedInUser.getId()); LOG.info("userid " + userId); service.addContact(loggedInUser, contactName); setContactAddable(false); } public void removeContact() { String contactName = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("contactName"); System.out.println("LoggedInRemove " + loggedInUser.getId()); System.out.println("RemoveContact: " + contactName); LOG.info("contactName " + contactName); LOG.info("u " + loggedInUser.getId()); LOG.info("userid " + userId); service.removeContact(loggedInUser, contactName); setContactAddable(true); } public StreamedContent getImage() { //todo maybe need to load from db if (user.getUserProfile().getPicture() != null) { return new DefaultStreamedContent(new ByteArrayInputStream(user.getUserProfile().getPicture())); } return null; } public void uploadPicture(FileUploadEvent event) { UploadedFile uploadedFile = event.getFile(); UserProfile userProfile = user.getUserProfile(); userProfile.setPicture(uploadedFile.getContents()); service.addPictureToProfile(userProfile); } public boolean isImageExists() { boolean imageExists = false; try { user.getUserProfile().getPicture(); imageExists = true; } catch (Exception e) { errorMsg = "Can't load your profile without errors! - pls contact the admin or try later"; LOG.error(errorMsg); setErrorMsg(errorMsg); } return imageExists; } private void validateUserPriviles(User u) { try { this.isAdmin = service.hasUserTheRole(UserService.ROLE.ADMIN, u); } catch (Exception e) { errorMsg = "Can't load your profile without errors! - pls contact the admin or try later"; LOG.error(errorMsg); setErrorMsg(errorMsg); } } private boolean hasUserPrivilege(UserService.ROLE role) { try { return service.hasUserTheRole(role, user); } catch (Exception e) { errorMsg = String.format("Can't check privilege of user: %s", user.getUsername()); LOG.error(errorMsg); setErrorMsg(errorMsg); return false; } } public User getUser(int id) { return service.findById(id); } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public StreamedContent getPhoto() { return photo; } public void setPhoto(StreamedContent photo) { this.photo = photo; } public List<User> getContacts() { return contacts; } public void setContacts(List<User> contacts) { this.contacts = contacts; } public List<Community> getCommunities() { return communities; } public void setCommunities(List<Community> communities) { this.communities = communities; } public UserProfile getUserProfile() { return userProfile; } public void setUserProfile(UserProfile info) { this.userProfile = info; } public String redirect() { return "/profile.xhtml?faces-redirect=true"; } public boolean isContactAddable() { return isContactAddable; } public void setContactAddable(boolean contactAddable) { this.isContactAddable = contactAddable; } public boolean isAdmin() { return isAdmin; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } public boolean isOwnProfile() { return ownProfile; } public void setOwnProfile(boolean ownProfile) { this.ownProfile = ownProfile; } public User getLoggedInUser() { return loggedInUser; } public String setMessageVisibility(String visibility) { return visibility; } public String getVisibility() { return visibility; } public void setVisibility(String visibility) { if(visibility==null) this.visibility = "default"; this.visibility = visibility; } private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); } }
Check null in imageExists
src/main/java/org/se/lab/web/UserDataBean.java
Check null in imageExists
<ide><path>rc/main/java/org/se/lab/web/UserDataBean.java <ide> <ide> public boolean isImageExists() { <ide> <del> boolean imageExists = false; <del> <del> try { <del> user.getUserProfile().getPicture(); <del> imageExists = true; <del> <del> } catch (Exception e) { <del> errorMsg = "Can't load your profile without errors! - pls contact the admin or try later"; <del> LOG.error(errorMsg); <del> setErrorMsg(errorMsg); <del> } <del> return imageExists; <del> } <add> if(user != null) <add> { <add> return user.getUserProfile().getPicture() != null; <add> <add> } <add> else <add> { <add> return false; <add> } <add>} <ide> <ide> private void validateUserPriviles(User u) { <ide> try {
JavaScript
apache-2.0
e839371d2117a0ee77c109c8928e20cd8a40d02c
0
benetech/math-speech-rule-editor,benetech/math-speech-rule-editor
/** * Route Mappings * (sails.config.routes) * * Your routes map URLs to views and controllers. * * If Sails receives a URL that doesn't match any of the routes below, * it will check for matching files (images, scripts, stylesheets, etc.) * in your assets directory. e.g. `http://localhost:1337/images/foo.jpg` * might match an image file: `/assets/images/foo.jpg` * * Finally, if those don't match either, the default 404 handler is triggered. * See `api/responses/notFound.js` to adjust your app's 404 logic. * * Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies * flat files from `assets` to `.tmp/public`. This allows you to do things like compile LESS or * CoffeeScript for the front-end. * * For more information on configuring custom routes, check out: * http://sailsjs.org/#/documentation/concepts/Routes/RouteTargetSyntax.html */ module.exports.routes = { /*************************************************************************** * * * Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, * * etc. depending on your default view engine) your home page. * * * * (Alternatively, remove this and add an `index.html` file in your * * `assets` directory) * * * ***************************************************************************/ '/': { view: 'homepage' }, /*************************************************************************** * * * Custom routes here... * * * * If a request to a URL doesn't match any of the custom routes above, it * * is matched against Sails route blueprints. See `config/blueprints.js` * * for configuration options and examples. * * * ***************************************************************************/ 'get /ruleSet/import': { controller: 'ImportExportController', action: 'import' }, 'get /seedData': { controller: 'ImportExportController', action: 'seedStatesAndCountries' }, 'get /ruleSet/previewExport': { controller: 'ImportExportController', action: 'previewExport' }, 'get /ruleSet/export': { controller: 'ImportExportController', action: 'export' }, 'get /rulesets': { controller: 'RuleSetController', action: 'ruleSets' }, 'get /rules': { controller: 'RuleSetController', action: 'rules' }, 'get /rule/:id': { controller: 'RuleSetController', action: 'rule' }, 'get /ruleset/:id': { controller: 'RuleSetController', action: 'ruleSet' }, 'get /ruleset/styles/:id': { controller: 'RuleSetController', action: 'ruleSetStyles' }, 'get /rule/mappings/:id': { controller: 'RuleSetController', action: 'ruleMappings' }, 'post /speech': { controller: 'SpeechRuleEngineController', action: 'convert' }, 'post /mapping': { controller: 'RuleSetController', action: 'createMapping' }, 'put /mapping/:id': { controller: 'RuleSetController', action: 'updateMapping' }, 'post /ruleset': { controller: 'RuleSetController', action: 'createRuleset' }, 'put /ruleset/:id': { controller: 'RuleSetController', action: 'updateRuleSet' }, 'get /countries': { controller: 'ReferenceDataController', action: 'countries' }, 'get /states': { controller: 'ReferenceDataController', action: 'states' }, 'get /mathmaps': { controller: 'RuleSetController', action: 'mathMaps' }, 'get /mathmap/categories/:id': { controller: 'RuleSetController', action: 'mathMapCategories' }, 'get /mathmapcategory/rules/:id': { controller: 'RuleSetController', action: 'categoryRules' } };
config/routes.js
/** * Route Mappings * (sails.config.routes) * * Your routes map URLs to views and controllers. * * If Sails receives a URL that doesn't match any of the routes below, * it will check for matching files (images, scripts, stylesheets, etc.) * in your assets directory. e.g. `http://localhost:1337/images/foo.jpg` * might match an image file: `/assets/images/foo.jpg` * * Finally, if those don't match either, the default 404 handler is triggered. * See `api/responses/notFound.js` to adjust your app's 404 logic. * * Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies * flat files from `assets` to `.tmp/public`. This allows you to do things like compile LESS or * CoffeeScript for the front-end. * * For more information on configuring custom routes, check out: * http://sailsjs.org/#/documentation/concepts/Routes/RouteTargetSyntax.html */ module.exports.routes = { /*************************************************************************** * * * Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, * * etc. depending on your default view engine) your home page. * * * * (Alternatively, remove this and add an `index.html` file in your * * `assets` directory) * * * ***************************************************************************/ '/': { view: 'homepage' }, /*************************************************************************** * * * Custom routes here... * * * * If a request to a URL doesn't match any of the custom routes above, it * * is matched against Sails route blueprints. See `config/blueprints.js` * * for configuration options and examples. * * * ***************************************************************************/ 'get /ruleSet/import': { controller: 'ImportExportController', action: 'import' }, 'get /seedData': { controller: 'ImportExportController', action: 'seedStatesAndCountries' }, 'get /ruleSet/previewExport': { controller: 'ImportExportController', action: 'previewExport' }, 'get /ruleSet/export': { controller: 'ImportExportController', action: 'export' }, 'get /rulesets/': { controller: 'RuleSetController', action: 'ruleSets' }, 'get /rules': { controller: 'RuleSetController', action: 'rules' }, 'get /rule/:id': { controller: 'RuleSetController', action: 'rule' }, 'get /ruleset/:id': { controller: 'RuleSetController', action: 'ruleSet' }, 'get /ruleset/styles/:id': { controller: 'RuleSetController', action: 'ruleSetStyles' }, 'get /rule/mappings/:id': { controller: 'RuleSetController', action: 'ruleMappings' }, 'post /speech': { controller: 'SpeechRuleEngineController', action: 'convert' }, 'post /mapping': { controller: 'RuleSetController', action: 'createMapping' }, 'put /mapping/:id': { controller: 'RuleSetController', action: 'updateMapping' }, 'post /ruleset': { controller: 'RuleSetController', action: 'createRuleset' }, 'put /ruleset/:id': { controller: 'RuleSetController', action: 'updateRuleSet' }, 'get /countries': { controller: 'ReferenceDataController', action: 'countries' }, 'get /states': { controller: 'ReferenceDataController', action: 'states' }, 'get /mathmaps': { controller: 'RuleSetController', action: 'mathMaps' }, 'get /mathmap/categories/:id': { controller: 'RuleSetController', action: 'mathMapCategories' }, 'get /mathmapcategory/rules/:id': { controller: 'RuleSetController', action: 'categoryRules' } };
FIx route
config/routes.js
FIx route
<ide><path>onfig/routes.js <ide> action: 'export' <ide> }, <ide> <del> 'get /rulesets/': { <add> 'get /rulesets': { <ide> controller: 'RuleSetController', <ide> action: 'ruleSets' <ide> },
Java
apache-2.0
892676254ace712b871ee437244f2e0ea849b038
0
emre-aydin/hazelcast,mesutcelik/hazelcast,tufangorel/hazelcast,Donnerbart/hazelcast,tufangorel/hazelcast,dsukhoroslov/hazelcast,dsukhoroslov/hazelcast,mdogan/hazelcast,Donnerbart/hazelcast,dbrimley/hazelcast,tkountis/hazelcast,emre-aydin/hazelcast,dbrimley/hazelcast,mesutcelik/hazelcast,mesutcelik/hazelcast,juanavelez/hazelcast,emre-aydin/hazelcast,tkountis/hazelcast,mdogan/hazelcast,tufangorel/hazelcast,juanavelez/hazelcast,Donnerbart/hazelcast,tkountis/hazelcast,dbrimley/hazelcast,mdogan/hazelcast
/* * Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved. * * 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.hazelcast.internal.nearcache; import com.hazelcast.config.NearCacheConfig; import com.hazelcast.internal.nearcache.impl.DefaultNearCache; import com.hazelcast.test.HazelcastSerialClassRunner; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; @RunWith(HazelcastSerialClassRunner.class) @Category({QuickTest.class, ParallelTest.class}) public class NearCacheTest extends NearCacheTestSupport { @Override protected NearCache<Integer, String> createNearCache(String name, NearCacheConfig nearCacheConfig, ManagedNearCacheRecordStore nearCacheRecordStore) { return new DefaultNearCache<Integer, String>(name, nearCacheConfig, nearCacheRecordStore, ss, executionService.getGlobalTaskScheduler(), null); } @Test public void getNearCacheName() { doGetNearCacheName(); } @Test public void getFromNearCache() { doGetFromNearCache(); } @Test public void putToNearCache() { doPutToNearCache(); } @Test public void removeFromNearCache() { doRemoveFromNearCache(); } @Test public void invalidateFromNearCache() { doInvalidateFromNearCache(); } @Test public void clearNearCache() { doClearNearCache(); } @Test public void destroyNearCache() { doDestroyNearCache(); } @Test public void configureInMemoryFormatForNearCache() { doConfigureInMemoryFormatForNearCache(); } @Test public void getNearCacheStatsFromNearCache() { doGetNearCacheStatsFromNearCache(); } @Test public void selectToSaveFromNearCache() { doSelectToSaveFromNearCache(); } @Test @Ignore public void createNearCacheAndWaitForExpirationCalledWithTTL() { doCreateNearCacheAndWaitForExpirationCalled(true); } @Test @Ignore public void createNearCacheAndWaitForExpirationCalledWithMaxIdleTime() { doCreateNearCacheAndWaitForExpirationCalled(false); } @Test public void putToNearCacheStatsAndSeeEvictionCheckIsDone() { doPutToNearCacheStatsAndSeeEvictionCheckIsDone(); } }
hazelcast/src/test/java/com/hazelcast/internal/nearcache/NearCacheTest.java
/* * Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved. * * 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.hazelcast.internal.nearcache; import com.hazelcast.config.NearCacheConfig; import com.hazelcast.internal.nearcache.impl.DefaultNearCache; import com.hazelcast.test.HazelcastSerialClassRunner; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; @RunWith(HazelcastSerialClassRunner.class) @Category({QuickTest.class, ParallelTest.class}) public class NearCacheTest extends NearCacheTestSupport { @Override protected NearCache<Integer, String> createNearCache(String name, NearCacheConfig nearCacheConfig, ManagedNearCacheRecordStore nearCacheRecordStore) { return new DefaultNearCache<Integer, String>(name, nearCacheConfig, nearCacheRecordStore, ss, executionService.getGlobalTaskScheduler(), null); } @Test public void getNearCacheName() { doGetNearCacheName(); } @Test public void getFromNearCache() { doGetFromNearCache(); } @Test public void putToNearCache() { doPutToNearCache(); } @Test public void removeFromNearCache() { doRemoveFromNearCache(); } @Test public void invalidateFromNearCache() { doInvalidateFromNearCache(); } @Test public void clearNearCache() { doClearNearCache(); } @Test public void destroyNearCache() { doDestroyNearCache(); } @Test public void configureInMemoryFormatForNearCache() { doConfigureInMemoryFormatForNearCache(); } @Test public void getNearCacheStatsFromNearCache() { doGetNearCacheStatsFromNearCache(); } @Test public void selectToSaveFromNearCache() { doSelectToSaveFromNearCache(); } @Test public void createNearCacheAndWaitForExpirationCalledWithTTL() { doCreateNearCacheAndWaitForExpirationCalled(true); } @Test public void createNearCacheAndWaitForExpirationCalledWithMaxIdleTime() { doCreateNearCacheAndWaitForExpirationCalled(false); } @Test public void putToNearCacheStatsAndSeeEvictionCheckIsDone() { doPutToNearCacheStatsAndSeeEvictionCheckIsDone(); } }
Ignored failing test methods in NearCacheTest
hazelcast/src/test/java/com/hazelcast/internal/nearcache/NearCacheTest.java
Ignored failing test methods in NearCacheTest
<ide><path>azelcast/src/test/java/com/hazelcast/internal/nearcache/NearCacheTest.java <ide> import com.hazelcast.test.HazelcastSerialClassRunner; <ide> import com.hazelcast.test.annotation.ParallelTest; <ide> import com.hazelcast.test.annotation.QuickTest; <add>import org.junit.Ignore; <ide> import org.junit.Test; <ide> import org.junit.experimental.categories.Category; <ide> import org.junit.runner.RunWith; <ide> } <ide> <ide> @Test <add> @Ignore <ide> public void createNearCacheAndWaitForExpirationCalledWithTTL() { <ide> doCreateNearCacheAndWaitForExpirationCalled(true); <ide> } <ide> <ide> @Test <add> @Ignore <ide> public void createNearCacheAndWaitForExpirationCalledWithMaxIdleTime() { <ide> doCreateNearCacheAndWaitForExpirationCalled(false); <ide> }
JavaScript
mit
0233a8c22f26568a3a0002ec7bf0dc45bd44644d
0
KuoE0/MPU6050-WebPlot,KuoE0/MPU6050-WebPlot
var ws = undefined; function update_MA(value) { if (value != '') { $('#moving-average-filter label').text('MA Filter (' + value + ')'); $('#MA-slider').val(value); ws.send("MAF " + value); } else { $('#moving-average-filter label').text('MA Filter'); } } $(function() { function get_series_data(data) { return data.signal; } function insert_signal(name) { var panel = $('#signal-panel .ui.form'); panel.append('<div class="field"><div id="' + name + '" class="ui toggle checkbox"><input type="checkbox" checked /><label>' + name + '</label></div></div>'); } var number_of_signal = 200; var plot = null; var legends = null; function init_draw(data) { plot = $.plot('#signal-plot', data, { series: { lines: { show: true, lineWidth: 1.5 }, shadowSize: 0 }, crosshair: { mode: "x" }, grid: { hoverable: true, autoHighlight: false }, xaxis: { show: false }, yaxis: { min: -36000, max: 36000 }, legend: { position: "sw" } }); for (var i = 0; i < data.length; ++i) { insert_signal(data[i].label); } $('.ui.checkbox').checkbox(); legends = $('#signal-plot .legendLabel'); } // Websocket connection ws = new WebSocket("ws://localhost:8888/ws"); ws.onmessage = function (evt) { if (plot == null) { var data = JSON.parse(evt.data); data = data.signal; init_draw(data); } var data = JSON.parse(evt.data); data = data.signal; // set data for plot plot.setData(data); // redraw graph plot.draw(); // uplate legend update_legend(); }; var latest_pos = null; var update_legend_timeout = null; function update_legend() { if (latest_pos == null) { return; } update_legend_timeout = null; var pos = latest_pos; var axes = plot.getAxes(); if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max || pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) { return; } var dataset = plot.getData(); for (var i = 0; i < dataset.length; ++i) { var series = dataset[i]; var idx = Math.floor(pos.x); var p1 = series.data[idx], p2 = series.data[idx + 1]; var ret = null; ret = (p1 == null) ? p2[1] : p1[1]; var new_label = series.label.replace(/=.*/, "= " + ret); legends.eq(i).text(new_label); } }; $('#signal-plot').bind("plothover", function (event, pos, iten) { latest_pos = pos; if (!update_legend_timeout) { update_legend_timeout = setTimeout(update_legend, 50); } }); $('#clear-btn').click(function () { ws.send("clear"); }); $('#status-btn').click(function () { // close connection if ($(this).hasClass('active')) { $(this).removeClass('active'); $(this).empty(); $(this).append("<i class='play icon'></i>"); ws.send("pause"); } // open connection else { $(this).addClass('active'); $(this).empty(); $(this).append("<i class='pause icon'></i>"); ws.send("play"); } }); $('#moving-average-filter').click(function () { if ($(this).hasClass('active')) { $(this).removeClass('active'); $('#MA-slider').toggle('slow'); $('#MA-slider').attr('disabled', true); update_MA(''); ws.send("MAF 0"); } else { $(this).addClass('active'); update_MA($('#MA-slider').val()); $('#MA-slider').toggle('fast'); $('#MA-slider').attr('disabled', false); } }); $('.ui.checkbox').checkbox(); });
static/js/main.js
var ws = undefined; function update_MA(value) { if (value != '') { $('#moving-average-filter label').text('MA Filter (' + value + ')'); $('#MA-slider').val(value); ws.send("MAF " + value); } else { $('#moving-average-filter label').text('MA Filter'); } } $(function() { function get_series_data(data) { // append value after each label for (var i = 0; i < data.signal.length; ++i) { data.signal[i].label = data.signal[i].label + " = 0"; } return data.signal; } function insert_signal(name) { var panel = $('#signal-panel .ui.form'); panel.append('<div class="field"><div id="' + name + '" class="ui toggle checkbox"><input type="checkbox" checked /><label>' + name + '</label></div></div>'); } var number_of_signal = 200; var plot = null; var legends = null; function init_draw(data) { plot = $.plot('#signal-plot', data, { series: { lines: { show: true, lineWidth: 1.5 }, shadowSize: 0 }, crosshair: { mode: "x" }, grid: { hoverable: true, autoHighlight: false }, xaxis: { show: false }, yaxis: { min: -36000, max: 36000 }, legend: { position: "sw" } }); for (var i = 0; i < data.length; ++i) { insert_signal(data[i].label); } $('.ui.checkbox').checkbox(); legends = $('#signal-plot .legendLabel'); } // Websocket connection ws = new WebSocket("ws://localhost:8888/ws"); ws.onmessage = function (evt) { if (plot == null) { var data = JSON.parse(evt.data); data = get_series_data(data); init_draw(data); } var data = JSON.parse(evt.data); data = get_series_data(data); // set data for plot plot.setData(data); // redraw graph plot.draw(); // uplate legend update_legend(); }; var latest_pos = null; var update_legend_timeout = null; function update_legend() { if (latest_pos == null) { return; } update_legend_timeout = null; var pos = latest_pos; var axes = plot.getAxes(); if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max || pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) { return; } var dataset = plot.getData(); for (var i = 0; i < dataset.length; ++i) { var series = dataset[i]; var idx = Math.floor(pos.x); var p1 = series.data[idx], p2 = series.data[idx + 1]; var ret = null; ret = (p1 == null) ? p2[1] : p1[1]; var new_label = series.label.replace(/=.*/, "= " + ret); legends.eq(i).text(new_label); } }; $('#signal-plot').bind("plothover", function (event, pos, iten) { latest_pos = pos; if (!update_legend_timeout) { update_legend_timeout = setTimeout(update_legend, 50); } }); $('#clear-btn').click(function () { ws.send("clear"); }); $('#status-btn').click(function () { // close connection if ($(this).hasClass('active')) { $(this).removeClass('active'); $(this).empty(); $(this).append("<i class='play icon'></i>"); ws.send("pause"); } // open connection else { $(this).addClass('active'); $(this).empty(); $(this).append("<i class='pause icon'></i>"); ws.send("play"); } }); $('#moving-average-filter').click(function () { if ($(this).hasClass('active')) { $(this).removeClass('active'); $('#MA-slider').toggle('slow'); $('#MA-slider').attr('disabled', true); update_MA(''); ws.send("MAF 0"); } else { $(this).addClass('active'); update_MA($('#MA-slider').val()); $('#MA-slider').toggle('fast'); $('#MA-slider').attr('disabled', false); } }); $('.ui.checkbox').checkbox(); });
dont append '= 0' to label
static/js/main.js
dont append '= 0' to label
<ide><path>tatic/js/main.js <ide> $(function() { <ide> <ide> function get_series_data(data) { <del> // append value after each label <del> for (var i = 0; i < data.signal.length; ++i) { <del> data.signal[i].label = data.signal[i].label + " = 0"; <del> } <del> <ide> return data.signal; <ide> } <ide> <ide> <ide> if (plot == null) { <ide> var data = JSON.parse(evt.data); <del> data = get_series_data(data); <add> data = data.signal; <ide> init_draw(data); <ide> } <ide> <ide> var data = JSON.parse(evt.data); <del> data = get_series_data(data); <add> data = data.signal; <ide> // set data for plot <ide> plot.setData(data); <ide> // redraw graph
Java
apache-2.0
346c7c8b82520112f3d62b762e1853badf0c3c8a
0
SatelliteApplicationsCatapult/tribble
package org.catapult.sa; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.*; import org.apache.maven.project.MavenProject; import org.catapult.sa.tribble.Fuzzer; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.classworlds.realm.DuplicateRealmException; import java.io.File; import java.net.MalformedURLException; /** * Simple maven plugin to run a fuzz test. */ @Mojo(name = "fuzztest", defaultPhase = LifecyclePhase.TEST, requiresDependencyCollection = ResolutionScope.TEST, requiresDependencyResolution = ResolutionScope.TEST) @Execute(phase = LifecyclePhase.TEST_COMPILE) public class TribblePlugin extends AbstractMojo { @Parameter(property = "fuzztest.target", required = true) public String target; @Parameter(property = "fuzztest.corpus", required = true, defaultValue = "corpus") public String corpusPath; @Parameter(property = "fuzztest.failed", required = true, defaultValue = "failed") public String failedPath; @Parameter(property = "fuzztest.threads", required = true, defaultValue = "2") public int threads; @Parameter(property = "fuzztest.timeout", required = true, defaultValue = "1000") public long timeout; @Parameter(property = "fuzztest.count", required = true, defaultValue = "-1") public long count; @Parameter(property = "fuzztest.verbose", required = true, defaultValue = "true") public boolean verbose; @Parameter(property = "fuzztest.disabledMutators", required = true, defaultValue = "") public String[] disabledMutators; @Parameter(property = "fuzztest.ignoreClasses") public String[] ignoreClasses; @Parameter( defaultValue="${project}", required = true, readonly = true) public MavenProject project; public void execute() throws MojoExecutionException { try { ClassLoader current = this.getClass().getClassLoader(); ClassRealm realm; if (current != null && current instanceof ClassRealm) { realm = (ClassRealm) current; } else { ClassWorld world = new ClassWorld(); realm = world.newRealm("plugin.tribble.container", this.getClass().getClassLoader()); } ClassRealm projectRealm = realm.createChildRealm("theproject"); String outputDir = project.getBuild().getOutputDirectory(); String testDir = project.getBuild().getTestOutputDirectory(); projectRealm.addURL(new File(outputDir).toURI().toURL()); projectRealm.addURL(new File(testDir).toURI().toURL()); for (Artifact a: project.getArtifacts()) { // don't add tribble again. Its already there via our own dependencies. Weird things happen if not. if (!(a.getGroupId().equals("org.catapult.sa") && a.getArtifactId().equals("tribble-core"))) { projectRealm.addURL(a.getFile().toURI().toURL()); } } Thread.currentThread().setContextClassLoader(projectRealm); Fuzzer fuzzer = new Fuzzer(corpusPath, failedPath, ignoreClasses, threads, timeout, count, verbose, disabledMutators); fuzzer.run(target, projectRealm); } catch (DuplicateRealmException | MalformedURLException e) { throw new MojoExecutionException("Could not run fuzz test. Class path problems.", e); } } }
tribble-maven-plugin/src/main/java/org/catapult/sa/TribblePlugin.java
package org.catapult.sa; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.*; import org.apache.maven.project.MavenProject; import org.catapult.sa.tribble.Fuzzer; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.classworlds.realm.DuplicateRealmException; import java.io.File; import java.net.MalformedURLException; /** * Simple maven plugin to run a fuzz test. */ @Mojo(name = "fuzztest", defaultPhase = LifecyclePhase.TEST, requiresDependencyCollection = ResolutionScope.TEST, requiresDependencyResolution = ResolutionScope.TEST) @Execute(phase = LifecyclePhase.TEST_COMPILE) public class TribblePlugin extends AbstractMojo { @Parameter(property = "fuzztest.target", required = true) public String target; @Parameter(property = "fuzztest.corpus", required = true, defaultValue = "corpus") public String corpusPath; @Parameter(property = "fuzztest.failed", required = true, defaultValue = "failed") public String failedPath; @Parameter(property = "fuzztest.threads", required = true, defaultValue = "2") public int threads; @Parameter(property = "fuzztest.timeout", required = true, defaultValue = "1000") public long timeout; @Parameter(property = "fuzztest.count", required = true, defaultValue = "-1") public long count; @Parameter(property = "fuzztest.verbose", required = true, defaultValue = "true") public boolean verbose; @Parameter(property = "fuzztext.disabledMutators", required = true, defaultValue = "") public String[] disabledMutators; @Parameter(property = "fuzztest.ignoreClasses") public String[] ignoreClasses; @Parameter( defaultValue="${project}", required = true, readonly = true) public MavenProject project; public void execute() throws MojoExecutionException { try { ClassLoader current = this.getClass().getClassLoader(); ClassRealm realm; if (current != null && current instanceof ClassRealm) { realm = (ClassRealm) current; } else { ClassWorld world = new ClassWorld(); realm = world.newRealm("plugin.tribble.container", this.getClass().getClassLoader()); } ClassRealm projectRealm = realm.createChildRealm("theproject"); String outputDir = project.getBuild().getOutputDirectory(); String testDir = project.getBuild().getTestOutputDirectory(); projectRealm.addURL(new File(outputDir).toURI().toURL()); projectRealm.addURL(new File(testDir).toURI().toURL()); for (Artifact a: project.getArtifacts()) { // don't add tribble again. Its already there via our own dependencies. Weird things happen if not. if (!(a.getGroupId().equals("org.catapult.sa") && a.getArtifactId().equals("tribble-core"))) { projectRealm.addURL(a.getFile().toURI().toURL()); } } Thread.currentThread().setContextClassLoader(projectRealm); Fuzzer fuzzer = new Fuzzer(corpusPath, failedPath, ignoreClasses, threads, timeout, count, verbose, disabledMutators); fuzzer.run(target, projectRealm); } catch (DuplicateRealmException | MalformedURLException e) { throw new MojoExecutionException("Could not run fuzz test. Class path problems.", e); } } }
fix property name
tribble-maven-plugin/src/main/java/org/catapult/sa/TribblePlugin.java
fix property name
<ide><path>ribble-maven-plugin/src/main/java/org/catapult/sa/TribblePlugin.java <ide> @Parameter(property = "fuzztest.verbose", required = true, defaultValue = "true") <ide> public boolean verbose; <ide> <del> @Parameter(property = "fuzztext.disabledMutators", required = true, defaultValue = "") <add> @Parameter(property = "fuzztest.disabledMutators", required = true, defaultValue = "") <ide> public String[] disabledMutators; <ide> <ide> @Parameter(property = "fuzztest.ignoreClasses")
Java
mit
f3e5f31871f90d66a4ae7d7c22dfc29520c8dd08
0
cbullers/cob-paint
COBConfig.java
package com.cob.paint; import java.awt.Color; import java.awt.Dimension; public class COBConfig { public static String LANGUAGE = "en"; // Sizes for the things..? public static Dimension APP_DIMENSION = new Dimension(1000,650); // Size of the whole application public static Dimension SLIDER_DIMENSION = new Dimension(30,500); // Size of the RGB sliders public static Dimension BRUSHSLIDER_DIMENSION = new Dimension(300, 30); // Brush size slider // Colors public static Color STARTING_COLOR = new Color(255,255,255); // The default foreground color public static Color BACKGROUND_COLOR = new Color(238,238,238); // The default background color // Language public static String SAVE_TOOLTIP = "Save image"; public static String PEN_TOOLTIP = "Pen tool"; public static String FOUNTAIN_TOOLTIP = "Fountain pen tool"; public static String ROLLER_TOOLTIP = "Roller tool"; public static String FILL_TOOLTIP = "Bucket tool"; public static String RECT_TOOLTIP = "Rectangle tool"; public static String UNDO_TOOLTIP = "Undo last action"; public static String ERASER_TOOLTIP = "Eraser tool"; public static String LINE_TOOLTIP = "Line tool"; public static String MULTI_TOOLTIP = "Multi-tool"; public static String TEXT_TOOLTIP = "Text tool"; public static String OPEN_TOOLTIP = "Open image"; }
Delete COBConfig.java
COBConfig.java
Delete COBConfig.java
<ide><path>OBConfig.java <del>package com.cob.paint; <del> <del>import java.awt.Color; <del>import java.awt.Dimension; <del> <del>public class COBConfig { <del> <del> public static String LANGUAGE = "en"; <del> <del> // Sizes for the things..? <del> public static Dimension APP_DIMENSION = new Dimension(1000,650); // Size of the whole application <del> public static Dimension SLIDER_DIMENSION = new Dimension(30,500); // Size of the RGB sliders <del> public static Dimension BRUSHSLIDER_DIMENSION = new Dimension(300, 30); // Brush size slider <del> <del> // Colors <del> public static Color STARTING_COLOR = new Color(255,255,255); // The default foreground color <del> public static Color BACKGROUND_COLOR = new Color(238,238,238); // The default background color <del> <del> // Language <del> public static String SAVE_TOOLTIP = "Save image"; <del> public static String PEN_TOOLTIP = "Pen tool"; <del> public static String FOUNTAIN_TOOLTIP = "Fountain pen tool"; <del> public static String ROLLER_TOOLTIP = "Roller tool"; <del> public static String FILL_TOOLTIP = "Bucket tool"; <del> public static String RECT_TOOLTIP = "Rectangle tool"; <del> public static String UNDO_TOOLTIP = "Undo last action"; <del> public static String ERASER_TOOLTIP = "Eraser tool"; <del> public static String LINE_TOOLTIP = "Line tool"; <del> public static String MULTI_TOOLTIP = "Multi-tool"; <del> public static String TEXT_TOOLTIP = "Text tool"; <del> public static String OPEN_TOOLTIP = "Open image"; <del>}
Java
apache-2.0
f80d8da878a5f990ea547cfef9e50dccbf41ebb7
0
bingo-open-source/bingo-core
/* Copyright 2004 BEA Systems, 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 bingo.lang.xml; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.util.EmptyStackException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Stack; import javax.xml.namespace.NamespaceContext; import bingo.lang.Strings; //from com.bea.xml.stream @SuppressWarnings({"unchecked","rawtypes"}) public class XmlWriterBaseImpl extends XmlWriterBase implements XmlWriter { protected static final String DEFAULTNS = ""; private Writer writer; private boolean startElementOpened = false; private boolean isEmpty = false; private CharsetEncoder encoder; // these two stacks are used to implement the // writeEndElement() method private Stack localNameStack = new Stack(); private Stack prefixStack = new Stack(); private Stack uriStack = new Stack(); private NamespaceContextImpl context = new NamespaceContextImpl(); private HashSet needToWrite; private boolean isPrefixDefaulting; private int defaultPrefixCount = 0; private HashSet setNeedsWritingNs = new HashSet(); XmlWriterBaseImpl() { } XmlWriterBaseImpl(Writer writer) { setWriter(writer); } public XmlWriter startDocument() throws XmlException { write("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); return this; } public XmlWriter startDocument(String version) throws XmlException { write("<?xml version=\""); write(version); write("\"?>"); return this; } public XmlWriter startDocument(String encoding, String version) throws XmlException { write("<?xml version=\""); write(version); write("\" encoding=\""); write(encoding); write("\"?>"); return this; } public XmlWriter startElement(String namespaceURI, String localName) throws XmlException { context.openScope(); return writeStartElementInternal(namespaceURI, localName); } public XmlWriter startElement(String prefix, String namespaceURI, String localName) throws XmlException { if (namespaceURI == null) throw new IllegalArgumentException("The namespace URI may not be null"); if (localName == null) throw new IllegalArgumentException("The local name may not be null"); if (prefix == null) throw new IllegalArgumentException("The prefix may not be null"); context.openScope(); prepareNamespace(namespaceURI); context.bindNamespace(prefix, namespaceURI); return writeStartElementInternal(namespaceURI, localName); } public XmlWriter startElement(String localName) throws XmlException { context.openScope(); return startElement("", localName); } public XmlWriter emptyElement(String localName) throws XmlException { return emptyElement("", localName); } public XmlWriter emptyElement(String namespaceURI, String localName) throws XmlException { openStartElement(); prepareNamespace(namespaceURI); isEmpty = true; write("<"); writeName("", namespaceURI, localName); return this; } public XmlWriter emptyElement(String prefix,String namespaceURI,String localName) throws XmlException { openStartElement(); prepareNamespace(namespaceURI); isEmpty = true; write("<"); write(prefix); write(":"); write(localName); return this; } public XmlWriter namespace(String namespaceURI) throws XmlException { if (!isOpen()) throw new XmlException("A start element must be written before the default namespace"); if (needsWritingNs(DEFAULTNS)) { write(" xmlns"); write("=\""); write(namespaceURI); write("\""); setPrefix(DEFAULTNS, namespaceURI); } return this; } public XmlWriter namespace(String prefix, String namespaceURI) throws XmlException { if (!isOpen()) throw new XmlException("A start element must be written before a namespace"); if (prefix == null || "".equals(prefix) || "xmlns".equals(prefix)) { namespace(namespaceURI); return this; } if (needsWritingNs(prefix)) { write(" xmlns:"); write(prefix); write("=\""); write(namespaceURI); write("\""); setPrefix(prefix, namespaceURI); } return this; } public XmlWriter attribute(String localName, String value) throws XmlException { return attribute("", localName, value); } public XmlWriter attribute(String namespaceURI, String localName, String value) throws XmlException { if (!isOpen()) { throw new XmlException("A start element must be written before an attribute"); } prepareNamespace(namespaceURI); write(" "); writeName("", namespaceURI, localName); write("=\""); writeCharactersInternal(value.toCharArray(), 0, value.length(), true); write("\""); return this; } public XmlWriter attribute(String prefix, String namespaceURI, String localName, String value) throws XmlException { if (!isOpen()) throw new XmlException("A start element must be written before an attribute"); prepareNamespace(namespaceURI); context.bindNamespace(prefix, namespaceURI); write(" "); writeName(prefix, namespaceURI, localName); write("=\""); writeCharactersInternal(value.toCharArray(), 0, value.length(), true); write("\""); return this; } public XmlWriter text(String text) throws XmlException { return text(text,true); } public XmlWriter text(String text, boolean escape) { closeStartElement(); if(escape && !Strings.isEmpty(text)){ return writeCharactersInternal(text.toCharArray(), 0, text.length(), false); }else{ write(text); return this; } } public XmlWriter cdata(String data) throws XmlException { closeStartElement(); write("<![CDATA["); if (data != null) write(data); write("]]>"); return this; } public XmlWriter comment(String data) throws XmlException { closeStartElement(); write("<!--"); if (data != null) write(data); write("-->"); return this; } public XmlWriter raw(String xml) throws XmlException { closeStartElement(); write(xml); return this; } public XmlWriter endElement() throws XmlException { /* * 07-Mar-2006, TSa: Empty elements do not need special handling, since this call only 'closes' them as a side * effect: real effect is for the open non-empty start element (non-empty just meaning it was written using full * writeStartElement() as opposed to writeEmptyElement()). */ //boolean wasEmpty = isEmpty; if (isOpen()) { closeStartElement(); } try { String prefix = (String) prefixStack.pop(); String local = (String) localNameStack.pop(); uriStack.pop(); //if(!wasEmpty) { openEndTag(); writeName(prefix, "", local); closeEndTag(); //} context.closeScope(); } catch (EmptyStackException e) { throw new XmlException("there is no start element to end",e); } return this; } public XmlWriter processingInstruction(String target) throws XmlException { closeStartElement(); return processingInstruction(target, null); } public XmlWriter processingInstruction(String target, String text) throws XmlException { closeStartElement(); write("<?"); if (target != null) { // isn't passing null an error, actually? write(target); } if (text != null) { // Need a separating white space write(' '); write(text); } write("?>"); return this; } public XmlWriter endDocument() throws XmlException { while (!localNameStack.isEmpty()) { endElement(); } return this; } public XmlWriter flush() throws XmlException { try { writer.flush(); } catch (IOException e) { throw new XmlException(e); } return this; } public void close() throws XmlException { try { writer.flush(); } catch (IOException e) { throw new XmlException(e); } finally { localNameStack.clear(); prefixStack.clear(); uriStack.clear(); setNeedsWritingNs.clear(); } } protected void setWriter(Writer writer) { this.writer = writer; if (writer instanceof OutputStreamWriter) { String charsetName = ((OutputStreamWriter) writer).getEncoding(); this.encoder = Charset.forName(charsetName).newEncoder(); } else { this.encoder = null; } } protected void write(String s) throws XmlException { try { writer.write(null == s ? "" : s); } catch (IOException e) { throw new XmlException(e); } } protected void write(char c) throws XmlException { try { writer.write(c); } catch (IOException e) { throw new XmlException(e); } } protected void write(char[] c) throws XmlException { try { writer.write(c); } catch (IOException e) { throw new XmlException(e); } } protected void write(char[] c, int start, int len) throws XmlException { try { writer.write(c, start, len); } catch (IOException e) { throw new XmlException(e); } } protected XmlWriter writeCharactersInternal(char characters[], int start, int length, boolean isAttributeValue) throws XmlException { if (length == 0) return this; // We expect the common case to be that people do not have these // characters in their XML so we make a pass through the char // array and check. If they're all good, we can call the // underlying Writer once with the entire char array. If we find // a bad character then we punt it to the slow routine. int i = 0; loop: for (; i < length; i++) { char c = characters[i + start]; switch (c) { case '\"': if (!isAttributeValue) { // no need to escape in regular content continue; } case '&': case '<': case '>': break loop; } if (c < 32) { /* * All non-space white space needs to be encoded in attribute values; in normal text tabs and LFs can be * left as is, but everything else (including CRs) needs to be quoted */ if (isAttributeValue || (c != '\t' && c != '\n')) { break loop; } } else if (c > 127) { // Above ascii range? if (encoder != null && !encoder.canEncode(c)) { break loop; } } } if (i < length) { // slow path slowWriteCharacters(characters, start, length, isAttributeValue); } else { // fast path write(characters, start, length); } return this; } private XmlWriter slowWriteCharacters(char chars[], int start, int length, boolean isAttributeValue) throws XmlException { loop: for (int i = 0; i < length; i++) { final char c = chars[i + start]; switch (c) { case '&': write("&amp;"); continue loop; case '<': write("&lt;"); continue loop; case '>': write("&gt;"); continue loop; case '\"': if (isAttributeValue) { write("&quot;"); continue loop; } break; default: if (c < 32) { if (isAttributeValue || (c != '\t' && c != '\n')) { write("&#"); write(Integer.toString(c)); write(';'); continue loop; } } else if (c > 127 && encoder != null && !encoder.canEncode(c)) { write("&#"); write(Integer.toString(c)); write(';'); continue loop; } } write(c); } return this; } protected void closeStartElement() throws XmlException { if (startElementOpened) { closeStartTag(); startElementOpened = false; } } protected boolean isOpen() { return startElementOpened; } protected void closeStartTag() throws XmlException { flushNamespace(); clearNeedsWritingNs(); if (isEmpty) { write("/>"); isEmpty = false; } else write(">"); } private void openStartElement() throws XmlException { if (startElementOpened) { closeStartTag(); } else { startElementOpened = true; } } protected String writeName(String prefix, String namespaceURI, String localName) throws XmlException { if (!("".equals(namespaceURI))) prefix = getPrefixInternal(namespaceURI); if (!("".equals(prefix))) { write(prefix); write(":"); } write(localName); return prefix; } private String getPrefixInternal(String namespaceURI) { String prefix = context.getPrefix(namespaceURI); if (prefix == null) { return ""; } return prefix; } protected String getURIInternal(String prefix) { String uri = context.getNamespaceURI(prefix); if (uri == null) { return ""; } return uri; } protected void openStartTag() throws XmlException { write("<"); } private boolean needToWrite(String uri) { if (needToWrite == null) { needToWrite = new HashSet(); } boolean needs = needToWrite.contains(uri); needToWrite.add(uri); return needs; } private void prepareNamespace(String uri) throws XmlException { if (!isPrefixDefaulting) return; if ("".equals(uri)) return; String prefix = getPrefix(uri); // if the prefix is bound then we can ignore and return if (prefix != null) return; defaultPrefixCount++; prefix = "ns" + defaultPrefixCount; setPrefix(prefix, uri); } // private void removeNamespace(String uri) { // if (!isPrefixDefaulting || needToWrite == null) return; // needToWrite.remove(uri); // } private void flushNamespace() throws XmlException { if (!isPrefixDefaulting || needToWrite == null) return; Iterator i = needToWrite.iterator(); while (i.hasNext()) { String uri = (String) i.next(); String prefix = context.getPrefix(uri); if (prefix == null) { throw new XmlException("Unable to default prefix with uri:" + uri); } namespace(prefix, uri); } needToWrite.clear(); } protected XmlWriter writeStartElementInternal(String namespaceURI, String localName) throws XmlException { if (namespaceURI == null) throw new IllegalArgumentException("The namespace URI may not be null"); if (localName == null) throw new IllegalArgumentException("The local name may not be null"); openStartElement(); openStartTag(); prepareNamespace(namespaceURI); prefixStack.push(writeName("", namespaceURI, localName)); localNameStack.push(localName); uriStack.push(namespaceURI); return this; } private void clearNeedsWritingNs() { setNeedsWritingNs.clear(); } private boolean needsWritingNs(String prefix) { boolean needs = !setNeedsWritingNs.contains(prefix); if (needs) { setNeedsWritingNs.add(prefix); } return needs; } protected void writeDTD(String dtd) throws XmlException { write(dtd); } protected void writeEntityRef(String name) throws XmlException { closeStartElement(); write("&"); write(name); write(";"); } protected void writeCharacters(char[] text, int start, int len) throws XmlException { closeStartElement(); writeCharactersInternal(text, start, len, false); } public String getPrefix(String uri) throws XmlException { return context.getPrefix(uri); } public void setPrefix(String prefix, String uri) throws XmlException { //if() { needToWrite(uri); context.bindNamespace(prefix, uri); //} } public void setDefaultNamespace(String uri) throws XmlException { needToWrite(uri); context.bindDefaultNameSpace(uri); } public void setNamespaceContext(NamespaceContext context) throws XmlException { if (context == null) throw new NullPointerException("The namespace " + " context may" + " not be null."); this.context = new NamespaceContextImpl(context); } public NamespaceContext getNamespaceContext() { return context; } protected void openEndTag() throws XmlException { write("</"); } protected void closeEndTag() throws XmlException { write(">"); } private static final class Symbol { String name; String value; int depth; Symbol(String name, String value, int depth) { this.name = name; this.value = value; this.depth = depth; } public String getName() { return name; } public String getValue() { return value; } // public int getDepth() { // return depth; // } public String toString() { return ("[" + depth + "][" + name + "][" + value + "]"); } } /** * Maintains a table for namespace scope * * * values = map from strings to stacks [a]->[value1,0],[value2,0] * * table = a stack of bindings */ private static final class SymbolTable { private int depth; private Stack table; private Map values; public SymbolTable() { depth = 0; table = new Stack(); values = new HashMap(); } // public void clear() { // depth = 0; // table.clear(); // values.clear(); // } // // // // // Gets the current depth // // // public int getDepth() { // return depth; // } // // public boolean withinElement() { // return depth > 0; // } // // Adds a name/value pair // public void put(String name, String value) { table.push(new Symbol(name, value, depth)); if (!values.containsKey(name)) { Stack valueStack = new Stack(); valueStack.push(value); values.put(name, valueStack); } else { Stack valueStack = (Stack) values.get(name); valueStack.push(value); } } // // Gets the value for a variable // public String get(String name) { Stack valueStack = (Stack) values.get(name); if (valueStack == null || valueStack.isEmpty()) return null; return (String) valueStack.peek(); } public Set getAll(String name) { HashSet result = new HashSet(); Iterator i = table.iterator(); while (i.hasNext()) { Symbol s = (Symbol) i.next(); if (name.equals(s.getName())) result.add(s.getValue()); } return result; } // // add a new highest level scope to the table // public void openScope() { depth++; } // // remove the highest level scope from the table // public void closeScope() { // Get the top binding Symbol symbol = (Symbol) table.peek(); int symbolDepth = symbol.depth; // check if it needs to be popped of the table while (symbolDepth == depth && !table.isEmpty()) { symbol = (Symbol) table.pop(); // pop its value as well Stack valueStack = (Stack) values.get(symbol.name); valueStack.pop(); // check the next binding if (!table.isEmpty()) { symbol = (Symbol) table.peek(); symbolDepth = symbol.depth; } else break; } depth--; } public String toString() { Iterator i = table.iterator(); String retVal = ""; while (i.hasNext()) { Symbol symbol = (Symbol) i.next(); retVal = retVal + symbol + "\n"; } return retVal; } } private static final class NamespaceContextImpl implements NamespaceContext { SymbolTable prefixTable = new SymbolTable(); SymbolTable uriTable = new SymbolTable(); NamespaceContext rootContext; public NamespaceContextImpl() { init(); } public NamespaceContextImpl(NamespaceContext rootContext) { this.rootContext = null; init(); } public void init() { bindNamespace("xml", "http://www.w3.org/XML/1998/namespace"); bindNamespace("xmlns", "http://www.w3.org/XML/1998/namespace"); } public void openScope() { prefixTable.openScope(); uriTable.openScope(); } public void closeScope() { prefixTable.closeScope(); uriTable.closeScope(); } public void bindNamespace(String prefix, String uri) { prefixTable.put(prefix, uri); uriTable.put(uri, prefix); } // public int getDepth() { // return prefixTable.getDepth(); // } public String getNamespaceURI(String prefix) { String value = prefixTable.get(prefix); if (value == null && rootContext != null) return rootContext.getNamespaceURI(prefix); else return value; } public String getPrefix(String uri) { String value = uriTable.get(uri); if (value == null && rootContext != null) return rootContext.getPrefix(uri); else return value; } public void bindDefaultNameSpace(String uri) { bindNamespace("", uri); } // public void unbindDefaultNameSpace() { // bindNamespace("", null); // } // // public void unbindNamespace(String prefix, String uri) { // prefixTable.put(prefix, null); // prefixTable.put(uri, null); // } // // public String getDefaultNameSpace() { // return getNamespaceURI(""); // } public Iterator getPrefixes(String uri) { return (uriTable.getAll(uri)).iterator(); } } }
core-lang/src/main/java/bingo/lang/xml/XmlWriterBaseImpl.java
/* Copyright 2004 BEA Systems, 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 bingo.lang.xml; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.util.EmptyStackException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Stack; import javax.xml.namespace.NamespaceContext; //from com.bea.xml.stream @SuppressWarnings({"unchecked","rawtypes"}) public class XmlWriterBaseImpl extends XmlWriterBase implements XmlWriter { protected static final String DEFAULTNS = ""; private Writer writer; private boolean startElementOpened = false; private boolean isEmpty = false; private CharsetEncoder encoder; // these two stacks are used to implement the // writeEndElement() method private Stack localNameStack = new Stack(); private Stack prefixStack = new Stack(); private Stack uriStack = new Stack(); private NamespaceContextImpl context = new NamespaceContextImpl(); private HashSet needToWrite; private boolean isPrefixDefaulting; private int defaultPrefixCount = 0; private HashSet setNeedsWritingNs = new HashSet(); XmlWriterBaseImpl() { } XmlWriterBaseImpl(Writer writer) { setWriter(writer); } public XmlWriter startDocument() throws XmlException { write("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); return this; } public XmlWriter startDocument(String version) throws XmlException { write("<?xml version=\""); write(version); write("\"?>"); return this; } public XmlWriter startDocument(String encoding, String version) throws XmlException { write("<?xml version=\""); write(version); write("\" encoding=\""); write(encoding); write("\"?>"); return this; } public XmlWriter startElement(String namespaceURI, String localName) throws XmlException { context.openScope(); return writeStartElementInternal(namespaceURI, localName); } public XmlWriter startElement(String prefix, String namespaceURI, String localName) throws XmlException { if (namespaceURI == null) throw new IllegalArgumentException("The namespace URI may not be null"); if (localName == null) throw new IllegalArgumentException("The local name may not be null"); if (prefix == null) throw new IllegalArgumentException("The prefix may not be null"); context.openScope(); prepareNamespace(namespaceURI); context.bindNamespace(prefix, namespaceURI); return writeStartElementInternal(namespaceURI, localName); } public XmlWriter startElement(String localName) throws XmlException { context.openScope(); return startElement("", localName); } public XmlWriter emptyElement(String localName) throws XmlException { return emptyElement("", localName); } public XmlWriter emptyElement(String namespaceURI, String localName) throws XmlException { openStartElement(); prepareNamespace(namespaceURI); isEmpty = true; write("<"); writeName("", namespaceURI, localName); return this; } public XmlWriter emptyElement(String prefix,String namespaceURI,String localName) throws XmlException { openStartElement(); prepareNamespace(namespaceURI); isEmpty = true; write("<"); write(prefix); write(":"); write(localName); return this; } public XmlWriter namespace(String namespaceURI) throws XmlException { if (!isOpen()) throw new XmlException("A start element must be written before the default namespace"); if (needsWritingNs(DEFAULTNS)) { write(" xmlns"); write("=\""); write(namespaceURI); write("\""); setPrefix(DEFAULTNS, namespaceURI); } return this; } public XmlWriter namespace(String prefix, String namespaceURI) throws XmlException { if (!isOpen()) throw new XmlException("A start element must be written before a namespace"); if (prefix == null || "".equals(prefix) || "xmlns".equals(prefix)) { namespace(namespaceURI); return this; } if (needsWritingNs(prefix)) { write(" xmlns:"); write(prefix); write("=\""); write(namespaceURI); write("\""); setPrefix(prefix, namespaceURI); } return this; } public XmlWriter attribute(String localName, String value) throws XmlException { return attribute("", localName, value); } public XmlWriter attribute(String namespaceURI, String localName, String value) throws XmlException { if (!isOpen()) { throw new XmlException("A start element must be written before an attribute"); } prepareNamespace(namespaceURI); write(" "); writeName("", namespaceURI, localName); write("=\""); writeCharactersInternal(value.toCharArray(), 0, value.length(), true); write("\""); return this; } public XmlWriter attribute(String prefix, String namespaceURI, String localName, String value) throws XmlException { if (!isOpen()) throw new XmlException("A start element must be written before an attribute"); prepareNamespace(namespaceURI); context.bindNamespace(prefix, namespaceURI); write(" "); writeName(prefix, namespaceURI, localName); write("=\""); writeCharactersInternal(value.toCharArray(), 0, value.length(), true); write("\""); return this; } public XmlWriter text(String text) throws XmlException { return text(text,true); } public XmlWriter text(String text, boolean escape) { closeStartElement(); if(escape){ return writeCharactersInternal(text.toCharArray(), 0, text.length(), false); }else{ write(text); return this; } } public XmlWriter cdata(String data) throws XmlException { closeStartElement(); write("<![CDATA["); if (data != null) write(data); write("]]>"); return this; } public XmlWriter comment(String data) throws XmlException { closeStartElement(); write("<!--"); if (data != null) write(data); write("-->"); return this; } public XmlWriter raw(String xml) throws XmlException { closeStartElement(); write(xml); return this; } public XmlWriter endElement() throws XmlException { /* * 07-Mar-2006, TSa: Empty elements do not need special handling, since this call only 'closes' them as a side * effect: real effect is for the open non-empty start element (non-empty just meaning it was written using full * writeStartElement() as opposed to writeEmptyElement()). */ //boolean wasEmpty = isEmpty; if (isOpen()) { closeStartElement(); } try { String prefix = (String) prefixStack.pop(); String local = (String) localNameStack.pop(); uriStack.pop(); //if(!wasEmpty) { openEndTag(); writeName(prefix, "", local); closeEndTag(); //} context.closeScope(); } catch (EmptyStackException e) { throw new XmlException("there is no start element to end",e); } return this; } public XmlWriter processingInstruction(String target) throws XmlException { closeStartElement(); return processingInstruction(target, null); } public XmlWriter processingInstruction(String target, String text) throws XmlException { closeStartElement(); write("<?"); if (target != null) { // isn't passing null an error, actually? write(target); } if (text != null) { // Need a separating white space write(' '); write(text); } write("?>"); return this; } public XmlWriter endDocument() throws XmlException { while (!localNameStack.isEmpty()) { endElement(); } return this; } public XmlWriter flush() throws XmlException { try { writer.flush(); } catch (IOException e) { throw new XmlException(e); } return this; } public void close() throws XmlException { try { writer.flush(); } catch (IOException e) { throw new XmlException(e); } finally { localNameStack.clear(); prefixStack.clear(); uriStack.clear(); setNeedsWritingNs.clear(); } } protected void setWriter(Writer writer) { this.writer = writer; if (writer instanceof OutputStreamWriter) { String charsetName = ((OutputStreamWriter) writer).getEncoding(); this.encoder = Charset.forName(charsetName).newEncoder(); } else { this.encoder = null; } } protected void write(String s) throws XmlException { try { writer.write(s); } catch (IOException e) { throw new XmlException(e); } } protected void write(char c) throws XmlException { try { writer.write(c); } catch (IOException e) { throw new XmlException(e); } } protected void write(char[] c) throws XmlException { try { writer.write(c); } catch (IOException e) { throw new XmlException(e); } } protected void write(char[] c, int start, int len) throws XmlException { try { writer.write(c, start, len); } catch (IOException e) { throw new XmlException(e); } } protected XmlWriter writeCharactersInternal(char characters[], int start, int length, boolean isAttributeValue) throws XmlException { if (length == 0) return this; // We expect the common case to be that people do not have these // characters in their XML so we make a pass through the char // array and check. If they're all good, we can call the // underlying Writer once with the entire char array. If we find // a bad character then we punt it to the slow routine. int i = 0; loop: for (; i < length; i++) { char c = characters[i + start]; switch (c) { case '\"': if (!isAttributeValue) { // no need to escape in regular content continue; } case '&': case '<': case '>': break loop; } if (c < 32) { /* * All non-space white space needs to be encoded in attribute values; in normal text tabs and LFs can be * left as is, but everything else (including CRs) needs to be quoted */ if (isAttributeValue || (c != '\t' && c != '\n')) { break loop; } } else if (c > 127) { // Above ascii range? if (encoder != null && !encoder.canEncode(c)) { break loop; } } } if (i < length) { // slow path slowWriteCharacters(characters, start, length, isAttributeValue); } else { // fast path write(characters, start, length); } return this; } private XmlWriter slowWriteCharacters(char chars[], int start, int length, boolean isAttributeValue) throws XmlException { loop: for (int i = 0; i < length; i++) { final char c = chars[i + start]; switch (c) { case '&': write("&amp;"); continue loop; case '<': write("&lt;"); continue loop; case '>': write("&gt;"); continue loop; case '\"': if (isAttributeValue) { write("&quot;"); continue loop; } break; default: if (c < 32) { if (isAttributeValue || (c != '\t' && c != '\n')) { write("&#"); write(Integer.toString(c)); write(';'); continue loop; } } else if (c > 127 && encoder != null && !encoder.canEncode(c)) { write("&#"); write(Integer.toString(c)); write(';'); continue loop; } } write(c); } return this; } protected void closeStartElement() throws XmlException { if (startElementOpened) { closeStartTag(); startElementOpened = false; } } protected boolean isOpen() { return startElementOpened; } protected void closeStartTag() throws XmlException { flushNamespace(); clearNeedsWritingNs(); if (isEmpty) { write("/>"); isEmpty = false; } else write(">"); } private void openStartElement() throws XmlException { if (startElementOpened) { closeStartTag(); } else { startElementOpened = true; } } protected String writeName(String prefix, String namespaceURI, String localName) throws XmlException { if (!("".equals(namespaceURI))) prefix = getPrefixInternal(namespaceURI); if (!("".equals(prefix))) { write(prefix); write(":"); } write(localName); return prefix; } private String getPrefixInternal(String namespaceURI) { String prefix = context.getPrefix(namespaceURI); if (prefix == null) { return ""; } return prefix; } protected String getURIInternal(String prefix) { String uri = context.getNamespaceURI(prefix); if (uri == null) { return ""; } return uri; } protected void openStartTag() throws XmlException { write("<"); } private boolean needToWrite(String uri) { if (needToWrite == null) { needToWrite = new HashSet(); } boolean needs = needToWrite.contains(uri); needToWrite.add(uri); return needs; } private void prepareNamespace(String uri) throws XmlException { if (!isPrefixDefaulting) return; if ("".equals(uri)) return; String prefix = getPrefix(uri); // if the prefix is bound then we can ignore and return if (prefix != null) return; defaultPrefixCount++; prefix = "ns" + defaultPrefixCount; setPrefix(prefix, uri); } // private void removeNamespace(String uri) { // if (!isPrefixDefaulting || needToWrite == null) return; // needToWrite.remove(uri); // } private void flushNamespace() throws XmlException { if (!isPrefixDefaulting || needToWrite == null) return; Iterator i = needToWrite.iterator(); while (i.hasNext()) { String uri = (String) i.next(); String prefix = context.getPrefix(uri); if (prefix == null) { throw new XmlException("Unable to default prefix with uri:" + uri); } namespace(prefix, uri); } needToWrite.clear(); } protected XmlWriter writeStartElementInternal(String namespaceURI, String localName) throws XmlException { if (namespaceURI == null) throw new IllegalArgumentException("The namespace URI may not be null"); if (localName == null) throw new IllegalArgumentException("The local name may not be null"); openStartElement(); openStartTag(); prepareNamespace(namespaceURI); prefixStack.push(writeName("", namespaceURI, localName)); localNameStack.push(localName); uriStack.push(namespaceURI); return this; } private void clearNeedsWritingNs() { setNeedsWritingNs.clear(); } private boolean needsWritingNs(String prefix) { boolean needs = !setNeedsWritingNs.contains(prefix); if (needs) { setNeedsWritingNs.add(prefix); } return needs; } protected void writeDTD(String dtd) throws XmlException { write(dtd); } protected void writeEntityRef(String name) throws XmlException { closeStartElement(); write("&"); write(name); write(";"); } protected void writeCharacters(char[] text, int start, int len) throws XmlException { closeStartElement(); writeCharactersInternal(text, start, len, false); } public String getPrefix(String uri) throws XmlException { return context.getPrefix(uri); } public void setPrefix(String prefix, String uri) throws XmlException { //if() { needToWrite(uri); context.bindNamespace(prefix, uri); //} } public void setDefaultNamespace(String uri) throws XmlException { needToWrite(uri); context.bindDefaultNameSpace(uri); } public void setNamespaceContext(NamespaceContext context) throws XmlException { if (context == null) throw new NullPointerException("The namespace " + " context may" + " not be null."); this.context = new NamespaceContextImpl(context); } public NamespaceContext getNamespaceContext() { return context; } protected void openEndTag() throws XmlException { write("</"); } protected void closeEndTag() throws XmlException { write(">"); } private static final class Symbol { String name; String value; int depth; Symbol(String name, String value, int depth) { this.name = name; this.value = value; this.depth = depth; } public String getName() { return name; } public String getValue() { return value; } // public int getDepth() { // return depth; // } public String toString() { return ("[" + depth + "][" + name + "][" + value + "]"); } } /** * Maintains a table for namespace scope * * * values = map from strings to stacks [a]->[value1,0],[value2,0] * * table = a stack of bindings */ private static final class SymbolTable { private int depth; private Stack table; private Map values; public SymbolTable() { depth = 0; table = new Stack(); values = new HashMap(); } // public void clear() { // depth = 0; // table.clear(); // values.clear(); // } // // // // // Gets the current depth // // // public int getDepth() { // return depth; // } // // public boolean withinElement() { // return depth > 0; // } // // Adds a name/value pair // public void put(String name, String value) { table.push(new Symbol(name, value, depth)); if (!values.containsKey(name)) { Stack valueStack = new Stack(); valueStack.push(value); values.put(name, valueStack); } else { Stack valueStack = (Stack) values.get(name); valueStack.push(value); } } // // Gets the value for a variable // public String get(String name) { Stack valueStack = (Stack) values.get(name); if (valueStack == null || valueStack.isEmpty()) return null; return (String) valueStack.peek(); } public Set getAll(String name) { HashSet result = new HashSet(); Iterator i = table.iterator(); while (i.hasNext()) { Symbol s = (Symbol) i.next(); if (name.equals(s.getName())) result.add(s.getValue()); } return result; } // // add a new highest level scope to the table // public void openScope() { depth++; } // // remove the highest level scope from the table // public void closeScope() { // Get the top binding Symbol symbol = (Symbol) table.peek(); int symbolDepth = symbol.depth; // check if it needs to be popped of the table while (symbolDepth == depth && !table.isEmpty()) { symbol = (Symbol) table.pop(); // pop its value as well Stack valueStack = (Stack) values.get(symbol.name); valueStack.pop(); // check the next binding if (!table.isEmpty()) { symbol = (Symbol) table.peek(); symbolDepth = symbol.depth; } else break; } depth--; } public String toString() { Iterator i = table.iterator(); String retVal = ""; while (i.hasNext()) { Symbol symbol = (Symbol) i.next(); retVal = retVal + symbol + "\n"; } return retVal; } } private static final class NamespaceContextImpl implements NamespaceContext { SymbolTable prefixTable = new SymbolTable(); SymbolTable uriTable = new SymbolTable(); NamespaceContext rootContext; public NamespaceContextImpl() { init(); } public NamespaceContextImpl(NamespaceContext rootContext) { this.rootContext = null; init(); } public void init() { bindNamespace("xml", "http://www.w3.org/XML/1998/namespace"); bindNamespace("xmlns", "http://www.w3.org/XML/1998/namespace"); } public void openScope() { prefixTable.openScope(); uriTable.openScope(); } public void closeScope() { prefixTable.closeScope(); uriTable.closeScope(); } public void bindNamespace(String prefix, String uri) { prefixTable.put(prefix, uri); uriTable.put(uri, prefix); } // public int getDepth() { // return prefixTable.getDepth(); // } public String getNamespaceURI(String prefix) { String value = prefixTable.get(prefix); if (value == null && rootContext != null) return rootContext.getNamespaceURI(prefix); else return value; } public String getPrefix(String uri) { String value = uriTable.get(uri); if (value == null && rootContext != null) return rootContext.getPrefix(uri); else return value; } public void bindDefaultNameSpace(String uri) { bindNamespace("", uri); } // public void unbindDefaultNameSpace() { // bindNamespace("", null); // } // // public void unbindNamespace(String prefix, String uri) { // prefixTable.put(prefix, null); // prefixTable.put(uri, null); // } // // public String getDefaultNameSpace() { // return getNamespaceURI(""); // } public Iterator getPrefixes(String uri) { return (uriTable.getAll(uri)).iterator(); } } }
fixed bug : write null text and set escape=true will throw NPE
core-lang/src/main/java/bingo/lang/xml/XmlWriterBaseImpl.java
fixed bug : write null text and set escape=true will throw NPE
<ide><path>ore-lang/src/main/java/bingo/lang/xml/XmlWriterBaseImpl.java <ide> <ide> import javax.xml.namespace.NamespaceContext; <ide> <add>import bingo.lang.Strings; <add> <ide> //from com.bea.xml.stream <ide> <ide> @SuppressWarnings({"unchecked","rawtypes"}) <ide> public XmlWriter text(String text, boolean escape) { <ide> closeStartElement(); <ide> <del> if(escape){ <add> if(escape && !Strings.isEmpty(text)){ <ide> return writeCharactersInternal(text.toCharArray(), 0, text.length(), false); <ide> }else{ <ide> write(text); <ide> <ide> protected void write(String s) throws XmlException { <ide> try { <del> writer.write(s); <add> writer.write(null == s ? "" : s); <ide> } catch (IOException e) { <ide> throw new XmlException(e); <ide> }
Java
apache-2.0
6249fef4c618505e0fa7025ff32ed72a3a96dd8e
0
gavanx/pdflearn,gavanx/pdflearn
/* * 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.pdfbox.rendering; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsDevice; import java.awt.Paint; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.TexturePaint; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.GeneralPath; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSNumber; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.common.function.PDFunction; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDVectorFont; import org.apache.pdfbox.pdmodel.graphics.PDLineDashPattern; import org.apache.pdfbox.pdmodel.graphics.blend.SoftMaskPaint; import org.apache.pdfbox.pdmodel.graphics.color.PDColor; import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace; import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceGray; import org.apache.pdfbox.pdmodel.graphics.color.PDPattern; import org.apache.pdfbox.pdmodel.graphics.form.PDTransparencyGroup; import org.apache.pdfbox.pdmodel.graphics.image.PDImage; import org.apache.pdfbox.pdmodel.graphics.pattern.PDAbstractPattern; import org.apache.pdfbox.pdmodel.graphics.pattern.PDShadingPattern; import org.apache.pdfbox.pdmodel.graphics.pattern.PDTilingPattern; import org.apache.pdfbox.pdmodel.graphics.shading.PDShading; import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState; import org.apache.pdfbox.pdmodel.graphics.state.PDSoftMask; import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationMarkup; import org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary; import org.apache.pdfbox.util.Matrix; import org.apache.pdfbox.util.Vector; /** * Paints a page in a PDF document to a Graphics context. May be subclassed to provide custom * rendering. * * <p>If you want to do custom graphics processing rather than Graphics2D rendering, then you should * subclass PDFGraphicsStreamEngine instead. Subclassing PageDrawer is only suitable for cases * where the goal is to render onto a Graphics2D surface. * * @author Ben Litchfield */ public class PageDrawer extends PDFGraphicsStreamEngine { private static final Log LOG = LogFactory.getLog(PageDrawer.class); // parent document renderer - note: this is needed for not-yet-implemented resource caching private final PDFRenderer renderer; // glyph caches private final Map<PDFont, GlyphCache> glyphCaches = new HashMap<PDFont, GlyphCache>(); // the graphics device to draw to, xform is the initial transform of the device (i.e. DPI) private Graphics2D graphics; private AffineTransform xform; // the page box to draw (usually the crop box but may be another) private PDRectangle pageSize; // clipping winding rule used for the clipping path private int clipWindingRule = -1; private GeneralPath linePath = new GeneralPath(); // last clipping path private Area lastClip; // buffered clipping area for text being drawn private Area textClippingArea; /** * Constructor. * * @param parameters Parameters for page drawing. * @throws IOException If there is an error loading properties from the file. */ public PageDrawer(PageDrawerParameters parameters) throws IOException { super(parameters.getPage()); this.renderer = parameters.getRenderer(); } /** * Returns the parent renderer. */ public final PDFRenderer getRenderer() { return renderer; } /** * Returns the underlying Graphics2D. May be null if drawPage has not yet been called. */ protected final Graphics2D getGraphics() { return graphics; } /** * Returns the current line path. This is reset to empty after each fill/stroke. */ protected final GeneralPath getLinePath() { return linePath; } /** * Sets high-quality rendering hints on the current Graphics2D. */ private void setRenderingHints() { graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } /** * Draws the page to the requested context. * * @param g The graphics context to draw onto. * @param pageSize The size of the page to draw. * @throws IOException If there is an IO error while drawing the page. */ public void drawPage(Graphics g, PDRectangle pageSize) throws IOException { graphics = (Graphics2D) g; xform = graphics.getTransform(); this.pageSize = pageSize; setRenderingHints(); graphics.translate(0, pageSize.getHeight()); graphics.scale(1, -1); // TODO use getStroke() to set the initial stroke graphics.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER)); // adjust for non-(0,0) crop box graphics.translate(-pageSize.getLowerLeftX(), -pageSize.getLowerLeftY()); processPage(getPage()); for (PDAnnotation annotation : getPage().getAnnotations()) { showAnnotation(annotation); } graphics = null; } /** * Draws the pattern stream to the requested context. * * @param g The graphics context to draw onto. * @param pattern The tiling pattern to be used. * @param colorSpace color space for this tiling. * @param color color for this tiling. * @param patternMatrix the pattern matrix * @throws IOException If there is an IO error while drawing the page. */ void drawTilingPattern(Graphics2D g, PDTilingPattern pattern, PDColorSpace colorSpace, PDColor color, Matrix patternMatrix) throws IOException { Graphics2D oldGraphics = graphics; graphics = g; GeneralPath oldLinePath = linePath; linePath = new GeneralPath(); Area oldLastClip = lastClip; lastClip = null; setRenderingHints(); processTilingPattern(pattern, color, colorSpace, patternMatrix); graphics = oldGraphics; linePath = oldLinePath; lastClip = oldLastClip; } /** * Returns an AWT paint for the given PDColor. */ protected Paint getPaint(PDColor color) throws IOException { PDColorSpace colorSpace = color.getColorSpace(); if (!(colorSpace instanceof PDPattern)) { float[] rgb = colorSpace.toRGB(color.getComponents()); return new Color(rgb[0], rgb[1], rgb[2]); } else { PDPattern patternSpace = (PDPattern)colorSpace; PDAbstractPattern pattern = patternSpace.getPattern(color); if (pattern instanceof PDTilingPattern) { PDTilingPattern tilingPattern = (PDTilingPattern) pattern; if (tilingPattern.getPaintType() == PDTilingPattern.PAINT_COLORED) { // colored tiling pattern return new TilingPaint(this, tilingPattern, xform); } else { // uncolored tiling pattern return new TilingPaint(this, tilingPattern, patternSpace.getUnderlyingColorSpace(), color, xform); } } else { PDShadingPattern shadingPattern = (PDShadingPattern)pattern; PDShading shading = shadingPattern.getShading(); if (shading == null) { LOG.error("shadingPattern is null, will be filled with transparency"); return new Color(0,0,0,0); } return shading.toPaint(Matrix.concatenate(getInitialMatrix(), shadingPattern.getMatrix())); } } } // sets the clipping path using caching for performance, we track lastClip manually because // Graphics2D#getClip() returns a new object instead of the same one passed to setClip private void setClip() { Area clippingPath = getGraphicsState().getCurrentClippingPath(); if (clippingPath != lastClip) { graphics.setClip(clippingPath); lastClip = clippingPath; } } @Override public void beginText() throws IOException { setClip(); beginTextClip(); } @Override public void endText() throws IOException { endTextClip(); } /** * Begin buffering the text clipping path, if any. */ private void beginTextClip() { // buffer the text clip because it represents a single clipping area textClippingArea = new Area(); } /** * End buffering the text clipping path, if any. */ private void endTextClip() { PDGraphicsState state = getGraphicsState(); RenderingMode renderingMode = state.getTextState().getRenderingMode(); // apply the buffered clip as one area if (renderingMode.isClip() && !textClippingArea.isEmpty()) { state.intersectClippingPath(textClippingArea); textClippingArea = null; } } @Override protected void showFontGlyph(Matrix textRenderingMatrix, PDFont font, int code, String unicode, Vector displacement) throws IOException { AffineTransform at = textRenderingMatrix.createAffineTransform(); at.concatenate(font.getFontMatrix().createAffineTransform()); // create cache if it does not exist PDVectorFont vectorFont = ((PDVectorFont)font); GlyphCache cache = glyphCaches.get(font); if (cache == null) { cache = new GlyphCache(vectorFont); glyphCaches.put(font, cache); } // cache glyph path if is not already cache GeneralPath path = cache.getPathForCharacterCode(code); if (path == null) { path = vectorFont.getNormalizedPath(code); cache.put(code, path); } drawGlyph(path, font, code, displacement, at); } /** * Renders a glyph. * * @param path the GeneralPath for the glyph * @param font the font * @param code character code * @param displacement the glyph's displacement (advance) * @param at the transformation * @throws IOException if something went wrong */ private void drawGlyph(GeneralPath path, PDFont font, int code, Vector displacement, AffineTransform at) throws IOException { PDGraphicsState state = getGraphicsState(); RenderingMode renderingMode = state.getTextState().getRenderingMode(); if (path != null) { // stretch non-embedded glyph if it does not match the width contained in the PDF if (!font.isEmbedded()) { float fontWidth = font.getWidthFromFont(code); if (fontWidth > 0 && // ignore spaces Math.abs(fontWidth - displacement.getX() * 1000) > 0.0001) { float pdfWidth = displacement.getX() * 1000; at.scale(pdfWidth / fontWidth, 1); } } // render glyph Shape glyph = at.createTransformedShape(path); if (renderingMode.isFill()) { graphics.setComposite(state.getNonStrokingJavaComposite()); graphics.setPaint(getNonStrokingPaint()); setClip(); graphics.fill(glyph); } if (renderingMode.isStroke()) { graphics.setComposite(state.getStrokingJavaComposite()); graphics.setPaint(getStrokingPaint()); graphics.setStroke(getStroke()); setClip(); graphics.draw(glyph); } if (renderingMode.isClip()) { textClippingArea.add(new Area(glyph)); } } } @Override public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3) { // to ensure that the path is created in the right direction, we have to create // it by combining single lines instead of creating a simple rectangle linePath.moveTo((float) p0.getX(), (float) p0.getY()); linePath.lineTo((float) p1.getX(), (float) p1.getY()); linePath.lineTo((float) p2.getX(), (float) p2.getY()); linePath.lineTo((float) p3.getX(), (float) p3.getY()); // close the subpath instead of adding the last line so that a possible set line // cap style isn't taken into account at the "beginning" of the rectangle linePath.closePath(); } /** * Generates AWT raster for a soft mask * * @param softMask soft mask * @return AWT raster for soft mask * @throws IOException */ private Raster createSoftMaskRaster(PDSoftMask softMask) throws IOException { TransparencyGroup transparencyGroup = new TransparencyGroup(softMask.getGroup(), true); COSName subtype = softMask.getSubType(); if (COSName.ALPHA.equals(subtype)) { return transparencyGroup.getAlphaRaster(); } else if (COSName.LUMINOSITY.equals(subtype)) { return transparencyGroup.getLuminosityRaster(); } else { throw new IOException("Invalid soft mask subtype."); } } private Paint applySoftMaskToPaint(Paint parentPaint, PDSoftMask softMask) throws IOException { if (softMask != null) { //TODO PDFBOX-2934 if (COSName.ALPHA.equals(softMask.getSubType())) { LOG.info("alpha smask not implemented yet, is ignored"); return parentPaint; } return new SoftMaskPaint(parentPaint, createSoftMaskRaster(softMask)); } else { return parentPaint; } } // returns the stroking AWT Paint private Paint getStrokingPaint() throws IOException { return applySoftMaskToPaint( getPaint(getGraphicsState().getStrokingColor()), getGraphicsState().getSoftMask()); } // returns the non-stroking AWT Paint private Paint getNonStrokingPaint() throws IOException { return getPaint(getGraphicsState().getNonStrokingColor()); } // create a new stroke based on the current CTM and the current stroke private BasicStroke getStroke() { PDGraphicsState state = getGraphicsState(); // apply the CTM float lineWidth = transformWidth(state.getLineWidth()); // minimum line width as used by Adobe Reader if (lineWidth < 0.25) { lineWidth = 0.25f; } PDLineDashPattern dashPattern = state.getLineDashPattern(); int phaseStart = dashPattern.getPhase(); float[] dashArray = dashPattern.getDashArray(); if (dashArray != null) { // apply the CTM for (int i = 0; i < dashArray.length; ++i) { // minimum line dash width avoids JVM crash, see PDFBOX-2373, PDFBOX-2929, PDFBOX-3204 float w = transformWidth(dashArray[i]); if (w != 0) { dashArray[i] = Math.max(w, 0.035f); } } phaseStart = (int)transformWidth(phaseStart); // empty dash array is illegal // avoid also infinite and NaN values (PDFBOX-3360) if (dashArray.length == 0 || Float.isInfinite(phaseStart) || Float.isNaN(phaseStart)) { dashArray = null; } else { for (int i = 0; i < dashArray.length; ++i) { if (Float.isInfinite(dashArray[i]) || Float.isNaN(dashArray[i])) { dashArray = null; break; } } } } return new BasicStroke(lineWidth, state.getLineCap(), state.getLineJoin(), state.getMiterLimit(), dashArray, phaseStart); } @Override public void strokePath() throws IOException { graphics.setComposite(getGraphicsState().getStrokingJavaComposite()); graphics.setPaint(getStrokingPaint()); graphics.setStroke(getStroke()); setClip(); graphics.draw(linePath); linePath.reset(); } @Override public void fillPath(int windingRule) throws IOException { graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); graphics.setPaint(getNonStrokingPaint()); setClip(); linePath.setWindingRule(windingRule); // disable anti-aliasing for rectangular paths, this is a workaround to avoid small stripes // which occur when solid fills are used to simulate piecewise gradients, see PDFBOX-2302 // note that we ignore paths with a width/height under 1 as these are fills used as strokes, // see PDFBOX-1658 for an example Rectangle2D bounds = linePath.getBounds2D(); boolean noAntiAlias = isRectangular(linePath) && bounds.getWidth() > 1 && bounds.getHeight() > 1; if (noAntiAlias) { graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } if (!(graphics.getPaint() instanceof Color)) { // apply clip to path to avoid oversized device bounds in shading contexts (PDFBOX-2901) Area area = new Area(linePath); area.intersect(new Area(graphics.getClip())); graphics.fill(area); } else { graphics.fill(linePath); } linePath.reset(); if (noAntiAlias) { // JDK 1.7 has a bug where rendering hints are reset by the above call to // the setRenderingHint method, so we re-set all hints, see PDFBOX-2302 setRenderingHints(); } } /** * Returns true if the given path is rectangular. */ private boolean isRectangular(GeneralPath path) { PathIterator iter = path.getPathIterator(null); double[] coords = new double[6]; int count = 0; int[] xs = new int[4]; int[] ys = new int[4]; while (!iter.isDone()) { switch(iter.currentSegment(coords)) { case PathIterator.SEG_MOVETO: if (count == 0) { xs[count] = (int)Math.floor(coords[0]); ys[count] = (int)Math.floor(coords[1]); } else { return false; } count++; break; case PathIterator.SEG_LINETO: if (count < 4) { xs[count] = (int)Math.floor(coords[0]); ys[count] = (int)Math.floor(coords[1]); } else { return false; } count++; break; case PathIterator.SEG_CUBICTO: return false; case PathIterator.SEG_CLOSE: break; } iter.next(); } if (count == 4) { return xs[0] == xs[1] || xs[0] == xs[2] || ys[0] == ys[1] || ys[0] == ys[3]; } return false; } /** * Fills and then strokes the path. * * @param windingRule The winding rule this path will use. * @throws IOException If there is an IO error while filling the path. */ @Override public void fillAndStrokePath(int windingRule) throws IOException { // TODO can we avoid cloning the path? GeneralPath path = (GeneralPath)linePath.clone(); fillPath(windingRule); linePath = path; strokePath(); } @Override public void clip(int windingRule) { // the clipping path will not be updated until the succeeding painting operator is called clipWindingRule = windingRule; } @Override public void moveTo(float x, float y) { linePath.moveTo(x, y); } @Override public void lineTo(float x, float y) { linePath.lineTo(x, y); } @Override public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3) { linePath.curveTo(x1, y1, x2, y2, x3, y3); } @Override public Point2D getCurrentPoint() { return linePath.getCurrentPoint(); } @Override public void closePath() { linePath.closePath(); } @Override public void endPath() { if (clipWindingRule != -1) { linePath.setWindingRule(clipWindingRule); getGraphicsState().intersectClippingPath(linePath); clipWindingRule = -1; } linePath.reset(); } @Override public void drawImage(PDImage pdImage) throws IOException { Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); AffineTransform at = ctm.createAffineTransform(); if (!pdImage.getInterpolate()) { boolean isScaledUp = pdImage.getWidth() < Math.round(at.getScaleX()) || pdImage.getHeight() < Math.round(at.getScaleY()); // if the image is scaled down, we use smooth interpolation, eg PDFBOX-2364 // only when scaled up do we use nearest neighbour, eg PDFBOX-2302 / mori-cvpr01.pdf // stencils are excluded from this rule (see survey.pdf) if (isScaledUp || pdImage.isStencil()) { graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); } } if (pdImage.isStencil()) { // fill the image with paint BufferedImage image = pdImage.getStencilImage(getNonStrokingPaint()); // draw the image drawBufferedImage(image, at); } else { // draw the image drawBufferedImage(pdImage.getImage(), at); } if (!pdImage.getInterpolate()) { // JDK 1.7 has a bug where rendering hints are reset by the above call to // the setRenderingHint method, so we re-set all hints, see PDFBOX-2302 setRenderingHints(); } } private void drawBufferedImage(BufferedImage image, AffineTransform at) throws IOException { graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); setClip(); PDSoftMask softMask = getGraphicsState().getSoftMask(); if( softMask != null ) { AffineTransform imageTransform = new AffineTransform(at); imageTransform.scale(1, -1); imageTransform.translate(0, -1); Paint awtPaint = new TexturePaint(image, new Rectangle2D.Double(imageTransform.getTranslateX(), imageTransform.getTranslateY(), imageTransform.getScaleX(), imageTransform.getScaleY())); awtPaint = applySoftMaskToPaint(awtPaint, softMask); graphics.setPaint(awtPaint); Rectangle2D unitRect = new Rectangle2D.Float(0, 0, 1, 1); graphics.fill(at.createTransformedShape(unitRect)); } else { COSBase transfer = getGraphicsState().getTransfer(); if (transfer instanceof COSArray || transfer instanceof COSDictionary) { image = applyTransferFunction(image, transfer); } int width = image.getWidth(null); int height = image.getHeight(null); AffineTransform imageTransform = new AffineTransform(at); imageTransform.scale(1.0 / width, -1.0 / height); imageTransform.translate(0, -height); graphics.drawImage(image, imageTransform, null); } } private BufferedImage applyTransferFunction(BufferedImage image, COSBase transfer) throws IOException { BufferedImage bim; if (image.getColorModel().hasAlpha()) { bim = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); } else { bim = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); } // prepare transfer functions (either one per color or one for all) // and maps (actually arrays[256] to be faster) to avoid calculating values several times Integer rMap[], gMap[], bMap[]; PDFunction rf, gf, bf; if (transfer instanceof COSArray) { COSArray ar = (COSArray) transfer; rf = PDFunction.create(ar.getObject(0)); gf = PDFunction.create(ar.getObject(1)); bf = PDFunction.create(ar.getObject(2)); rMap = new Integer[256]; gMap = new Integer[256]; bMap = new Integer[256]; } else { rf = PDFunction.create(transfer); gf = rf; bf = rf; rMap = new Integer[256]; gMap = rMap; bMap = rMap; } // apply the transfer function to each color, but keep alpha float input[] = new float[1]; for (int x = 0; x < image.getWidth(); ++x) { for (int y = 0; y < image.getHeight(); ++y) { int rgb = image.getRGB(x, y); int ri = (rgb >> 16) & 0xFF; int gi = (rgb >> 8) & 0xFF; int bi = rgb & 0xFF; int ro, go, bo; if (rMap[ri] != null) { ro = rMap[ri]; } else { input[0] = (ri & 0xFF) / 255f; ro = (int) (rf.eval(input)[0] * 255); rMap[ri] = ro; } if (gMap[gi] != null) { go = gMap[gi]; } else { input[0] = (gi & 0xFF) / 255f; go = (int) (gf.eval(input)[0] * 255); gMap[gi] = go; } if (bMap[bi] != null) { bo = bMap[bi]; } else { input[0] = (bi & 0xFF) / 255f; bo = (int) (bf.eval(input)[0] * 255); bMap[bi] = bo; } bim.setRGB(x, y, (rgb & 0xFF000000) | (ro << 16) | (go << 8) | bo); } } return bim; } @Override public void shadingFill(COSName shadingName) throws IOException { PDShading shading = getResources().getShading(shadingName); Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); Paint paint = shading.toPaint(ctm); graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); graphics.setPaint(paint); graphics.setClip(null); lastClip = null; graphics.fill(getGraphicsState().getCurrentClippingPath()); } @Override public void showAnnotation(PDAnnotation annotation) throws IOException { lastClip = null; //TODO support more annotation flags (Invisible, NoZoom, NoRotate) // Example for NoZoom can be found in p5 of PDFBOX-2348 int deviceType = graphics.getDeviceConfiguration().getDevice().getType(); if (deviceType == GraphicsDevice.TYPE_PRINTER && !annotation.isPrinted()) { return; } if (deviceType == GraphicsDevice.TYPE_RASTER_SCREEN && annotation.isNoView()) { return; } if (annotation.isHidden()) { return; } super.showAnnotation(annotation); if (annotation.getAppearance() == null) { if (annotation instanceof PDAnnotationLink) { drawAnnotationLinkBorder((PDAnnotationLink) annotation); } if (annotation instanceof PDAnnotationMarkup && annotation.getSubtype().equals(PDAnnotationMarkup.SUB_TYPE_INK)) { drawAnnotationInk((PDAnnotationMarkup) annotation); } } } // return border info. BorderStyle must be provided as parameter because // method is not available in the base class private AnnotationBorder getAnnotationBorder(PDAnnotation annotation, PDBorderStyleDictionary borderStyle) { AnnotationBorder ab = new AnnotationBorder(); COSArray border = annotation.getBorder(); if (borderStyle == null) { if (border.get(2) instanceof COSNumber) { ab.width = ((COSNumber) border.getObject(2)).floatValue(); } if (border.size() > 3) { COSBase base3 = border.getObject(3); if (base3 instanceof COSArray) { ab.dashArray = ((COSArray) base3).toFloatArray(); } } } else { ab.width = borderStyle.getWidth(); if (borderStyle.getStyle().equals(PDBorderStyleDictionary.STYLE_DASHED)) { ab.dashArray = borderStyle.getDashStyle().getDashArray(); } if (borderStyle.getStyle().equals(PDBorderStyleDictionary.STYLE_UNDERLINE)) { ab.underline = true; } } ab.color = annotation.getColor(); if (ab.color == null) { // spec is unclear, but black seems to be the right thing to do ab.color = new PDColor(new float[] { 0 }, PDDeviceGray.INSTANCE); } if (ab.dashArray != null) { boolean allZero = true; for (float f : ab.dashArray) { if (f != 0) { allZero = false; break; } } if (allZero) { ab.dashArray = null; } } return ab; } private void drawAnnotationLinkBorder(PDAnnotationLink link) throws IOException { AnnotationBorder ab = getAnnotationBorder(link, link.getBorderStyle()); if (ab.width == 0 || ab.color.getComponents().length == 0) { return; } PDRectangle rectangle = link.getRectangle(); Stroke oldStroke = graphics.getStroke(); graphics.setPaint(getPaint(ab.color)); BasicStroke stroke = new BasicStroke(ab.width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10, ab.dashArray, 0); graphics.setStroke(stroke); graphics.setClip(null); if (ab.underline) { graphics.drawLine((int) rectangle.getLowerLeftX(), (int) rectangle.getLowerLeftY(), (int) (rectangle.getLowerLeftX() + rectangle.getWidth()), (int) rectangle.getLowerLeftY()); } else { graphics.drawRect((int) rectangle.getLowerLeftX(), (int) rectangle.getLowerLeftY(), (int) rectangle.getWidth(), (int) rectangle.getHeight()); } graphics.setStroke(oldStroke); } private void drawAnnotationInk(PDAnnotationMarkup inkAnnotation) throws IOException { if (!inkAnnotation.getCOSObject().containsKey(COSName.INKLIST)) { return; } //TODO there should be an InkAnnotation class with a getInkList method COSBase base = inkAnnotation.getCOSObject().getDictionaryObject(COSName.INKLIST); if (!(base instanceof COSArray)) { return; } // PDF spec does not mention /Border for ink annotations, but it is used if /BS is not available AnnotationBorder ab = getAnnotationBorder(inkAnnotation, inkAnnotation.getBorderStyle()); if (ab.width == 0 || ab.color.getComponents().length == 0) { return; } graphics.setPaint(getPaint(ab.color)); Stroke oldStroke = graphics.getStroke(); BasicStroke stroke = new BasicStroke(ab.width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10, ab.dashArray, 0); graphics.setStroke(stroke); graphics.setClip(null); COSArray pathsArray = (COSArray) base; for (COSBase baseElement : (Iterable<? extends COSBase>) pathsArray.toList()) { if (!(baseElement instanceof COSArray)) { continue; } COSArray pathArray = (COSArray) baseElement; int nPoints = pathArray.size() / 2; // "When drawn, the points shall be connected by straight lines or curves // in an implementation-dependent way" - we do lines. GeneralPath path = new GeneralPath(); for (int i = 0; i < nPoints; ++i) { COSBase bx = pathArray.getObject(i * 2); COSBase by = pathArray.getObject(i * 2 + 1); if (bx instanceof COSNumber && by instanceof COSNumber) { float x = ((COSNumber) bx).floatValue(); float y = ((COSNumber) by).floatValue(); if (i == 0) { path.moveTo(x, y); } else { path.lineTo(x, y); } } } graphics.draw(path); } graphics.setStroke(oldStroke); } @Override public void showTransparencyGroup(PDTransparencyGroup form) throws IOException { TransparencyGroup group = new TransparencyGroup(form, false); graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); setClip(); // both the DPI xform and the CTM were already applied to the group, so all we do // here is draw it directly onto the Graphics2D device at the appropriate position PDRectangle bbox = group.getBBox(); AffineTransform prev = graphics.getTransform(); float x = bbox.getLowerLeftX(); float y = pageSize.getHeight() - bbox.getLowerLeftY() - bbox.getHeight(); graphics.setTransform(AffineTransform.getTranslateInstance(x * xform.getScaleX(), y * xform.getScaleY())); PDSoftMask softMask = getGraphicsState().getSoftMask(); if (softMask != null) { BufferedImage image = group.getImage(); Paint awtPaint = new TexturePaint(image, new Rectangle2D.Float(0, 0, image.getWidth(), image.getHeight())); awtPaint = applySoftMaskToPaint(awtPaint, softMask); // todo: PDFBOX-994 problem here? graphics.setPaint(awtPaint); graphics.fill(new Rectangle2D.Float(0, 0, bbox.getWidth() * (float)xform.getScaleX(), bbox.getHeight() * (float)xform.getScaleY())); } else { graphics.drawImage(group.getImage(), null, null); } graphics.setTransform(prev); } private static class AnnotationBorder { private float[] dashArray = null; private boolean underline = false; private float width = 0; private PDColor color; } /** * Transparency group. **/ private final class TransparencyGroup { private final BufferedImage image; private final PDRectangle bbox; private final int minX; private final int minY; private final int width; private final int height; /** * Creates a buffered image for a transparency group result. */ private TransparencyGroup(PDTransparencyGroup form, boolean isSoftMask) throws IOException { Graphics2D g2dOriginal = graphics; Area lastClipOriginal = lastClip; // get the CTM x Form Matrix transform Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); Matrix transform = Matrix.concatenate(ctm, form.getMatrix()); // transform the bbox GeneralPath transformedBox = form.getBBox().transform(transform); // clip the bbox to prevent giant bboxes from consuming all memory Area clip = (Area)getGraphicsState().getCurrentClippingPath().clone(); clip.intersect(new Area(transformedBox)); Rectangle2D clipRect = clip.getBounds2D(); this.bbox = new PDRectangle((float)clipRect.getX(), (float)clipRect.getY(), (float)clipRect.getWidth(), (float)clipRect.getHeight()); // apply the underlying Graphics2D device's DPI transform Shape deviceClip = xform.createTransformedShape(clip); Rectangle2D bounds = deviceClip.getBounds2D(); minX = (int) Math.floor(bounds.getMinX()); minY = (int) Math.floor(bounds.getMinY()); int maxX = (int) Math.floor(bounds.getMaxX()) + 1; int maxY = (int) Math.floor(bounds.getMaxY()) + 1; width = maxX - minX; height = maxY - minY; image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // FIXME - color space Graphics2D g = image.createGraphics(); // flip y-axis g.translate(0, height); g.scale(1, -1); // apply device transform (DPI) g.transform(xform); // adjust the origin g.translate(-clipRect.getX(), -clipRect.getY()); graphics = g; try { if (isSoftMask) { processSoftMask(form); } else { processTransparencyGroup(form); } } finally { lastClip = lastClipOriginal; graphics.dispose(); graphics = g2dOriginal; } } public BufferedImage getImage() { return image; } public PDRectangle getBBox() { return bbox; } public Raster getAlphaRaster() { return image.getAlphaRaster(); } public Raster getLuminosityRaster() { BufferedImage gray = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); Graphics g = gray.getGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); return gray.getRaster(); } } }
pdfbox/src/main/java/org/apache/pdfbox/rendering/PageDrawer.java
/* * 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.pdfbox.rendering; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsDevice; import java.awt.Paint; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.TexturePaint; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.GeneralPath; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSNumber; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.common.function.PDFunction; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDVectorFont; import org.apache.pdfbox.pdmodel.graphics.PDLineDashPattern; import org.apache.pdfbox.pdmodel.graphics.blend.SoftMaskPaint; import org.apache.pdfbox.pdmodel.graphics.color.PDColor; import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace; import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceGray; import org.apache.pdfbox.pdmodel.graphics.color.PDPattern; import org.apache.pdfbox.pdmodel.graphics.form.PDTransparencyGroup; import org.apache.pdfbox.pdmodel.graphics.image.PDImage; import org.apache.pdfbox.pdmodel.graphics.pattern.PDAbstractPattern; import org.apache.pdfbox.pdmodel.graphics.pattern.PDShadingPattern; import org.apache.pdfbox.pdmodel.graphics.pattern.PDTilingPattern; import org.apache.pdfbox.pdmodel.graphics.shading.PDShading; import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState; import org.apache.pdfbox.pdmodel.graphics.state.PDSoftMask; import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationMarkup; import org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary; import org.apache.pdfbox.util.Matrix; import org.apache.pdfbox.util.Vector; /** * Paints a page in a PDF document to a Graphics context. May be subclassed to provide custom * rendering. * * <p>If you want to do custom graphics processing rather than Graphics2D rendering, then you should * subclass PDFGraphicsStreamEngine instead. Subclassing PageDrawer is only suitable for cases * where the goal is to render onto a Graphics2D surface. * * @author Ben Litchfield */ public class PageDrawer extends PDFGraphicsStreamEngine { private static final Log LOG = LogFactory.getLog(PageDrawer.class); // parent document renderer - note: this is needed for not-yet-implemented resource caching private final PDFRenderer renderer; // glyph caches private final Map<PDFont, GlyphCache> glyphCaches = new HashMap<PDFont, GlyphCache>(); // the graphics device to draw to, xform is the initial transform of the device (i.e. DPI) private Graphics2D graphics; private AffineTransform xform; // the page box to draw (usually the crop box but may be another) private PDRectangle pageSize; // clipping winding rule used for the clipping path private int clipWindingRule = -1; private GeneralPath linePath = new GeneralPath(); // last clipping path private Area lastClip; // buffered clipping area for text being drawn private Area textClippingArea; /** * Constructor. * * @param parameters Parameters for page drawing. * @throws IOException If there is an error loading properties from the file. */ public PageDrawer(PageDrawerParameters parameters) throws IOException { super(parameters.getPage()); this.renderer = parameters.getRenderer(); } /** * Returns the parent renderer. */ public final PDFRenderer getRenderer() { return renderer; } /** * Returns the underlying Graphics2D. May be null if drawPage has not yet been called. */ protected final Graphics2D getGraphics() { return graphics; } /** * Returns the current line path. This is reset to empty after each fill/stroke. */ protected final GeneralPath getLinePath() { return linePath; } /** * Sets high-quality rendering hints on the current Graphics2D. */ private void setRenderingHints() { graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } /** * Draws the page to the requested context. * * @param g The graphics context to draw onto. * @param pageSize The size of the page to draw. * @throws IOException If there is an IO error while drawing the page. */ public void drawPage(Graphics g, PDRectangle pageSize) throws IOException { graphics = (Graphics2D) g; xform = graphics.getTransform(); this.pageSize = pageSize; setRenderingHints(); graphics.translate(0, pageSize.getHeight()); graphics.scale(1, -1); // TODO use getStroke() to set the initial stroke graphics.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER)); // adjust for non-(0,0) crop box graphics.translate(-pageSize.getLowerLeftX(), -pageSize.getLowerLeftY()); processPage(getPage()); for (PDAnnotation annotation : getPage().getAnnotations()) { showAnnotation(annotation); } graphics = null; } /** * Draws the pattern stream to the requested context. * * @param g The graphics context to draw onto. * @param pattern The tiling pattern to be used. * @param colorSpace color space for this tiling. * @param color color for this tiling. * @param patternMatrix the pattern matrix * @throws IOException If there is an IO error while drawing the page. */ void drawTilingPattern(Graphics2D g, PDTilingPattern pattern, PDColorSpace colorSpace, PDColor color, Matrix patternMatrix) throws IOException { Graphics2D oldGraphics = graphics; graphics = g; GeneralPath oldLinePath = linePath; linePath = new GeneralPath(); Area oldLastClip = lastClip; lastClip = null; setRenderingHints(); processTilingPattern(pattern, color, colorSpace, patternMatrix); graphics = oldGraphics; linePath = oldLinePath; lastClip = oldLastClip; } /** * Returns an AWT paint for the given PDColor. */ protected Paint getPaint(PDColor color) throws IOException { PDColorSpace colorSpace = color.getColorSpace(); if (!(colorSpace instanceof PDPattern)) { float[] rgb = colorSpace.toRGB(color.getComponents()); return new Color(rgb[0], rgb[1], rgb[2]); } else { PDPattern patternSpace = (PDPattern)colorSpace; PDAbstractPattern pattern = patternSpace.getPattern(color); if (pattern instanceof PDTilingPattern) { PDTilingPattern tilingPattern = (PDTilingPattern) pattern; if (tilingPattern.getPaintType() == PDTilingPattern.PAINT_COLORED) { // colored tiling pattern return new TilingPaint(this, tilingPattern, xform); } else { // uncolored tiling pattern return new TilingPaint(this, tilingPattern, patternSpace.getUnderlyingColorSpace(), color, xform); } } else { PDShadingPattern shadingPattern = (PDShadingPattern)pattern; PDShading shading = shadingPattern.getShading(); if (shading == null) { LOG.error("shadingPattern is null, will be filled with transparency"); return new Color(0,0,0,0); } return shading.toPaint(Matrix.concatenate(getInitialMatrix(), shadingPattern.getMatrix())); } } } // sets the clipping path using caching for performance, we track lastClip manually because // Graphics2D#getClip() returns a new object instead of the same one passed to setClip private void setClip() { Area clippingPath = getGraphicsState().getCurrentClippingPath(); if (clippingPath != lastClip) { graphics.setClip(clippingPath); lastClip = clippingPath; } } @Override public void beginText() throws IOException { setClip(); beginTextClip(); } @Override public void endText() throws IOException { endTextClip(); } /** * Begin buffering the text clipping path, if any. */ private void beginTextClip() { // buffer the text clip because it represents a single clipping area textClippingArea = new Area(); } /** * End buffering the text clipping path, if any. */ private void endTextClip() { PDGraphicsState state = getGraphicsState(); RenderingMode renderingMode = state.getTextState().getRenderingMode(); // apply the buffered clip as one area if (renderingMode.isClip() && !textClippingArea.isEmpty()) { state.intersectClippingPath(textClippingArea); textClippingArea = null; } } @Override protected void showFontGlyph(Matrix textRenderingMatrix, PDFont font, int code, String unicode, Vector displacement) throws IOException { AffineTransform at = textRenderingMatrix.createAffineTransform(); at.concatenate(font.getFontMatrix().createAffineTransform()); // create cache if it does not exist PDVectorFont vectorFont = ((PDVectorFont)font); GlyphCache cache = glyphCaches.get(font); if (cache == null) { cache = new GlyphCache(vectorFont); glyphCaches.put(font, cache); } // cache glyph path if is not already cache GeneralPath path = cache.getPathForCharacterCode(code); if (path == null) { path = vectorFont.getNormalizedPath(code); cache.put(code, path); } drawGlyph(path, font, code, displacement, at); } /** * Render the font using the Glyph2D interface. * * @param path the Glyph2D implementation provided a GeneralPath for each glyph * @param font the font * @param code character code * @param displacement the glyph's displacement (advance) * @param at the transformation * @throws IOException if something went wrong */ private void drawGlyph(GeneralPath path, PDFont font, int code, Vector displacement, AffineTransform at) throws IOException { PDGraphicsState state = getGraphicsState(); RenderingMode renderingMode = state.getTextState().getRenderingMode(); if (path != null) { // stretch non-embedded glyph if it does not match the width contained in the PDF if (!font.isEmbedded()) { float fontWidth = font.getWidthFromFont(code); if (fontWidth > 0 && // ignore spaces Math.abs(fontWidth - displacement.getX() * 1000) > 0.0001) { float pdfWidth = displacement.getX() * 1000; at.scale(pdfWidth / fontWidth, 1); } } // render glyph Shape glyph = at.createTransformedShape(path); if (renderingMode.isFill()) { graphics.setComposite(state.getNonStrokingJavaComposite()); graphics.setPaint(getNonStrokingPaint()); setClip(); graphics.fill(glyph); } if (renderingMode.isStroke()) { graphics.setComposite(state.getStrokingJavaComposite()); graphics.setPaint(getStrokingPaint()); graphics.setStroke(getStroke()); setClip(); graphics.draw(glyph); } if (renderingMode.isClip()) { textClippingArea.add(new Area(glyph)); } } } @Override public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3) { // to ensure that the path is created in the right direction, we have to create // it by combining single lines instead of creating a simple rectangle linePath.moveTo((float) p0.getX(), (float) p0.getY()); linePath.lineTo((float) p1.getX(), (float) p1.getY()); linePath.lineTo((float) p2.getX(), (float) p2.getY()); linePath.lineTo((float) p3.getX(), (float) p3.getY()); // close the subpath instead of adding the last line so that a possible set line // cap style isn't taken into account at the "beginning" of the rectangle linePath.closePath(); } /** * Generates AWT raster for a soft mask * * @param softMask soft mask * @return AWT raster for soft mask * @throws IOException */ private Raster createSoftMaskRaster(PDSoftMask softMask) throws IOException { TransparencyGroup transparencyGroup = new TransparencyGroup(softMask.getGroup(), true); COSName subtype = softMask.getSubType(); if (COSName.ALPHA.equals(subtype)) { return transparencyGroup.getAlphaRaster(); } else if (COSName.LUMINOSITY.equals(subtype)) { return transparencyGroup.getLuminosityRaster(); } else { throw new IOException("Invalid soft mask subtype."); } } private Paint applySoftMaskToPaint(Paint parentPaint, PDSoftMask softMask) throws IOException { if (softMask != null) { //TODO PDFBOX-2934 if (COSName.ALPHA.equals(softMask.getSubType())) { LOG.info("alpha smask not implemented yet, is ignored"); return parentPaint; } return new SoftMaskPaint(parentPaint, createSoftMaskRaster(softMask)); } else { return parentPaint; } } // returns the stroking AWT Paint private Paint getStrokingPaint() throws IOException { return applySoftMaskToPaint( getPaint(getGraphicsState().getStrokingColor()), getGraphicsState().getSoftMask()); } // returns the non-stroking AWT Paint private Paint getNonStrokingPaint() throws IOException { return getPaint(getGraphicsState().getNonStrokingColor()); } // create a new stroke based on the current CTM and the current stroke private BasicStroke getStroke() { PDGraphicsState state = getGraphicsState(); // apply the CTM float lineWidth = transformWidth(state.getLineWidth()); // minimum line width as used by Adobe Reader if (lineWidth < 0.25) { lineWidth = 0.25f; } PDLineDashPattern dashPattern = state.getLineDashPattern(); int phaseStart = dashPattern.getPhase(); float[] dashArray = dashPattern.getDashArray(); if (dashArray != null) { // apply the CTM for (int i = 0; i < dashArray.length; ++i) { // minimum line dash width avoids JVM crash, see PDFBOX-2373, PDFBOX-2929, PDFBOX-3204 float w = transformWidth(dashArray[i]); if (w != 0) { dashArray[i] = Math.max(w, 0.035f); } } phaseStart = (int)transformWidth(phaseStart); // empty dash array is illegal // avoid also infinite and NaN values (PDFBOX-3360) if (dashArray.length == 0 || Float.isInfinite(phaseStart) || Float.isNaN(phaseStart)) { dashArray = null; } else { for (int i = 0; i < dashArray.length; ++i) { if (Float.isInfinite(dashArray[i]) || Float.isNaN(dashArray[i])) { dashArray = null; break; } } } } return new BasicStroke(lineWidth, state.getLineCap(), state.getLineJoin(), state.getMiterLimit(), dashArray, phaseStart); } @Override public void strokePath() throws IOException { graphics.setComposite(getGraphicsState().getStrokingJavaComposite()); graphics.setPaint(getStrokingPaint()); graphics.setStroke(getStroke()); setClip(); graphics.draw(linePath); linePath.reset(); } @Override public void fillPath(int windingRule) throws IOException { graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); graphics.setPaint(getNonStrokingPaint()); setClip(); linePath.setWindingRule(windingRule); // disable anti-aliasing for rectangular paths, this is a workaround to avoid small stripes // which occur when solid fills are used to simulate piecewise gradients, see PDFBOX-2302 // note that we ignore paths with a width/height under 1 as these are fills used as strokes, // see PDFBOX-1658 for an example Rectangle2D bounds = linePath.getBounds2D(); boolean noAntiAlias = isRectangular(linePath) && bounds.getWidth() > 1 && bounds.getHeight() > 1; if (noAntiAlias) { graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } if (!(graphics.getPaint() instanceof Color)) { // apply clip to path to avoid oversized device bounds in shading contexts (PDFBOX-2901) Area area = new Area(linePath); area.intersect(new Area(graphics.getClip())); graphics.fill(area); } else { graphics.fill(linePath); } linePath.reset(); if (noAntiAlias) { // JDK 1.7 has a bug where rendering hints are reset by the above call to // the setRenderingHint method, so we re-set all hints, see PDFBOX-2302 setRenderingHints(); } } /** * Returns true if the given path is rectangular. */ private boolean isRectangular(GeneralPath path) { PathIterator iter = path.getPathIterator(null); double[] coords = new double[6]; int count = 0; int[] xs = new int[4]; int[] ys = new int[4]; while (!iter.isDone()) { switch(iter.currentSegment(coords)) { case PathIterator.SEG_MOVETO: if (count == 0) { xs[count] = (int)Math.floor(coords[0]); ys[count] = (int)Math.floor(coords[1]); } else { return false; } count++; break; case PathIterator.SEG_LINETO: if (count < 4) { xs[count] = (int)Math.floor(coords[0]); ys[count] = (int)Math.floor(coords[1]); } else { return false; } count++; break; case PathIterator.SEG_CUBICTO: return false; case PathIterator.SEG_CLOSE: break; } iter.next(); } if (count == 4) { return xs[0] == xs[1] || xs[0] == xs[2] || ys[0] == ys[1] || ys[0] == ys[3]; } return false; } /** * Fills and then strokes the path. * * @param windingRule The winding rule this path will use. * @throws IOException If there is an IO error while filling the path. */ @Override public void fillAndStrokePath(int windingRule) throws IOException { // TODO can we avoid cloning the path? GeneralPath path = (GeneralPath)linePath.clone(); fillPath(windingRule); linePath = path; strokePath(); } @Override public void clip(int windingRule) { // the clipping path will not be updated until the succeeding painting operator is called clipWindingRule = windingRule; } @Override public void moveTo(float x, float y) { linePath.moveTo(x, y); } @Override public void lineTo(float x, float y) { linePath.lineTo(x, y); } @Override public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3) { linePath.curveTo(x1, y1, x2, y2, x3, y3); } @Override public Point2D getCurrentPoint() { return linePath.getCurrentPoint(); } @Override public void closePath() { linePath.closePath(); } @Override public void endPath() { if (clipWindingRule != -1) { linePath.setWindingRule(clipWindingRule); getGraphicsState().intersectClippingPath(linePath); clipWindingRule = -1; } linePath.reset(); } @Override public void drawImage(PDImage pdImage) throws IOException { Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); AffineTransform at = ctm.createAffineTransform(); if (!pdImage.getInterpolate()) { boolean isScaledUp = pdImage.getWidth() < Math.round(at.getScaleX()) || pdImage.getHeight() < Math.round(at.getScaleY()); // if the image is scaled down, we use smooth interpolation, eg PDFBOX-2364 // only when scaled up do we use nearest neighbour, eg PDFBOX-2302 / mori-cvpr01.pdf // stencils are excluded from this rule (see survey.pdf) if (isScaledUp || pdImage.isStencil()) { graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); } } if (pdImage.isStencil()) { // fill the image with paint BufferedImage image = pdImage.getStencilImage(getNonStrokingPaint()); // draw the image drawBufferedImage(image, at); } else { // draw the image drawBufferedImage(pdImage.getImage(), at); } if (!pdImage.getInterpolate()) { // JDK 1.7 has a bug where rendering hints are reset by the above call to // the setRenderingHint method, so we re-set all hints, see PDFBOX-2302 setRenderingHints(); } } private void drawBufferedImage(BufferedImage image, AffineTransform at) throws IOException { graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); setClip(); PDSoftMask softMask = getGraphicsState().getSoftMask(); if( softMask != null ) { AffineTransform imageTransform = new AffineTransform(at); imageTransform.scale(1, -1); imageTransform.translate(0, -1); Paint awtPaint = new TexturePaint(image, new Rectangle2D.Double(imageTransform.getTranslateX(), imageTransform.getTranslateY(), imageTransform.getScaleX(), imageTransform.getScaleY())); awtPaint = applySoftMaskToPaint(awtPaint, softMask); graphics.setPaint(awtPaint); Rectangle2D unitRect = new Rectangle2D.Float(0, 0, 1, 1); graphics.fill(at.createTransformedShape(unitRect)); } else { COSBase transfer = getGraphicsState().getTransfer(); if (transfer instanceof COSArray || transfer instanceof COSDictionary) { image = applyTransferFunction(image, transfer); } int width = image.getWidth(null); int height = image.getHeight(null); AffineTransform imageTransform = new AffineTransform(at); imageTransform.scale(1.0 / width, -1.0 / height); imageTransform.translate(0, -height); graphics.drawImage(image, imageTransform, null); } } private BufferedImage applyTransferFunction(BufferedImage image, COSBase transfer) throws IOException { BufferedImage bim; if (image.getColorModel().hasAlpha()) { bim = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); } else { bim = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); } // prepare transfer functions (either one per color or one for all) // and maps (actually arrays[256] to be faster) to avoid calculating values several times Integer rMap[], gMap[], bMap[]; PDFunction rf, gf, bf; if (transfer instanceof COSArray) { COSArray ar = (COSArray) transfer; rf = PDFunction.create(ar.getObject(0)); gf = PDFunction.create(ar.getObject(1)); bf = PDFunction.create(ar.getObject(2)); rMap = new Integer[256]; gMap = new Integer[256]; bMap = new Integer[256]; } else { rf = PDFunction.create(transfer); gf = rf; bf = rf; rMap = new Integer[256]; gMap = rMap; bMap = rMap; } // apply the transfer function to each color, but keep alpha float input[] = new float[1]; for (int x = 0; x < image.getWidth(); ++x) { for (int y = 0; y < image.getHeight(); ++y) { int rgb = image.getRGB(x, y); int ri = (rgb >> 16) & 0xFF; int gi = (rgb >> 8) & 0xFF; int bi = rgb & 0xFF; int ro, go, bo; if (rMap[ri] != null) { ro = rMap[ri]; } else { input[0] = (ri & 0xFF) / 255f; ro = (int) (rf.eval(input)[0] * 255); rMap[ri] = ro; } if (gMap[gi] != null) { go = gMap[gi]; } else { input[0] = (gi & 0xFF) / 255f; go = (int) (gf.eval(input)[0] * 255); gMap[gi] = go; } if (bMap[bi] != null) { bo = bMap[bi]; } else { input[0] = (bi & 0xFF) / 255f; bo = (int) (bf.eval(input)[0] * 255); bMap[bi] = bo; } bim.setRGB(x, y, (rgb & 0xFF000000) | (ro << 16) | (go << 8) | bo); } } return bim; } @Override public void shadingFill(COSName shadingName) throws IOException { PDShading shading = getResources().getShading(shadingName); Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); Paint paint = shading.toPaint(ctm); graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); graphics.setPaint(paint); graphics.setClip(null); lastClip = null; graphics.fill(getGraphicsState().getCurrentClippingPath()); } @Override public void showAnnotation(PDAnnotation annotation) throws IOException { lastClip = null; //TODO support more annotation flags (Invisible, NoZoom, NoRotate) // Example for NoZoom can be found in p5 of PDFBOX-2348 int deviceType = graphics.getDeviceConfiguration().getDevice().getType(); if (deviceType == GraphicsDevice.TYPE_PRINTER && !annotation.isPrinted()) { return; } if (deviceType == GraphicsDevice.TYPE_RASTER_SCREEN && annotation.isNoView()) { return; } if (annotation.isHidden()) { return; } super.showAnnotation(annotation); if (annotation.getAppearance() == null) { if (annotation instanceof PDAnnotationLink) { drawAnnotationLinkBorder((PDAnnotationLink) annotation); } if (annotation instanceof PDAnnotationMarkup && annotation.getSubtype().equals(PDAnnotationMarkup.SUB_TYPE_INK)) { drawAnnotationInk((PDAnnotationMarkup) annotation); } } } // return border info. BorderStyle must be provided as parameter because // method is not available in the base class private AnnotationBorder getAnnotationBorder(PDAnnotation annotation, PDBorderStyleDictionary borderStyle) { AnnotationBorder ab = new AnnotationBorder(); COSArray border = annotation.getBorder(); if (borderStyle == null) { if (border.get(2) instanceof COSNumber) { ab.width = ((COSNumber) border.getObject(2)).floatValue(); } if (border.size() > 3) { COSBase base3 = border.getObject(3); if (base3 instanceof COSArray) { ab.dashArray = ((COSArray) base3).toFloatArray(); } } } else { ab.width = borderStyle.getWidth(); if (borderStyle.getStyle().equals(PDBorderStyleDictionary.STYLE_DASHED)) { ab.dashArray = borderStyle.getDashStyle().getDashArray(); } if (borderStyle.getStyle().equals(PDBorderStyleDictionary.STYLE_UNDERLINE)) { ab.underline = true; } } ab.color = annotation.getColor(); if (ab.color == null) { // spec is unclear, but black seems to be the right thing to do ab.color = new PDColor(new float[] { 0 }, PDDeviceGray.INSTANCE); } if (ab.dashArray != null) { boolean allZero = true; for (float f : ab.dashArray) { if (f != 0) { allZero = false; break; } } if (allZero) { ab.dashArray = null; } } return ab; } private void drawAnnotationLinkBorder(PDAnnotationLink link) throws IOException { AnnotationBorder ab = getAnnotationBorder(link, link.getBorderStyle()); if (ab.width == 0 || ab.color.getComponents().length == 0) { return; } PDRectangle rectangle = link.getRectangle(); Stroke oldStroke = graphics.getStroke(); graphics.setPaint(getPaint(ab.color)); BasicStroke stroke = new BasicStroke(ab.width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10, ab.dashArray, 0); graphics.setStroke(stroke); graphics.setClip(null); if (ab.underline) { graphics.drawLine((int) rectangle.getLowerLeftX(), (int) rectangle.getLowerLeftY(), (int) (rectangle.getLowerLeftX() + rectangle.getWidth()), (int) rectangle.getLowerLeftY()); } else { graphics.drawRect((int) rectangle.getLowerLeftX(), (int) rectangle.getLowerLeftY(), (int) rectangle.getWidth(), (int) rectangle.getHeight()); } graphics.setStroke(oldStroke); } private void drawAnnotationInk(PDAnnotationMarkup inkAnnotation) throws IOException { if (!inkAnnotation.getCOSObject().containsKey(COSName.INKLIST)) { return; } //TODO there should be an InkAnnotation class with a getInkList method COSBase base = inkAnnotation.getCOSObject().getDictionaryObject(COSName.INKLIST); if (!(base instanceof COSArray)) { return; } // PDF spec does not mention /Border for ink annotations, but it is used if /BS is not available AnnotationBorder ab = getAnnotationBorder(inkAnnotation, inkAnnotation.getBorderStyle()); if (ab.width == 0 || ab.color.getComponents().length == 0) { return; } graphics.setPaint(getPaint(ab.color)); Stroke oldStroke = graphics.getStroke(); BasicStroke stroke = new BasicStroke(ab.width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10, ab.dashArray, 0); graphics.setStroke(stroke); graphics.setClip(null); COSArray pathsArray = (COSArray) base; for (COSBase baseElement : (Iterable<? extends COSBase>) pathsArray.toList()) { if (!(baseElement instanceof COSArray)) { continue; } COSArray pathArray = (COSArray) baseElement; int nPoints = pathArray.size() / 2; // "When drawn, the points shall be connected by straight lines or curves // in an implementation-dependent way" - we do lines. GeneralPath path = new GeneralPath(); for (int i = 0; i < nPoints; ++i) { COSBase bx = pathArray.getObject(i * 2); COSBase by = pathArray.getObject(i * 2 + 1); if (bx instanceof COSNumber && by instanceof COSNumber) { float x = ((COSNumber) bx).floatValue(); float y = ((COSNumber) by).floatValue(); if (i == 0) { path.moveTo(x, y); } else { path.lineTo(x, y); } } } graphics.draw(path); } graphics.setStroke(oldStroke); } @Override public void showTransparencyGroup(PDTransparencyGroup form) throws IOException { TransparencyGroup group = new TransparencyGroup(form, false); graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); setClip(); // both the DPI xform and the CTM were already applied to the group, so all we do // here is draw it directly onto the Graphics2D device at the appropriate position PDRectangle bbox = group.getBBox(); AffineTransform prev = graphics.getTransform(); float x = bbox.getLowerLeftX(); float y = pageSize.getHeight() - bbox.getLowerLeftY() - bbox.getHeight(); graphics.setTransform(AffineTransform.getTranslateInstance(x * xform.getScaleX(), y * xform.getScaleY())); PDSoftMask softMask = getGraphicsState().getSoftMask(); if (softMask != null) { BufferedImage image = group.getImage(); Paint awtPaint = new TexturePaint(image, new Rectangle2D.Float(0, 0, image.getWidth(), image.getHeight())); awtPaint = applySoftMaskToPaint(awtPaint, softMask); // todo: PDFBOX-994 problem here? graphics.setPaint(awtPaint); graphics.fill(new Rectangle2D.Float(0, 0, bbox.getWidth() * (float)xform.getScaleX(), bbox.getHeight() * (float)xform.getScaleY())); } else { graphics.drawImage(group.getImage(), null, null); } graphics.setTransform(prev); } private static class AnnotationBorder { private float[] dashArray = null; private boolean underline = false; private float width = 0; private PDColor color; } /** * Transparency group. **/ private final class TransparencyGroup { private final BufferedImage image; private final PDRectangle bbox; private final int minX; private final int minY; private final int width; private final int height; /** * Creates a buffered image for a transparency group result. */ private TransparencyGroup(PDTransparencyGroup form, boolean isSoftMask) throws IOException { Graphics2D g2dOriginal = graphics; Area lastClipOriginal = lastClip; // get the CTM x Form Matrix transform Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); Matrix transform = Matrix.concatenate(ctm, form.getMatrix()); // transform the bbox GeneralPath transformedBox = form.getBBox().transform(transform); // clip the bbox to prevent giant bboxes from consuming all memory Area clip = (Area)getGraphicsState().getCurrentClippingPath().clone(); clip.intersect(new Area(transformedBox)); Rectangle2D clipRect = clip.getBounds2D(); this.bbox = new PDRectangle((float)clipRect.getX(), (float)clipRect.getY(), (float)clipRect.getWidth(), (float)clipRect.getHeight()); // apply the underlying Graphics2D device's DPI transform Shape deviceClip = xform.createTransformedShape(clip); Rectangle2D bounds = deviceClip.getBounds2D(); minX = (int) Math.floor(bounds.getMinX()); minY = (int) Math.floor(bounds.getMinY()); int maxX = (int) Math.floor(bounds.getMaxX()) + 1; int maxY = (int) Math.floor(bounds.getMaxY()) + 1; width = maxX - minX; height = maxY - minY; image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // FIXME - color space Graphics2D g = image.createGraphics(); // flip y-axis g.translate(0, height); g.scale(1, -1); // apply device transform (DPI) g.transform(xform); // adjust the origin g.translate(-clipRect.getX(), -clipRect.getY()); graphics = g; try { if (isSoftMask) { processSoftMask(form); } else { processTransparencyGroup(form); } } finally { lastClip = lastClipOriginal; graphics.dispose(); graphics = g2dOriginal; } } public BufferedImage getImage() { return image; } public PDRectangle getBBox() { return bbox; } public Raster getAlphaRaster() { return image.getAlphaRaster(); } public Raster getLuminosityRaster() { BufferedImage gray = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); Graphics g = gray.getGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); return gray.getRaster(); } } }
PDFBOX-3459: Update JavaDoc git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1755777 13f79535-47bb-0310-9956-ffa450edef68
pdfbox/src/main/java/org/apache/pdfbox/rendering/PageDrawer.java
PDFBOX-3459: Update JavaDoc
<ide><path>dfbox/src/main/java/org/apache/pdfbox/rendering/PageDrawer.java <ide> } <ide> <ide> /** <del> * Render the font using the Glyph2D interface. <add> * Renders a glyph. <ide> * <del> * @param path the Glyph2D implementation provided a GeneralPath for each glyph <add> * @param path the GeneralPath for the glyph <ide> * @param font the font <ide> * @param code character code <ide> * @param displacement the glyph's displacement (advance)
Java
bsd-3-clause
81a64d8052226a9e405770db0ca438fa8f6e5b2b
0
NCIP/cadsr-semantic-tools,NCIP/cadsr-semantic-tools
package gov.nih.nci.ncicb.cadsr.loader.validator; import java.util.*; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.ElementsLists; import gov.nih.nci.ncicb.cadsr.loader.util.*; public class ConceptCodeValidator implements Validator { private ElementsLists elements; private ValidationItems items = ValidationItems.getInstance(); public ConceptCodeValidator(ElementsLists elements) { this.elements = elements; } /** * returns a list of Validation errors. */ public ValidationItems validate() { List<ObjectClass> ocs = (List<ObjectClass>)elements.getElements(DomainObjectFactory.newObjectClass().getClass()); if(ocs != null) for(ObjectClass o : ocs) { if(StringUtil.isEmpty(o.getPreferredName())) items.addItem(new ValidationError("Class: " + o.getLongName() + " has no concept code.", o)); else { checkConcepts(o); } } List<Property> props = (List<Property>)elements.getElements(DomainObjectFactory.newProperty().getClass()); if(props != null) for(Property o : props ) if(StringUtil.isEmpty(o.getPreferredName())) items.addItem(new ValidationError("Attribute: " + o.getLongName() + " has no concept code.", o)); else { checkConcepts(o); } // List<Concept> concepts = (List<Concept>)elements.getElements(DomainObjectFactory.newConcept().getClass()); // if(concepts != null) { // for(Concept o : concepts ) { // Concept o = (Concept)it.next(); // if(o.getPreferredName() == null) { // } else { // if(o.getLongName() == null) // items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.longName", o.getPreferredName()), o)); // if(o.getPreferredDefinition() == null) { // items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.definition", o.getPreferredName()), o)); // } // if(o.getDefinitionSource() == null) // items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.source", o.getPreferredName()), o)); // } // } // } return items; } private void checkConcepts(AdminComponent ac) { String[] conStr = ac.getPreferredName().split(":"); for(String s : conStr) { Concept con = LookupUtil.lookupConcept(s); if(con.getLongName() == null) items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.longName", con.getPreferredName()), ac)); if(con.getPreferredDefinition() == null) { items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.definition", con.getPreferredName()), ac)); } if(con.getDefinitionSource() == null) items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.source", con.getPreferredName()), ac)); } } }
src/gov/nih/nci/ncicb/cadsr/loader/validator/ConceptCodeValidator.java
package gov.nih.nci.ncicb.cadsr.loader.validator; import java.util.*; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.ElementsLists; import gov.nih.nci.ncicb.cadsr.loader.util.*; public class ConceptCodeValidator implements Validator { private ElementsLists elements; public ConceptCodeValidator(ElementsLists elements) { this.elements = elements; } /** * returns a list of Validation errors. */ public ValidationItems validate() { ValidationItems items = ValidationItems.getInstance(); // List conceptErrors = (List)elements.getElements(ConceptError.class); // if(conceptErrors != null) // for(Iterator it = conceptErrors.iterator(); it.hasNext(); ) { // ConceptError o = (ConceptError)it.next(); // errors.add(o); // } ObjectClass oc = DomainObjectFactory.newObjectClass(); List ocs = (List)elements.getElements(oc.getClass()); if(ocs != null) for(Iterator it = ocs.iterator(); it.hasNext(); ) { ObjectClass o = (ObjectClass)it.next(); if(o.getPreferredName() == null || o.getPreferredName().length() < 4) { items.addItem(new ValidationError("Class: " + o.getLongName() + " has no concept code.", o)); } } Property prop = DomainObjectFactory.newProperty(); List props = elements.getElements(prop.getClass()); if(props != null) for(Iterator it = props.iterator(); it.hasNext(); ) { Property o = (Property)it.next(); if(o.getPreferredName() == null || o.getPreferredName().length() < 4) { items.addItem(new ValidationError("Attribute: " + o.getLongName() + " has no concept code.", o)); } } Concept con = DomainObjectFactory.newConcept(); List concepts = elements.getElements(con.getClass()); if(concepts != null) { for(Iterator it = concepts.iterator(); it.hasNext(); ) { Concept o = (Concept)it.next(); if(o.getPreferredName() == null) { // capture this above. Dont need any more. // errors.add(new ValidationError(SEVERITY_ERROR, // PropertyAccessor.getProperty("validation.concept.missing"))); } else { if(o.getLongName() == null) items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.longName", o.getPreferredName()), o)); if(o.getPreferredDefinition() == null) { items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.definition", o.getPreferredName()), o)); } if(o.getDefinitionSource() == null) items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.source", o.getPreferredName()), o)); } } } return items; } }
fixes validation of OCs and Props SVN-Revision: 428
src/gov/nih/nci/ncicb/cadsr/loader/validator/ConceptCodeValidator.java
fixes validation of OCs and Props
<ide><path>rc/gov/nih/nci/ncicb/cadsr/loader/validator/ConceptCodeValidator.java <ide> <ide> private ElementsLists elements; <ide> <add> private ValidationItems items = ValidationItems.getInstance(); <add> <ide> public ConceptCodeValidator(ElementsLists elements) { <ide> this.elements = elements; <ide> } <ide> * returns a list of Validation errors. <ide> */ <ide> public ValidationItems validate() { <del> ValidationItems items = ValidationItems.getInstance(); <ide> <del>// List conceptErrors = (List)elements.getElements(ConceptError.class); <del>// if(conceptErrors != null) <del>// for(Iterator it = conceptErrors.iterator(); it.hasNext(); ) { <del>// ConceptError o = (ConceptError)it.next(); <del>// errors.add(o); <del>// } <del> <del> ObjectClass oc = DomainObjectFactory.newObjectClass(); <del> List ocs = (List)elements.getElements(oc.getClass()); <add> List<ObjectClass> ocs = (List<ObjectClass>)elements.getElements(DomainObjectFactory.newObjectClass().getClass()); <ide> if(ocs != null) <del> for(Iterator it = ocs.iterator(); it.hasNext(); ) { <del> ObjectClass o = (ObjectClass)it.next(); <del> if(o.getPreferredName() == null || o.getPreferredName().length() < 4) { <add> for(ObjectClass o : ocs) { <add> if(StringUtil.isEmpty(o.getPreferredName())) <ide> items.addItem(new ValidationError("Class: " + o.getLongName() + " has no concept code.", o)); <add> else { <add> checkConcepts(o); <ide> } <del> } <del> <del> Property prop = DomainObjectFactory.newProperty(); <del> List props = elements.getElements(prop.getClass()); <del> if(props != null) <del> for(Iterator it = props.iterator(); it.hasNext(); ) { <del> Property o = (Property)it.next(); <del> if(o.getPreferredName() == null || o.getPreferredName().length() < 4) { <del> items.addItem(new ValidationError("Attribute: " + o.getLongName() + " has no concept code.", o)); <del> } <del> } <add> } <ide> <ide> <del> Concept con = DomainObjectFactory.newConcept(); <del> List concepts = elements.getElements(con.getClass()); <del> if(concepts != null) { <del> for(Iterator it = concepts.iterator(); it.hasNext(); ) { <del> Concept o = (Concept)it.next(); <del> if(o.getPreferredName() == null) { <del> // capture this above. Dont need any more. <del>// errors.add(new ValidationError(SEVERITY_ERROR, <del>// PropertyAccessor.getProperty("validation.concept.missing"))); <del> } else { <del> if(o.getLongName() == null) <del> items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.longName", o.getPreferredName()), o)); <del> if(o.getPreferredDefinition() == null) { <del> items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.definition", o.getPreferredName()), o)); <del> } <del> if(o.getDefinitionSource() == null) <del> items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.source", o.getPreferredName()), o)); <add> List<Property> props = (List<Property>)elements.getElements(DomainObjectFactory.newProperty().getClass()); <add> if(props != null) <add> for(Property o : props ) <add> if(StringUtil.isEmpty(o.getPreferredName())) <add> items.addItem(new ValidationError("Attribute: " + o.getLongName() + " has no concept code.", o)); <add> else { <add> checkConcepts(o); <ide> } <del> } <del> } <add> <add>// List<Concept> concepts = (List<Concept>)elements.getElements(DomainObjectFactory.newConcept().getClass()); <add>// if(concepts != null) { <add>// for(Concept o : concepts ) { <add>// Concept o = (Concept)it.next(); <add>// if(o.getPreferredName() == null) { <add> <add>// } else { <add>// if(o.getLongName() == null) <add>// items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.longName", o.getPreferredName()), o)); <add>// if(o.getPreferredDefinition() == null) { <add>// items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.definition", o.getPreferredName()), o)); <add>// } <add>// if(o.getDefinitionSource() == null) <add>// items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.source", o.getPreferredName()), o)); <add>// } <add>// } <add>// } <ide> <ide> return items; <ide> } <ide> <add> private void checkConcepts(AdminComponent ac) { <add> String[] conStr = ac.getPreferredName().split(":"); <add> for(String s : conStr) { <add> Concept con = LookupUtil.lookupConcept(s); <add> if(con.getLongName() == null) <add> items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.longName", con.getPreferredName()), ac)); <add> if(con.getPreferredDefinition() == null) { <add> items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.definition", con.getPreferredName()), ac)); <add> } <add> if(con.getDefinitionSource() == null) <add> items.addItem(new ValidationError(PropertyAccessor.getProperty("validation.concept.missing.source", con.getPreferredName()), ac)); <add> } <add> } <add> <ide> }
Java
bsd-3-clause
ddd327d80c3c90eee9c85922d42400c4c9363961
0
NCIP/caaers,CBIIT/caaers,CBIIT/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers,NCIP/caaers,NCIP/caaers,CBIIT/caaers
package gov.nih.nci.cabig.caaers.web.ae; import gov.nih.nci.cabig.caaers.dao.AdverseEventReportingPeriodDao; import gov.nih.nci.cabig.caaers.dao.ExpeditedAdverseEventReportDao; import gov.nih.nci.cabig.caaers.dao.StudyDao; import gov.nih.nci.cabig.caaers.dao.report.ReportDefinitionDao; import gov.nih.nci.cabig.caaers.domain.AdverseEvent; import gov.nih.nci.cabig.caaers.domain.AdverseEventReportingPeriod; import gov.nih.nci.cabig.caaers.domain.Ctc; import gov.nih.nci.cabig.caaers.domain.CtcCategory; import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport; import gov.nih.nci.cabig.caaers.domain.LabLoad; import gov.nih.nci.cabig.caaers.domain.Outcome; import gov.nih.nci.cabig.caaers.domain.OutcomeType; import gov.nih.nci.cabig.caaers.domain.Participant; import gov.nih.nci.cabig.caaers.domain.ReportStatus; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.domain.StudyParticipantAssignment; import gov.nih.nci.cabig.caaers.domain.dto.ApplicableReportDefinitionsDTO; import gov.nih.nci.cabig.caaers.domain.dto.EvaluationResultDTO; import gov.nih.nci.cabig.caaers.domain.dto.ReportDefinitionWrapper; import gov.nih.nci.cabig.caaers.domain.dto.ReportDefinitionWrapper.ActionType; import gov.nih.nci.cabig.caaers.domain.report.Report; import gov.nih.nci.cabig.caaers.domain.report.ReportDefinition; import gov.nih.nci.cabig.caaers.service.EvaluationService; import gov.nih.nci.cabig.caaers.utils.DateUtils; import gov.nih.nci.cabig.caaers.utils.DurationUtils; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; /** * @author Sameer Sawanth * @author Biju Joseph * */ public class CaptureAdverseEventInputCommand implements AdverseEventInputCommand { private ReportDefinitionDao reportDefinitionDao; private ExpeditedAdverseEventReportDao aeReportDao; private Participant participant; private Study study; private EvaluationService evaluationService; protected AdverseEventReportingPeriod adverseEventReportingPeriod; protected AdverseEventReportingPeriodDao adverseEventReportingPeriodDao; private StudyDao studyDao; private List<CtcCategory> ctcCategories; private Integer primaryAdverseEventId; private List<Map<Integer, Boolean>> outcomes; private List<String> outcomeOtherDetails; private ApplicableReportDefinitionsDTO applicableReportDefinitions; private EvaluationResultDTO evaluationResult; //aeReportId - {messages} private Map<Integer, List<String>> rulesMessageMap; private Map<Integer, List<ReportTableRow>> recommendedReportTableMap; private Map<Integer, List<ReportTableRow>> applicableReportTableMap; //aeReportId - aeReport private Map<Integer, ExpeditedAdverseEventReport> aeReportIndexMap; private ReviewAndReportResult reviewResult; private Ctc ctcVersion; private boolean workflowEnabled = false; private String _action; private String reportingMethod; protected HashMap<String, Boolean> errorsForFields; protected String verbatim; public CaptureAdverseEventInputCommand(){ this.outcomes = new ArrayList<Map<Integer,Boolean>>(); this.outcomeOtherDetails = new ArrayList<String>(); this.rulesMessageMap = new LinkedHashMap<Integer, List<String>>(); this.recommendedReportTableMap = new LinkedHashMap<Integer, List<ReportTableRow>>(); this.applicableReportTableMap = new LinkedHashMap<Integer, List<ReportTableRow>>(); aeReportIndexMap = new HashMap<Integer, ExpeditedAdverseEventReport>(); } public CaptureAdverseEventInputCommand(AdverseEventReportingPeriodDao adverseEventReportingPeriodDao, EvaluationService evaluationService, ReportDefinitionDao reportDefinitionDao, StudyDao studyDao, ExpeditedAdverseEventReportDao aeReportDao){ this(); this.adverseEventReportingPeriodDao = adverseEventReportingPeriodDao; this.evaluationService = evaluationService; this.reportDefinitionDao = reportDefinitionDao; this.studyDao = studyDao; this.aeReportDao = aeReportDao; } /** * This method will check if the study is AdEERS submittable. * @return */ public boolean isNonAdeersStudy(){ if(study == null) return false; return !study.getAdeersReporting(); } /** * Will return true, if the primary sponsor of this study is DCP. * @return */ public boolean isDCPSponsoredStudy(){ if(study == null) return false; return StringUtils.equals("DCP", study.getPrimarySponsorCode()); } /** * This method will save the {@link AdverseEventReportingPeriod}. */ public void save() { save(true); } public void save(boolean incrementAeTermVersion){ Set<AdverseEvent> allAEs = new HashSet<AdverseEvent>(); //create a set of all AEs in all suggested reports if(getEvaluationResult() != null) { Map<Integer, List<AdverseEvent>> allAeMap = getEvaluationResult().getAllAeMap(); for (List<AdverseEvent> listAes : allAeMap.values()) { allAEs.addAll(listAes); } } if(this.getAdverseEventReportingPeriod() != null){ //initialize the graded date. for(AdverseEvent ae : adverseEventReportingPeriod.getAdverseEvents()){ ae.initailzeGradedDate(); ae.initializePostSubmissionUpdatedDate(); //increment the version of AETerm if(incrementAeTermVersion && ae.getAdverseEventTerm() != null){ Integer version = ae.getAdverseEventTerm().getVersion(); version = (version == null) ? 0 : version + 1; ae.getAdverseEventTerm().setVersion(version); } //match the ae in the reporting period to the one in the evaluated AE results //and copy over the requires reporting flag status for (AdverseEvent adverseEvent : allAEs) { if(ae.getId().equals(adverseEvent.getId())) { ae.setRequiresReporting(adverseEvent.getRequiresReporting()); break; } } } // ToDo - delegate to gov.nih.nci.cabig.caaers.domain.repository.AdverseEventReportingPeriodRepository adverseEventReportingPeriodDao.save(this.getAdverseEventReportingPeriod()); } } /** * This method returns the type of the command object (reportingPeriod) * */ public String getCommandType(){ return "reportingPeriod"; } // // /** // * This method will return the ReportDefinition which are selected by user // * page. // */ // public List<ReportDefinition> getSelectedReportDefinitions() { // List<ReportDefinition> reportDefs = new ArrayList<ReportDefinition>(); //// //// for (Map.Entry<Integer, Boolean> entry : reportDefinitionMap.entrySet()) { //// if (entry.getValue() != null && entry.getValue()){ //// ReportDefinition reportDef = reportDefinitionIndexMap.get(entry.getKey()); //// if(reportDef != null) reportDefs.add(reportDef); //// } //// } // return reportDefs; // } /** * This method will initialize the outcomes and outcomeOtherDetails, in the command. */ public void initializeOutcomes() { outcomeOtherDetails.clear(); outcomes.clear(); int i = 0; //This method will populate the outcome map and the outcomeSerious details map. for(AdverseEvent ae : getAdverseEvents()){ //update the command bounded variables with default values outcomeOtherDetails.add(""); LinkedHashMap<Integer, Boolean> oneOutcomeMap = new LinkedHashMap<Integer, Boolean>(); outcomes.add(oneOutcomeMap); //in this pass we will update the outcome details based on the OUTCOME db values if(ae != null){ //in this pass we will initialize all the outcomes to default 'FALSE' and other details to empty string. for(OutcomeType outcomeType : OutcomeType.values()){ oneOutcomeMap.put(outcomeType.getCode(), Boolean.FALSE); } for(Outcome outcome : ae.getOutcomes()){ oneOutcomeMap.put(outcome.getOutcomeType().getCode(), Boolean.TRUE); if(outcome.getOutcomeType().equals(OutcomeType.OTHER_SERIOUS)){ outcomeOtherDetails.set(i, outcome.getOther()); } } } i++; } } /** * This method will synchronize the outcomes list associated with the adverse event. * Death and hospitalization are sync'd on the UI by JS. * If the serious(outcome) not available in the outcomes list, it will be added. * Remove all the other outcomes present in the list (means user deselected a previously selected one) */ public void synchronizeOutcome() { int size = (getAdverseEvents() == null) ? 0 : getAdverseEvents().size(); for(int i = 0; i < size; i++){ AdverseEvent ae = getAdverseEvents().get(i); if(ae == null) continue; //update the other outcomes based on the user selection Map<Integer, Boolean> outcomeMap = getOutcomes().get(i); for (Map.Entry<Integer, Boolean> entry : outcomeMap.entrySet()) { if (entry.getValue()) { OutcomeType outcomeType = OutcomeType.getByCode(entry.getKey()); if(!isOutcomePresent(OutcomeType.getByCode(entry.getKey()), ae.getOutcomes())){ Outcome newOutcome = new Outcome(); newOutcome.setOutcomeType(outcomeType); if(outcomeType == OutcomeType.OTHER_SERIOUS) newOutcome.setOther(getOutcomeOtherDetails().get(i)); ae.addOutcome(newOutcome); } } else { OutcomeType outcomeType = OutcomeType.getByCode(entry.getKey()); removeOutcomeIfPresent(outcomeType, ae.getOutcomes()); } } } } /** * Returns true, if an Outcome of a specific type is present in the list of outcomes */ public boolean isOutcomePresent(OutcomeType type, List<Outcome> outcomes){ if(outcomes == null || outcomes.isEmpty()) return false; for(Outcome o : outcomes){ if(o.getOutcomeType() == type) return true; } return false; } /** * Removes an outcome type, if it is present. */ private boolean removeOutcomeIfPresent(OutcomeType type, List<Outcome> outcomes){ if(outcomes == null || outcomes.isEmpty()) return false; Outcome obj = null; for(Outcome o : outcomes){ if(o.getOutcomeType() == type){ obj = o; break; } } if(obj == null) return false; return outcomes.remove(obj); } public List<AdverseEvent> getAdverseEvents() { return adverseEventReportingPeriod.getAdverseEvents(); } public void setAdverseEventReportingPeriodDao( AdverseEventReportingPeriodDao adverseEventReportingPeriodDao) { this.adverseEventReportingPeriodDao = adverseEventReportingPeriodDao; } public Ctc getCtcVersion() { return ctcVersion; } public void setCtcVersion(Ctc ctcVersion) { this.ctcVersion = ctcVersion; } public Integer getTermCode(){ return null; } //this method is added to satisfy the UI requirements, so to be moved to the command class public void setTermCode(Integer ignore){} public StudyParticipantAssignment getAssignment() { return adverseEventReportingPeriod.getAssignment(); } public boolean getIgnoreCompletedStudy() { return false; } public Participant getParticipant() { return participant; } public Study getStudy() { return study; } public Participant getParticipantID() { return participant; } public Study getStudyID() { return study; } public String getTreatmentDescriptionType() { // TODO Auto-generated method stub return null; } public void setTreatmentDescriptionType(String type) { // TODO Auto-generated method stub } public void setParticipant(Participant participant) { this.participant = participant; } public void setStudy(Study study) { this.study = study; } public void setParticipantID(Participant participant) { this.participant = participant; } public void setStudyID(Study study) { this.study = study; } public AdverseEventReportingPeriod getAdverseEventReportingPeriod() { return adverseEventReportingPeriod; } public void setAdverseEventReportingPeriod(AdverseEventReportingPeriod adverseEventReportingPeriod) { this.adverseEventReportingPeriod = adverseEventReportingPeriod; } public void setCtcCategories(List<CtcCategory> ctcCategories) { this.ctcCategories = ctcCategories; } public List<CtcCategory> getCtcCategories() { if(ctcCategories == null){ if(adverseEventReportingPeriod != null) setCtcCategories(adverseEventReportingPeriod.getStudy().getAeTerminology().getCtcVersion().getCategories()); } return ctcCategories; } public EvaluationService getEvaluationService() { return evaluationService; } public void setEvaluationService(EvaluationService evaluationService) { this.evaluationService = evaluationService; } public Integer getPrimaryAdverseEventId() { return primaryAdverseEventId; } public void setPrimaryAdverseEventId(Integer primaryAdverseEventId) { this.primaryAdverseEventId = primaryAdverseEventId; } public ReviewAndReportResult getReviewResult() { return reviewResult; } public void setReviewResult(ReviewAndReportResult reviewResult) { this.reviewResult = reviewResult; } public boolean getWorkflowEnabled() { return workflowEnabled; } public void setWorkflowEnabled(boolean workflowEnabled) { this.workflowEnabled = workflowEnabled; } //hasLabs public boolean isAssociatedToLabAlerts(){ List<LabLoad> labs = getAssignment().getLabLoads(); return (labs != null) && !labs.isEmpty(); } public boolean isAssociatedToWorkflow(){ if(getAdverseEventReportingPeriod() == null) return false; return getAdverseEventReportingPeriod().getWorkflowId() != null; } public boolean isHavingSolicitedAEs(){ if(adverseEventReportingPeriod == null) return false; if(adverseEventReportingPeriod.getAdverseEvents() == null) return false; for(AdverseEvent ae : adverseEventReportingPeriod.getAdverseEvents()) if(ae.getSolicited()) return true; return false; } public String get_action() { return _action; } public void set_action(String _action) { this._action = _action; } public String getReportingMethod() { return reportingMethod; } public void setReportingMethod(String reportingMethod) { this.reportingMethod = reportingMethod; } public List<Map<Integer, Boolean>> getOutcomes() { return outcomes; } public void setOutcomes(List<Map<Integer, Boolean>> outcomes) { this.outcomes = outcomes; } public List<String> getOutcomeOtherDetails() { return outcomeOtherDetails; } public void setOutcomeOtherDetails(List<String> outcomeOtherDetails) { this.outcomeOtherDetails = outcomeOtherDetails; } public HashMap<String, Boolean> getErrorsForFields() { return errorsForFields; } public void setErrorsForFields(HashMap<String, Boolean> errorsForFields) { this.errorsForFields = errorsForFields; } public EvaluationResultDTO getEvaluationResult() { return evaluationResult; } public void setEvaluationResult(EvaluationResultDTO evaluationResult) { this.evaluationResult = evaluationResult; } public ApplicableReportDefinitionsDTO getApplicableReportDefinitions() { return applicableReportDefinitions; } public void setApplicableReportDefinitions( ApplicableReportDefinitionsDTO applicableReportDefinitions) { this.applicableReportDefinitions = applicableReportDefinitions; } public Map<Integer, List<String>> getRulesEngineMessageMap() { return rulesMessageMap; } public void setRulesEngineMessageMap(Map<Integer, List<String>> rulesMessageMap) { this.rulesMessageMap = rulesMessageMap; } public Map<Integer, List<ReportTableRow>> getRecommendedReportTableMap() { return recommendedReportTableMap; } public void setRecommendedReportTableMap( Map<Integer, List<ReportTableRow>> recomendedReportTableMap) { this.recommendedReportTableMap = recomendedReportTableMap; } public Map<Integer, List<ReportTableRow>> getApplicableReportTableMap() { return applicableReportTableMap; } public void setApplicableReportTableMap( Map<Integer, List<ReportTableRow>> applicableReportTableMap) { this.applicableReportTableMap = applicableReportTableMap; } public Integer getZero(){ return ZERO; } public void findApplicableReportDefinitions(){ //only once per page flow if(applicableReportDefinitions == null){ applicableReportDefinitions = evaluationService.applicableReportDefinitions(getAdverseEventReportingPeriod().getStudy(), getAssignment()); } } public void evaluateSAERules(){ evaluationResult = evaluationService.evaluateSAERules(getAdverseEventReportingPeriod()); } public void generateReadableRulesMessage(){ rulesMessageMap.clear(); //for default(new data collection) rulesMessageMap.put(ZERO, generateReadableRulesMessage(ZERO)); //for each aeReport, find the rules message for(ExpeditedAdverseEventReport aeReport : getAdverseEventReportingPeriod().getAeReports()){ rulesMessageMap.put(aeReport.getId(), generateReadableRulesMessage(aeReport.getId())); } } public List<String> generateReadableRulesMessage(Integer id){ //checklist will hold the report defs, for which message is already printed. List<ReportDefinition> checklist = new ArrayList<ReportDefinition>(); ArrayList<String> messages = new ArrayList<String>(); //for amendments. Set<ReportDefinitionWrapper> amendWrappers = evaluationResult.getAmendmentMap().get(id); if(amendWrappers != null && !amendWrappers.isEmpty()){ for(ReportDefinitionWrapper wrapper : amendWrappers){ messages.add(wrapper.getReadableMessage()); if(wrapper.getSubstitute() != null){ checklist.add(wrapper.getSubstitute()); } } } //for withdraw Set<ReportDefinitionWrapper> withdrawWrappers = evaluationResult.getWithdrawalMap().get(id); if(withdrawWrappers != null && !withdrawWrappers.isEmpty()){ for(ReportDefinitionWrapper wrapper : withdrawWrappers){ messages.add(wrapper.getReadableMessage()); if(wrapper.getSubstitute() != null){ checklist.add(wrapper.getSubstitute()); } } } //for edit Set<ReportDefinitionWrapper> editWrappers = evaluationResult.getEditMap().get(id); if(editWrappers != null && !editWrappers.isEmpty()){ for(ReportDefinitionWrapper wrapper : editWrappers){ messages.add(wrapper.getReadableMessage()); if(wrapper.getSubstitute() != null){ checklist.add(wrapper.getSubstitute()); } } } //for create (only add it is not in checklist Set<ReportDefinitionWrapper> createWrappers = evaluationResult.getCreateMap().get(id); if(createWrappers != null && !createWrappers.isEmpty()){ for(ReportDefinitionWrapper wrapper : createWrappers){ if(checklist.contains(wrapper.getDef())) continue; //do not add messages.add(wrapper.getReadableMessage()); } } return messages; } //will create a map with aeReportID as key, and ExpeditedAdverseEventReport as value public void refreshAeReportIdIndex(){ aeReportIndexMap.clear(); aeReportIndexMap.put(ZERO, null); //for new one for(ExpeditedAdverseEventReport aeReport : getAdverseEventReportingPeriod().getAeReports()){ aeReportIndexMap.put(aeReport.getId(), aeReport); } } /** * This method will create the value objects that needs to be displayed on the UI for recommended options. */ public void refreshRecommendedReportTable(){ recommendedReportTableMap.clear(); //for every report id (including ZERO) for(Integer aeReportId : aeReportIndexMap.keySet()){ //do for the default (new data collection). List<ReportTableRow> tableRows = new ArrayList<ReportTableRow>(); //for the default data collection (which will be new) List<AdverseEvent> seriousAdverseEvents = evaluationResult.getSeriousAdverseEvents(aeReportId); Date updatedDate = null; Date gradedDate = null; if(CollectionUtils.isNotEmpty(seriousAdverseEvents)){ updatedDate = AdverseEventReportingPeriod.findEarliestPostSubmissionUpdatedDate(seriousAdverseEvents); gradedDate = AdverseEventReportingPeriod.findEarliestGradedDate(seriousAdverseEvents); } if(updatedDate == null) updatedDate = new Date(); if(gradedDate == null) gradedDate = new Date(); //join the amend, withdraw, edit and create maps. List<ReportDefinitionWrapper> wrappers = new ArrayList<ReportDefinitionWrapper>(); Set<ReportDefinitionWrapper> ammendWrappers = evaluationResult.getAmendmentMap().get(aeReportId); if(ammendWrappers != null) wrappers.addAll(ammendWrappers); Set<ReportDefinitionWrapper> withdrawWrappers = evaluationResult.getWithdrawalMap().get(aeReportId); if(withdrawWrappers != null) wrappers.addAll(withdrawWrappers); Set<ReportDefinitionWrapper> editWrappers = evaluationResult.getEditMap().get(aeReportId); if(editWrappers != null) wrappers.addAll(editWrappers); Set<ReportDefinitionWrapper> createWrappers = evaluationResult.getCreateMap().get(aeReportId); if(createWrappers != null) wrappers.addAll(createWrappers); for(ReportDefinitionWrapper wrapper: wrappers){ //if there is already a report created from the same group. use updated date. Date baseDate = gradedDate; if(wrapper.getAction() == ActionType.CREATE){ ExpeditedAdverseEventReport aeReport = aeReportIndexMap.get(aeReportId); if(aeReport != null){ if(aeReport.hasExistingReportsOfSameOrganizationAndType(wrapper.getDef())){ baseDate = updatedDate; } } } ReportTableRow row = ReportTableRow.createReportTableRow(wrapper.getDef(), baseDate, wrapper.getAction()); row.setAeReportId(aeReportId); if(wrapper.getAction() == ActionType.AMEND){ row.setStatus(wrapper.getStatus()); row.setDue(""); }else if(wrapper.getAction() == ActionType.WITHDRAW || wrapper.getAction() == ActionType.EDIT) { row.setDue(DurationUtils.formatDuration(wrapper.getDueOn().getTime() - new Date().getTime(), wrapper.getDef().getTimeScaleUnitType().getFormat())); row.setStatus(wrapper.getStatus()); }else { row.setStatus(wrapper.getStatus()); } tableRows.add(row); } recommendedReportTableMap.put(aeReportId, tableRows); } } /** * This method will create the value objects, that are to be displayed on UI for override options. * Note:- Will update the stringent flag, for those reports which fall after the recomended report. */ public void refreshApplicableReportTable(){ applicableReportTableMap.clear(); //for every report id (including ZERO) for(Integer aeReportId : aeReportIndexMap.keySet()){ //find the earliest graded date, used while evaluating the aes. //for the default data collection (which will be new) List<AdverseEvent> seriousAdverseEvents = evaluationResult.getSeriousAdverseEvents(aeReportId); Date updatedDate = null; Date gradedDate = null; if(CollectionUtils.isNotEmpty(seriousAdverseEvents)){ updatedDate = AdverseEventReportingPeriod.findEarliestPostSubmissionUpdatedDate(seriousAdverseEvents); gradedDate = AdverseEventReportingPeriod.findEarliestGradedDate(seriousAdverseEvents); }else{ List<AdverseEvent> applicableAdverseEvents = evaluationResult.getAllAeMap().get(aeReportId); updatedDate = AdverseEventReportingPeriod.findEarliestPostSubmissionUpdatedDate(applicableAdverseEvents); gradedDate = AdverseEventReportingPeriod.findEarliestGradedDate(applicableAdverseEvents); } if(updatedDate == null) updatedDate = new Date(); if(gradedDate == null) gradedDate = new Date(); //all report defs (load them as default) List<ReportDefinition> allReportDefs = applicableReportDefinitions.getReportDefinitions(); Map<Integer, ReportTableRow> rowMap = new LinkedHashMap<Integer, ReportTableRow>(); ExpeditedAdverseEventReport aeReport = aeReportIndexMap.get(aeReportId); Date baseDate = gradedDate; List<Report> reportsToAmendList = new ArrayList<Report>(); List<ReportDefinitionWrapper> createAndEditWrappers = new ArrayList<ReportDefinitionWrapper>(); //needed to filter less stringent reports. //create a map, consisting of report definitions for(ReportDefinition rd : allReportDefs){ if(aeReport != null && aeReport.hasExistingReportsOfSameOrganizationAndType(rd)) { baseDate = updatedDate; reportsToAmendList.addAll(aeReport.findReportsToAmmend(rd)); } ReportTableRow row = ReportTableRow.createReportTableRow(rd, baseDate, ActionType.CREATE); row.setAeReportId(aeReportId); row.setStatus("Not started"); row.setOtherStatus(""); row.setOtherDue(""); row.setGrpStatus(""); row.setGrpDue(""); rowMap.put(rd.getId(), row); } //for each reports to amend, make sure, we have their group actions set to amend. for(Report report : reportsToAmendList){ ReportTableRow row = rowMap.get(report.getReportDefinition().getId()); if(row != null && row.getGrpAction() != ActionType.AMEND){ row.setAction(ActionType.AMEND); row.setGrpAction(ActionType.AMEND); row.setStatus("Being amended"); row.setGrpStatus("Being amended"); row.setGrpDue("Submitted on " + DateUtils.formatDate(report.getSubmittedOn())); } } Set<ReportDefinitionWrapper> createWrappers = evaluationResult.getCreateMap().get(aeReportId); if(createWrappers != null){ for(ReportDefinitionWrapper wrapper: createWrappers){ ReportTableRow row = rowMap.get(wrapper.getDef().getId()); if(row == null) continue; row.setPreSelected(true); row.setGrpAction(null); row.setOtherAction(null); createAndEditWrappers.add(wrapper); } } Set<ReportDefinitionWrapper> editWrappers = evaluationResult.getEditMap().get(aeReportId); if(editWrappers != null){ for(ReportDefinitionWrapper wrapper: editWrappers){ ReportTableRow row = rowMap.get(wrapper.getDef().getId()); if(row == null) continue; row.setPreSelected(true); row.setAction(ActionType.EDIT); row.setGrpAction(ActionType.WITHDRAW); row.setOtherAction(ActionType.WITHDRAW); row.setStatus(wrapper.getStatus()); row.setGrpStatus("Being withdrawn"); row.setOtherStatus("Being withdrawn"); row.setDue(DurationUtils.formatDuration(wrapper.getDueOn().getTime() - new Date().getTime(), wrapper.getDef().getTimeScaleUnitType().getFormat())); row.setGrpDue(""); row.setOtherDue(""); createAndEditWrappers.add(wrapper); } } Set<ReportDefinitionWrapper> withdrawWrappers = evaluationResult.getWithdrawalMap().get(aeReportId); if(withdrawWrappers != null){ for(ReportDefinitionWrapper wrapper: withdrawWrappers){ ReportTableRow row = rowMap.get(wrapper.getDef().getId()); if(row == null) continue; row.setAction(ActionType.EDIT); row.setGrpAction(ActionType.WITHDRAW); row.setOtherAction(ActionType.WITHDRAW); row.setStatus(wrapper.getStatus()); row.setGrpStatus("Being withdrawn"); row.setOtherStatus("Being withdrawn"); row.setDue(DurationUtils.formatDuration(wrapper.getDueOn().getTime() - new Date().getTime(), wrapper.getDef().getTimeScaleUnitType().getFormat())); row.setGrpDue(""); row.setOtherDue(""); //preselect the other one if(wrapper.getSubstitute() != null){ ReportTableRow anotherRow = rowMap.get(wrapper.getSubstitute().getId()); if(anotherRow != null) anotherRow.setPreSelected(true); } } } Set<ReportDefinitionWrapper> ammendWrappers = evaluationResult.getAmendmentMap().get(aeReportId); if(ammendWrappers != null){ for(ReportDefinitionWrapper wrapper: ammendWrappers){ ReportTableRow row = rowMap.get(wrapper.getDef().getId()); if(row == null) continue; row.setAction(ActionType.AMEND); row.setGrpAction(ActionType.AMEND); row.setStatus("Being amended"); row.setGrpStatus("Being amended"); row.setOtherStatus(""); row.setGrpDue("Submitted on " + DateUtils.formatDate(wrapper.getSubmittedOn())); row.setOtherDue(""); //preselect the other one if(rowMap.get(wrapper.getSubstitute().getId()) != null){ rowMap.get(wrapper.getSubstitute().getId()).setPreSelected(true); } } } Date now = DateUtils.today(); for(ReportDefinitionWrapper wrapper: createAndEditWrappers){ ReportDefinition rd = wrapper.getDef(); String grp = "grp-" + rd.getOrganization().getId() + "-"+rd.getGroup().getId(); Date expectedDue = rd.getExpectedDueDate(now); for(Map.Entry<Integer, ReportTableRow> rowEntry : rowMap.entrySet()){ if(rd.getId().equals(rowEntry.getKey())) continue; //ignore if it is the same report. if(!StringUtils.equals(grp, rowEntry.getValue().getGroup())) continue; //ignore different group Date actualDue = rowEntry.getValue().getReportDefinition().getExpectedDueDate(now); if(DateUtils.compateDateAndTime(expectedDue, actualDue) < 0){ rowEntry.getValue().setStringent(false); } } } applicableReportTableMap.put(aeReportId, new ArrayList<ReportTableRow>(rowMap.values())); } } /** * Will return a map, containing the report definition Id as key and the base date (to calculate due date) * as value. * * @param aeReportId * @return */ public Map<Integer, Date> findBaseDateMap(Integer aeReportId){ List<ReportTableRow> applicableReportDefinitionRows = applicableReportTableMap.get(aeReportId); Map<Integer, Date > dateMap = new HashMap<Integer, Date>(); for(ReportTableRow row : applicableReportDefinitionRows){ dateMap.put(row.getReportDefinition().getId(), row.getBaseDate()); } return dateMap; } /** * Will populate the reportIds to get amended, in the review result. */ public void populateReportsToAmend(){ ExpeditedAdverseEventReport aeReport = aeReportIndexMap.get(reviewResult.getAeReportId()); if(aeReport != null){ List<Report> completedReports = aeReport.listReportsHavingStatus(ReportStatus.COMPLETED); for(ReportDefinition rd : reviewResult.getAmendList()){ for(Report report : completedReports){ if(report.getReportDefinition().getId().equals(rd.getId())){ reviewResult.getReportsToAmmendList().add(report); } } } } } /** * This method will populate the report-Ids to be withdrawn. */ public void populateReportsToWithdraw(){ ExpeditedAdverseEventReport aeReport = aeReportIndexMap.get(reviewResult.getAeReportId()); if(aeReport != null){ List<Report> activeReports = aeReport.getActiveReports(); for(ReportDefinition rd : reviewResult.getWithdrawList()){ for(Report report : activeReports){ if(report.getReportDefinition().getId().equals(rd.getId())){ reviewResult.getReportsToWithdraw().add(report); } } } } } /** * This method will populate the reports to un-amend. */ public void populateReportsToUnAmend(){ ExpeditedAdverseEventReport aeReport = aeReportIndexMap.get(reviewResult.getAeReportId()); List<ReportDefinition> tentativeList = new ArrayList<ReportDefinition>(); List<ReportDefinition> potentialList = new ArrayList<ReportDefinition>(); if(aeReport != null){ //throw away, if this one is getting replaced for(ReportDefinition rdWithdraw : reviewResult.getWithdrawList()){ boolean potentialCandidate = true; for(ReportDefinition rdCreate : reviewResult.getCreateList()){ if(rdCreate.isOfSameReportTypeAndOrganization(rdWithdraw)){ potentialCandidate = false; break; } } if(potentialCandidate){ //may be chance for unamend. tentativeList.add(rdWithdraw); } }//rdWithdraw //check if the potential ones are the only active reports, of the group. List<Report> activeReports = aeReport.getActiveReports(); for(ReportDefinition rd : tentativeList){ boolean hasOtherFromSameOrg = true; for(Report report :activeReports){ if(rd.getId().equals(report.getId())){ hasOtherFromSameOrg = false; continue; //same so ignore (withdrawing exiting rd). } if(report.getReportDefinition().isOfSameReportTypeAndOrganization(rd)){ hasOtherFromSameOrg = true; } } if(!hasOtherFromSameOrg){ potentialList.add(rd); } }//potentialCandidateList //okay, now find the report associated to each. for(ReportDefinition rd : potentialList){ Report report = aeReport.findLastAmendedReport(rd); if(report != null){ reviewResult.getReportsToUnAmendList().add(report); } } }//aeReport } public String getVerbatim() { return verbatim; } public void setVerbatim(String verbatim) { this.verbatim = verbatim; } }
caAERS/software/web/src/main/java/gov/nih/nci/cabig/caaers/web/ae/CaptureAdverseEventInputCommand.java
package gov.nih.nci.cabig.caaers.web.ae; import gov.nih.nci.cabig.caaers.dao.AdverseEventReportingPeriodDao; import gov.nih.nci.cabig.caaers.dao.ExpeditedAdverseEventReportDao; import gov.nih.nci.cabig.caaers.dao.StudyDao; import gov.nih.nci.cabig.caaers.dao.report.ReportDefinitionDao; import gov.nih.nci.cabig.caaers.domain.AdverseEvent; import gov.nih.nci.cabig.caaers.domain.AdverseEventReportingPeriod; import gov.nih.nci.cabig.caaers.domain.Ctc; import gov.nih.nci.cabig.caaers.domain.CtcCategory; import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport; import gov.nih.nci.cabig.caaers.domain.LabLoad; import gov.nih.nci.cabig.caaers.domain.Outcome; import gov.nih.nci.cabig.caaers.domain.OutcomeType; import gov.nih.nci.cabig.caaers.domain.Participant; import gov.nih.nci.cabig.caaers.domain.ReportStatus; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.domain.StudyParticipantAssignment; import gov.nih.nci.cabig.caaers.domain.dto.ApplicableReportDefinitionsDTO; import gov.nih.nci.cabig.caaers.domain.dto.EvaluationResultDTO; import gov.nih.nci.cabig.caaers.domain.dto.ReportDefinitionWrapper; import gov.nih.nci.cabig.caaers.domain.dto.ReportDefinitionWrapper.ActionType; import gov.nih.nci.cabig.caaers.domain.report.Report; import gov.nih.nci.cabig.caaers.domain.report.ReportDefinition; import gov.nih.nci.cabig.caaers.service.EvaluationService; import gov.nih.nci.cabig.caaers.utils.DateUtils; import gov.nih.nci.cabig.caaers.utils.DurationUtils; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; /** * @author Sameer Sawanth * @author Biju Joseph * */ public class CaptureAdverseEventInputCommand implements AdverseEventInputCommand { private ReportDefinitionDao reportDefinitionDao; private ExpeditedAdverseEventReportDao aeReportDao; private Participant participant; private Study study; private EvaluationService evaluationService; protected AdverseEventReportingPeriod adverseEventReportingPeriod; protected AdverseEventReportingPeriodDao adverseEventReportingPeriodDao; private StudyDao studyDao; private List<CtcCategory> ctcCategories; private Integer primaryAdverseEventId; private List<Map<Integer, Boolean>> outcomes; private List<String> outcomeOtherDetails; private ApplicableReportDefinitionsDTO applicableReportDefinitions; private EvaluationResultDTO evaluationResult; //aeReportId - {messages} private Map<Integer, List<String>> rulesMessageMap; private Map<Integer, List<ReportTableRow>> recommendedReportTableMap; private Map<Integer, List<ReportTableRow>> applicableReportTableMap; //aeReportId - aeReport private Map<Integer, ExpeditedAdverseEventReport> aeReportIndexMap; private ReviewAndReportResult reviewResult; private Ctc ctcVersion; private boolean workflowEnabled = false; private String _action; private String reportingMethod; protected HashMap<String, Boolean> errorsForFields; protected String verbatim; public CaptureAdverseEventInputCommand(){ this.outcomes = new ArrayList<Map<Integer,Boolean>>(); this.outcomeOtherDetails = new ArrayList<String>(); this.rulesMessageMap = new LinkedHashMap<Integer, List<String>>(); this.recommendedReportTableMap = new LinkedHashMap<Integer, List<ReportTableRow>>(); this.applicableReportTableMap = new LinkedHashMap<Integer, List<ReportTableRow>>(); aeReportIndexMap = new HashMap<Integer, ExpeditedAdverseEventReport>(); } public CaptureAdverseEventInputCommand(AdverseEventReportingPeriodDao adverseEventReportingPeriodDao, EvaluationService evaluationService, ReportDefinitionDao reportDefinitionDao, StudyDao studyDao, ExpeditedAdverseEventReportDao aeReportDao){ this(); this.adverseEventReportingPeriodDao = adverseEventReportingPeriodDao; this.evaluationService = evaluationService; this.reportDefinitionDao = reportDefinitionDao; this.studyDao = studyDao; this.aeReportDao = aeReportDao; } /** * This method will check if the study is AdEERS submittable. * @return */ public boolean isNonAdeersStudy(){ if(study == null) return false; return !study.getAdeersReporting(); } /** * Will return true, if the primary sponsor of this study is DCP. * @return */ public boolean isDCPSponsoredStudy(){ if(study == null) return false; return StringUtils.equals("DCP", study.getPrimarySponsorCode()); } /** * This method will save the {@link AdverseEventReportingPeriod}. */ public void save() { save(true); } public void save(boolean incrementAeTermVersion){ if(this.getAdverseEventReportingPeriod() != null){ //initialize the graded date. for(AdverseEvent ae : adverseEventReportingPeriod.getAdverseEvents()){ ae.initailzeGradedDate(); ae.initializePostSubmissionUpdatedDate(); //increment the version of AETerm if(incrementAeTermVersion && ae.getAdverseEventTerm() != null){ Integer version = ae.getAdverseEventTerm().getVersion(); version = (version == null) ? 0 : version + 1; ae.getAdverseEventTerm().setVersion(version); } } // ToDo - delegate to gov.nih.nci.cabig.caaers.domain.repository.AdverseEventReportingPeriodRepository adverseEventReportingPeriodDao.save(this.getAdverseEventReportingPeriod()); } } /** * This method returns the type of the command object (reportingPeriod) * */ public String getCommandType(){ return "reportingPeriod"; } // // /** // * This method will return the ReportDefinition which are selected by user // * page. // */ // public List<ReportDefinition> getSelectedReportDefinitions() { // List<ReportDefinition> reportDefs = new ArrayList<ReportDefinition>(); //// //// for (Map.Entry<Integer, Boolean> entry : reportDefinitionMap.entrySet()) { //// if (entry.getValue() != null && entry.getValue()){ //// ReportDefinition reportDef = reportDefinitionIndexMap.get(entry.getKey()); //// if(reportDef != null) reportDefs.add(reportDef); //// } //// } // return reportDefs; // } /** * This method will initialize the outcomes and outcomeOtherDetails, in the command. */ public void initializeOutcomes() { outcomeOtherDetails.clear(); outcomes.clear(); int i = 0; //This method will populate the outcome map and the outcomeSerious details map. for(AdverseEvent ae : getAdverseEvents()){ //update the command bounded variables with default values outcomeOtherDetails.add(""); LinkedHashMap<Integer, Boolean> oneOutcomeMap = new LinkedHashMap<Integer, Boolean>(); outcomes.add(oneOutcomeMap); //in this pass we will update the outcome details based on the OUTCOME db values if(ae != null){ //in this pass we will initialize all the outcomes to default 'FALSE' and other details to empty string. for(OutcomeType outcomeType : OutcomeType.values()){ oneOutcomeMap.put(outcomeType.getCode(), Boolean.FALSE); } for(Outcome outcome : ae.getOutcomes()){ oneOutcomeMap.put(outcome.getOutcomeType().getCode(), Boolean.TRUE); if(outcome.getOutcomeType().equals(OutcomeType.OTHER_SERIOUS)){ outcomeOtherDetails.set(i, outcome.getOther()); } } } i++; } } /** * This method will synchronize the outcomes list associated with the adverse event. * Death and hospitalization are sync'd on the UI by JS. * If the serious(outcome) not available in the outcomes list, it will be added. * Remove all the other outcomes present in the list (means user deselected a previously selected one) */ public void synchronizeOutcome() { int size = (getAdverseEvents() == null) ? 0 : getAdverseEvents().size(); for(int i = 0; i < size; i++){ AdverseEvent ae = getAdverseEvents().get(i); if(ae == null) continue; //update the other outcomes based on the user selection Map<Integer, Boolean> outcomeMap = getOutcomes().get(i); for (Map.Entry<Integer, Boolean> entry : outcomeMap.entrySet()) { if (entry.getValue()) { OutcomeType outcomeType = OutcomeType.getByCode(entry.getKey()); if(!isOutcomePresent(OutcomeType.getByCode(entry.getKey()), ae.getOutcomes())){ Outcome newOutcome = new Outcome(); newOutcome.setOutcomeType(outcomeType); if(outcomeType == OutcomeType.OTHER_SERIOUS) newOutcome.setOther(getOutcomeOtherDetails().get(i)); ae.addOutcome(newOutcome); } } else { OutcomeType outcomeType = OutcomeType.getByCode(entry.getKey()); removeOutcomeIfPresent(outcomeType, ae.getOutcomes()); } } } } /** * Returns true, if an Outcome of a specific type is present in the list of outcomes */ public boolean isOutcomePresent(OutcomeType type, List<Outcome> outcomes){ if(outcomes == null || outcomes.isEmpty()) return false; for(Outcome o : outcomes){ if(o.getOutcomeType() == type) return true; } return false; } /** * Removes an outcome type, if it is present. */ private boolean removeOutcomeIfPresent(OutcomeType type, List<Outcome> outcomes){ if(outcomes == null || outcomes.isEmpty()) return false; Outcome obj = null; for(Outcome o : outcomes){ if(o.getOutcomeType() == type){ obj = o; break; } } if(obj == null) return false; return outcomes.remove(obj); } public List<AdverseEvent> getAdverseEvents() { return adverseEventReportingPeriod.getAdverseEvents(); } public void setAdverseEventReportingPeriodDao( AdverseEventReportingPeriodDao adverseEventReportingPeriodDao) { this.adverseEventReportingPeriodDao = adverseEventReportingPeriodDao; } public Ctc getCtcVersion() { return ctcVersion; } public void setCtcVersion(Ctc ctcVersion) { this.ctcVersion = ctcVersion; } public Integer getTermCode(){ return null; } //this method is added to satisfy the UI requirements, so to be moved to the command class public void setTermCode(Integer ignore){} public StudyParticipantAssignment getAssignment() { return adverseEventReportingPeriod.getAssignment(); } public boolean getIgnoreCompletedStudy() { return false; } public Participant getParticipant() { return participant; } public Study getStudy() { return study; } public Participant getParticipantID() { return participant; } public Study getStudyID() { return study; } public String getTreatmentDescriptionType() { // TODO Auto-generated method stub return null; } public void setTreatmentDescriptionType(String type) { // TODO Auto-generated method stub } public void setParticipant(Participant participant) { this.participant = participant; } public void setStudy(Study study) { this.study = study; } public void setParticipantID(Participant participant) { this.participant = participant; } public void setStudyID(Study study) { this.study = study; } public AdverseEventReportingPeriod getAdverseEventReportingPeriod() { return adverseEventReportingPeriod; } public void setAdverseEventReportingPeriod(AdverseEventReportingPeriod adverseEventReportingPeriod) { this.adverseEventReportingPeriod = adverseEventReportingPeriod; } public void setCtcCategories(List<CtcCategory> ctcCategories) { this.ctcCategories = ctcCategories; } public List<CtcCategory> getCtcCategories() { if(ctcCategories == null){ if(adverseEventReportingPeriod != null) setCtcCategories(adverseEventReportingPeriod.getStudy().getAeTerminology().getCtcVersion().getCategories()); } return ctcCategories; } public EvaluationService getEvaluationService() { return evaluationService; } public void setEvaluationService(EvaluationService evaluationService) { this.evaluationService = evaluationService; } public Integer getPrimaryAdverseEventId() { return primaryAdverseEventId; } public void setPrimaryAdverseEventId(Integer primaryAdverseEventId) { this.primaryAdverseEventId = primaryAdverseEventId; } public ReviewAndReportResult getReviewResult() { return reviewResult; } public void setReviewResult(ReviewAndReportResult reviewResult) { this.reviewResult = reviewResult; } public boolean getWorkflowEnabled() { return workflowEnabled; } public void setWorkflowEnabled(boolean workflowEnabled) { this.workflowEnabled = workflowEnabled; } //hasLabs public boolean isAssociatedToLabAlerts(){ List<LabLoad> labs = getAssignment().getLabLoads(); return (labs != null) && !labs.isEmpty(); } public boolean isAssociatedToWorkflow(){ if(getAdverseEventReportingPeriod() == null) return false; return getAdverseEventReportingPeriod().getWorkflowId() != null; } public boolean isHavingSolicitedAEs(){ if(adverseEventReportingPeriod == null) return false; if(adverseEventReportingPeriod.getAdverseEvents() == null) return false; for(AdverseEvent ae : adverseEventReportingPeriod.getAdverseEvents()) if(ae.getSolicited()) return true; return false; } public String get_action() { return _action; } public void set_action(String _action) { this._action = _action; } public String getReportingMethod() { return reportingMethod; } public void setReportingMethod(String reportingMethod) { this.reportingMethod = reportingMethod; } public List<Map<Integer, Boolean>> getOutcomes() { return outcomes; } public void setOutcomes(List<Map<Integer, Boolean>> outcomes) { this.outcomes = outcomes; } public List<String> getOutcomeOtherDetails() { return outcomeOtherDetails; } public void setOutcomeOtherDetails(List<String> outcomeOtherDetails) { this.outcomeOtherDetails = outcomeOtherDetails; } public HashMap<String, Boolean> getErrorsForFields() { return errorsForFields; } public void setErrorsForFields(HashMap<String, Boolean> errorsForFields) { this.errorsForFields = errorsForFields; } public EvaluationResultDTO getEvaluationResult() { return evaluationResult; } public void setEvaluationResult(EvaluationResultDTO evaluationResult) { this.evaluationResult = evaluationResult; } public ApplicableReportDefinitionsDTO getApplicableReportDefinitions() { return applicableReportDefinitions; } public void setApplicableReportDefinitions( ApplicableReportDefinitionsDTO applicableReportDefinitions) { this.applicableReportDefinitions = applicableReportDefinitions; } public Map<Integer, List<String>> getRulesEngineMessageMap() { return rulesMessageMap; } public void setRulesEngineMessageMap(Map<Integer, List<String>> rulesMessageMap) { this.rulesMessageMap = rulesMessageMap; } public Map<Integer, List<ReportTableRow>> getRecommendedReportTableMap() { return recommendedReportTableMap; } public void setRecommendedReportTableMap( Map<Integer, List<ReportTableRow>> recomendedReportTableMap) { this.recommendedReportTableMap = recomendedReportTableMap; } public Map<Integer, List<ReportTableRow>> getApplicableReportTableMap() { return applicableReportTableMap; } public void setApplicableReportTableMap( Map<Integer, List<ReportTableRow>> applicableReportTableMap) { this.applicableReportTableMap = applicableReportTableMap; } public Integer getZero(){ return ZERO; } public void findApplicableReportDefinitions(){ //only once per page flow if(applicableReportDefinitions == null){ applicableReportDefinitions = evaluationService.applicableReportDefinitions(getAdverseEventReportingPeriod().getStudy(), getAssignment()); } } public void evaluateSAERules(){ evaluationResult = evaluationService.evaluateSAERules(getAdverseEventReportingPeriod()); } public void generateReadableRulesMessage(){ rulesMessageMap.clear(); //for default(new data collection) rulesMessageMap.put(ZERO, generateReadableRulesMessage(ZERO)); //for each aeReport, find the rules message for(ExpeditedAdverseEventReport aeReport : getAdverseEventReportingPeriod().getAeReports()){ rulesMessageMap.put(aeReport.getId(), generateReadableRulesMessage(aeReport.getId())); } } public List<String> generateReadableRulesMessage(Integer id){ //checklist will hold the report defs, for which message is already printed. List<ReportDefinition> checklist = new ArrayList<ReportDefinition>(); ArrayList<String> messages = new ArrayList<String>(); //for amendments. Set<ReportDefinitionWrapper> amendWrappers = evaluationResult.getAmendmentMap().get(id); if(amendWrappers != null && !amendWrappers.isEmpty()){ for(ReportDefinitionWrapper wrapper : amendWrappers){ messages.add(wrapper.getReadableMessage()); if(wrapper.getSubstitute() != null){ checklist.add(wrapper.getSubstitute()); } } } //for withdraw Set<ReportDefinitionWrapper> withdrawWrappers = evaluationResult.getWithdrawalMap().get(id); if(withdrawWrappers != null && !withdrawWrappers.isEmpty()){ for(ReportDefinitionWrapper wrapper : withdrawWrappers){ messages.add(wrapper.getReadableMessage()); if(wrapper.getSubstitute() != null){ checklist.add(wrapper.getSubstitute()); } } } //for edit Set<ReportDefinitionWrapper> editWrappers = evaluationResult.getEditMap().get(id); if(editWrappers != null && !editWrappers.isEmpty()){ for(ReportDefinitionWrapper wrapper : editWrappers){ messages.add(wrapper.getReadableMessage()); if(wrapper.getSubstitute() != null){ checklist.add(wrapper.getSubstitute()); } } } //for create (only add it is not in checklist Set<ReportDefinitionWrapper> createWrappers = evaluationResult.getCreateMap().get(id); if(createWrappers != null && !createWrappers.isEmpty()){ for(ReportDefinitionWrapper wrapper : createWrappers){ if(checklist.contains(wrapper.getDef())) continue; //do not add messages.add(wrapper.getReadableMessage()); } } return messages; } //will create a map with aeReportID as key, and ExpeditedAdverseEventReport as value public void refreshAeReportIdIndex(){ aeReportIndexMap.clear(); aeReportIndexMap.put(ZERO, null); //for new one for(ExpeditedAdverseEventReport aeReport : getAdverseEventReportingPeriod().getAeReports()){ aeReportIndexMap.put(aeReport.getId(), aeReport); } } /** * This method will create the value objects that needs to be displayed on the UI for recommended options. */ public void refreshRecommendedReportTable(){ recommendedReportTableMap.clear(); //for every report id (including ZERO) for(Integer aeReportId : aeReportIndexMap.keySet()){ //do for the default (new data collection). List<ReportTableRow> tableRows = new ArrayList<ReportTableRow>(); //for the default data collection (which will be new) List<AdverseEvent> seriousAdverseEvents = evaluationResult.getSeriousAdverseEvents(aeReportId); Date updatedDate = null; Date gradedDate = null; if(CollectionUtils.isNotEmpty(seriousAdverseEvents)){ updatedDate = AdverseEventReportingPeriod.findEarliestPostSubmissionUpdatedDate(seriousAdverseEvents); gradedDate = AdverseEventReportingPeriod.findEarliestGradedDate(seriousAdverseEvents); } if(updatedDate == null) updatedDate = new Date(); if(gradedDate == null) gradedDate = new Date(); //join the amend, withdraw, edit and create maps. List<ReportDefinitionWrapper> wrappers = new ArrayList<ReportDefinitionWrapper>(); Set<ReportDefinitionWrapper> ammendWrappers = evaluationResult.getAmendmentMap().get(aeReportId); if(ammendWrappers != null) wrappers.addAll(ammendWrappers); Set<ReportDefinitionWrapper> withdrawWrappers = evaluationResult.getWithdrawalMap().get(aeReportId); if(withdrawWrappers != null) wrappers.addAll(withdrawWrappers); Set<ReportDefinitionWrapper> editWrappers = evaluationResult.getEditMap().get(aeReportId); if(editWrappers != null) wrappers.addAll(editWrappers); Set<ReportDefinitionWrapper> createWrappers = evaluationResult.getCreateMap().get(aeReportId); if(createWrappers != null) wrappers.addAll(createWrappers); for(ReportDefinitionWrapper wrapper: wrappers){ //if there is already a report created from the same group. use updated date. Date baseDate = gradedDate; if(wrapper.getAction() == ActionType.CREATE){ ExpeditedAdverseEventReport aeReport = aeReportIndexMap.get(aeReportId); if(aeReport != null){ if(aeReport.hasExistingReportsOfSameOrganizationAndType(wrapper.getDef())){ baseDate = updatedDate; } } } ReportTableRow row = ReportTableRow.createReportTableRow(wrapper.getDef(), baseDate, wrapper.getAction()); row.setAeReportId(aeReportId); if(wrapper.getAction() == ActionType.AMEND){ row.setStatus(wrapper.getStatus()); row.setDue(""); }else if(wrapper.getAction() == ActionType.WITHDRAW || wrapper.getAction() == ActionType.EDIT) { row.setDue(DurationUtils.formatDuration(wrapper.getDueOn().getTime() - new Date().getTime(), wrapper.getDef().getTimeScaleUnitType().getFormat())); row.setStatus(wrapper.getStatus()); }else { row.setStatus(wrapper.getStatus()); } tableRows.add(row); } recommendedReportTableMap.put(aeReportId, tableRows); } } /** * This method will create the value objects, that are to be displayed on UI for override options. * Note:- Will update the stringent flag, for those reports which fall after the recomended report. */ public void refreshApplicableReportTable(){ applicableReportTableMap.clear(); //for every report id (including ZERO) for(Integer aeReportId : aeReportIndexMap.keySet()){ //find the earliest graded date, used while evaluating the aes. //for the default data collection (which will be new) List<AdverseEvent> seriousAdverseEvents = evaluationResult.getSeriousAdverseEvents(aeReportId); Date updatedDate = null; Date gradedDate = null; if(CollectionUtils.isNotEmpty(seriousAdverseEvents)){ updatedDate = AdverseEventReportingPeriod.findEarliestPostSubmissionUpdatedDate(seriousAdverseEvents); gradedDate = AdverseEventReportingPeriod.findEarliestGradedDate(seriousAdverseEvents); }else{ List<AdverseEvent> applicableAdverseEvents = evaluationResult.getAllAeMap().get(aeReportId); updatedDate = AdverseEventReportingPeriod.findEarliestPostSubmissionUpdatedDate(applicableAdverseEvents); gradedDate = AdverseEventReportingPeriod.findEarliestGradedDate(applicableAdverseEvents); } if(updatedDate == null) updatedDate = new Date(); if(gradedDate == null) gradedDate = new Date(); //all report defs (load them as default) List<ReportDefinition> allReportDefs = applicableReportDefinitions.getReportDefinitions(); Map<Integer, ReportTableRow> rowMap = new LinkedHashMap<Integer, ReportTableRow>(); ExpeditedAdverseEventReport aeReport = aeReportIndexMap.get(aeReportId); Date baseDate = gradedDate; List<Report> reportsToAmendList = new ArrayList<Report>(); List<ReportDefinitionWrapper> createAndEditWrappers = new ArrayList<ReportDefinitionWrapper>(); //needed to filter less stringent reports. //create a map, consisting of report definitions for(ReportDefinition rd : allReportDefs){ if(aeReport != null && aeReport.hasExistingReportsOfSameOrganizationAndType(rd)) { baseDate = updatedDate; reportsToAmendList.addAll(aeReport.findReportsToAmmend(rd)); } ReportTableRow row = ReportTableRow.createReportTableRow(rd, baseDate, ActionType.CREATE); row.setAeReportId(aeReportId); row.setStatus("Not started"); row.setOtherStatus(""); row.setOtherDue(""); row.setGrpStatus(""); row.setGrpDue(""); rowMap.put(rd.getId(), row); } //for each reports to amend, make sure, we have their group actions set to amend. for(Report report : reportsToAmendList){ ReportTableRow row = rowMap.get(report.getReportDefinition().getId()); if(row != null && row.getGrpAction() != ActionType.AMEND){ row.setAction(ActionType.AMEND); row.setGrpAction(ActionType.AMEND); row.setStatus("Being amended"); row.setGrpStatus("Being amended"); row.setGrpDue("Submitted on " + DateUtils.formatDate(report.getSubmittedOn())); } } Set<ReportDefinitionWrapper> createWrappers = evaluationResult.getCreateMap().get(aeReportId); if(createWrappers != null){ for(ReportDefinitionWrapper wrapper: createWrappers){ ReportTableRow row = rowMap.get(wrapper.getDef().getId()); if(row == null) continue; row.setPreSelected(true); row.setGrpAction(null); row.setOtherAction(null); createAndEditWrappers.add(wrapper); } } Set<ReportDefinitionWrapper> editWrappers = evaluationResult.getEditMap().get(aeReportId); if(editWrappers != null){ for(ReportDefinitionWrapper wrapper: editWrappers){ ReportTableRow row = rowMap.get(wrapper.getDef().getId()); if(row == null) continue; row.setPreSelected(true); row.setAction(ActionType.EDIT); row.setGrpAction(ActionType.WITHDRAW); row.setOtherAction(ActionType.WITHDRAW); row.setStatus(wrapper.getStatus()); row.setGrpStatus("Being withdrawn"); row.setOtherStatus("Being withdrawn"); row.setDue(DurationUtils.formatDuration(wrapper.getDueOn().getTime() - new Date().getTime(), wrapper.getDef().getTimeScaleUnitType().getFormat())); row.setGrpDue(""); row.setOtherDue(""); createAndEditWrappers.add(wrapper); } } Set<ReportDefinitionWrapper> withdrawWrappers = evaluationResult.getWithdrawalMap().get(aeReportId); if(withdrawWrappers != null){ for(ReportDefinitionWrapper wrapper: withdrawWrappers){ ReportTableRow row = rowMap.get(wrapper.getDef().getId()); if(row == null) continue; row.setAction(ActionType.EDIT); row.setGrpAction(ActionType.WITHDRAW); row.setOtherAction(ActionType.WITHDRAW); row.setStatus(wrapper.getStatus()); row.setGrpStatus("Being withdrawn"); row.setOtherStatus("Being withdrawn"); row.setDue(DurationUtils.formatDuration(wrapper.getDueOn().getTime() - new Date().getTime(), wrapper.getDef().getTimeScaleUnitType().getFormat())); row.setGrpDue(""); row.setOtherDue(""); //preselect the other one if(wrapper.getSubstitute() != null){ ReportTableRow anotherRow = rowMap.get(wrapper.getSubstitute().getId()); if(anotherRow != null) anotherRow.setPreSelected(true); } } } Set<ReportDefinitionWrapper> ammendWrappers = evaluationResult.getAmendmentMap().get(aeReportId); if(ammendWrappers != null){ for(ReportDefinitionWrapper wrapper: ammendWrappers){ ReportTableRow row = rowMap.get(wrapper.getDef().getId()); if(row == null) continue; row.setAction(ActionType.AMEND); row.setGrpAction(ActionType.AMEND); row.setStatus("Being amended"); row.setGrpStatus("Being amended"); row.setOtherStatus(""); row.setGrpDue("Submitted on " + DateUtils.formatDate(wrapper.getSubmittedOn())); row.setOtherDue(""); //preselect the other one if(rowMap.get(wrapper.getSubstitute().getId()) != null){ rowMap.get(wrapper.getSubstitute().getId()).setPreSelected(true); } } } Date now = DateUtils.today(); for(ReportDefinitionWrapper wrapper: createAndEditWrappers){ ReportDefinition rd = wrapper.getDef(); String grp = "grp-" + rd.getOrganization().getId() + "-"+rd.getGroup().getId(); Date expectedDue = rd.getExpectedDueDate(now); for(Map.Entry<Integer, ReportTableRow> rowEntry : rowMap.entrySet()){ if(rd.getId().equals(rowEntry.getKey())) continue; //ignore if it is the same report. if(!StringUtils.equals(grp, rowEntry.getValue().getGroup())) continue; //ignore different group Date actualDue = rowEntry.getValue().getReportDefinition().getExpectedDueDate(now); if(DateUtils.compateDateAndTime(expectedDue, actualDue) < 0){ rowEntry.getValue().setStringent(false); } } } applicableReportTableMap.put(aeReportId, new ArrayList<ReportTableRow>(rowMap.values())); } } /** * Will return a map, containing the report definition Id as key and the base date (to calculate due date) * as value. * * @param aeReportId * @return */ public Map<Integer, Date> findBaseDateMap(Integer aeReportId){ List<ReportTableRow> applicableReportDefinitionRows = applicableReportTableMap.get(aeReportId); Map<Integer, Date > dateMap = new HashMap<Integer, Date>(); for(ReportTableRow row : applicableReportDefinitionRows){ dateMap.put(row.getReportDefinition().getId(), row.getBaseDate()); } return dateMap; } /** * Will populate the reportIds to get amended, in the review result. */ public void populateReportsToAmend(){ ExpeditedAdverseEventReport aeReport = aeReportIndexMap.get(reviewResult.getAeReportId()); if(aeReport != null){ List<Report> completedReports = aeReport.listReportsHavingStatus(ReportStatus.COMPLETED); for(ReportDefinition rd : reviewResult.getAmendList()){ for(Report report : completedReports){ if(report.getReportDefinition().getId().equals(rd.getId())){ reviewResult.getReportsToAmmendList().add(report); } } } } } /** * This method will populate the report-Ids to be withdrawn. */ public void populateReportsToWithdraw(){ ExpeditedAdverseEventReport aeReport = aeReportIndexMap.get(reviewResult.getAeReportId()); if(aeReport != null){ List<Report> activeReports = aeReport.getActiveReports(); for(ReportDefinition rd : reviewResult.getWithdrawList()){ for(Report report : activeReports){ if(report.getReportDefinition().getId().equals(rd.getId())){ reviewResult.getReportsToWithdraw().add(report); } } } } } /** * This method will populate the reports to un-amend. */ public void populateReportsToUnAmend(){ ExpeditedAdverseEventReport aeReport = aeReportIndexMap.get(reviewResult.getAeReportId()); List<ReportDefinition> tentativeList = new ArrayList<ReportDefinition>(); List<ReportDefinition> potentialList = new ArrayList<ReportDefinition>(); if(aeReport != null){ //throw away, if this one is getting replaced for(ReportDefinition rdWithdraw : reviewResult.getWithdrawList()){ boolean potentialCandidate = true; for(ReportDefinition rdCreate : reviewResult.getCreateList()){ if(rdCreate.isOfSameReportTypeAndOrganization(rdWithdraw)){ potentialCandidate = false; break; } } if(potentialCandidate){ //may be chance for unamend. tentativeList.add(rdWithdraw); } }//rdWithdraw //check if the potential ones are the only active reports, of the group. List<Report> activeReports = aeReport.getActiveReports(); for(ReportDefinition rd : tentativeList){ boolean hasOtherFromSameOrg = true; for(Report report :activeReports){ if(rd.getId().equals(report.getId())){ hasOtherFromSameOrg = false; continue; //same so ignore (withdrawing exiting rd). } if(report.getReportDefinition().isOfSameReportTypeAndOrganization(rd)){ hasOtherFromSameOrg = true; } } if(!hasOtherFromSameOrg){ potentialList.add(rd); } }//potentialCandidateList //okay, now find the report associated to each. for(ReportDefinition rd : potentialList){ Report report = aeReport.findLastAmendedReport(rd); if(report != null){ reviewResult.getReportsToUnAmendList().add(report); } } }//aeReport } public String getVerbatim() { return verbatim; } public void setVerbatim(String verbatim) { this.verbatim = verbatim; } }
CAAERS-6044 : Fix to save the evaluation result for required reporting SVN-Revision: 17332
caAERS/software/web/src/main/java/gov/nih/nci/cabig/caaers/web/ae/CaptureAdverseEventInputCommand.java
CAAERS-6044 : Fix to save the evaluation result for required reporting
<ide><path>aAERS/software/web/src/main/java/gov/nih/nci/cabig/caaers/web/ae/CaptureAdverseEventInputCommand.java <ide> import java.util.ArrayList; <ide> import java.util.Date; <ide> import java.util.HashMap; <add>import java.util.HashSet; <ide> import java.util.LinkedHashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> <ide> <ide> public void save(boolean incrementAeTermVersion){ <add> Set<AdverseEvent> allAEs = new HashSet<AdverseEvent>(); <add> //create a set of all AEs in all suggested reports <add> if(getEvaluationResult() != null) { <add> Map<Integer, List<AdverseEvent>> allAeMap = getEvaluationResult().getAllAeMap(); <add> for (List<AdverseEvent> listAes : allAeMap.values()) { <add> allAEs.addAll(listAes); <add> } <add> } <ide> if(this.getAdverseEventReportingPeriod() != null){ <ide> //initialize the graded date. <ide> for(AdverseEvent ae : adverseEventReportingPeriod.getAdverseEvents()){ <ide> ae.getAdverseEventTerm().setVersion(version); <ide> <ide> } <add> <add> //match the ae in the reporting period to the one in the evaluated AE results <add> //and copy over the requires reporting flag status <add> for (AdverseEvent adverseEvent : allAEs) { <add> if(ae.getId().equals(adverseEvent.getId())) { <add> ae.setRequiresReporting(adverseEvent.getRequiresReporting()); <add> break; <add> } <add> } <ide> } <ide> <ide> // ToDo - delegate to gov.nih.nci.cabig.caaers.domain.repository.AdverseEventReportingPeriodRepository
Java
apache-2.0
8c9bf23bf6ab4481ee350c0d897352d837499eb6
0
gonmarques/commons-collections,sandrineBeauche/commons-collections,mohanaraosv/commons-collections,apache/commons-collections,apache/commons-collections,mohanaraosv/commons-collections,mohanaraosv/commons-collections,sandrineBeauche/commons-collections,sandrineBeauche/commons-collections,jankill/commons-collections,MuShiiii/commons-collections,apache/commons-collections,MuShiiii/commons-collections,gonmarques/commons-collections,jankill/commons-collections,jankill/commons-collections,MuShiiii/commons-collections
/* * 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.commons.collections.set; import java.util.Set; import org.apache.commons.collections.collection.AbstractCollectionDecorator; /** * Decorates another <code>Set</code> to provide additional behaviour. * <p> * Methods are forwarded directly to the decorated set. * * @param <E> the type of the elements in the set * @since Commons Collections 3.0 * @version $Revision$ $Date$ * * @author Stephen Colebourne */ public abstract class AbstractSetDecorator<E> extends AbstractCollectionDecorator<E> implements Set<E> { /** Serialization version */ private static final long serialVersionUID = -4678668309576958546L; /** * Constructor only used in deserialization, do not use otherwise. * @since Commons Collections 3.1 */ protected AbstractSetDecorator() { super(); } /** * Constructor that wraps (not copies). * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ protected AbstractSetDecorator(Set<E> set) { super(set); } /** * Gets the set being decorated. * * @return the decorated set */ protected Set<E> decorated() { return (Set<E>) super.decorated(); } }
src/java/org/apache/commons/collections/set/AbstractSetDecorator.java
/* * 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.commons.collections.set; import java.util.Set; import org.apache.commons.collections.collection.AbstractCollectionDecorator; /** * Decorates another <code>Set</code> to provide additional behaviour. * <p> * Methods are forwarded directly to the decorated set. * * @since Commons Collections 3.0 * @version $Revision$ $Date$ * * @author Stephen Colebourne */ public abstract class AbstractSetDecorator extends AbstractCollectionDecorator implements Set { /** * Constructor only used in deserialization, do not use otherwise. * @since Commons Collections 3.1 */ protected AbstractSetDecorator() { super(); } /** * Constructor that wraps (not copies). * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ protected AbstractSetDecorator(Set set) { super(set); } /** * Gets the set being decorated. * * @return the decorated set */ protected Set getSet() { return (Set) getCollection(); } }
Merging from -r468106:814127 of collections_jdk5_branch - namely where this code was generified; mostly in r738956. Also see the following revisions: ------------------------------------------------------------------------ r471186 | scolebourne | 2006-11-04 05:47:51 -0800 (Sat, 04 Nov 2006) | 1 line Remove getSet() and getSortedSet() - use decorated() ------------------------------------------------------------------------ r471173 | scolebourne | 2006-11-04 04:07:39 -0800 (Sat, 04 Nov 2006) | 1 line Abstract*Decorator - Generify and use covariant return types ------------------------------------------------------------------------ git-svn-id: 53f0c1087cb9b05f99ff63ab1f4d1687a227fef1@815095 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/commons/collections/set/AbstractSetDecorator.java
Merging from -r468106:814127 of collections_jdk5_branch - namely where this code was generified; mostly in r738956.
<ide><path>rc/java/org/apache/commons/collections/set/AbstractSetDecorator.java <ide> * <p> <ide> * Methods are forwarded directly to the decorated set. <ide> * <add> * @param <E> the type of the elements in the set <ide> * @since Commons Collections 3.0 <ide> * @version $Revision$ $Date$ <ide> * <ide> * @author Stephen Colebourne <ide> */ <del>public abstract class AbstractSetDecorator extends AbstractCollectionDecorator implements Set { <add>public abstract class AbstractSetDecorator<E> extends AbstractCollectionDecorator<E> implements <add> Set<E> { <add> <add> /** Serialization version */ <add> private static final long serialVersionUID = -4678668309576958546L; <ide> <ide> /** <ide> * Constructor only used in deserialization, do not use otherwise. <ide> * @param set the set to decorate, must not be null <ide> * @throws IllegalArgumentException if set is null <ide> */ <del> protected AbstractSetDecorator(Set set) { <add> protected AbstractSetDecorator(Set<E> set) { <ide> super(set); <ide> } <ide> <ide> * <ide> * @return the decorated set <ide> */ <del> protected Set getSet() { <del> return (Set) getCollection(); <add> protected Set<E> decorated() { <add> return (Set<E>) super.decorated(); <ide> } <ide> <ide> }
Java
agpl-3.0
21fd76be5d31f2606a93e4129da26e80be923169
0
iu-uits-es/kc,UniversityOfHawaiiORS/kc,geothomasp/kcmit,jwillia/kc-old1,geothomasp/kcmit,ColostateResearchServices/kc,ColostateResearchServices/kc,UniversityOfHawaiiORS/kc,jwillia/kc-old1,mukadder/kc,ColostateResearchServices/kc,jwillia/kc-old1,mukadder/kc,geothomasp/kcmit,UniversityOfHawaiiORS/kc,kuali/kc,kuali/kc,mukadder/kc,geothomasp/kcmit,geothomasp/kcmit,iu-uits-es/kc,jwillia/kc-old1,kuali/kc,iu-uits-es/kc
/* * Copyright 2005-2010 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * 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.kuali.kra.award.budget; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.lang.StringUtils; import org.kuali.kra.award.budget.document.AwardBudgetDocument; import org.kuali.kra.award.budget.document.AwardBudgetDocumentVersion; import org.kuali.kra.award.budget.document.authorization.AwardBudgetTask; import org.kuali.kra.award.document.AwardDocument; import org.kuali.kra.award.home.Award; import org.kuali.kra.budget.BudgetDecimal; import org.kuali.kra.budget.core.Budget; import org.kuali.kra.budget.document.authorization.BudgetTask; import org.kuali.kra.budget.versions.BudgetDocumentVersion; import org.kuali.kra.budget.web.struts.form.BudgetForm; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KraServiceLocator; import org.kuali.kra.infrastructure.TaskName; import org.kuali.kra.service.TaskAuthorizationService; import org.kuali.rice.core.api.CoreApiServiceLocator; import org.kuali.rice.core.api.config.property.ConfigurationService; import org.kuali.rice.kew.api.WorkflowDocument; import org.kuali.rice.kns.datadictionary.HeaderNavigation; import org.kuali.rice.kns.web.ui.ExtraButton; import org.kuali.rice.kns.web.ui.HeaderField; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.service.KRADServiceLocator; import org.kuali.rice.krad.util.GlobalVariables; public class AwardBudgetForm extends BudgetForm { /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 9001767909548738932L; private String awardInMultipleNodeHierarchy; private String budgetParentId; private AwardBudgetPeriodSummaryCalculatedAmount awardBudgetPeriodSummaryCalculatedAmount; /** {@inheritDoc} */ @Override protected String getDefaultDocumentTypeName() { return "AwardBudgetDocument"; } public AwardBudgetForm() { super(); awardBudgetPeriodSummaryCalculatedAmount = new AwardBudgetPeriodSummaryCalculatedAmount(); } public void initialize() { super.initialize(); getBudgetDocument().initialize(); } /** * Gets the awardInMultipleNodeHierarchy attribute. * @return Returns the awardInMultipleNodeHierarchy. */ public String getAwardInMultipleNodeHierarchy() { return awardInMultipleNodeHierarchy; } /** * Sets the awardInMultipleNodeHierarchy attribute value. * @param awardInMultipleNodeHierarchy The awardInMultipleNodeHierarchy to set. */ public void setAwardInMultipleNodeHierarchy(String awardInMultipleNodeHierarchy) { this.awardInMultipleNodeHierarchy = awardInMultipleNodeHierarchy; } public String getActionPrefix(){ return "awardBudget"; } public AwardBudgetDocument getAwardBudgetDocument() { return (AwardBudgetDocument)super.getBudgetDocument(); } public List<ExtraButton> getExtraActionsButtons() { // clear out the extra buttons array extraButtons.clear(); AwardBudgetDocument doc = this.getAwardBudgetDocument(); String externalImageURL = Constants.KRA_EXTERNALIZABLE_IMAGES_URI_KEY; String krImageURL = Constants.KR_EXTERNALIZABLE_IMAGES_URI_KEY; ConfigurationService configurationService = KRADServiceLocator.getKualiConfigurationService(); TaskAuthorizationService tas = KraServiceLocator.getService(TaskAuthorizationService.class); if (tas.isAuthorized(GlobalVariables.getUserSession().getPrincipalId(), new AwardBudgetTask(TaskName.TOGGLE_AWARD_BUDGET_STATUS, doc))) { String toggleAwardStatusButtonImage = buildExtraButtonSourceURI("buttonsmall_toggleBudgetStatus.gif"); addExtraButton("methodToCall.toggleAwardBudgetStatus", toggleAwardStatusButtonImage, "Toggle Budget Status"); } if( tas.isAuthorized(GlobalVariables.getUserSession().getPrincipalId(), new AwardBudgetTask(TaskName.POST_AWARD_BUDGET,doc ))) { String postAwardBudgetImage = buildExtraButtonSourceURI("buttonsmall_postawardbudget.gif"); addExtraButton("methodToCall.postAwardBudget", postAwardBudgetImage, "Post Budget"); } if( tas.isAuthorized(GlobalVariables.getUserSession().getPrincipalId(), new BudgetTask("awardBudget", "rejectBudget", doc))) { addExtraButton("methodToCall.reject", configurationService.getPropertyValueAsString(externalImageURL) + "buttonsmall_reject.gif", "Reject"); } if( tas.isAuthorized(GlobalVariables.getUserSession().getPrincipalId(), new BudgetTask("awardBudget", "cancelBudget", doc))) { addExtraButton("methodToCall.cancel", configurationService.getPropertyValueAsString(krImageURL) + "buttonsmall_cancel.gif", "Cancel"); } return extraButtons; } /** * This is a utility method to add a new button to the extra buttons * collection. * * @param property * @param source * @param altText */ protected void addExtraButton(String property, String source, String altText){ ExtraButton newButton = new ExtraButton(); newButton.setExtraButtonProperty(property); newButton.setExtraButtonSource(source); newButton.setExtraButtonAltText(altText); extraButtons.add(newButton); } /** * Sets the budgetParentId attribute value. * @param budgetParentId The budgetParentId to set. */ public void setBudgetParentId(String budgetParentId) { this.budgetParentId = budgetParentId; } /** * Gets the budgetParentId attribute. * @return Returns the budgetParentId. */ public String getBudgetParentId() { return budgetParentId; } /** * This method is to define whether FnA rate type is editable in Budget Overview panel. * @return true if any FnA rates defined in award */ public String getFnARateFlagEditable(){ return Boolean.toString(!getAwardBudgetDocument().getAwardBudget().getOhRatesNonEditable()); } /* * Following 4 methods override base function of Budget. For Award Budgets, header should display info about budget, * not parent Award document. */ @Override protected HeaderField getHeaderDocNumber() { return new HeaderField("DataDictionary.DocumentHeader.attributes.documentNumber", getBudgetDocument() == null ? null : getBudgetDocument().getDocumentNumber()); } @Override protected HeaderField getHeaderDocStatus (WorkflowDocument parentWorkflowDocument) { AwardBudgetExt abe = this.getAwardBudgetDocument().getAwardBudget(); return new HeaderField("DataDictionary.AttributeReferenceDummy.attributes.workflowDocumentStatus", abe.getAwardBudgetStatus().getDescription()); } @Override protected HeaderField getHeaderDocInitiator(WorkflowDocument parentWorkflowDocument) { WorkflowDocument doc = getBudgetDocument().getDocumentHeader().getWorkflowDocument(); return new HeaderField("DataDictionary.AttributeReferenceDummy.attributes.initiatorNetworkId", doc.getInitiatorPrincipalId()); } @Override protected HeaderField getHeaderDocCreateDate(WorkflowDocument parentWorkflowDocument) { Date ts = getBudgetDocument().getDocumentHeader().getWorkflowDocument().getDateCreated().toDate(); String updateDateStr = CoreApiServiceLocator.getDateTimeService().toString(ts, "hh:mm a MM/dd/yyyy"); return new HeaderField("DataDictionary.AttributeReferenceDummy.attributes.createDate", updateDateStr); } /** * Gets the awardBudgetPeriodSummaryCalculatedAmount attribute. * @return Returns the awardBudgetPeriodSummaryCalculatedAmount. */ public AwardBudgetPeriodSummaryCalculatedAmount getAwardBudgetPeriodSummaryCalculatedAmount() { return awardBudgetPeriodSummaryCalculatedAmount; } /** * Sets the awardBudgetPeriodSummaryCalculatedAmount attribute value. * @param awardBudgetPeriodSummaryCalculatedAmount The awardBudgetPeriodSummaryCalculatedAmount to set. */ public void setAwardBudgetPeriodSummaryCalculatedAmount( AwardBudgetPeriodSummaryCalculatedAmount awardBudgetPeriodSummaryCalculatedAmount) { this.awardBudgetPeriodSummaryCalculatedAmount = awardBudgetPeriodSummaryCalculatedAmount; } /* * Remove "Modular Budget" tab from award budget * */ @Override public HeaderNavigation[] getHeaderNavigationTabs() { HeaderNavigation[] navigation = super.getHeaderNavigationTabs(); List<HeaderNavigation> resultList = new ArrayList<HeaderNavigation>(); for (HeaderNavigation nav : navigation) { if (StringUtils.equals(nav.getHeaderTabNavigateTo(),"modularBudget")) { } else { resultList.add(nav); } } HeaderNavigation[] result = new HeaderNavigation[resultList.size()]; resultList.toArray(result); return result; } /** * * @see org.kuali.kra.budget.web.struts.form.BudgetForm#getCanModifyBudgetRates() */ @Override public boolean getCanModifyBudgetRates() { boolean retVal = this.getEditingMode().containsKey("modifyBudgets"); return retVal; } /** * * This method returns the award associated with the award budget. * @return */ public Award getAward() { AwardDocument ad = (AwardDocument) this.getAwardBudgetDocument().getParentDocument(); ad.getBudgetDocumentVersions(); Award award = ad.getAward(); return award; } /** * * This method returns the obligated total for this award budget, which is getPreviousObligatedTotal().add(getObligatedChange()). * @return */ public BudgetDecimal getObligatedTotal() { // getPreviousObligatedTotal + getObligatedChange return getPreviousObligatedTotal().add(getObligatedChange()); } /** * * This method returns the previous budget's obligation amount. * @return */ public BudgetDecimal getPreviousObligatedTotal() { //sum up all the previous changes AwardBudgetExt awardBudgetExt = this.getAwardBudgetDocument().getAwardBudget(); AwardDocument ad = (AwardDocument) this.getAwardBudgetDocument().getParentDocument(); List<Budget> allBudgets = new ArrayList<Budget>(); List<AwardBudgetDocumentVersion> awardBudgetDocuments = ad.getBudgetDocumentVersions(); for (AwardBudgetDocumentVersion version : awardBudgetDocuments) { allBudgets.add(version.findBudget()); } return getSumOfAllPreviousBudgetChanges(awardBudgetExt, allBudgets); } /** * * This method sums up all the previous changes of the prior budget versions. * @param curentAwardBudgetExt * @param allBudgets * @return */ protected BudgetDecimal getSumOfAllPreviousBudgetChanges(AwardBudgetExt curentAwardBudgetExt, List<Budget> allBudgets) { if (curentAwardBudgetExt != null && curentAwardBudgetExt.getPrevBudget() != null) { BudgetDecimal previousTotalCost = curentAwardBudgetExt.getPrevBudget().getTotalCostLimit(); AwardBudgetExt previousAwardBudget = findAwardBudgetExt(curentAwardBudgetExt.getPrevBudget().getBudgetId(), allBudgets); return previousTotalCost.add(getSumOfAllPreviousBudgetChanges(previousAwardBudget, allBudgets)); } return BudgetDecimal.ZERO; } /** * * This method finds a particular budget in the list of budgets based on the budget id. If no budget is found, a null is returned. * @param budgetId * @param allBudgets * @return */ protected AwardBudgetExt findAwardBudgetExt(Long budgetId, List<Budget> allBudgets) { for (Budget budget : allBudgets) { if (budget.getBudgetId().equals(budgetId)) { return (AwardBudgetExt) budget; } } return null; } /** * * This method returns the difference in the obligation total between this budget, and the previous. * @return */ public BudgetDecimal getObligatedChange() { //return getObligatedTotal().subtract(getPreviousObligatedTotal()); AwardBudgetExt budget = this.getAwardBudgetDocument().getAwardBudget(); if (budget != null && budget.getTotalCostLimit() != null) { return budget.getTotalCostLimit(); } else { return BudgetDecimal.ZERO; } } }
src/main/java/org/kuali/kra/award/budget/AwardBudgetForm.java
/* * Copyright 2005-2010 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * 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.kuali.kra.award.budget; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.lang.StringUtils; import org.kuali.kra.award.budget.document.AwardBudgetDocument; import org.kuali.kra.award.budget.document.AwardBudgetDocumentVersion; import org.kuali.kra.award.budget.document.authorization.AwardBudgetTask; import org.kuali.kra.award.document.AwardDocument; import org.kuali.kra.award.home.Award; import org.kuali.kra.budget.BudgetDecimal; import org.kuali.kra.budget.core.Budget; import org.kuali.kra.budget.document.authorization.BudgetTask; import org.kuali.kra.budget.versions.BudgetDocumentVersion; import org.kuali.kra.budget.web.struts.form.BudgetForm; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KraServiceLocator; import org.kuali.kra.infrastructure.TaskName; import org.kuali.kra.service.TaskAuthorizationService; import org.kuali.rice.core.api.CoreApiServiceLocator; import org.kuali.rice.core.api.config.property.ConfigurationService; import org.kuali.rice.kew.api.WorkflowDocument; import org.kuali.rice.kns.datadictionary.HeaderNavigation; import org.kuali.rice.kns.web.ui.ExtraButton; import org.kuali.rice.kns.web.ui.HeaderField; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.service.KRADServiceLocator; import org.kuali.rice.krad.util.GlobalVariables; public class AwardBudgetForm extends BudgetForm { /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 9001767909548738932L; private String awardInMultipleNodeHierarchy; private String budgetParentId; private AwardBudgetPeriodSummaryCalculatedAmount awardBudgetPeriodSummaryCalculatedAmount; public AwardBudgetForm() { super(); awardBudgetPeriodSummaryCalculatedAmount = new AwardBudgetPeriodSummaryCalculatedAmount(); } public void initialize() { super.initialize(); getBudgetDocument().initialize(); } /** * Gets the awardInMultipleNodeHierarchy attribute. * @return Returns the awardInMultipleNodeHierarchy. */ public String getAwardInMultipleNodeHierarchy() { return awardInMultipleNodeHierarchy; } /** * Sets the awardInMultipleNodeHierarchy attribute value. * @param awardInMultipleNodeHierarchy The awardInMultipleNodeHierarchy to set. */ public void setAwardInMultipleNodeHierarchy(String awardInMultipleNodeHierarchy) { this.awardInMultipleNodeHierarchy = awardInMultipleNodeHierarchy; } public String getActionPrefix(){ return "awardBudget"; } public AwardBudgetDocument getAwardBudgetDocument() { return (AwardBudgetDocument)super.getBudgetDocument(); } public List<ExtraButton> getExtraActionsButtons() { // clear out the extra buttons array extraButtons.clear(); AwardBudgetDocument doc = this.getAwardBudgetDocument(); String externalImageURL = Constants.KRA_EXTERNALIZABLE_IMAGES_URI_KEY; String krImageURL = Constants.KR_EXTERNALIZABLE_IMAGES_URI_KEY; ConfigurationService configurationService = KRADServiceLocator.getKualiConfigurationService(); TaskAuthorizationService tas = KraServiceLocator.getService(TaskAuthorizationService.class); if (tas.isAuthorized(GlobalVariables.getUserSession().getPrincipalId(), new AwardBudgetTask(TaskName.TOGGLE_AWARD_BUDGET_STATUS, doc))) { String toggleAwardStatusButtonImage = buildExtraButtonSourceURI("buttonsmall_toggleBudgetStatus.gif"); addExtraButton("methodToCall.toggleAwardBudgetStatus", toggleAwardStatusButtonImage, "Toggle Budget Status"); } if( tas.isAuthorized(GlobalVariables.getUserSession().getPrincipalId(), new AwardBudgetTask(TaskName.POST_AWARD_BUDGET,doc ))) { String postAwardBudgetImage = buildExtraButtonSourceURI("buttonsmall_postawardbudget.gif"); addExtraButton("methodToCall.postAwardBudget", postAwardBudgetImage, "Post Budget"); } if( tas.isAuthorized(GlobalVariables.getUserSession().getPrincipalId(), new BudgetTask("awardBudget", "rejectBudget", doc))) { addExtraButton("methodToCall.reject", configurationService.getPropertyValueAsString(externalImageURL) + "buttonsmall_reject.gif", "Reject"); } if( tas.isAuthorized(GlobalVariables.getUserSession().getPrincipalId(), new BudgetTask("awardBudget", "cancelBudget", doc))) { addExtraButton("methodToCall.cancel", configurationService.getPropertyValueAsString(krImageURL) + "buttonsmall_cancel.gif", "Cancel"); } return extraButtons; } /** * This is a utility method to add a new button to the extra buttons * collection. * * @param property * @param source * @param altText */ protected void addExtraButton(String property, String source, String altText){ ExtraButton newButton = new ExtraButton(); newButton.setExtraButtonProperty(property); newButton.setExtraButtonSource(source); newButton.setExtraButtonAltText(altText); extraButtons.add(newButton); } /** * Sets the budgetParentId attribute value. * @param budgetParentId The budgetParentId to set. */ public void setBudgetParentId(String budgetParentId) { this.budgetParentId = budgetParentId; } /** * Gets the budgetParentId attribute. * @return Returns the budgetParentId. */ public String getBudgetParentId() { return budgetParentId; } /** * This method is to define whether FnA rate type is editable in Budget Overview panel. * @return true if any FnA rates defined in award */ public String getFnARateFlagEditable(){ return Boolean.toString(!getAwardBudgetDocument().getAwardBudget().getOhRatesNonEditable()); } /* * Following 4 methods override base function of Budget. For Award Budgets, header should display info about budget, * not parent Award document. */ @Override protected HeaderField getHeaderDocNumber() { return new HeaderField("DataDictionary.DocumentHeader.attributes.documentNumber", getBudgetDocument() == null ? null : getBudgetDocument().getDocumentNumber()); } @Override protected HeaderField getHeaderDocStatus (WorkflowDocument parentWorkflowDocument) { AwardBudgetExt abe = this.getAwardBudgetDocument().getAwardBudget(); return new HeaderField("DataDictionary.AttributeReferenceDummy.attributes.workflowDocumentStatus", abe.getAwardBudgetStatus().getDescription()); } @Override protected HeaderField getHeaderDocInitiator(WorkflowDocument parentWorkflowDocument) { WorkflowDocument doc = getBudgetDocument().getDocumentHeader().getWorkflowDocument(); return new HeaderField("DataDictionary.AttributeReferenceDummy.attributes.initiatorNetworkId", doc.getInitiatorPrincipalId()); } @Override protected HeaderField getHeaderDocCreateDate(WorkflowDocument parentWorkflowDocument) { Date ts = getBudgetDocument().getDocumentHeader().getWorkflowDocument().getDateCreated().toDate(); String updateDateStr = CoreApiServiceLocator.getDateTimeService().toString(ts, "hh:mm a MM/dd/yyyy"); return new HeaderField("DataDictionary.AttributeReferenceDummy.attributes.createDate", updateDateStr); } /** * Gets the awardBudgetPeriodSummaryCalculatedAmount attribute. * @return Returns the awardBudgetPeriodSummaryCalculatedAmount. */ public AwardBudgetPeriodSummaryCalculatedAmount getAwardBudgetPeriodSummaryCalculatedAmount() { return awardBudgetPeriodSummaryCalculatedAmount; } /** * Sets the awardBudgetPeriodSummaryCalculatedAmount attribute value. * @param awardBudgetPeriodSummaryCalculatedAmount The awardBudgetPeriodSummaryCalculatedAmount to set. */ public void setAwardBudgetPeriodSummaryCalculatedAmount( AwardBudgetPeriodSummaryCalculatedAmount awardBudgetPeriodSummaryCalculatedAmount) { this.awardBudgetPeriodSummaryCalculatedAmount = awardBudgetPeriodSummaryCalculatedAmount; } /* * Remove "Modular Budget" tab from award budget * */ @Override public HeaderNavigation[] getHeaderNavigationTabs() { HeaderNavigation[] navigation = super.getHeaderNavigationTabs(); List<HeaderNavigation> resultList = new ArrayList<HeaderNavigation>(); for (HeaderNavigation nav : navigation) { if (StringUtils.equals(nav.getHeaderTabNavigateTo(),"modularBudget")) { } else { resultList.add(nav); } } HeaderNavigation[] result = new HeaderNavigation[resultList.size()]; resultList.toArray(result); return result; } /** * * @see org.kuali.kra.budget.web.struts.form.BudgetForm#getCanModifyBudgetRates() */ @Override public boolean getCanModifyBudgetRates() { boolean retVal = this.getEditingMode().containsKey("modifyBudgets"); return retVal; } /** * * This method returns the award associated with the award budget. * @return */ public Award getAward() { AwardDocument ad = (AwardDocument) this.getAwardBudgetDocument().getParentDocument(); ad.getBudgetDocumentVersions(); Award award = ad.getAward(); return award; } /** * * This method returns the obligated total for this award budget, which is getPreviousObligatedTotal().add(getObligatedChange()). * @return */ public BudgetDecimal getObligatedTotal() { // getPreviousObligatedTotal + getObligatedChange return getPreviousObligatedTotal().add(getObligatedChange()); } /** * * This method returns the previous budget's obligation amount. * @return */ public BudgetDecimal getPreviousObligatedTotal() { //sum up all the previous changes AwardBudgetExt awardBudgetExt = this.getAwardBudgetDocument().getAwardBudget(); AwardDocument ad = (AwardDocument) this.getAwardBudgetDocument().getParentDocument(); List<Budget> allBudgets = new ArrayList<Budget>(); List<AwardBudgetDocumentVersion> awardBudgetDocuments = ad.getBudgetDocumentVersions(); for (AwardBudgetDocumentVersion version : awardBudgetDocuments) { allBudgets.add(version.findBudget()); } return getSumOfAllPreviousBudgetChanges(awardBudgetExt, allBudgets); } /** * * This method sums up all the previous changes of the prior budget versions. * @param curentAwardBudgetExt * @param allBudgets * @return */ protected BudgetDecimal getSumOfAllPreviousBudgetChanges(AwardBudgetExt curentAwardBudgetExt, List<Budget> allBudgets) { if (curentAwardBudgetExt != null && curentAwardBudgetExt.getPrevBudget() != null) { BudgetDecimal previousTotalCost = curentAwardBudgetExt.getPrevBudget().getTotalCostLimit(); AwardBudgetExt previousAwardBudget = findAwardBudgetExt(curentAwardBudgetExt.getPrevBudget().getBudgetId(), allBudgets); return previousTotalCost.add(getSumOfAllPreviousBudgetChanges(previousAwardBudget, allBudgets)); } return BudgetDecimal.ZERO; } /** * * This method finds a particular budget in the list of budgets based on the budget id. If no budget is found, a null is returned. * @param budgetId * @param allBudgets * @return */ protected AwardBudgetExt findAwardBudgetExt(Long budgetId, List<Budget> allBudgets) { for (Budget budget : allBudgets) { if (budget.getBudgetId().equals(budgetId)) { return (AwardBudgetExt) budget; } } return null; } /** * * This method returns the difference in the obligation total between this budget, and the previous. * @return */ public BudgetDecimal getObligatedChange() { //return getObligatedTotal().subtract(getPreviousObligatedTotal()); AwardBudgetExt budget = this.getAwardBudgetDocument().getAwardBudget(); if (budget != null && budget.getTotalCostLimit() != null) { return budget.getTotalCostLimit(); } else { return BudgetDecimal.ZERO; } } }
KCINFR-537: Clean up help doc in Budget
src/main/java/org/kuali/kra/award/budget/AwardBudgetForm.java
KCINFR-537: Clean up help doc in Budget
<ide><path>rc/main/java/org/kuali/kra/award/budget/AwardBudgetForm.java <ide> private String budgetParentId; <ide> private AwardBudgetPeriodSummaryCalculatedAmount awardBudgetPeriodSummaryCalculatedAmount; <ide> <add> /** {@inheritDoc} */ <add> @Override <add> protected String getDefaultDocumentTypeName() { <add> return "AwardBudgetDocument"; <add> } <add> <ide> public AwardBudgetForm() { <ide> super(); <ide> awardBudgetPeriodSummaryCalculatedAmount = new AwardBudgetPeriodSummaryCalculatedAmount();
Java
mit
69b671586097d3df07461d0c1436f029b6290e4d
0
ViliusKraujutis/tvarkau-vilniu,vilnius/tvarkau-vilniu,vilnius/tvarkau-vilniu
package lt.vilnius.tvarkau; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import lt.vilnius.tvarkau.fragments.ProblemDetailFragment; /** * An activity representing a single Problem detail screen. This * activity is only used narrow width devices. On tablet-size devices, * item details are presented side-by-side with a list of items * in a {@link ProblemsListActivity}. */ public class ProblemDetailActivity extends AppCompatActivity { public static Intent getStartActivityIntent(Context context, int problemId) { Intent intent = new Intent(context, ProblemDetailActivity.class); intent.putExtra(ProblemDetailFragment.ARG_ITEM_ID, problemId); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_problem_detail); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Show the Up button in the action bar. ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity // (e.g. when rotating the screen from portrait to landscape). // In this case, the fragment will automatically be re-added // to its container so we don't need to manually add it. // For more information, see the Fragments API guide at: // // http://developer.android.com/guide/components/fragments.html // if (savedInstanceState == null) { // Create the detail fragment and add it to the activity // using a fragment transaction. int problemId = getIntent().getIntExtra(ProblemDetailFragment.ARG_ITEM_ID, 0); ProblemDetailFragment fragment = ProblemDetailFragment.getInstance(problemId); getSupportFragmentManager().beginTransaction() .add(R.id.problem_detail_container, fragment) .commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } }
app/src/main/java/lt/vilnius/tvarkau/ProblemDetailActivity.java
package lt.vilnius.tvarkau; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import lt.vilnius.tvarkau.fragments.ProblemDetailFragment; /** * An activity representing a single Problem detail screen. This * activity is only used narrow width devices. On tablet-size devices, * item details are presented side-by-side with a list of items * in a {@link ProblemsListActivity}. */ public class ProblemDetailActivity extends AppCompatActivity { public static Intent getStartActivityIntent(Context context, int problemId) { Intent intent = new Intent(context, ProblemDetailActivity.class); intent.putExtra(ProblemDetailFragment.ARG_ITEM_ID, problemId); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_problem_detail); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Show the Up button in the action bar. ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity // (e.g. when rotating the screen from portrait to landscape). // In this case, the fragment will automatically be re-added // to its container so we don't need to manually add it. // For more information, see the Fragments API guide at: // // http://developer.android.com/guide/components/fragments.html // if (savedInstanceState == null) { // Create the detail fragment and add it to the activity // using a fragment transaction. int problemId = getIntent().getIntExtra(ProblemDetailFragment.ARG_ITEM_ID, 0); ProblemDetailFragment fragment = ProblemDetailFragment.getInstance(problemId); getSupportFragmentManager().beginTransaction() .add(R.id.problem_detail_container, fragment) .commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // NavUtils.navigateUpTo(this, new Intent(this, ProblemsListActivity.class)); return true; } return super.onOptionsItemSelected(item); } }
Navigate up same behaviour as back pressed
app/src/main/java/lt/vilnius/tvarkau/ProblemDetailActivity.java
Navigate up same behaviour as back pressed
<ide><path>pp/src/main/java/lt/vilnius/tvarkau/ProblemDetailActivity.java <ide> import android.content.Context; <ide> import android.content.Intent; <ide> import android.os.Bundle; <del>import android.support.v4.app.NavUtils; <ide> import android.support.v7.app.ActionBar; <ide> import android.support.v7.app.AppCompatActivity; <ide> import android.support.v7.widget.Toolbar; <ide> <ide> @Override <ide> public boolean onOptionsItemSelected(MenuItem item) { <del> int id = item.getItemId(); <del> if (id == android.R.id.home) { <del> // This ID represents the Home or Up button. In the case of this <del> // activity, the Up button is shown. Use NavUtils to allow users <del> // to navigate up one level in the application structure. For <del> // more details, see the Navigation pattern on Android Design: <del> // <del> // http://developer.android.com/design/patterns/navigation.html#up-vs-back <del> // <del> NavUtils.navigateUpTo(this, new Intent(this, ProblemsListActivity.class)); <del> return true; <add> switch (item.getItemId()) { <add> case android.R.id.home: <add> onBackPressed(); <add> return true; <add> default: <add> return super.onOptionsItemSelected(item); <ide> } <del> return super.onOptionsItemSelected(item); <ide> } <ide> }
Java
apache-2.0
0027f074d18c1816bb75da84c2e20e82ab4c6544
0
subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/base,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai
package io.subutai.core.environment.impl.workflow.modification.steps; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.net.util.SubnetUtils; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import io.subutai.common.environment.EnvironmentModificationException; import io.subutai.common.environment.Topology; import io.subutai.common.network.Gateways; import io.subutai.common.network.Vni; import io.subutai.common.peer.Peer; import io.subutai.common.peer.PeerException; import io.subutai.common.tracker.TrackerOperation; import io.subutai.core.environment.impl.entity.EnvironmentImpl; import io.subutai.core.peer.api.PeerManager; public class VNISetupStep { private static final Logger LOG = LoggerFactory.getLogger( VNISetupStep.class ); private final Topology topology; private final EnvironmentImpl environment; private final PeerManager peerManager; private final TrackerOperation trackerOperation; public VNISetupStep( final Topology topology, final EnvironmentImpl environment, final PeerManager peerManager, final TrackerOperation trackerOperation ) { this.topology = topology; this.environment = environment; this.peerManager = peerManager; this.trackerOperation = trackerOperation; } public void execute() throws EnvironmentModificationException, PeerException { Set<Peer> newPeers = peerManager.resolve( topology.getAllPeers() ); //remove already participating peers newPeers.removeAll( environment.getPeers() ); newPeers.remove( peerManager.getLocalPeer() ); ExecutorService executorService = Executors.newFixedThreadPool( newPeers.size() ); ExecutorCompletionService<Peer> completionService = new ExecutorCompletionService<>( executorService ); //obtain reserved gateways final Map<Peer, Gateways> reservedGateways = Maps.newConcurrentMap(); for ( final Peer peer : newPeers ) { completionService.submit( new Callable<Peer>() { @Override public Peer call() throws Exception { reservedGateways.put( peer, peer.getGateways() ); return peer; } } ); } Set<Peer> succeededPeers = Sets.newHashSet(); for ( Peer ignored : newPeers ) { try { Future<Peer> f = completionService.take(); succeededPeers.add( f.get() ); } catch ( ExecutionException | InterruptedException e ) { LOG.error( "Problems obtaining reserved gateways", e ); } } for ( Peer succeededPeer : succeededPeers ) { trackerOperation .addLog( String.format( "Obtained reserved gateways from peer %s", succeededPeer.getName() ) ); } Set<Peer> failedPeers = Sets.newHashSet( newPeers ); failedPeers.removeAll( succeededPeers ); for ( Peer failedPeer : failedPeers ) { trackerOperation .addLog( String.format( "Failed to obtain reserved gateways from peer %s", failedPeer.getName() ) ); } if ( !failedPeers.isEmpty() ) { throw new EnvironmentModificationException( "Failed to obtain reserved gateways from all peers" ); } //check availability of subnet SubnetUtils subnetUtils = new SubnetUtils( environment.getSubnetCidr() ); String environmentGatewayIp = subnetUtils.getInfo().getLowAddress(); for ( Map.Entry<Peer, Gateways> peerGateways : reservedGateways.entrySet() ) { Peer peer = peerGateways.getKey(); Gateways gateways = peerGateways.getValue(); if ( gateways.findGatewayByIp( environmentGatewayIp ) != null ) { throw new EnvironmentModificationException( String.format( "Subnet %s is already used on peer %s", environment.getSubnetCidr(), peer.getName() ) ); } } //TODO: add gateway & p2p IP to reserve vni final Vni environmentVni = new Vni( environment.getVni(), environment.getId() ); //check reserved vnis for ( final Peer peer : newPeers ) { for ( final Vni vni : peer.getReservedVnis().list() ) { if ( vni.getVni() == environmentVni.getVni() && !Objects .equals( vni.getEnvironmentId(), environmentVni.getEnvironmentId() ) ) { throw new EnvironmentModificationException( String.format( "Vni %d is already used on peer %s", environment.getVni(), peer.getName() ) ); } } } for ( final Peer peer : newPeers ) { completionService.submit( new Callable<Peer>() { @Override public Peer call() throws Exception { peer.reserveVni( environmentVni ); return peer; } } ); } succeededPeers.clear(); for ( Peer ignored : newPeers ) { try { Future<Peer> f = completionService.take(); succeededPeers.add( f.get() ); } catch ( ExecutionException | InterruptedException e ) { LOG.error( "Problems reserving VNI", e ); } } for ( Peer succeededPeer : succeededPeers ) { trackerOperation.addLog( String.format( "Reserved VNI on peer %s", succeededPeer.getName() ) ); } failedPeers = Sets.newHashSet( newPeers ); failedPeers.removeAll( succeededPeers ); for ( Peer failedPeer : failedPeers ) { trackerOperation.addLog( String.format( "Failed to reserve VNI on peer %s", failedPeer.getName() ) ); } if ( !failedPeers.isEmpty() ) { throw new EnvironmentModificationException( "Failed to reserve VNI on all peers" ); } } }
management/server/core/environment-manager/environment-manager-impl/src/main/java/io/subutai/core/environment/impl/workflow/modification/steps/VNISetupStep.java
package io.subutai.core.environment.impl.workflow.modification.steps; import java.util.Map; import java.util.Objects; import java.util.Set; import org.apache.commons.net.util.SubnetUtils; import com.google.common.collect.Maps; import io.subutai.common.environment.EnvironmentModificationException; import io.subutai.common.environment.Topology; import io.subutai.common.network.Gateways; import io.subutai.common.network.Vni; import io.subutai.common.peer.Peer; import io.subutai.common.peer.PeerException; import io.subutai.core.environment.impl.entity.EnvironmentImpl; import io.subutai.core.peer.api.PeerManager; public class VNISetupStep { private final Topology topology; private final EnvironmentImpl environment; private final PeerManager peerManager; public VNISetupStep( final Topology topology, final EnvironmentImpl environment, final PeerManager peerManager ) { this.topology = topology; this.environment = environment; this.peerManager = peerManager; } public void execute() throws EnvironmentModificationException, PeerException { Set<Peer> newPeers = peerManager.resolve( topology.getAllPeers() ); //remove already participating peers newPeers.removeAll( environment.getPeers() ); newPeers.remove( peerManager.getLocalPeer() ); //obtain reserved gateways Map<Peer, Gateways> reservedGateways = Maps.newHashMap(); for ( Peer peer : newPeers ) { reservedGateways.put( peer, peer.getGateways() ); } //check availability of subnet SubnetUtils subnetUtils = new SubnetUtils( environment.getSubnetCidr() ); String environmentGatewayIp = subnetUtils.getInfo().getLowAddress(); for ( Map.Entry<Peer, Gateways> peerGateways : reservedGateways.entrySet() ) { Peer peer = peerGateways.getKey(); Gateways gateways = peerGateways.getValue(); if ( gateways.findGatewayByIp( environmentGatewayIp ) != null ) { throw new EnvironmentModificationException( String.format( "Subnet %s is already used on peer %s", environment.getSubnetCidr(), peer.getName() ) ); } } //TODO: add gateway & p2p IP to reserve vni Vni environmentVni = new Vni( environment.getVni(), environment.getId() ); //check reserved vnis for ( final Peer peer : newPeers ) { for ( final Vni vni : peer.getReservedVnis().list() ) { if ( vni.getVni() == environmentVni.getVni() && !Objects .equals( vni.getEnvironmentId(), environmentVni.getEnvironmentId() ) ) { throw new EnvironmentModificationException( String.format( "Vni %d is already used on peer %s", environment.getVni(), peer.getName() ) ); } } } for ( final Peer peer : newPeers ) { peer.reserveVni( environmentVni ); } } }
parallelized VNI reservation
management/server/core/environment-manager/environment-manager-impl/src/main/java/io/subutai/core/environment/impl/workflow/modification/steps/VNISetupStep.java
parallelized VNI reservation
<ide><path>anagement/server/core/environment-manager/environment-manager-impl/src/main/java/io/subutai/core/environment/impl/workflow/modification/steps/VNISetupStep.java <ide> import java.util.Map; <ide> import java.util.Objects; <ide> import java.util.Set; <add>import java.util.concurrent.Callable; <add>import java.util.concurrent.ExecutionException; <add>import java.util.concurrent.ExecutorCompletionService; <add>import java.util.concurrent.ExecutorService; <add>import java.util.concurrent.Executors; <add>import java.util.concurrent.Future; <add> <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <ide> <ide> import org.apache.commons.net.util.SubnetUtils; <ide> <ide> import com.google.common.collect.Maps; <add>import com.google.common.collect.Sets; <ide> <ide> import io.subutai.common.environment.EnvironmentModificationException; <ide> import io.subutai.common.environment.Topology; <ide> import io.subutai.common.network.Vni; <ide> import io.subutai.common.peer.Peer; <ide> import io.subutai.common.peer.PeerException; <add>import io.subutai.common.tracker.TrackerOperation; <ide> import io.subutai.core.environment.impl.entity.EnvironmentImpl; <ide> import io.subutai.core.peer.api.PeerManager; <ide> <ide> <ide> public class VNISetupStep <ide> { <add> private static final Logger LOG = LoggerFactory.getLogger( VNISetupStep.class ); <add> <ide> private final Topology topology; <ide> private final EnvironmentImpl environment; <ide> private final PeerManager peerManager; <add> private final TrackerOperation trackerOperation; <ide> <ide> <del> public VNISetupStep( final Topology topology, final EnvironmentImpl environment, final PeerManager peerManager ) <add> public VNISetupStep( final Topology topology, final EnvironmentImpl environment, final PeerManager peerManager, <add> final TrackerOperation trackerOperation ) <ide> { <ide> this.topology = topology; <ide> this.environment = environment; <ide> this.peerManager = peerManager; <add> this.trackerOperation = trackerOperation; <ide> } <ide> <ide> <ide> newPeers.removeAll( environment.getPeers() ); <ide> newPeers.remove( peerManager.getLocalPeer() ); <ide> <add> ExecutorService executorService = Executors.newFixedThreadPool( newPeers.size() ); <add> ExecutorCompletionService<Peer> completionService = new ExecutorCompletionService<>( executorService ); <add> <ide> //obtain reserved gateways <del> Map<Peer, Gateways> reservedGateways = Maps.newHashMap(); <del> for ( Peer peer : newPeers ) <add> final Map<Peer, Gateways> reservedGateways = Maps.newConcurrentMap(); <add> for ( final Peer peer : newPeers ) <ide> { <del> reservedGateways.put( peer, peer.getGateways() ); <add> completionService.submit( new Callable<Peer>() <add> { <add> @Override <add> public Peer call() throws Exception <add> { <add> reservedGateways.put( peer, peer.getGateways() ); <add> return peer; <add> } <add> } ); <add> } <add> <add> Set<Peer> succeededPeers = Sets.newHashSet(); <add> for ( Peer ignored : newPeers ) <add> { <add> try <add> { <add> Future<Peer> f = completionService.take(); <add> succeededPeers.add( f.get() ); <add> } <add> catch ( ExecutionException | InterruptedException e ) <add> { <add> LOG.error( "Problems obtaining reserved gateways", e ); <add> } <add> } <add> <add> for ( Peer succeededPeer : succeededPeers ) <add> { <add> trackerOperation <add> .addLog( String.format( "Obtained reserved gateways from peer %s", succeededPeer.getName() ) ); <add> } <add> <add> Set<Peer> failedPeers = Sets.newHashSet( newPeers ); <add> failedPeers.removeAll( succeededPeers ); <add> <add> for ( Peer failedPeer : failedPeers ) <add> { <add> trackerOperation <add> .addLog( String.format( "Failed to obtain reserved gateways from peer %s", failedPeer.getName() ) ); <add> } <add> <add> if ( !failedPeers.isEmpty() ) <add> { <add> throw new EnvironmentModificationException( "Failed to obtain reserved gateways from all peers" ); <ide> } <ide> <ide> //check availability of subnet <ide> } <ide> <ide> //TODO: add gateway & p2p IP to reserve vni <del> Vni environmentVni = new Vni( environment.getVni(), environment.getId() ); <add> final Vni environmentVni = new Vni( environment.getVni(), environment.getId() ); <ide> <ide> //check reserved vnis <ide> for ( final Peer peer : newPeers ) <ide> } <ide> } <ide> <add> <ide> for ( final Peer peer : newPeers ) <ide> { <del> peer.reserveVni( environmentVni ); <add> completionService.submit( new Callable<Peer>() <add> { <add> @Override <add> public Peer call() throws Exception <add> { <add> peer.reserveVni( environmentVni ); <add> return peer; <add> } <add> } ); <add> } <add> <add> succeededPeers.clear(); <add> for ( Peer ignored : newPeers ) <add> { <add> try <add> { <add> Future<Peer> f = completionService.take(); <add> succeededPeers.add( f.get() ); <add> } <add> catch ( ExecutionException | InterruptedException e ) <add> { <add> LOG.error( "Problems reserving VNI", e ); <add> } <add> } <add> <add> for ( Peer succeededPeer : succeededPeers ) <add> { <add> trackerOperation.addLog( String.format( "Reserved VNI on peer %s", succeededPeer.getName() ) ); <add> } <add> <add> failedPeers = Sets.newHashSet( newPeers ); <add> failedPeers.removeAll( succeededPeers ); <add> <add> for ( Peer failedPeer : failedPeers ) <add> { <add> trackerOperation.addLog( String.format( "Failed to reserve VNI on peer %s", failedPeer.getName() ) ); <add> } <add> <add> if ( !failedPeers.isEmpty() ) <add> { <add> throw new EnvironmentModificationException( "Failed to reserve VNI on all peers" ); <ide> } <ide> } <ide> }
JavaScript
mit
3c5897bf15222f93a0a0f18ab7d8f1da68b6c0f4
0
zachelrath/nforce,heroku/force.js,chrishic/nforce
// module dependencies var request = require('request'); var qs = require('querystring'); var url = require('url'); var Record = require('./lib/record'); var QueryStream = require('./lib/querystream'); // constants var AUTH_ENDPOINT = 'https://login.salesforce.com/services/oauth2/authorize'; var TEST_AUTH_ENDPOINT = 'https://test.salesforce.com/services/oauth2/authorize'; var LOGIN_URI = 'https://login.salesforce.com/services/oauth2/token'; var TEST_LOGIN_URI = 'https://test.salesforce.com/services/oauth2/token'; var API_VERSIONS = ['v20.0', 'v21.0', 'v22.0', 'v23.0', 'v24.0']; // nforce connection object var Connection = function(opts) { if(!opts) opts = {}; if(!opts.clientId || typeof opts.clientId !== 'string') { throw new Error('Invalid or missing clientId'); } else { this.clientId = opts.clientId; } if(!opts.clientSecret || typeof opts.clientSecret !== 'string') { throw new Error('Invalid or missing clientSecret'); } else { this.clientSecret = opts.clientSecret; } if(!opts.redirectUri || typeof opts.redirectUri !== 'string') { throw new Error('Invalid or missing redirectUri'); } else { this.redirectUri = opts.redirectUri; } if(typeof opts.cacheMetadata !== 'undefined') { if(typeof opts.cacheMetadata !== 'boolean') throw new Error('cacheMetadata must be a boolean'); this.cacheMetadata = opts.cacheMetadata; } else { // caching is defaulted to false this.cacheMetadata = true; } if(this.cacheMetadata) { this._cache = { keyPrefixes: {}, sObjects: {} } } if(opts.apiVersion) { if(typeof opts.apiVersion === 'number') { opts.apiVersion = opts.apiVersion.toString(); if(opts.apiVersion.length === 2) opts.apiVersion = opts.apiVersion + '.0'; } opts.apiVersion = opts.apiVersion.toLowerCase(); if(/^\d\d\.\d$/g.test(opts.apiVersion)) { opts.apiVersion = 'v' + opts.apiVersion; } else if(/^\d\d$/g.test(opts.apiVersion)) { opts.apiVersion = 'v' + opts.apiVersion + '.0'; } else if(/^v\d\d$/g.test(opts.apiVersion)) { opts.apiVersion = opts.apiVersion + '.0'; } if(API_VERSIONS.indexOf(opts.apiVersion) === -1 ) { throw new Error(opts.apiVersion + ' is an invalid api version'); } else { this.apiVersion = opts.apiVersion; } } else { this.apiVersion = 'v24.0'; } if(opts.environment) { if(opts.environment.toLowerCase() == 'sandbox' || opts.environment.toLowerCase() == 'production') { this.environment = opts.environment.toLowerCase(); } else { throw new Error(opts.environment + ' is an invalid environment'); } } else { this.environment = 'production'; } } // oauth methods Connection.prototype.getAuthUri = function() { var self = this; var opts = { 'response_type': 'code', 'client_id': self.clientId, 'client_secret': self.clientSecret, 'redirect_uri': self.redirectUri } if(self.environment == 'sandbox') { return TEST_AUTH_ENDPOINT + '?' + qs.stringify(opts); } else { return AUTH_ENDPOINT + '?' + qs.stringify(opts); } } Connection.prototype.authenticate = function(opts, callback) { var self = this; if(!opts) opts = {}; var bodyOpts = { 'client_id': self.clientId, 'client_secret': self.clientSecret, } if(opts.code) { bodyOpts['grant_type'] = 'authorization_code'; bodyOpts['code'] = opts.code; bodyOpts['redirect_uri'] = self.redirectUri; } else if(opts.username && opts.password) { bodyOpts['grant_type'] = 'password'; bodyOpts['username'] = opts.username; bodyOpts['password'] = opts.password; if(opts.securityToken) { bodyOpts['password'] = bodyOpts['password'] + opts.securityToken; } } else { var err = new Error('You must either supply a code, or username and password'); callback(err, null); return; } var uri = (self.environment == 'sandbox') ? TEST_LOGIN_URI : LOGIN_URI; var reqOpts = { uri: uri, method: 'POST', body: qs.stringify(bodyOpts), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } request(reqOpts, function(err, res, body){ if(!err && res.statusCode == 200) { if(body) body = JSON.parse(body); callback(null, body); } else if(!err) { if(body) body = JSON.parse(body); err = new Error(body.error + ' - ' + body.error_description); err.statusCode = res.statusCode; callback(err, null); } else { callback(err, null); } }); } Connection.prototype.refreshToken = function(oauth, callback) { if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); if(!oauth.refresh_token) return callback(new Error('You must supply a refresh token')); var self = this; var bodyOpts = { 'client_id': self.clientId, 'client_secret': self.clientSecret, 'grant_type': 'refresh_token', 'redirect_uri': self.redirectUri, 'refresh_token': oauth.refresh_token } var uri = (self.environment == 'sandbox') ? TEST_LOGIN_URI : LOGIN_URI; var reqOpts = { uri: uri, method: 'POST', body: qs.stringify(bodyOpts), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } request(reqOpts, function(err, res, body){ if(!err && res.statusCode == 200) { if(body) body = JSON.parse(body); callback(null, body); } else if(!err) { if(body) body = JSON.parse(body); err = new Error(body.error + ' - ' + body.error_description); err.statusCode = res.statusCode; callback(err, null); } else { callback(err, null); } }); } // api methods Connection.prototype.getIdentity = function(oauth, callback) { if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var opts = { uri: oauth.id, method: 'GET'} apiRequest(opts, oauth, callback); } Connection.prototype.getVersions = function(callback) { request('http://na1.salesforce.com/services/data/', function(err, res, body){ if(!err && res.statusCode == 200) { callback(null, JSON.parse(body)); } else { callback(err, null); } }); } Connection.prototype.getResources = function(oauth, callback) { if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion; var opts = { uri: uri, method: 'GET' } apiRequest(opts, oauth, callback); } Connection.prototype.getSObjects = function(oauth, callback) { var self = this; if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects'; var opts = { uri: uri, method: 'GET' } apiRequest(opts, oauth, function(err, resp){ if(err) { callback(err, null); } else { if(self.cacheMetadata) { for(var obj in resp.sobjects) { var so = resp.sobjects[obj]; if(so.keyPrefix != null) self._cache.keyPrefixes[so.keyPrefix] = so.name; } } callback(null, resp); } }); } Connection.prototype.getMetadata = function(data, oauth, callback) { if(typeof data !== 'string') { return callback(new Error('Type must be in the form of a string'), null); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data; var opts = { uri: uri, method: 'GET' } apiRequest(opts, oauth, callback); } Connection.prototype.getDescribe = function(data, oauth, callback) { if(typeof data !== 'string') { return callback(new Error('Type must be in the form of a string'), null); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data + '/describe'; var opts = { uri: uri, method: 'GET' } apiRequest(opts, oauth, callback); } Connection.prototype.insert = function(data, oauth, callback) { if(typeof data.attributes.type !== 'string') { return callback(new Error('Type must be in the form of a string'), null); } if(typeof data.fieldValues !== 'object') { return callback(new Error('fieldValues must be in the form of an object'), null); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data.attributes.type; var opts = { uri: uri, method: 'POST', body: JSON.stringify(data.getFieldValues()) } apiRequest(opts, oauth, callback); } Connection.prototype.update = function(data, oauth, callback) { if(typeof data.attributes.type !== 'string') { return callback(new Error('Type must be in the form of a string'), null); } if(!data.getId()) { return callback(new Error('You must specify an id in the form of a string')); } if(typeof data.fieldValues !== 'object') { return callback(new Error('fieldValues must be in the form of an object'), null); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data.attributes.type + '/' + data.getId(); var opts = { uri: uri, method: 'PATCH', body: JSON.stringify(data.getFieldValues()) } apiRequest(opts, oauth, callback); } Connection.prototype.upsert = function(data, oauth, callback) { if(typeof data.attributes.type !== 'string') { return callback(new Error('Type must be in the form of a string'), null); } if(!data.attributes.externalId || !data.attributes.externalIdField) { return callback(new Error('Invalid external id or external id field')); } if(typeof data.fieldValues !== 'object') { return callback(new Error('fieldValues must be in the form of an object'), null); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data.attributes.type + '/' + data.attributes.externalIdField + '/' + data.attributes.externalId; var opts = { uri: uri, method: 'PATCH', body: JSON.stringify(data.getFieldValues()) } apiRequest(opts, oauth, callback); } Connection.prototype.delete = function(data, oauth, callback) { if(typeof data.attributes.type !== 'string') { return callback(new Error('Type must be in the form of a string'), null); } if(!data.getId()) { return callback(new Error('You must specify an id in the form of a string')); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data.attributes.type + '/' + data.getId(); var opts = { uri: uri, method: 'DELETE'} apiRequest(opts, oauth, callback); } Connection.prototype.getRecord = function(data, oauth, callback) { if(typeof data.attributes.type !== 'string') { return callback(new Error('Type must be in the form of a string'), null); } if(!data.getId()) { return callback(new Error('You must specify an id in the form of a string')); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data.attributes.type + '/' + data.getId(); if(data.fields) { var query = {} if(typeof data.fields === 'string') { query.fields = data.fields; } else if(typeof data.fields === 'object' && data.fields.length) { query.fields = data.fields.join(); } uri += '?' + qs.stringify(query); } var opts = { uri: uri, method: 'GET'} apiRequest(opts, oauth, function(err, resp){ if(!err) { resp = new Record(resp); } callback(err, resp); }); } Connection.prototype.query = function(query, oauth, callback) { var self = this; var recs = []; var stream = new QueryStream(); if(typeof query !== 'string') { return callback(new Error('You must specify a query')); } if(!callback || typeof callback !== 'function') callback = function(){} if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var queryNext = function(url) { self.getUrl(url, oauth, function(err, resp) { if(err) return callback(err, resp); if(resp.records && resp.records.length > 0) { stream.write(JSON.stringify(resp)); } if(resp.nextRecordsUrl) { queryNext(resp.nextRecordsUrl); } else { stream.end(); } }); } var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/query'; var opts = { uri: uri, method: 'GET', qs: { q: query } } apiRequest(opts, oauth, function(err, resp){ if(!err) { if(resp.records && resp.records.length > 0) { stream.write(JSON.stringify(resp)); for(var i=0; i<resp.records.length; i++) { recs.push(new Record(resp.records[i])); } resp.records = recs; } if(resp.nextRecordsUrl && stream.isStreaming()) { console.log('not streaming'); queryNext(resp.nextRecordsUrl); } else { console.log('not streaming'); callback(err, resp); stream.end(); } } else { stream.end(); callback(err, resp); } }); return stream; } Connection.prototype.search = function(search, oauth, callback) { if(typeof search !== 'string') { return callback(new Error('Search must be in string form'), null); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/search'; var opts = { uri: uri, method: 'GET', qs: { q: search } } apiRequest(opts, oauth, function(err, resp){ if(!err) { if(resp.length) { var recs = []; for(var i=0; i<resp.length; i++) { recs.push(new Record(resp[i])); } resp = recs; } } callback(err, resp); }); } Connection.prototype.getUrl = function(url, oauth, callback) { if(typeof url !== 'string') { return callback(new Error('Url must be in string form'), null); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + url; var opts = { uri: uri, method: 'GET' } apiRequest(opts, oauth, callback); } // chatter api methods // express middleware Connection.prototype.expressOAuth = function(opts) { var self = this; var matchUrl = url.parse(this.redirectUri); matchUrl.pathname.replace(/\/$/, ''); if(opts.onSuccess && opts.onSuccess.substring(0,1) !== '/') { opts.onSuccess = '/' + opts.onSuccess; } if(opts.onError && opts.onError.substring(0,1) !== '/') { opts.onError = '/' + opts.onError; } return function(req, res, next) { if(req.session && req.query.code) { var url = req.url.replace(/\?.*/i, '').replace(/\/$/, ''); if(matchUrl.pathname == url) { // its an oauth callback self.authenticate({ code: req.query.code}, function(err, resp){ if(!err) { req.session.oauth = resp; if(opts.onSuccess) { res.redirect(opts.onSuccess); } else { res.redirect('/'); } } else { // not sure how to handle the error right now. if(opts.onError) { // need to dump the error messages into the querystring res.redirect(opts.onError) } else { next(); } } }); } } else { next(); } } } // utility methods var validateOAuth = function(oauth) { if(!oauth || !oauth.instance_url || !oauth.access_token) { return false; } else { return true; } } var apiRequest = function(opts, oauth, callback) { var token = 'OAuth ' + oauth.access_token; opts.headers = { 'Content-Type': 'application/json', 'Authorization': token } request(opts, function(err, res, body) { if(!err && res.statusCode == 200 || res.statusCode == 201 || res.statusCode == 202 || res.statusCode == 204) { if(body) body = JSON.parse(body); callback(null, body); } else if(!err) { if(body) body = JSON.parse(body); err = new Error(body[0].message); err.errorCode = body[0].errorCode; err.statusCode = res.statusCode; callback(err, null); } else { callback(err, null); } }); } // exports module.exports.createConnection = function(opts) { return new Connection(opts); } module.exports.createSObject = function(type, fields) { var data = { attributes: {} } data.attributes.type = type; var rec = new Record(data); if(fields) { for(var key in fields) { rec[key] = fields[key]; } } return rec; } module.exports.version = '0.1.1';
index.js
// module dependencies var request = require('request'); var qs = require('querystring'); var url = require('url'); var Record = require('./lib/record'); var QueryStream = require('./lib/querystream'); // constants var AUTH_ENDPOINT = 'https://login.salesforce.com/services/oauth2/authorize'; var TEST_AUTH_ENDPOINT = 'https://test.salesforce.com/services/oauth2/authorize'; var LOGIN_URI = 'https://login.salesforce.com/services/oauth2/token'; var TEST_LOGIN_URI = 'https://test.salesforce.com/services/oauth2/token'; var API_VERSIONS = ['v20.0', 'v21.0', 'v22.0', 'v23.0', 'v24.0']; // nforce connection object var Connection = function(opts) { if(!opts) opts = {}; if(!opts.clientId || typeof opts.clientId !== 'string') { throw new Error('Invalid or missing clientId'); } else { this.clientId = opts.clientId; } if(!opts.clientSecret || typeof opts.clientSecret !== 'string') { throw new Error('Invalid or missing clientSecret'); } else { this.clientSecret = opts.clientSecret; } if(!opts.redirectUri || typeof opts.redirectUri !== 'string') { throw new Error('Invalid or missing redirectUri'); } else { this.redirectUri = opts.redirectUri; } if(typeof opts.cacheMetadata !== 'undefined') { if(typeof opts.cacheMetadata !== 'boolean') throw new Error('cacheMetadata must be a boolean'); this.cacheMetadata = opts.cacheMetadata; } else { // caching is defaulted to false this.cacheMetadata = true; } if(this.cacheMetadata) { this._cache = { keyPrefixes: {}, sObjects: {} } } if(opts.apiVersion) { if(typeof opts.apiVersion === 'number') { opts.apiVersion = opts.apiVersion.toString(); if(opts.apiVersion.length === 2) opts.apiVersion = opts.apiVersion + '.0'; } opts.apiVersion = opts.apiVersion.toLowerCase(); if(/^\d\d\.\d$/g.test(opts.apiVersion)) { opts.apiVersion = 'v' + opts.apiVersion; } else if(/^\d\d$/g.test(opts.apiVersion)) { opts.apiVersion = 'v' + opts.apiVersion + '.0'; } else if(/^v\d\d$/g.test(opts.apiVersion)) { opts.apiVersion = opts.apiVersion + '.0'; } if(API_VERSIONS.indexOf(opts.apiVersion) === -1 ) { throw new Error(opts.apiVersion + ' is an invalid api version'); } else { this.apiVersion = opts.apiVersion; } } else { this.apiVersion = 'v24.0'; } if(opts.environment) { if(opts.environment.toLowerCase() == 'sandbox' || opts.environment.toLowerCase() == 'production') { this.environment = opts.environment.toLowerCase(); } else { throw new Error(opts.environment + ' is an invalid environment'); } } else { this.environment = 'production'; } } // oauth methods Connection.prototype.getAuthUri = function() { var self = this; var opts = { 'response_type': 'code', 'client_id': self.clientId, 'client_secret': self.clientSecret, 'redirect_uri': self.redirectUri } if(self.environment == 'sandbox') { return TEST_AUTH_ENDPOINT + '?' + qs.stringify(opts); } else { return AUTH_ENDPOINT + '?' + qs.stringify(opts); } } Connection.prototype.authenticate = function(opts, callback) { var self = this; if(!opts) opts = {}; var bodyOpts = { 'client_id': self.clientId, 'client_secret': self.clientSecret, } if(opts.code) { bodyOpts['grant_type'] = 'authorization_code'; bodyOpts['code'] = opts.code; bodyOpts['redirect_uri'] = self.redirectUri; } else if(opts.username && opts.password) { bodyOpts['grant_type'] = 'password'; bodyOpts['username'] = opts.username; bodyOpts['password'] = opts.password; if(opts.securityToken) { bodyOpts['password'] = bodyOpts['password'] + opts.securityToken; } } else { var err = new Error('You must either supply a code, or username and password'); callback(err, null); return; } var uri = (self.environment == 'sandbox') ? TEST_LOGIN_URI : LOGIN_URI; var reqOpts = { uri: uri, method: 'POST', body: qs.stringify(bodyOpts), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } request(reqOpts, function(err, res, body){ if(!err && res.statusCode == 200) { if(body) body = JSON.parse(body); callback(null, body); } else if(!err) { if(body) body = JSON.parse(body); err = new Error(body.error + ' - ' + body.error_description); err.statusCode = res.statusCode; callback(err, null); } else { callback(err, null); } }); } Connection.prototype.refreshToken = function(oauth, callback) { if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); if(!oauth.refresh_token) return callback(new Error('You must supply a refresh token')); var self = this; var bodyOpts = { 'client_id': self.clientId, 'client_secret': self.clientSecret, 'grant_type': 'refresh_token', 'redirect_uri': self.redirectUri, 'refresh_token': oauth.refresh_token } var uri = (self.environment == 'sandbox') ? TEST_LOGIN_URI : LOGIN_URI; var reqOpts = { uri: uri, method: 'POST', body: qs.stringify(bodyOpts), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } request(reqOpts, function(err, res, body){ if(!err && res.statusCode == 200) { if(body) body = JSON.parse(body); callback(null, body); } else if(!err) { if(body) body = JSON.parse(body); err = new Error(body.error + ' - ' + body.error_description); err.statusCode = res.statusCode; callback(err, null); } else { callback(err, null); } }); } // api methods Connection.prototype.getIdentity = function(oauth, callback) { if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var opts = { uri: oauth.id, method: 'GET'} apiRequest(opts, oauth, callback); } Connection.prototype.getVersions = function(callback) { request('http://na1.salesforce.com/services/data/', function(err, res, body){ if(!err && res.statusCode == 200) { callback(null, JSON.parse(body)); } else { callback(err, null); } }); } Connection.prototype.getResources = function(oauth, callback) { if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion; var opts = { uri: uri, method: 'GET' } apiRequest(opts, oauth, callback); } Connection.prototype.getSObjects = function(oauth, callback) { var self = this; if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects'; var opts = { uri: uri, method: 'GET' } apiRequest(opts, oauth, function(err, resp){ if(err) { callback(err, null); } else { if(self.cacheMetadata) { for(var obj in resp.sobjects) { var so = resp.sobjects[obj]; if(so.keyPrefix != null) self._cache.keyPrefixes[so.keyPrefix] = so.name; } } callback(null, resp); } }); } Connection.prototype.getMetadata = function(data, oauth, callback) { if(typeof data !== 'string') { return callback(new Error('Type must be in the form of a string'), null); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data; var opts = { uri: uri, method: 'GET' } apiRequest(opts, oauth, callback); } Connection.prototype.getDescribe = function(data, oauth, callback) { if(typeof data.type !== 'string') { return callback(new Error('Type must be in the form of a string'), null); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data.type + '/describe'; var opts = { uri: uri, method: 'GET' } apiRequest(opts, oauth, callback); } Connection.prototype.insert = function(data, oauth, callback) { if(typeof data.attributes.type !== 'string') { return callback(new Error('Type must be in the form of a string'), null); } if(typeof data.fieldValues !== 'object') { return callback(new Error('fieldValues must be in the form of an object'), null); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data.attributes.type; var opts = { uri: uri, method: 'POST', body: JSON.stringify(data.getFieldValues()) } apiRequest(opts, oauth, callback); } Connection.prototype.update = function(data, oauth, callback) { if(typeof data.attributes.type !== 'string') { return callback(new Error('Type must be in the form of a string'), null); } if(!data.getId()) { return callback(new Error('You must specify an id in the form of a string')); } if(typeof data.fieldValues !== 'object') { return callback(new Error('fieldValues must be in the form of an object'), null); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data.attributes.type + '/' + data.getId(); var opts = { uri: uri, method: 'PATCH', body: JSON.stringify(data.getFieldValues()) } apiRequest(opts, oauth, callback); } Connection.prototype.upsert = function(data, oauth, callback) { if(typeof data.attributes.type !== 'string') { return callback(new Error('Type must be in the form of a string'), null); } if(!data.attributes.externalId || !data.attributes.externalIdField) { return callback(new Error('Invalid external id or external id field')); } if(typeof data.fieldValues !== 'object') { return callback(new Error('fieldValues must be in the form of an object'), null); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data.attributes.type + '/' + data.attributes.externalIdField + '/' + data.attributes.externalId; var opts = { uri: uri, method: 'PATCH', body: JSON.stringify(data.getFieldValues()) } apiRequest(opts, oauth, callback); } Connection.prototype.delete = function(data, oauth, callback) { if(typeof data.attributes.type !== 'string') { return callback(new Error('Type must be in the form of a string'), null); } if(!data.getId()) { return callback(new Error('You must specify an id in the form of a string')); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data.attributes.type + '/' + data.getId(); var opts = { uri: uri, method: 'DELETE'} apiRequest(opts, oauth, callback); } Connection.prototype.getRecord = function(data, oauth, callback) { if(typeof data.attributes.type !== 'string') { return callback(new Error('Type must be in the form of a string'), null); } if(!data.getId()) { return callback(new Error('You must specify an id in the form of a string')); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data.attributes.type + '/' + data.getId(); if(data.fields) { var query = {} if(typeof data.fields === 'string') { query.fields = data.fields; } else if(typeof data.fields === 'object' && data.fields.length) { query.fields = data.fields.join(); } uri += '?' + qs.stringify(query); } var opts = { uri: uri, method: 'GET'} apiRequest(opts, oauth, function(err, resp){ if(!err) { resp = new Record(resp); } callback(err, resp); }); } Connection.prototype.query = function(query, oauth, callback) { var self = this; var recs = []; var stream = new QueryStream(); if(typeof query !== 'string') { return callback(new Error('You must specify a query')); } if(!callback || typeof callback !== 'function') callback = function(){} if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var queryNext = function(url) { self.getUrl(url, oauth, function(err, resp) { if(err) return callback(err, resp); if(resp.records && resp.records.length > 0) { stream.write(JSON.stringify(resp)); } if(resp.nextRecordsUrl) { queryNext(resp.nextRecordsUrl); } else { stream.end(); } }); } var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/query'; var opts = { uri: uri, method: 'GET', qs: { q: query } } apiRequest(opts, oauth, function(err, resp){ if(!err) { if(resp.records && resp.records.length > 0) { stream.write(JSON.stringify(resp)); for(var i=0; i<resp.records.length; i++) { recs.push(new Record(resp.records[i])); } resp.records = recs; } if(resp.nextRecordsUrl && stream.isStreaming()) { console.log('not streaming'); queryNext(resp.nextRecordsUrl); } else { console.log('not streaming'); callback(err, resp); stream.end(); } } else { stream.end(); callback(err, resp); } }); return stream; } Connection.prototype.search = function(search, oauth, callback) { if(typeof search !== 'string') { return callback(new Error('Search must be in string form'), null); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/search'; var opts = { uri: uri, method: 'GET', qs: { q: search } } apiRequest(opts, oauth, function(err, resp){ if(!err) { if(resp.length) { var recs = []; for(var i=0; i<resp.length; i++) { recs.push(new Record(resp[i])); } resp = recs; } } callback(err, resp); }); } Connection.prototype.getUrl = function(url, oauth, callback) { if(typeof url !== 'string') { return callback(new Error('Url must be in string form'), null); } if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); var uri = oauth.instance_url + url; var opts = { uri: uri, method: 'GET' } apiRequest(opts, oauth, callback); } // chatter api methods // express middleware Connection.prototype.expressOAuth = function(opts) { var self = this; var matchUrl = url.parse(this.redirectUri); matchUrl.pathname.replace(/\/$/, ''); if(opts.onSuccess && opts.onSuccess.substring(0,1) !== '/') { opts.onSuccess = '/' + opts.onSuccess; } if(opts.onError && opts.onError.substring(0,1) !== '/') { opts.onError = '/' + opts.onError; } return function(req, res, next) { if(req.session && req.query.code) { var url = req.url.replace(/\?.*/i, '').replace(/\/$/, ''); if(matchUrl.pathname == url) { // its an oauth callback self.authenticate({ code: req.query.code}, function(err, resp){ if(!err) { req.session.oauth = resp; if(opts.onSuccess) { res.redirect(opts.onSuccess); } else { res.redirect('/'); } } else { // not sure how to handle the error right now. if(opts.onError) { // need to dump the error messages into the querystring res.redirect(opts.onError) } else { next(); } } }); } } else { next(); } } } // utility methods var validateOAuth = function(oauth) { if(!oauth || !oauth.instance_url || !oauth.access_token) { return false; } else { return true; } } var apiRequest = function(opts, oauth, callback) { var token = 'OAuth ' + oauth.access_token; opts.headers = { 'Content-Type': 'application/json', 'Authorization': token } request(opts, function(err, res, body) { if(!err && res.statusCode == 200 || res.statusCode == 201 || res.statusCode == 202 || res.statusCode == 204) { if(body) body = JSON.parse(body); callback(null, body); } else if(!err) { if(body) body = JSON.parse(body); err = new Error(body[0].message); err.errorCode = body[0].errorCode; err.statusCode = res.statusCode; callback(err, null); } else { callback(err, null); } }); } // exports module.exports.createConnection = function(opts) { return new Connection(opts); } module.exports.createSObject = function(type, fields) { var data = { attributes: {} } data.attributes.type = type; var rec = new Record(data); if(fields) { for(var key in fields) { rec[key] = fields[key]; } } return rec; } module.exports.version = '0.1.1';
changed from hash to simple string
index.js
changed from hash to simple string
<ide><path>ndex.js <ide> } <ide> <ide> Connection.prototype.getDescribe = function(data, oauth, callback) { <del> if(typeof data.type !== 'string') { <del> return callback(new Error('Type must be in the form of a string'), null); <del> } <del> if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); <del> var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data.type + '/describe'; <add> if(typeof data !== 'string') { <add> return callback(new Error('Type must be in the form of a string'), null); <add> } <add> if(!validateOAuth(oauth)) return callback(new Error('Invalid oauth object argument'), null); <add> var uri = oauth.instance_url + '/services/data/' + this.apiVersion + '/sobjects/' + data + '/describe'; <ide> var opts = { uri: uri, method: 'GET' } <ide> apiRequest(opts, oauth, callback); <ide> }
Java
apache-2.0
862f50355f8fc97814ffd44e76c23e14f781b473
0
chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq
/** * 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.bugs; import javax.jms.BytesMessage; import javax.jms.Connection; import javax.jms.DeliveryMode; import javax.jms.MessageProducer; import javax.jms.Session; import junit.framework.TestCase; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.jmx.QueueViewMBean; import org.apache.activemq.broker.region.Queue; import org.apache.activemq.broker.region.RegionBroker; import org.apache.activemq.broker.region.policy.PolicyEntry; import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ4930Test extends TestCase { private static final Logger LOG = LoggerFactory.getLogger(AMQ4930Test.class); final int messageCount = 150; final int messageSize = 1024*1024; final int maxBrowsePageSize = 50; final ActiveMQQueue bigQueue = new ActiveMQQueue("BIG"); BrokerService broker; ActiveMQConnectionFactory factory; protected void configureBroker() throws Exception { broker.setDeleteAllMessagesOnStartup(true); broker.setAdvisorySupport(false); broker.getSystemUsage().getMemoryUsage().setLimit(1*1024*1024); PolicyMap pMap = new PolicyMap(); PolicyEntry policy = new PolicyEntry(); // disable expriy processing as this will call browse in parallel policy.setExpireMessagesPeriod(0); policy.setMaxPageSize(maxBrowsePageSize); policy.setMaxBrowsePageSize(maxBrowsePageSize); pMap.setDefaultEntry(policy); broker.setDestinationPolicy(pMap); } public void testBrowsePendingNonPersistent() throws Exception { doTestBrowsePending(DeliveryMode.NON_PERSISTENT); } public void testBrowsePendingPersistent() throws Exception { doTestBrowsePending(DeliveryMode.PERSISTENT); } public void testWithStatsDisabled() throws Exception { ((RegionBroker)broker.getRegionBroker()).getDestinationStatistics().setEnabled(false); doTestBrowsePending(DeliveryMode.PERSISTENT); } public void doTestBrowsePending(int deliveryMode) throws Exception { Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(bigQueue); producer.setDeliveryMode(deliveryMode); BytesMessage bytesMessage = session.createBytesMessage(); bytesMessage.writeBytes(new byte[messageSize]); for (int i = 0; i < messageCount; i++) { producer.send(bigQueue, bytesMessage); } final QueueViewMBean queueViewMBean = (QueueViewMBean) broker.getManagementContext().newProxyInstance(broker.getAdminView().getQueues()[0], QueueViewMBean.class, false); LOG.info(queueViewMBean.getName() + " Size: " + queueViewMBean.getEnqueueCount()); connection.close(); assertFalse("Cache disabled on q", queueViewMBean.isCacheEnabled()); // ensure repeated browse does now blow mem final Queue underTest = (Queue) ((RegionBroker)broker.getRegionBroker()).getQueueRegion().getDestinationMap().get(bigQueue); // do twice to attempt to pull in 2*maxBrowsePageSize which uses up the system memory limit Message[] browsed = underTest.browse(); LOG.info("Browsed: " + browsed.length); assertEquals("maxBrowsePageSize", maxBrowsePageSize, browsed.length); browsed = underTest.browse(); LOG.info("Browsed: " + browsed.length); assertEquals("maxBrowsePageSize", maxBrowsePageSize, browsed.length); Runtime.getRuntime().gc(); long free = Runtime.getRuntime().freeMemory()/1024; LOG.info("free at start of check: " + free); // check for memory growth for (int i=0; i<10; i++) { LOG.info("free: " + Runtime.getRuntime().freeMemory()/1024); browsed = underTest.browse(); LOG.info("Browsed: " + browsed.length); assertEquals("maxBrowsePageSize", maxBrowsePageSize, browsed.length); Runtime.getRuntime().gc(); Runtime.getRuntime().gc(); assertTrue("No growth: " + Runtime.getRuntime().freeMemory()/1024 + " >= " + (free - (free * 0.2)), Runtime.getRuntime().freeMemory()/1024 >= (free - (free * 0.2))); } } protected void setUp() throws Exception { super.setUp(); broker = new BrokerService(); broker.setBrokerName("thisOne"); configureBroker(); broker.start(); factory = new ActiveMQConnectionFactory("vm://thisOne?jms.alwaysSyncSend=true"); factory.setWatchTopicAdvisories(false); } protected void tearDown() throws Exception { super.tearDown(); if (broker != null) { broker.stop(); broker = null; } } }
activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4930Test.java
/** * 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.bugs; import javax.jms.BytesMessage; import javax.jms.Connection; import javax.jms.DeliveryMode; import javax.jms.MessageProducer; import javax.jms.Session; import junit.framework.TestCase; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.jmx.QueueViewMBean; import org.apache.activemq.broker.region.Queue; import org.apache.activemq.broker.region.RegionBroker; import org.apache.activemq.broker.region.policy.PolicyEntry; import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ4930Test extends TestCase { private static final Logger LOG = LoggerFactory.getLogger(AMQ4930Test.class); final int messageCount = 150; final int messageSize = 1024*1024; final int maxBrowsePageSize = 50; final ActiveMQQueue bigQueue = new ActiveMQQueue("BIG"); BrokerService broker; ActiveMQConnectionFactory factory; protected void configureBroker() throws Exception { broker.setDeleteAllMessagesOnStartup(true); broker.setAdvisorySupport(false); broker.getSystemUsage().getMemoryUsage().setLimit(1*1024*1024); PolicyMap pMap = new PolicyMap(); PolicyEntry policy = new PolicyEntry(); // disable expriy processing as this will call browse in parallel policy.setExpireMessagesPeriod(0); policy.setMaxPageSize(maxBrowsePageSize); policy.setMaxBrowsePageSize(maxBrowsePageSize); pMap.setDefaultEntry(policy); broker.setDestinationPolicy(pMap); } public void testBrowsePendingNonPersistent() throws Exception { doTestBrowsePending(DeliveryMode.NON_PERSISTENT); } public void testBrowsePendingPersistent() throws Exception { doTestBrowsePending(DeliveryMode.PERSISTENT); } public void testWithStatsDisabled() throws Exception { ((RegionBroker)broker.getRegionBroker()).getDestinationStatistics().setEnabled(false); doTestBrowsePending(DeliveryMode.PERSISTENT); } public void doTestBrowsePending(int deliveryMode) throws Exception { Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(bigQueue); producer.setDeliveryMode(deliveryMode); BytesMessage bytesMessage = session.createBytesMessage(); bytesMessage.writeBytes(new byte[messageSize]); for (int i = 0; i < messageCount; i++) { producer.send(bigQueue, bytesMessage); } final QueueViewMBean queueViewMBean = (QueueViewMBean) broker.getManagementContext().newProxyInstance(broker.getAdminView().getQueues()[0], QueueViewMBean.class, false); LOG.info(queueViewMBean.getName() + " Size: " + queueViewMBean.getEnqueueCount()); connection.close(); assertFalse("Cache disabled on q", queueViewMBean.isCacheEnabled()); // ensure repeated browse does now blow mem final Queue underTest = (Queue) ((RegionBroker)broker.getRegionBroker()).getQueueRegion().getDestinationMap().get(bigQueue); // do twice to attempt to pull in 2*maxBrowsePageSize which uses up the system memory limit Message[] browsed = underTest.browse(); LOG.info("Browsed: " + browsed.length); assertEquals("maxBrowsePageSize", maxBrowsePageSize, browsed.length); browsed = underTest.browse(); LOG.info("Browsed: " + browsed.length); assertEquals("maxBrowsePageSize", maxBrowsePageSize, browsed.length); Runtime.getRuntime().gc(); long free = Runtime.getRuntime().freeMemory()/1024; LOG.info("free at start of check: " + free); // check for memory growth for (int i=0; i<10; i++) { LOG.info("free: " + Runtime.getRuntime().freeMemory()/1024); browsed = underTest.browse(); LOG.info("Browsed: " + browsed.length); assertEquals("maxBrowsePageSize", maxBrowsePageSize, browsed.length); Runtime.getRuntime().gc(); Runtime.getRuntime().gc(); assertTrue("No growth: " + Runtime.getRuntime().freeMemory()/1024, Runtime.getRuntime().freeMemory()/1024 >= (free - (free * 0.1))); } } protected void setUp() throws Exception { super.setUp(); broker = new BrokerService(); broker.setBrokerName("thisOne"); configureBroker(); broker.start(); factory = new ActiveMQConnectionFactory("vm://thisOne?jms.alwaysSyncSend=true"); factory.setWatchTopicAdvisories(false); } protected void tearDown() throws Exception { super.tearDown(); if (broker != null) { broker.stop(); broker = null; } } }
give test more gc wiggle room - AMQ-4930
activemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4930Test.java
give test more gc wiggle room - AMQ-4930
<ide><path>ctivemq-unit-tests/src/test/java/org/apache/activemq/bugs/AMQ4930Test.java <ide> assertEquals("maxBrowsePageSize", maxBrowsePageSize, browsed.length); <ide> Runtime.getRuntime().gc(); <ide> Runtime.getRuntime().gc(); <del> assertTrue("No growth: " + Runtime.getRuntime().freeMemory()/1024, Runtime.getRuntime().freeMemory()/1024 >= (free - (free * 0.1))); <add> assertTrue("No growth: " + Runtime.getRuntime().freeMemory()/1024 + " >= " + (free - (free * 0.2)), Runtime.getRuntime().freeMemory()/1024 >= (free - (free * 0.2))); <ide> } <ide> } <ide>
Java
bsd-3-clause
c92f83c0488112ac0a33f56d6965c6651c39ab1b
0
bluerover/6lbr,arurke/contiki,arurke/contiki,MohamedSeliem/contiki,arurke/contiki,MohamedSeliem/contiki,MohamedSeliem/contiki,arurke/contiki,MohamedSeliem/contiki,arurke/contiki,MohamedSeliem/contiki,arurke/contiki,bluerover/6lbr,bluerover/6lbr,bluerover/6lbr,MohamedSeliem/contiki,arurke/contiki,bluerover/6lbr,bluerover/6lbr,bluerover/6lbr,MohamedSeliem/contiki
/* * Copyright (c) 2012, Swedish Institute of Computer Science. * 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 Institute 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 INSTITUTE 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 INSTITUTE 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.contikios.cooja.plugins.skins; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.awt.Polygon; import java.util.ArrayList; import java.util.Observable; import java.util.Observer; import org.apache.log4j.Logger; import org.contikios.cooja.ClassDescription; import org.contikios.cooja.Mote; import org.contikios.cooja.RadioConnection; import org.contikios.cooja.Simulation; import org.contikios.cooja.SupportedArguments; import org.contikios.cooja.TimeEvent; import org.contikios.cooja.interfaces.Position; import org.contikios.cooja.interfaces.Radio; import org.contikios.cooja.plugins.Visualizer; import org.contikios.cooja.plugins.VisualizerSkin; import org.contikios.cooja.radiomediums.AbstractRadioMedium; /** * Radio traffic history visualizer skin. * * @see UDGMVisualizerSkin * @author Fredrik Osterlind */ @ClassDescription("Radio traffic") @SupportedArguments(radioMediums = {AbstractRadioMedium.class}) public class TrafficVisualizerSkin implements VisualizerSkin { private static final Logger logger = Logger.getLogger(TrafficVisualizerSkin.class); private final int MAX_HISTORY_SIZE = 200; private boolean active = false; private Simulation simulation = null; private Visualizer visualizer = null; private AbstractRadioMedium radioMedium = null; private ArrayList<RadioConnectionArrow> historyList = new ArrayList<RadioConnectionArrow>(); private RadioConnectionArrow[] history = null; private Observer radioMediumObserver = new Observer() { @Override public void update(Observable obs, Object obj) { RadioConnection last = radioMedium.getLastConnection(); if (last != null && historyList.size() < MAX_HISTORY_SIZE) { historyList.add(new RadioConnectionArrow(last)); history = historyList.toArray(new RadioConnectionArrow[0]); visualizer.repaint(500); } } }; private final TimeEvent ageArrowsTimeEvent = new TimeEvent(0) { @Override public void execute(long t) { if (!active) { return; } if (historyList.size() > 0) { boolean hasOld = false; /* Increase age */ for (RadioConnectionArrow connArrow : historyList) { connArrow.increaseAge(); if(connArrow.getAge() >= connArrow.getMaxAge()) { hasOld = true; } } /* Remove too old arrows */ if (hasOld) { RadioConnectionArrow[] historyArr = historyList.toArray(new RadioConnectionArrow[0]); for (RadioConnectionArrow connArrow : historyArr) { if(connArrow.getAge() >= connArrow.getMaxAge()) { historyList.remove(connArrow); } } historyArr = historyList.toArray(new RadioConnectionArrow[0]); } visualizer.repaint(500); } /* Reschedule myself */ simulation.scheduleEvent(this, t + 100*Simulation.MILLISECOND); } }; @Override public void setActive(final Simulation simulation, Visualizer vis) { this.radioMedium = (AbstractRadioMedium) simulation.getRadioMedium(); this.simulation = simulation; this.visualizer = vis; this.active = true; simulation.invokeSimulationThread(new Runnable() { @Override public void run() { historyList.clear(); history = null; /* Start observing radio medium for transmissions */ radioMedium.addRadioMediumObserver(radioMediumObserver); /* Fade away arrows */ simulation.scheduleEvent(ageArrowsTimeEvent, simulation.getSimulationTime() + 100*Simulation.MILLISECOND); } }); } @Override public void setInactive() { this.active = false; if (simulation == null) { /* Skin was never activated */ return; } /* Stop observing radio medium */ radioMedium.deleteRadioMediumObserver(radioMediumObserver); } @Override public Color[] getColorOf(Mote mote) { return null; } private final Polygon arrowPoly = new Polygon(); private void drawArrow(Graphics g, int xSource, int ySource, int xDest, int yDest, int delta) { double dx = xSource - xDest; double dy = ySource - yDest; double dir = Math.atan2(dx, dy); double len = Math.sqrt(dx * dx + dy * dy); dx /= len; dy /= len; len -= delta; xDest = xSource - (int) (dx * len); yDest = ySource - (int) (dy * len); g.drawLine(xDest, yDest, xSource, ySource); final int size = 8; arrowPoly.reset(); arrowPoly.addPoint(xDest, yDest); arrowPoly.addPoint(xDest + xCor(size, dir + 0.5), yDest + yCor(size, dir + 0.5)); arrowPoly.addPoint(xDest + xCor(size, dir - 0.5), yDest + yCor(size, dir - 0.5)); arrowPoly.addPoint(xDest, yDest); g.fillPolygon(arrowPoly); } private int yCor(int len, double dir) { return (int)(0.5 + len * Math.cos(dir)); } private int xCor(int len, double dir) { return (int)(0.5 + len * Math.sin(dir)); } @Override public void paintBeforeMotes(Graphics g) { RadioConnectionArrow[] historyCopy = history; if (historyCopy == null) { return; } for (RadioConnectionArrow connArrow : historyCopy) { float colorHistoryIndex = (float)connArrow.getAge() / (float)connArrow.getMaxAge(); g.setColor(new Color(colorHistoryIndex, colorHistoryIndex, 1.0f)); Radio source = connArrow.getConnection().getSource(); Point sourcePoint = visualizer.transformPositionToPixel(source.getPosition()); /* If there is no destination, paint red circles to indicate untransmitted message */ if (connArrow.getConnection().getDestinations().length == 0) { g.setColor(new Color(1.0f, colorHistoryIndex, colorHistoryIndex)); g.drawOval(sourcePoint.x - 20, sourcePoint.y - 20, 40, 40); g.drawOval(sourcePoint.x - 30, sourcePoint.y - 30, 60, 60); continue; } for (Radio destRadio : connArrow.getConnection().getDestinations()) { Position destPos = destRadio.getPosition(); Point destPoint = visualizer.transformPositionToPixel(destPos); drawArrow(g, sourcePoint.x, sourcePoint.y, destPoint.x, destPoint.y, 8); } } } @Override public void paintAfterMotes(Graphics g) { } @Override public Visualizer getVisualizer() { return visualizer; } private static class RadioConnectionArrow { private final RadioConnection conn; private int age; private static final int MAX_AGE = 10; RadioConnectionArrow(RadioConnection conn) { this.conn = conn; this.age = 0; } public void increaseAge() { if (age < MAX_AGE) { age++; } } public int getAge() { return age; } public RadioConnection getConnection() { return conn; } public int getMaxAge() { return MAX_AGE; } } }
tools/cooja/java/org/contikios/cooja/plugins/skins/TrafficVisualizerSkin.java
/* * Copyright (c) 2012, Swedish Institute of Computer Science. * 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 Institute 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 INSTITUTE 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 INSTITUTE 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.contikios.cooja.plugins.skins; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.awt.Polygon; import java.util.ArrayList; import java.util.Observable; import java.util.Observer; import org.apache.log4j.Logger; import org.contikios.cooja.ClassDescription; import org.contikios.cooja.Mote; import org.contikios.cooja.RadioConnection; import org.contikios.cooja.Simulation; import org.contikios.cooja.SupportedArguments; import org.contikios.cooja.TimeEvent; import org.contikios.cooja.interfaces.Position; import org.contikios.cooja.interfaces.Radio; import org.contikios.cooja.plugins.Visualizer; import org.contikios.cooja.plugins.VisualizerSkin; import org.contikios.cooja.radiomediums.AbstractRadioMedium; /** * Radio traffic history visualizer skin. * * @see UDGMVisualizerSkin * @author Fredrik Osterlind */ @ClassDescription("Radio traffic") @SupportedArguments(radioMediums = {AbstractRadioMedium.class}) public class TrafficVisualizerSkin implements VisualizerSkin { private static final Logger logger = Logger.getLogger(TrafficVisualizerSkin.class); private final int MAX_HISTORY_SIZE = 200; private boolean active = false; private Simulation simulation = null; private Visualizer visualizer = null; private AbstractRadioMedium radioMedium = null; private ArrayList<RadioConnectionArrow> historyList = new ArrayList<RadioConnectionArrow>(); private RadioConnectionArrow[] history = null; private Observer radioMediumObserver = new Observer() { @Override public void update(Observable obs, Object obj) { RadioConnection last = radioMedium.getLastConnection(); if (last != null && historyList.size() < MAX_HISTORY_SIZE) { historyList.add(new RadioConnectionArrow(last)); history = historyList.toArray(new RadioConnectionArrow[0]); visualizer.repaint(500); } } }; private final TimeEvent ageArrowsTimeEvent = new TimeEvent(0) { @Override public void execute(long t) { if (!active) { return; } if (historyList.size() > 0) { boolean hasOld = false; /* Increase age */ for (RadioConnectionArrow connArrow : historyList) { connArrow.increaseAge(); if(connArrow.getAge() >= connArrow.getMaxAge()) { hasOld = true; } } /* Remove too old arrows */ if (hasOld) { RadioConnectionArrow[] historyArr = historyList.toArray(new RadioConnectionArrow[0]); for (RadioConnectionArrow connArrow : historyArr) { if(connArrow.getAge() >= connArrow.getMaxAge()) { historyList.remove(connArrow); } } historyArr = historyList.toArray(new RadioConnectionArrow[0]); } visualizer.repaint(500); } /* Reschedule myself */ simulation.scheduleEvent(this, t + 100*Simulation.MILLISECOND); } }; @Override public void setActive(final Simulation simulation, Visualizer vis) { this.radioMedium = (AbstractRadioMedium) simulation.getRadioMedium(); this.simulation = simulation; this.visualizer = vis; this.active = true; simulation.invokeSimulationThread(new Runnable() { @Override public void run() { historyList.clear(); history = null; /* Start observing radio medium for transmissions */ radioMedium.addRadioMediumObserver(radioMediumObserver); /* Fade away arrows */ simulation.scheduleEvent(ageArrowsTimeEvent, simulation.getSimulationTime() + 100*Simulation.MILLISECOND); } }); } @Override public void setInactive() { this.active = false; if (simulation == null) { /* Skin was never activated */ return; } /* Stop observing radio medium */ radioMedium.deleteRadioMediumObserver(radioMediumObserver); } @Override public Color[] getColorOf(Mote mote) { return null; } private final Polygon arrowPoly = new Polygon(); private void drawArrow(Graphics g, int xSource, int ySource, int xDest, int yDest, int delta) { double dx = xSource - xDest; double dy = ySource - yDest; double dir = Math.atan2(dx, dy); double len = Math.sqrt(dx * dx + dy * dy); dx /= len; dy /= len; len -= delta; xDest = xSource - (int) (dx * len); yDest = ySource - (int) (dy * len); g.drawLine(xDest, yDest, xSource, ySource); final int size = 8; arrowPoly.reset(); arrowPoly.addPoint(xDest, yDest); arrowPoly.addPoint(xDest + xCor(size, dir + 0.5), yDest + yCor(size, dir + 0.5)); arrowPoly.addPoint(xDest + xCor(size, dir - 0.5), yDest + yCor(size, dir - 0.5)); arrowPoly.addPoint(xDest, yDest); g.fillPolygon(arrowPoly); } private int yCor(int len, double dir) { return (int)(0.5 + len * Math.cos(dir)); } private int xCor(int len, double dir) { return (int)(0.5 + len * Math.sin(dir)); } @Override public void paintBeforeMotes(Graphics g) { RadioConnectionArrow[] historyCopy = history; if (historyCopy == null) { return; } for (RadioConnectionArrow connArrow : historyCopy) { float colorHistoryIndex = (float)connArrow.getAge() / (float)connArrow.getMaxAge(); g.setColor(new Color(colorHistoryIndex, colorHistoryIndex, 1.0f)); Radio source = connArrow.getConnection().getSource(); Point sourcePoint = visualizer.transformPositionToPixel(source.getPosition()); for (Radio destRadio : connArrow.getConnection().getDestinations()) { Position destPos = destRadio.getPosition(); Point destPoint = visualizer.transformPositionToPixel(destPos); drawArrow(g, sourcePoint.x, sourcePoint.y, destPoint.x, destPoint.y, 8); } } } @Override public void paintAfterMotes(Graphics g) { } @Override public Visualizer getVisualizer() { return visualizer; } private static class RadioConnectionArrow { private final RadioConnection conn; private int age; private static final int MAX_AGE = 10; RadioConnectionArrow(RadioConnection conn) { this.conn = conn; this.age = 0; } public void increaseAge() { if (age < MAX_AGE) { age++; } } public int getAge() { return age; } public RadioConnection getConnection() { return conn; } public int getMaxAge() { return MAX_AGE; } } }
[cooja] skins/TrafficVisualizerSkin: Indicate sent but unreceived messages by a red double circle around mote
tools/cooja/java/org/contikios/cooja/plugins/skins/TrafficVisualizerSkin.java
[cooja] skins/TrafficVisualizerSkin: Indicate sent but unreceived messages by a red double circle around mote
<ide><path>ools/cooja/java/org/contikios/cooja/plugins/skins/TrafficVisualizerSkin.java <ide> g.setColor(new Color(colorHistoryIndex, colorHistoryIndex, 1.0f)); <ide> Radio source = connArrow.getConnection().getSource(); <ide> Point sourcePoint = visualizer.transformPositionToPixel(source.getPosition()); <add> /* If there is no destination, paint red circles to indicate untransmitted message */ <add> if (connArrow.getConnection().getDestinations().length == 0) { <add> g.setColor(new Color(1.0f, colorHistoryIndex, colorHistoryIndex)); <add> g.drawOval(sourcePoint.x - 20, sourcePoint.y - 20, 40, 40); <add> g.drawOval(sourcePoint.x - 30, sourcePoint.y - 30, 60, 60); <add> continue; <add> } <ide> for (Radio destRadio : connArrow.getConnection().getDestinations()) { <ide> Position destPos = destRadio.getPosition(); <ide> Point destPoint = visualizer.transformPositionToPixel(destPos);
Java
mit
143cc9aecbafa45d3dd4333badf1d6005aee2c6d
0
SpongePowered/Mixin,simon816/Mixin
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered.org <http://www.spongepowered.org> * Copyright (c) contributors * * 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 org.spongepowered.asm.mixin.transformer; import java.util.ArrayList; import java.util.Collections; 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 org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.lib.tree.FieldInsnNode; import org.spongepowered.asm.lib.tree.FieldNode; import org.spongepowered.asm.lib.tree.FrameNode; import org.spongepowered.asm.lib.tree.MethodInsnNode; import org.spongepowered.asm.lib.tree.MethodNode; import org.spongepowered.asm.mixin.transformer.ClassInfo.Member.Type; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; /** * Information about a class, used as a way of keeping track of class hierarchy * information needed to support more complex mixin behaviour such as detached * superclass and mixin inheritance. */ public class ClassInfo extends TreeInfo { /** * <p>To all intents and purposes, the "real" class hierarchy and the mixin * class hierarchy exist in parallel, this means that for some hierarchy * validation operations we need to walk <em>across</em> to the other * hierarchy in order to allow meaningful validation to occur.</p> * * <p>This enum defines the type of traversal operations which are allowed * for a particular lookup.</p> * * <p>Each traversal type has a <code>next</code> property which defines * the traversal type to use on the <em>next</em> step of the hierarchy * validation. For example, the type {@link #IMMEDIATE} which requires an * immediate match falls through to {@link #NONE} on the next step, which * prevents further traversals from occurring in the lookup.</p> */ public static enum Traversal { /** * No traversals are allowed. */ NONE(null, false), /** * Traversal is allowed at all stages. */ ALL(null, true), /** * Traversal is allowed at the bottom of the hierarchy but no further. */ IMMEDIATE(Traversal.NONE, true), /** * Traversal is allowed only on superclasses and not at the bottom of * the hierarchy. */ SUPER(Traversal.ALL, false); private final Traversal next; private final boolean traverse; private Traversal(Traversal next, boolean traverse) { this.next = next != null ? next : this; this.traverse = traverse; } public Traversal next() { return this.next; } public boolean canTraverse() { return this.traverse; } } /** * Information about frames in a method */ public static class FrameData { private static final String[] FRAMETYPES = { "NEW", "FULL", "APPEND", "CHOP", "SAME", "SAME1" }; public final int index; public final int type; public final int locals; FrameData(int index, int type, int locals) { this.index = index; this.type = type; this.locals = locals; } FrameData(int index, FrameNode frameNode) { this.index = index; this.type = frameNode.type; this.locals = frameNode.local != null ? frameNode.local.size() : 0; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return String.format("FrameData[index=%d, type=%s, locals=%d]", this.index, FrameData.FRAMETYPES[this.type + 1], this.locals); } } /** * Information about a member in this class */ abstract static class Member { static enum Type { METHOD, FIELD } /** * Member type */ private final Type type; /** * The original name of the member */ private final String memberName; /** * The member's signature */ private final String memberDesc; /** * True if this member was injected by a mixin, false if it was * originally part of the class */ private final boolean isInjected; /** * Access modifiers */ private final int modifiers; /** * Current name of the member, may be different from {@link #memberName} * if the member has been renamed */ private String currentName; protected Member(Member member) { this(member.type, member.memberName, member.memberDesc, member.modifiers, member.isInjected); this.currentName = member.currentName; } protected Member(Type type, String name, String desc, int access) { this(type, name, desc, access, false); } protected Member(Type type, String name, String desc, int access, boolean injected) { this.type = type; this.memberName = name; this.memberDesc = desc; this.isInjected = injected; this.currentName = name; this.modifiers = access; } public String getOriginalName() { return this.memberName; } public String getName() { return this.currentName; } public String getDesc() { return this.memberDesc; } public boolean isInjected() { return this.isInjected; } public boolean isRenamed() { return this.currentName != this.memberName; } public boolean isPrivate() { return (this.modifiers & Opcodes.ACC_PRIVATE) != 0; } // Abstract because this has to be static in order to contain the enum public abstract ClassInfo getOwner(); public int getAccess() { return this.modifiers; } public void renameTo(String name) { this.currentName = name; } public boolean equals(String name, String desc) { return (this.memberName.equals(name) || this.currentName.equals(name)) && this.memberDesc.equals(desc); } @Override public boolean equals(Object obj) { if (!(obj instanceof Member)) { return false; } Member other = (Member)obj; return (other.memberName.equals(this.memberName) || other.currentName.equals(this.currentName)) && other.memberDesc.equals(this.memberDesc); } @Override public int hashCode() { return this.toString().hashCode(); } @Override public String toString() { return this.memberName + this.memberDesc; } } /** * A method */ public class Method extends Member { private final List<FrameData> frames; public Method(Member member) { super(member); this.frames = member instanceof Method ? ((Method)member).frames : null; } public Method(MethodNode method) { this(method, false); } public Method(MethodNode method, boolean injected) { super(Type.METHOD, method.name, method.desc, method.access, injected); this.frames = this.gatherFrames(method); } public Method(String name, String desc) { super(Type.METHOD, name, desc, Opcodes.ACC_PUBLIC, false); this.frames = null; } public Method(String name, String desc, int access) { super(Type.METHOD, name, desc, access, false); this.frames = null; } public Method(String name, String desc, int access, boolean injected) { super(Type.METHOD, name, desc, access, injected); this.frames = null; } private List<FrameData> gatherFrames(MethodNode method) { List<FrameData> frames = new ArrayList<FrameData>(); for (Iterator<AbstractInsnNode> iter = method.instructions.iterator(); iter.hasNext();) { AbstractInsnNode insn = iter.next(); if (insn instanceof FrameNode) { frames.add(new FrameData(method.instructions.indexOf(insn), (FrameNode)insn)); } } return frames; } public List<FrameData> getFrames() { return this.frames; } @Override public ClassInfo getOwner() { return ClassInfo.this; } @Override public boolean equals(Object obj) { if (!(obj instanceof Method)) { return false; } return super.equals(obj); } } /** * A field */ class Field extends Member { public Field(Member member) { super(member); } public Field(FieldNode field) { this(field, false); } public Field(FieldNode field, boolean injected) { super(Type.FIELD, field.name, field.desc, field.access, injected); } public Field(String name, String desc, int access) { super(Type.FIELD, name, desc, access, false); } public Field(String name, String desc, int access, boolean injected) { super(Type.FIELD, name, desc, access, injected); } @Override public ClassInfo getOwner() { return ClassInfo.this; } @Override public boolean equals(Object obj) { if (!(obj instanceof Field)) { return false; } return super.equals(obj); } } private static final Logger logger = LogManager.getLogger("mixin"); private static final String JAVA_LANG_OBJECT = "java/lang/Object"; /** * Loading and parsing classes is expensive, so keep a cache of all the * information we generate */ private static final Map<String, ClassInfo> cache = new HashMap<String, ClassInfo>(); private static final ClassInfo OBJECT = new ClassInfo(); static { ClassInfo.cache.put(ClassInfo.JAVA_LANG_OBJECT, ClassInfo.OBJECT); } /** * Class name (binary name) */ private final String name; /** * Class superclass name (binary name) */ private final String superName; /** * Outer class name */ private final String outerName; /** * True either if this is not an inner class or if it is an inner class but * does not contain a reference to its outer class. */ private final boolean isProbablyStatic; /** * Interfaces */ private final Set<String> interfaces; /** * Public and protected methods (instance) methods in this class */ private final Set<Method> methods; /** * Public and protected fields in this class */ private final Set<Field> fields; /** * Mixins which target this class */ private final Set<MixinInfo> mixins = new HashSet<MixinInfo>(); /** * Map of mixin types to corresponding supertypes, to avoid repeated * lookups */ private final Map<ClassInfo, ClassInfo> correspondingTypes = new HashMap<ClassInfo, ClassInfo>(); /** * Mixin info if this class is a mixin itself */ private final MixinInfo mixin; /** * True if this is a mixin rather than a class */ private final boolean isMixin; /** * True if this is an interface */ private final boolean isInterface; /** * Access flags */ private final int access; /** * Superclass reference, not initialised until required */ private ClassInfo superClass; /** * Outer class reference, not initialised until required */ private ClassInfo outerClass; /** * Private constructor used to initialise the ClassInfo for {@link Object} */ private ClassInfo() { this.name = ClassInfo.JAVA_LANG_OBJECT; this.superName = null; this.outerName = null; this.isProbablyStatic = true; this.methods = ImmutableSet.<Method>of( new Method("getClass", "()Ljava/lang/Class;"), new Method("hashCode", "()I"), new Method("equals", "(Ljava/lang/Object;)Z"), new Method("clone", "()Ljava/lang/Object;"), new Method("toString", "()Ljava/lang/String;"), new Method("notify", "()V"), new Method("notifyAll", "()V"), new Method("wait", "(J)V"), new Method("wait", "(JI)V"), new Method("wait", "()V"), new Method("finalize", "()V") ); this.fields = Collections.<Field>emptySet(); this.isInterface = false; this.interfaces = Collections.<String>emptySet(); this.access = Opcodes.ACC_PUBLIC; this.isMixin = false; this.mixin = null; } /** * Initialise a ClassInfo from the supplied {@link ClassNode} * * @param classNode Class node to inspect */ private ClassInfo(ClassNode classNode) { this.name = classNode.name; this.superName = classNode.superName != null ? classNode.superName : ClassInfo.JAVA_LANG_OBJECT; this.methods = new HashSet<Method>(); this.fields = new HashSet<Field>(); this.isInterface = ((classNode.access & Opcodes.ACC_INTERFACE) != 0); this.interfaces = new HashSet<String>(); this.access = classNode.access; this.isMixin = classNode instanceof MixinClassNode; this.mixin = this.isMixin ? ((MixinClassNode)classNode).getMixin() : null; this.interfaces.addAll(classNode.interfaces); for (MethodNode method : classNode.methods) { this.addMethod(method, this.isMixin); } boolean isProbablyStatic = true; String outerName = classNode.outerClass; if (outerName == null) { for (FieldNode field : classNode.fields) { if ((field.access & Opcodes.ACC_SYNTHETIC) != 0) { if (field.name.startsWith("this$")) { isProbablyStatic = false; outerName = field.desc; if (outerName.startsWith("L")) { outerName = outerName.substring(1, outerName.length() - 1); } } } if ((field.access & Opcodes.ACC_STATIC) == 0) { this.fields.add(new Field(field, this.isMixin)); } } } this.isProbablyStatic = isProbablyStatic; this.outerName = outerName; } void addInterface(String iface) { this.interfaces.add(iface); } void addMethod(MethodNode method) { this.addMethod(method, true); } private void addMethod(MethodNode method, boolean injected) { if (!method.name.startsWith("<") && (method.access & Opcodes.ACC_STATIC) == 0) { this.methods.add(new Method(method, injected)); } } /** * Add a mixin which targets this class */ void addMixin(MixinInfo mixin) { if (this.isMixin) { throw new IllegalArgumentException("Cannot add target " + this.name + " for " + mixin.getClassName() + " because the target is a mixin"); } this.mixins.add(mixin); } /** * Get all mixins which target this class */ public Set<MixinInfo> getMixins() { return Collections.<MixinInfo>unmodifiableSet(this.mixins); } /** * Get whether this class is a mixin */ public boolean isMixin() { return this.isMixin; } /** * Get whether this class has ACC_PUBLIC */ public boolean isPublic() { return (this.access & Opcodes.ACC_PUBLIC) != 0; } /** * Get whether this class has ACC_ABSTRACT */ public boolean isAbstract() { return (this.access & Opcodes.ACC_ABSTRACT) != 0; } /** * Get whether this class has ACC_SYNTHETIC */ public boolean isSynthetic() { return (this.access & Opcodes.ACC_SYNTHETIC) != 0; } /** * Get whether this class is probably static (or is not an inner class) */ public boolean isProbablyStatic() { return this.isProbablyStatic; } /** * Get whether this class is an inner class */ public boolean isInner() { return this.outerName != null; } /** * Get whether this is an interface or not */ public boolean isInterface() { return this.isInterface; } /** * Returns the answer to life, the universe and everything */ public Set<String> getInterfaces() { return Collections.<String>unmodifiableSet(this.interfaces); } @Override public String toString() { return this.name; } public int getAccess() { return this.access; } /** * Get the class name (binary name) */ public String getName() { return this.name; } /** * Get the superclass name (binary name) */ public String getSuperName() { return this.superName; } /** * Get the superclass info, can return null if the superclass cannot be * resolved */ public ClassInfo getSuperClass() { if (this.superClass == null && this.superName != null) { this.superClass = ClassInfo.forName(this.superName); } return this.superClass; } /** * Get the name of the outer class, or null if this is not an inner class */ public String getOuterName() { return this.outerName; } /** * Get the outer class info, can return null if the outer class cannot be * resolved or if this is not an inner class */ public ClassInfo getOuterClass() { if (this.outerClass == null && this.outerName != null) { this.outerClass = ClassInfo.forName(this.outerName); } return this.outerClass; } /** * Class targets */ List<ClassInfo> getTargets() { if (this.mixin != null) { List<ClassInfo> targets = new ArrayList<ClassInfo>(); targets.add(this); targets.addAll(this.mixin.getTargets()); return targets; } return ImmutableList.<ClassInfo>of(this); } /** * Get class/interface methods * * @return read-only view of class methods */ public Set<Method> getMethods() { return Collections.<Method>unmodifiableSet(this.methods); } /** * If this is an interface, returns a set containing all methods in this * interface and all super interfaces. If this is a class, returns a set * containing all methods for all interfaces implemented by this class and * all super interfaces of those interfaces. * * @return read-only view of class methods */ public Set<Method> getInterfaceMethods() { Set<Method> methods = new HashSet<Method>(); ClassInfo superClass = this.addMethodsRecursive(methods); if (!this.isInterface) { while (superClass != null && superClass != ClassInfo.OBJECT) { superClass = superClass.addMethodsRecursive(methods); } } return Collections.<Method>unmodifiableSet(methods); } /** * Recursive function used by {@link #getInterfaceMethods} to add all * interface methods to the supplied set * * @param methods Method set to add to * @return superclass reference, used to make the code above more fluent */ private ClassInfo addMethodsRecursive(Set<Method> methods) { if (this.isInterface) { methods.addAll(this.methods); } else if (!this.isMixin) { for (MixinInfo mixin : this.mixins) { mixin.getClassInfo().addMethodsRecursive(methods); } } for (String iface : this.interfaces) { ClassInfo.forName(iface).addMethodsRecursive(methods); } return this.getSuperClass(); } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Name of the superclass to search for in the hierarchy * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(String superClass) { return this.hasSuperClass(superClass, Traversal.NONE); } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Name of the superclass to search for in the hierarchy * @param traversal Traversal type to allow during this lookup * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(String superClass, Traversal traversal) { if (ClassInfo.JAVA_LANG_OBJECT.equals(superClass)) { return true; } return this.findSuperClass(superClass, traversal) != null; } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Superclass to search for in the hierarchy * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(ClassInfo superClass) { return this.hasSuperClass(superClass, Traversal.NONE); } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Superclass to search for in the hierarchy * @param traversal Traversal type to allow during this lookup * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(ClassInfo superClass, Traversal traversal) { if (ClassInfo.OBJECT == superClass) { return true; } return this.findSuperClass(superClass.name, traversal) != null; } /** * Search for the specified superclass in this class's hierarchy. If found * returns the ClassInfo, otherwise returns null * * @param superClass Superclass name to search for * @return Matched superclass or null if not found */ public ClassInfo findSuperClass(String superClass) { return this.findSuperClass(superClass, Traversal.NONE); } /** * Search for the specified superclass in this class's hierarchy. If found * returns the ClassInfo, otherwise returns null * * @param superClass Superclass name to search for * @param traversal Traversal type to allow during this lookup * @return Matched superclass or null if not found */ public ClassInfo findSuperClass(String superClass, Traversal traversal) { ClassInfo superClassInfo = this.getSuperClass(); if (superClassInfo != null) { List<ClassInfo> targets = superClassInfo.getTargets(); for (ClassInfo superTarget : targets) { if (superClass.equals(superTarget.getName())) { return superClassInfo; } ClassInfo found = superTarget.findSuperClass(superClass, traversal.next()); if (found != null) { return found; } } } if (traversal.canTraverse()) { for (MixinInfo mixin : this.mixins) { ClassInfo targetSuper = mixin.getClassInfo().findSuperClass(superClass, traversal); if (targetSuper != null) { return targetSuper; } } } return null; } /** * Walks up this class's hierarchy to find the first class targetted by the * specified mixin. This is used during mixin application to translate a * mixin reference to a "real class" reference <em>in the context of <b>this * </b> class</em>. * * @param mixin Mixin class to search for * @return corresponding (target) class for the specified mixin or null if * no corresponding mixin was found */ ClassInfo findCorrespondingType(ClassInfo mixin) { if (mixin == null || !mixin.isMixin || this.isMixin) { return null; } ClassInfo correspondingType = this.correspondingTypes.get(mixin); if (correspondingType == null) { correspondingType = this.findSuperTypeForMixin(mixin); this.correspondingTypes.put(mixin, correspondingType); } return correspondingType; } /* (non-Javadoc) * Only used by findCorrespondingType(), used as a convenience so that * sanity checks and caching can be handled more elegantly */ private ClassInfo findSuperTypeForMixin(ClassInfo mixin) { ClassInfo superClass = this; while (superClass != null && superClass != ClassInfo.OBJECT) { for (MixinInfo minion : superClass.mixins) { if (minion.getClassInfo().equals(mixin)) { return superClass; } } superClass = superClass.getSuperClass(); } return null; } /** * Find out whether this (mixin) class has another mixin in its superclass * hierarchy. This method always returns false for non-mixin classes. * * @return true if and only if one or more mixins are found in the hierarchy * of this mixin */ public boolean hasMixinInHierarchy() { if (!this.isMixin) { return false; } ClassInfo superClass = this.getSuperClass(); while (superClass != null && superClass != ClassInfo.OBJECT) { if (superClass.isMixin) { return true; } superClass = superClass.getSuperClass(); } return false; } /** * Find out whether this (non-mixin) class has a mixin targetting * <em>any</em> of its superclasses. This method always returns false for * mixin classes. * * @return true if and only if one or more classes in this class's hierarchy * are targetted by a mixin */ public boolean hasMixinTargetInHierarchy() { if (this.isMixin) { return false; } ClassInfo superClass = this.getSuperClass(); while (superClass != null && superClass != ClassInfo.OBJECT) { if (superClass.mixins.size() > 0) { return true; } superClass = superClass.getSuperClass(); } return false; } /** * Finds the specified private or protected method in this class's hierarchy * * @param method Method to search for * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(MethodNode method, boolean includeThisClass) { return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE); } /** * Finds the specified private or protected method in this class's hierarchy * * @param method Method to search for * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses * @param includePrivate Include private members in the search * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(MethodNode method, boolean includeThisClass, boolean includePrivate) { return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE, includePrivate); } /** * Finds the specified public or protected method in this class's hierarchy * * @param method Method to search for * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(MethodInsnNode method, boolean includeThisClass) { return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE); } /** * Finds the specified public or protected method in this class's hierarchy * * @param method Method to search for * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses * @param includePrivate Include private members in the search * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(MethodInsnNode method, boolean includeThisClass, boolean includePrivate) { return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE, includePrivate); } /** * Finds the specified public or protected method in this class's hierarchy * * @param name Method name to search for * @param desc Method descriptor * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass) { return this.findMethodInHierarchy(name, desc, includeThisClass, Traversal.NONE); } /** * Finds the specified public or protected method in this class's hierarchy * * @param name Method name to search for * @param desc Method descriptor * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses * @param traversal Traversal type to allow during this lookup * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal) { return this.findMethodInHierarchy(name, desc, includeThisClass, traversal, false); } /** * Finds the specified public or protected method in this class's hierarchy * * @param name Method name to search for * @param desc Method descriptor * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses * @param traversal Traversal type to allow during this lookup * @param includePrivate Include private members in the search * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, boolean includePrivate) { return this.findInHierarchy(name, desc, includeThisClass, traversal, includePrivate, Type.METHOD); } /** * Finds the specified private or protected field in this class's hierarchy * * @param field Field to search for * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(FieldNode field, boolean includeThisClass) { return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE); } /** * Finds the specified private or protected field in this class's hierarchy * * @param field Field to search for * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @param includePrivate Include private members in the search * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(FieldNode field, boolean includeThisClass, boolean includePrivate) { return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE, includePrivate); } /** * Finds the specified public or protected field in this class's hierarchy * * @param field Field to search for * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(FieldInsnNode field, boolean includeThisClass) { return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE); } /** * Finds the specified public or protected field in this class's hierarchy * * @param field Field to search for * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @param includePrivate Include private members in the search * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(FieldInsnNode field, boolean includeThisClass, boolean includePrivate) { return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE, includePrivate); } /** * Finds the specified public or protected field in this class's hierarchy * * @param name Field name to search for * @param desc Field descriptor * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass) { return this.findFieldInHierarchy(name, desc, includeThisClass, Traversal.NONE); } /** * Finds the specified public or protected field in this class's hierarchy * * @param name Field name to search for * @param desc Field descriptor * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @param traversal Traversal type to allow during this lookup * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal) { return this.findFieldInHierarchy(name, desc, includeThisClass, traversal, false); } /** * Finds the specified public or protected field in this class's hierarchy * * @param name Field name to search for * @param desc Field descriptor * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @param traversal Traversal type to allow during this lookup * @param includePrivate Include private members in the search * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, boolean includePrivate) { return this.findInHierarchy(name, desc, includeThisClass, traversal, includePrivate, Type.FIELD); } /** * Finds a public or protected member in the hierarchy of this class which * matches the supplied details * * @param name Member name to search * @param desc Member descriptor * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @param traversal Traversal type to allow during this lookup * @param priv Include private members in the search * @param type Type of member to search for (field or method) * @return the discovered member or null if the member could not be resolved */ private <M extends Member> M findInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, boolean priv, Type type) { if (includeThisClass) { M member = this.findMember(name, desc, priv, type); if (member != null) { return member; } if (traversal.canTraverse()) { for (MixinInfo mixin : this.mixins) { M mixinMember = mixin.getClassInfo().findMember(name, desc, priv, type); if (mixinMember != null) { return this.cloneMember(mixinMember); } } } } ClassInfo superClassInfo = this.getSuperClass(); if (superClassInfo != null) { for (ClassInfo superTarget : superClassInfo.getTargets()) { // Do not search for private members in superclasses, pass priv as false M member = superTarget.findInHierarchy(name, desc, true, traversal.next(), false, type); if (member != null) { return member; } } } return null; } /** * Effectively a clone method for member, placed here so that the enclosing * instance for the inner class is this class and not the enclosing instance * of the existing class. Basically creates a cloned member with this * ClassInfo as its parent. * * @param member * @return */ @SuppressWarnings("unchecked") private <M extends Member> M cloneMember(M member) { if (member instanceof Method) { return (M)new Method(member); } return (M)new Field(member); } /** * Finds the specified public or protected method in this class * * @param method Method to search for * @return the method object or null if the method could not be resolved */ public Method findMethod(MethodNode method) { return this.findMethod(method.name, method.desc, false); } /** * Finds the specified public or protected method in this class * * @param method Method to search for * @param includePrivate also search private fields * @return the method object or null if the method could not be resolved */ public Method findMethod(MethodNode method, boolean includePrivate) { return this.findMethod(method.name, method.desc, includePrivate); } /** * Finds the specified public or protected method in this class * * @param method Method to search for * @return the method object or null if the method could not be resolved */ public Method findMethod(MethodInsnNode method) { return this.findMethod(method.name, method.desc, false); } /** * Finds the specified public or protected method in this class * * @param method Method to search for * @param includePrivate also search private fields * @return the method object or null if the method could not be resolved */ public Method findMethod(MethodInsnNode method, boolean includePrivate) { return this.findMethod(method.name, method.desc, includePrivate); } /** * Finds the specified public or protected method in this class * * @param name Method name to search for * @param desc Method signature to search for * @param includePrivate also search private fields * @return the method object or null if the method could not be resolved */ public Method findMethod(String name, String desc, boolean includePrivate) { return this.findMember(name, desc, includePrivate, Type.METHOD); } /** * Finds the specified field in this class * * @param field Field to search for * @return the field object or null if the field could not be resolved */ public Field findField(FieldNode field) { return this.findField(field.name, field.desc, (field.access & Opcodes.ACC_PRIVATE) != 0); } /** * Finds the specified public or protected method in this class * * @param field Field to search for * @param includePrivate also search private fields * @return the field object or null if the field could not be resolved */ public Field findField(FieldInsnNode field, boolean includePrivate) { return this.findField(field.name, field.desc, includePrivate); } /** * Finds the specified field in this class * * @param name Field name to search for * @param desc Field signature to search for * @param includePrivate also search private fields * @return the field object or null if the field could not be resolved */ public Field findField(String name, String desc, boolean includePrivate) { return this.findMember(name, desc, includePrivate, Type.FIELD); } /** * Finds the specified member in this class * * @param name Field name to search for * @param desc Field signature to search for * @param includePrivate also search private fields * @param memberType Type of member list to search * @return the field object or null if the field could not be resolved */ private <M extends Member> M findMember(String name, String desc, boolean includePrivate, Type memberType) { @SuppressWarnings("unchecked") Set<M> members = (Set<M>)(memberType == Type.METHOD ? this.methods : this.fields); for (M member : members) { if (member.equals(name, desc) && (includePrivate || !member.isPrivate())) { return member; } } return null; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object other) { if (!(other instanceof ClassInfo)) { return false; } return ((ClassInfo)other).name.equals(this.name); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return this.name.hashCode(); } /** * Return a ClassInfo for the supplied {@link ClassNode}. If a ClassInfo for * the class was already defined, then the original ClassInfo is returned * from the internal cache. Otherwise a new ClassInfo is created and * returned. * * @param classNode * @return */ static ClassInfo fromClassNode(ClassNode classNode) { ClassInfo info = ClassInfo.cache.get(classNode.name); if (info == null) { info = new ClassInfo(classNode); ClassInfo.cache.put(classNode.name, info); } return info; } /** * Return a ClassInfo for the specified class name, fetches the ClassInfo * from the cache where possible * * @param className Binary name of the class to look up * @return ClassInfo for the specified class name or null if the specified * name cannot be resolved for some reason */ public static ClassInfo forName(String className) { className = className.replace('.', '/'); ClassInfo info = ClassInfo.cache.get(className); if (info == null) { try { ClassNode classNode = TreeInfo.getClassNode(className); info = new ClassInfo(classNode); } catch (Exception ex) { ex.printStackTrace(); } // Put null in the cache if load failed ClassInfo.cache.put(className, info); ClassInfo.logger.trace("Added class metadata for {} to metadata cache", className); } return info; } }
src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered.org <http://www.spongepowered.org> * Copyright (c) contributors * * 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 org.spongepowered.asm.mixin.transformer; import java.util.ArrayList; import java.util.Collections; 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 org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.lib.tree.FieldInsnNode; import org.spongepowered.asm.lib.tree.FieldNode; import org.spongepowered.asm.lib.tree.FrameNode; import org.spongepowered.asm.lib.tree.MethodInsnNode; import org.spongepowered.asm.lib.tree.MethodNode; import org.spongepowered.asm.mixin.transformer.ClassInfo.Member.Type; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; /** * Information about a class, used as a way of keeping track of class hierarchy * information needed to support more complex mixin behaviour such as detached * superclass and mixin inheritance. */ public class ClassInfo extends TreeInfo { /** * <p>To all intents and purposes, the "real" class hierarchy and the mixin * class hierarchy exist in parallel, this means that for some hierarchy * validation operations we need to walk <em>across</em> to the other * hierarchy in order to allow meaningful validation to occur.</p> * * <p>This enum defines the type of traversal operations which are allowed * for a particular lookup.</p> * * <p>Each traversal type has a <code>next</code> property which defines * the traversal type to use on the <em>next</em> step of the hierarchy * validation. For example, the type {@link #IMMEDIATE} which requires an * immediate match falls through to {@link #NONE} on the next step, which * prevents further traversals from occurring in the lookup.</p> */ public static enum Traversal { /** * No traversals are allowed. */ NONE(null, false), /** * Traversal is allowed at all stages. */ ALL(null, true), /** * Traversal is allowed at the bottom of the hierarchy but no further. */ IMMEDIATE(Traversal.NONE, true), /** * Traversal is allowed only on superclasses and not at the bottom of * the hierarchy. */ SUPER(Traversal.ALL, false); private final Traversal next; private final boolean traverse; private Traversal(Traversal next, boolean traverse) { this.next = next != null ? next : this; this.traverse = traverse; } public Traversal next() { return this.next; } public boolean canTraverse() { return this.traverse; } } /** * Information about frames in a method */ public static class FrameData { private static final String[] FRAMETYPES = { "NEW", "FULL", "APPEND", "CHOP", "SAME", "SAME1" }; public final int index; public final int type; public final int locals; FrameData(int index, int type, int locals) { this.index = index; this.type = type; this.locals = locals; } FrameData(int index, FrameNode frameNode) { this.index = index; this.type = frameNode.type; this.locals = frameNode.local != null ? frameNode.local.size() : 0; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return String.format("FrameData[index=%d, type=%s, locals=%d]", this.index, FrameData.FRAMETYPES[this.type + 1], this.locals); } } /** * Information about a member in this class */ abstract static class Member { static enum Type { METHOD, FIELD } /** * Member type */ private final Type type; /** * The original name of the member */ private final String memberName; /** * The member's signature */ private final String memberDesc; /** * True if this member was injected by a mixin, false if it was * originally part of the class */ private final boolean isInjected; /** * Access modifiers */ private final int modifiers; /** * Current name of the member, may be different from {@link #memberName} * if the member has been renamed */ private String currentName; protected Member(Member member) { this(member.type, member.memberName, member.memberDesc, member.modifiers, member.isInjected); this.currentName = member.currentName; } protected Member(Type type, String name, String desc, int access) { this(type, name, desc, access, false); } protected Member(Type type, String name, String desc, int access, boolean injected) { this.type = type; this.memberName = name; this.memberDesc = desc; this.isInjected = injected; this.currentName = name; this.modifiers = access; } public String getOriginalName() { return this.memberName; } public String getName() { return this.currentName; } public String getDesc() { return this.memberDesc; } public boolean isInjected() { return this.isInjected; } public boolean isRenamed() { return this.currentName != this.memberName; } public boolean isPrivate() { return (this.modifiers & Opcodes.ACC_PRIVATE) != 0; } // Abstract because this has to be static in order to contain the enum public abstract ClassInfo getOwner(); public int getAccess() { return this.modifiers; } public void renameTo(String name) { this.currentName = name; } public boolean equals(String name, String desc) { return (this.memberName.equals(name) || this.currentName.equals(name)) && this.memberDesc.equals(desc); } @Override public boolean equals(Object obj) { if (!(obj instanceof Member)) { return false; } Member other = (Member)obj; return (other.memberName.equals(this.memberName) || other.currentName.equals(this.currentName)) && other.memberDesc.equals(this.memberDesc); } @Override public int hashCode() { return this.toString().hashCode(); } @Override public String toString() { return this.memberName + this.memberDesc; } } /** * A method */ public class Method extends Member { private final List<FrameData> frames; public Method(Member member) { super(member); this.frames = member instanceof Method ? ((Method)member).frames : null; } public Method(MethodNode method) { this(method, false); } public Method(MethodNode method, boolean injected) { super(Type.METHOD, method.name, method.desc, method.access, injected); this.frames = this.gatherFrames(method); } public Method(String name, String desc) { super(Type.METHOD, name, desc, Opcodes.ACC_PUBLIC, false); this.frames = null; } public Method(String name, String desc, int access) { super(Type.METHOD, name, desc, access, false); this.frames = null; } public Method(String name, String desc, int access, boolean injected) { super(Type.METHOD, name, desc, access, injected); this.frames = null; } private List<FrameData> gatherFrames(MethodNode method) { List<FrameData> frames = new ArrayList<FrameData>(); for (Iterator<AbstractInsnNode> iter = method.instructions.iterator(); iter.hasNext();) { AbstractInsnNode insn = iter.next(); if (insn instanceof FrameNode) { frames.add(new FrameData(method.instructions.indexOf(insn), (FrameNode)insn)); } } return frames; } public List<FrameData> getFrames() { return this.frames; } @Override public ClassInfo getOwner() { return ClassInfo.this; } @Override public boolean equals(Object obj) { if (!(obj instanceof Method)) { return false; } return super.equals(obj); } } /** * A field */ class Field extends Member { public Field(Member member) { super(member); } public Field(FieldNode field) { this(field, false); } public Field(FieldNode field, boolean injected) { super(Type.FIELD, field.name, field.desc, field.access, injected); } public Field(String name, String desc, int access) { super(Type.FIELD, name, desc, access, false); } public Field(String name, String desc, int access, boolean injected) { super(Type.FIELD, name, desc, access, injected); } @Override public ClassInfo getOwner() { return ClassInfo.this; } @Override public boolean equals(Object obj) { if (!(obj instanceof Field)) { return false; } return super.equals(obj); } } private static final Logger logger = LogManager.getLogger("mixin"); private static final String JAVA_LANG_OBJECT = "java/lang/Object"; /** * Loading and parsing classes is expensive, so keep a cache of all the * information we generate */ private static final Map<String, ClassInfo> cache = new HashMap<String, ClassInfo>(); private static final ClassInfo OBJECT = new ClassInfo(); static { ClassInfo.cache.put(ClassInfo.JAVA_LANG_OBJECT, ClassInfo.OBJECT); } /** * Class name (binary name) */ private final String name; /** * Class superclass name (binary name) */ private final String superName; /** * Outer class name */ private final String outerName; /** * True either if this is not an inner class or if it is an inner class but * does not contain a reference to its outer class. */ private final boolean isProbablyStatic; /** * Interfaces */ private final Set<String> interfaces; /** * Public and protected methods (instance) methods in this class */ private final Set<Method> methods; /** * Public and protected fields in this class */ private final Set<Field> fields; /** * Mixins which target this class */ private final Set<MixinInfo> mixins = new HashSet<MixinInfo>(); /** * Map of mixin types to corresponding supertypes, to avoid repeated * lookups */ private final Map<ClassInfo, ClassInfo> correspondingTypes = new HashMap<ClassInfo, ClassInfo>(); /** * Mixin info if this class is a mixin itself */ private final MixinInfo mixin; /** * True if this is a mixin rather than a class */ private final boolean isMixin; /** * True if this is an interface */ private final boolean isInterface; /** * Access flags */ private final int access; /** * Superclass reference, not initialised until required */ private ClassInfo superClass; /** * Outer class reference, not initialised until required */ private ClassInfo outerClass; /** * Private constructor used to initialise the ClassInfo for {@link Object} */ private ClassInfo() { this.name = ClassInfo.JAVA_LANG_OBJECT; this.superName = null; this.outerName = null; this.isProbablyStatic = true; this.methods = ImmutableSet.<Method>of( new Method("getClass", "()Ljava/lang/Class;"), new Method("hashCode", "()I"), new Method("equals", "(Ljava/lang/Object;)Z"), new Method("clone", "()Ljava/lang/Object;"), new Method("toString", "()Ljava/lang/String;"), new Method("notify", "()V"), new Method("notifyAll", "()V"), new Method("wait", "(J)V"), new Method("wait", "(JI)V"), new Method("wait", "()V"), new Method("finalize", "()V") ); this.fields = Collections.<Field>emptySet(); this.isInterface = false; this.interfaces = Collections.<String>emptySet(); this.access = Opcodes.ACC_PUBLIC; this.isMixin = false; this.mixin = null; } /** * Initialise a ClassInfo from the supplied {@link ClassNode} * * @param classNode Class node to inspect */ private ClassInfo(ClassNode classNode) { this.name = classNode.name; this.superName = classNode.superName != null ? classNode.superName : ClassInfo.JAVA_LANG_OBJECT; this.methods = new HashSet<Method>(); this.fields = new HashSet<Field>(); this.isInterface = ((classNode.access & Opcodes.ACC_INTERFACE) != 0); this.interfaces = new HashSet<String>(); this.access = classNode.access; this.isMixin = classNode instanceof MixinClassNode; this.mixin = this.isMixin ? ((MixinClassNode)classNode).getMixin() : null; this.interfaces.addAll(classNode.interfaces); for (MethodNode method : classNode.methods) { this.addMethod(method, this.isMixin); } boolean isProbablyStatic = true; String outerName = classNode.outerClass; if (outerName == null) { for (FieldNode field : classNode.fields) { if ((field.access & Opcodes.ACC_SYNTHETIC) != 0) { if (field.name.startsWith("this$")) { isProbablyStatic = false; outerName = field.desc; if (outerName.startsWith("L")) { outerName = outerName.substring(1, outerName.length() - 1); } } } if ((field.access & Opcodes.ACC_STATIC) == 0) { this.fields.add(new Field(field, this.isMixin)); } } } this.isProbablyStatic = isProbablyStatic; this.outerName = outerName; } void addInterface(String iface) { this.interfaces.add(iface); } void addMethod(MethodNode method) { this.addMethod(method, true); } private void addMethod(MethodNode method, boolean injected) { if (!method.name.startsWith("<") && (method.access & Opcodes.ACC_STATIC) == 0) { this.methods.add(new Method(method, injected)); } } /** * Add a mixin which targets this class */ void addMixin(MixinInfo mixin) { if (this.isMixin) { throw new IllegalArgumentException("Cannot add target " + this.name + " for " + mixin.getClassName() + " because the target is a mixin"); } this.mixins.add(mixin); } /** * Get all mixins which target this class */ public Set<MixinInfo> getMixins() { return Collections.<MixinInfo>unmodifiableSet(this.mixins); } /** * Get whether this class is a mixin */ public boolean isMixin() { return this.isMixin; } /** * Get whether this class has ACC_PUBLIC */ public boolean isPublic() { return (this.access & Opcodes.ACC_PUBLIC) != 0; } /** * Get whether this class has ACC_ABSTRACT */ public boolean isAbstract() { return (this.access & Opcodes.ACC_ABSTRACT) != 0; } /** * Get whether this class has ACC_SYNTHETIC */ public boolean isSynthetic() { return (this.access & Opcodes.ACC_SYNTHETIC) != 0; } /** * Get whether this class is probably static (or is not an inner class) */ public boolean isProbablyStatic() { return this.isProbablyStatic; } /** * Get whether this class is an inner class */ public boolean isInner() { return this.outerName != null; } /** * Get whether this is an interface or not */ public boolean isInterface() { return this.isInterface; } /** * Returns the answer to life, the universe and everything */ public Set<String> getInterfaces() { return Collections.<String>unmodifiableSet(this.interfaces); } @Override public String toString() { return this.name; } public int getAccess() { return this.access; } /** * Get the class name (binary name) */ public String getName() { return this.name; } /** * Get the superclass name (binary name) */ public String getSuperName() { return this.superName; } /** * Get the superclass info, can return null if the superclass cannot be * resolved */ public ClassInfo getSuperClass() { if (this.superClass == null && this.superName != null) { this.superClass = ClassInfo.forName(this.superName); } return this.superClass; } /** * Get the name of the outer class, or null if this is not an inner class */ public String getOuterName() { return this.outerName; } /** * Get the outer class info, can return null if the outer class cannot be * resolved or if this is not an inner class */ public ClassInfo getOuterClass() { if (this.outerClass == null && this.outerName != null) { this.outerClass = ClassInfo.forName(this.outerName); } return this.outerClass; } /** * Class targets */ List<ClassInfo> getTargets() { if (this.mixin != null) { List<ClassInfo> targets = new ArrayList<ClassInfo>(); targets.add(this); targets.addAll(this.mixin.getTargets()); return targets; } return ImmutableList.<ClassInfo>of(this); } /** * Get class/interface methods * * @return read-only view of class methods */ public Set<Method> getMethods() { return Collections.<Method>unmodifiableSet(this.methods); } /** * If this is an interface, returns a set containing all methods in this * interface and all super interfaces. If this is a class, returns a set * containing all methods for all interfaces implemented by this class and * all super interfaces of those interfaces. * * @return read-only view of class methods */ public Set<Method> getInterfaceMethods() { Set<Method> methods = new HashSet<Method>(); ClassInfo superClass = this.addMethodsRecursive(methods); if (!this.isInterface) { while (superClass != null && superClass != ClassInfo.OBJECT) { superClass = superClass.addMethodsRecursive(methods); } } return Collections.<Method>unmodifiableSet(methods); } /** * Recursive function used by {@link #getInterfaceMethods} to add all * interface methods to the supplied set * * @param methods Method set to add to * @return superclass reference, used to make the code above more fluent */ private ClassInfo addMethodsRecursive(Set<Method> methods) { if (this.isInterface) { methods.addAll(this.methods); } else if (!this.isMixin) { for (MixinInfo mixin : this.mixins) { mixin.getClassInfo().addMethodsRecursive(methods); } } for (String iface : this.interfaces) { ClassInfo.forName(iface).addMethodsRecursive(methods); } return this.getSuperClass(); } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Name of the superclass to search for in the hierarchy * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(String superClass) { return this.hasSuperClass(superClass, Traversal.NONE); } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Name of the superclass to search for in the hierarchy * @param traversal Traversal type to allow during this lookup * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(String superClass, Traversal traversal) { if (ClassInfo.JAVA_LANG_OBJECT.equals(superClass)) { return true; } return this.findSuperClass(superClass, traversal) != null; } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Superclass to search for in the hierarchy * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(ClassInfo superClass) { return this.hasSuperClass(superClass, Traversal.NONE); } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Superclass to search for in the hierarchy * @param traversal Traversal type to allow during this lookup * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(ClassInfo superClass, Traversal traversal) { if (ClassInfo.OBJECT == superClass) { return true; } return this.findSuperClass(superClass.name, traversal) != null; } /** * Search for the specified superclass in this class's hierarchy. If found * returns the ClassInfo, otherwise returns null * * @param superClass Superclass name to search for * @return Matched superclass or null if not found */ public ClassInfo findSuperClass(String superClass) { return this.findSuperClass(superClass, Traversal.NONE); } /** * Search for the specified superclass in this class's hierarchy. If found * returns the ClassInfo, otherwise returns null * * @param superClass Superclass name to search for * @param traversal Traversal type to allow during this lookup * @return Matched superclass or null if not found */ public ClassInfo findSuperClass(String superClass, Traversal traversal) { ClassInfo superClassInfo = this.getSuperClass(); if (superClassInfo != null) { List<ClassInfo> targets = superClassInfo.getTargets(); for (ClassInfo superTarget : targets) { if (superClass.equals(superTarget.getName())) { return superClassInfo; } ClassInfo found = superTarget.findSuperClass(superClass, traversal.next()); if (found != null) { return found; } } } if (traversal.canTraverse()) { for (MixinInfo mixin : this.mixins) { ClassInfo targetSuper = mixin.getClassInfo().findSuperClass(superClass, traversal); if (targetSuper != null) { return targetSuper; } } } return null; } /** * Walks up this class's hierarchy to find the first class targetted by the * specified mixin. This is used during mixin application to translate a * mixin reference to a "real class" reference <em>in the context of <b>this * </b> class</em>. * * @param mixin Mixin class to search for * @return corresponding (target) class for the specified mixin or null if * no corresponding mixin was found */ ClassInfo findCorrespondingType(ClassInfo mixin) { if (mixin == null || !mixin.isMixin || this.isMixin) { return null; } ClassInfo correspondingType = this.correspondingTypes.get(mixin); if (correspondingType == null) { correspondingType = this.findSuperTypeForMixin(mixin); this.correspondingTypes.put(mixin, correspondingType); } return correspondingType; } /* (non-Javadoc) * Only used by findCorrespondingType(), used as a convenience so that * sanity checks and caching can be handled more elegantly */ private ClassInfo findSuperTypeForMixin(ClassInfo mixin) { ClassInfo superClass = this; while (superClass != null && superClass != ClassInfo.OBJECT) { for (MixinInfo minion : superClass.mixins) { if (minion.getClassInfo().equals(mixin)) { return superClass; } } superClass = superClass.getSuperClass(); } return null; } /** * Find out whether this (mixin) class has another mixin in its superclass * hierarchy. This method always returns false for non-mixin classes. * * @return true if and only if one or more mixins are found in the hierarchy * of this mixin */ public boolean hasMixinInHierarchy() { if (!this.isMixin) { return false; } ClassInfo superClass = this.getSuperClass(); while (superClass != null && superClass != ClassInfo.OBJECT) { if (superClass.isMixin) { return true; } superClass = superClass.getSuperClass(); } return false; } /** * Find out whether this (non-mixin) class has a mixin targetting * <em>any</em> of its superclasses. This method always returns false for * mixin classes. * * @return true if and only if one or more classes in this class's hierarchy * are targetted by a mixin */ public boolean hasMixinTargetInHierarchy() { if (this.isMixin) { return false; } ClassInfo superClass = this.getSuperClass(); while (superClass != null && superClass != ClassInfo.OBJECT) { if (superClass.mixins.size() > 0) { return true; } superClass = superClass.getSuperClass(); } return false; } /** * Finds the specified private or protected method in this class's hierarchy * * @param method Method to search for * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(MethodNode method, boolean includeThisClass) { return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE); } /** * Finds the specified private or protected method in this class's hierarchy * * @param method Method to search for * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses * @param includePrivate Include private members in the search * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(MethodNode method, boolean includeThisClass, boolean includePrivate) { return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE, includePrivate); } /** * Finds the specified public or protected method in this class's hierarchy * * @param method Method to search for * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(MethodInsnNode method, boolean includeThisClass) { return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE); } /** * Finds the specified public or protected method in this class's hierarchy * * @param method Method to search for * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses * @param includePrivate Include private members in the search * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(MethodInsnNode method, boolean includeThisClass, boolean includePrivate) { return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE, includePrivate); } /** * Finds the specified public or protected method in this class's hierarchy * * @param name Method name to search for * @param desc Method descriptor * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass) { return this.findMethodInHierarchy(name, desc, includeThisClass, Traversal.NONE); } /** * Finds the specified public or protected method in this class's hierarchy * * @param name Method name to search for * @param desc Method descriptor * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses * @param traversal Traversal type to allow during this lookup * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal) { return this.findMethodInHierarchy(name, desc, includeThisClass, traversal, false); } /** * Finds the specified public or protected method in this class's hierarchy * * @param name Method name to search for * @param desc Method descriptor * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses * @param traversal Traversal type to allow during this lookup * @param includePrivate Include private members in the search * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, boolean includePrivate) { return this.findInHierarchy(name, desc, includeThisClass, traversal, includePrivate, Type.METHOD); } /** * Finds the specified private or protected field in this class's hierarchy * * @param field Field to search for * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(FieldNode field, boolean includeThisClass) { return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE); } /** * Finds the specified private or protected field in this class's hierarchy * * @param field Field to search for * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @param includePrivate Include private members in the search * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(FieldNode field, boolean includeThisClass, boolean includePrivate) { return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE, includePrivate); } /** * Finds the specified public or protected field in this class's hierarchy * * @param field Field to search for * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(FieldInsnNode field, boolean includeThisClass) { return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE); } /** * Finds the specified public or protected field in this class's hierarchy * * @param field Field to search for * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @param includePrivate Include private members in the search * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(FieldInsnNode field, boolean includeThisClass, boolean includePrivate) { return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE, includePrivate); } /** * Finds the specified public or protected field in this class's hierarchy * * @param name Field name to search for * @param desc Field descriptor * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass) { return this.findFieldInHierarchy(name, desc, includeThisClass, Traversal.NONE); } /** * Finds the specified public or protected field in this class's hierarchy * * @param name Field name to search for * @param desc Field descriptor * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @param traversal Traversal type to allow during this lookup * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal) { return this.findFieldInHierarchy(name, desc, includeThisClass, traversal, false); } /** * Finds the specified public or protected field in this class's hierarchy * * @param name Field name to search for * @param desc Field descriptor * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @param traversal Traversal type to allow during this lookup * @param includePrivate Include private members in the search * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, boolean includePrivate) { return this.findInHierarchy(name, desc, includeThisClass, traversal, includePrivate, Type.FIELD); } /** * Finds a public or protected member in the hierarchy of this class which * matches the supplied details * * @param name Member name to search * @param desc Member descriptor * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses * @param traversal Traversal type to allow during this lookup * @param priv Include private members in the search * @param type Type of member to search for (field or method) * @return the discovered member or null if the member could not be resolved */ private <M extends Member> M findInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, boolean priv, Type type) { if (includeThisClass) { M member = this.findMember(name, desc, priv, type); if (member != null) { return member; } if (traversal.canTraverse()) { for (MixinInfo mixin : this.mixins) { M mixinMember = mixin.getClassInfo().findMember(name, desc, priv, type); if (mixinMember != null) { return this.cloneMember(mixinMember); } } } } ClassInfo superClassInfo = this.getSuperClass(); if (superClassInfo != null) { for (ClassInfo superTarget : superClassInfo.getTargets()) { // Do not search for private members in superclasses, pass priv as false M member = superTarget.findInHierarchy(name, desc, true, traversal.next(), false, type); if (member != null) { return member; } } } return null; } /** * Effectively a clone method for member, placed here so that the enclosing * instance for the inner class is this class and not the enclosing instance * of the existing class. Basically creates a cloned member with this * ClassInfo as its parent. * * @param member * @return */ @SuppressWarnings("unchecked") private <M extends Member> M cloneMember(M member) { if (member instanceof Method) { return (M)new Method(member); } return (M)new Field(member); } /** * Finds the specified public or protected method in this class * * @param method Method to search for * @return the method object or null if the method could not be resolved */ public Method findMethod(MethodNode method) { return this.findMethod(method.name, method.desc, false); } /** * Finds the specified public or protected method in this class * * @param method Method to search for * @param includePrivate also search private fields * @return the method object or null if the method could not be resolved */ public Method findMethod(MethodNode method, boolean includePrivate) { return this.findMethod(method.name, method.desc, includePrivate); } /** * Finds the specified public or protected method in this class * * @param method Method to search for * @return the method object or null if the method could not be resolved */ public Method findMethod(MethodInsnNode method) { return this.findMethod(method.name, method.desc, false); } /** * Finds the specified public or protected method in this class * * @param method Method to search for * @param includePrivate also search private fields * @return the method object or null if the method could not be resolved */ public Method findMethod(MethodInsnNode method, boolean includePrivate) { return this.findMethod(method.name, method.desc, includePrivate); } /** * Finds the specified public or protected method in this class * * @param method Method name to search for * @param desc Method signature to search for * @param includePrivate also search private fields * @return the method object or null if the method could not be resolved */ public Method findMethod(String name, String desc, boolean includePrivate) { return this.findMember(name, desc, includePrivate, Type.METHOD); } /** * Finds the specified field in this class * * @param field Field to search for * @return the field object or null if the field could not be resolved */ public Field findField(FieldNode field) { return this.findField(field.name, field.desc, (field.access & Opcodes.ACC_PRIVATE) != 0); } /** * Finds the specified public or protected method in this class * * @param field Field to search for * @param includePrivate also search private fields * @return the field object or null if the field could not be resolved */ public Field findField(FieldInsnNode field, boolean includePrivate) { return this.findField(field.name, field.desc, includePrivate); } /** * Finds the specified field in this class * * @param name Field name to search for * @param desc Field signature to search for * @param includePrivate also search private fields * @return the field object or null if the field could not be resolved */ public Field findField(String name, String desc, boolean includePrivate) { return this.findMember(name, desc, includePrivate, Type.FIELD); } /** * Finds the specified member in this class * * @param name Field name to search for * @param desc Field signature to search for * @param includePrivate also search private fields * @param memberType Type of member list to search * @return the field object or null if the field could not be resolved */ private <M extends Member> M findMember(String name, String desc, boolean includePrivate, Type memberType) { @SuppressWarnings("unchecked") Set<M> members = (Set<M>)(memberType == Type.METHOD ? this.methods : this.fields); for (M member : members) { if (member.equals(name, desc) && (includePrivate || !member.isPrivate())) { return member; } } return null; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object other) { if (!(other instanceof ClassInfo)) { return false; } return ((ClassInfo)other).name.equals(this.name); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return this.name.hashCode(); } /** * Return a ClassInfo for the supplied {@link ClassNode}. If a ClassInfo for * the class was already defined, then the original ClassInfo is returned * from the internal cache. Otherwise a new ClassInfo is created and * returned. * * @param classNode * @return */ static ClassInfo fromClassNode(ClassNode classNode) { ClassInfo info = ClassInfo.cache.get(classNode.name); if (info == null) { info = new ClassInfo(classNode); ClassInfo.cache.put(classNode.name, info); } return info; } /** * Return a ClassInfo for the specified class name, fetches the ClassInfo * from the cache where possible * * @param className Binary name of the class to look up * @return ClassInfo for the specified class name or null if the specified * name cannot be resolved for some reason */ public static ClassInfo forName(String className) { className = className.replace('.', '/'); ClassInfo info = ClassInfo.cache.get(className); if (info == null) { try { ClassNode classNode = TreeInfo.getClassNode(className); info = new ClassInfo(classNode); } catch (Exception ex) { ex.printStackTrace(); } // Put null in the cache if load failed ClassInfo.cache.put(className, info); ClassInfo.logger.trace("Added class metadata for {} to metadata cache", className); } return info; } }
Fix minor javadoc issue
src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
Fix minor javadoc issue
<ide><path>rc/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java <ide> /** <ide> * Finds the specified public or protected method in this class <ide> * <del> * @param method Method name to search for <add> * @param name Method name to search for <ide> * @param desc Method signature to search for <ide> * @param includePrivate also search private fields <ide> * @return the method object or null if the method could not be resolved
Java
epl-1.0
35b207e9d5f8b5e2e3a07c79034fba5e0ea3a613
0
floralvikings/jenjin
package com.jenjinstudios.core.io; import org.testng.Assert; import org.testng.annotations.Test; import java.io.*; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.util.logging.Level; import java.util.logging.Logger; /** * Test the {@code MessageOutputStream} class. * * @author Caleb Brinkman */ @SuppressWarnings("MagicNumber") public class MessageOutputStreamTest { private static final MessageRegistry MESSAGE_REGISTRY = MessageRegistry.getInstance(); private static final Logger LOGGER = Logger.getLogger(MessageOutputStreamTest.class.getName()); /** * Test writing a message to the stream. * * @throws Exception If there's an exception. */ @Test public void testWriteMessage() throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); MessageOutputStream mos = new MessageOutputStream(bos); Message msg = MESSAGE_REGISTRY.createMessage("InvalidMessage"); msg.setArgument("messageID", (short) -255); msg.setArgument("messageName", "FooBar"); mos.writeMessage(msg); byte[] bytes = bos.toByteArray(); mos.close(); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); MessageInputStream mis = new MessageInputStream(bis); Message readMsg = mis.readMessage(); Assert.assertEquals(readMsg.getArgs(), msg.getArgs(), "Message arguments not equal."); } /** * Test writing an encrypted message with no key sent. * * @throws Exception If there's an exception. */ @Test(expectedExceptions = IOException.class) public void testEncryptedMessageNoPublicKey() throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); MessageOutputStream mos = new MessageOutputStream(bos); Message msg = MESSAGE_REGISTRY.createMessage("TestEncryptedMessage"); msg.setArgument("encryptedString", "FooBar"); mos.writeMessage(msg); } /** * Test sending a correct encrypted message. * * @throws Exception If there's an exception. */ @Test public void testEncryptedMessage() throws Exception { KeyPair keyPair = generateRSAKeyPair(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); MessageOutputStream mos = new MessageOutputStream(bos); mos.setPublicKey(keyPair.getPublic()); Message msg = MESSAGE_REGISTRY.createMessage("TestEncryptedMessage"); msg.setArgument("encryptedString", "FooBar"); mos.writeMessage(msg); byte[] bytes = bos.toByteArray(); mos.close(); DataInput dis = new DataInputStream(new ByteArrayInputStream(bytes)); short id = dis.readShort(); boolean encrypted = dis.readBoolean(); String encStr = dis.readUTF(); Assert.assertEquals(id, msg.getID(), "Message IDs not equal"); Assert.assertTrue(encrypted); Assert.assertNotEquals(encStr, msg.getArgument("encryptedString")); } /** * Test writing a message with each type of argument. * * @throws Exception If there's an exception. */ @Test public void testAllTypesMessage() throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); MessageOutputStream mos = new MessageOutputStream(bos); Message msg = MESSAGE_REGISTRY.createMessage("TestAllTypesMessage"); msg.setArgument("testString", "SNAFU"); msg.setArgument("testInt", 123); msg.setArgument("testLong", 456L); msg.setArgument("testDouble", 4.567); msg.setArgument("testFloat", 0.123f); msg.setArgument("testShort", (short) 789); msg.setArgument("testBoolean", true); msg.setArgument("testByte", (byte) 101); msg.setArgument("testByteArray", new byte[]{2, 3, 5, 7, 11}); msg.setArgument("testStringArray", new String[]{"Foo", "Bar"}); mos.writeMessage(msg); byte[] bytes = bos.toByteArray(); mos.close(); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); MessageInputStream mis = new MessageInputStream(bis); Message readMsg = mis.readMessage(); Assert.assertEquals(readMsg.getArgs(), msg.getArgs()); } private static KeyPair generateRSAKeyPair() { KeyPair keyPair = null; try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(512); keyPair = keyPairGenerator.generateKeyPair(); } catch (NoSuchAlgorithmException e) { LOGGER.log(Level.SEVERE, "Unable to create RSA key pair!", e); } return keyPair; } }
jenjin-core/src/test/java/com/jenjinstudios/core/io/MessageOutputStreamTest.java
package com.jenjinstudios.core.io; import org.testng.Assert; import org.testng.annotations.Test; import java.io.*; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.util.logging.Level; import java.util.logging.Logger; /** * Test the {@code MessageOutputStream} class. * * @author Caleb Brinkman */ @SuppressWarnings("MagicNumber") public class MessageOutputStreamTest { private static final MessageRegistry MESSAGE_REGISTRY = MessageRegistry.getInstance(); private static final Logger LOGGER = Logger.getLogger(MessageOutputStreamTest.class.getName()); /** * Test writing a message to the stream. * * @throws Exception If there's an exception. */ @Test public void testWriteMessage() throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); MessageOutputStream mos = new MessageOutputStream(bos); Message msg = MESSAGE_REGISTRY.createMessage("InvalidMessage"); msg.setArgument("messageID", (short) -255); msg.setArgument("messageName", "FooBar"); mos.writeMessage(msg); byte[] bytes = bos.toByteArray(); mos.close(); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); MessageInputStream mis = new MessageInputStream(bis); Message readMsg = mis.readMessage(); Assert.assertEquals(readMsg.getArgs(), msg.getArgs(), "Message arguments not equal."); } /** * Test writing an encrypted message with no key sent. * * @throws Exception If there's an exception. */ @Test(expectedExceptions = IOException.class) public void testEncryptedMessageNoPublicKey() throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); MessageOutputStream mos = new MessageOutputStream(bos); Message msg = MESSAGE_REGISTRY.createMessage("TestEncryptedMessage"); msg.setArgument("encryptedString", "FooBar"); mos.writeMessage(msg); } /** * Test sending a correct encrypted message. * * @throws Exception If there's an exception. */ @Test public void testEncryptedMessage() throws Exception { KeyPair keyPair = generateRSAKeyPair(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); MessageOutputStream mos = new MessageOutputStream(bos); mos.setPublicKey(keyPair.getPublic()); Message msg = MESSAGE_REGISTRY.createMessage("TestEncryptedMessage"); msg.setArgument("encryptedString", "FooBar"); mos.writeMessage(msg); byte[] bytes = bos.toByteArray(); mos.close(); DataInput dis = new DataInputStream(new ByteArrayInputStream(bytes)); short id = dis.readShort(); boolean encrypted = dis.readBoolean(); String encStr = dis.readUTF(); Assert.assertEquals(id, msg.getID()); Assert.assertTrue(encrypted); Assert.assertNotEquals(encStr, msg.getArgument("encryptedString")); } /** * Test writing a message with each type of argument. * * @throws Exception If there's an exception. */ @Test public void testAllTypesMessage() throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); MessageOutputStream mos = new MessageOutputStream(bos); Message msg = MESSAGE_REGISTRY.createMessage("TestAllTypesMessage"); msg.setArgument("testString", "SNAFU"); msg.setArgument("testInt", 123); msg.setArgument("testLong", 456L); msg.setArgument("testDouble", 4.567); msg.setArgument("testFloat", 0.123f); msg.setArgument("testShort", (short) 789); msg.setArgument("testBoolean", true); msg.setArgument("testByte", (byte) 101); msg.setArgument("testByteArray", new byte[]{2, 3, 5, 7, 11}); msg.setArgument("testStringArray", new String[]{"Foo", "Bar"}); mos.writeMessage(msg); byte[] bytes = bos.toByteArray(); mos.close(); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); MessageInputStream mis = new MessageInputStream(bis); Message readMsg = mis.readMessage(); Assert.assertEquals(readMsg.getArgs(), msg.getArgs()); } private static KeyPair generateRSAKeyPair() { KeyPair keyPair = null; try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(512); keyPair = keyPairGenerator.generateKeyPair(); } catch (NoSuchAlgorithmException e) { LOGGER.log(Level.SEVERE, "Unable to create RSA key pair!", e); } return keyPair; } }
Added assertion message.
jenjin-core/src/test/java/com/jenjinstudios/core/io/MessageOutputStreamTest.java
Added assertion message.
<ide><path>enjin-core/src/test/java/com/jenjinstudios/core/io/MessageOutputStreamTest.java <ide> boolean encrypted = dis.readBoolean(); <ide> String encStr = dis.readUTF(); <ide> <del> Assert.assertEquals(id, msg.getID()); <add> Assert.assertEquals(id, msg.getID(), "Message IDs not equal"); <ide> Assert.assertTrue(encrypted); <ide> Assert.assertNotEquals(encStr, msg.getArgument("encryptedString")); <ide>
Java
apache-2.0
e9136cfd354d28ca9e953b282f4c327a0362d587
0
maobaolong/alluxio,wwjiang007/alluxio,Alluxio/alluxio,Alluxio/alluxio,maobaolong/alluxio,Alluxio/alluxio,Alluxio/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,maobaolong/alluxio,maobaolong/alluxio,maobaolong/alluxio,wwjiang007/alluxio,Alluxio/alluxio,maobaolong/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,Alluxio/alluxio,Alluxio/alluxio,maobaolong/alluxio,Alluxio/alluxio,maobaolong/alluxio,Alluxio/alluxio,maobaolong/alluxio,Alluxio/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,maobaolong/alluxio,wwjiang007/alluxio
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.hub.test; import alluxio.conf.AlluxioConfiguration; import alluxio.conf.InstancedConfiguration; import alluxio.conf.PropertyKey; import alluxio.conf.ServerConfiguration; import alluxio.hub.manager.process.ManagerProcessContext; import alluxio.security.authentication.AuthType; import org.junit.ClassRule; import org.junit.rules.TemporaryFolder; public class BaseHubTest { @ClassRule public static final TemporaryFolder TEST_CONF_DIR = new TemporaryFolder(); @ClassRule public static final TemporaryFolder TEST_PRESTO_CONF_DIR = new TemporaryFolder(); protected static InstancedConfiguration getTestConfig() throws Exception { InstancedConfiguration c = new InstancedConfiguration(ServerConfiguration.global().copyProperties()); c.set(PropertyKey.HUB_CLUSTER_ID, "0000"); c.set(PropertyKey.HUB_MANAGER_REGISTER_RETRY_TIME, "1sec"); c.set(PropertyKey.HUB_MANAGER_RPC_PORT, 0); c.set(PropertyKey.HUB_MANAGER_EXECUTOR_THREADS_MIN, 0); c.set(PropertyKey.HUB_AGENT_RPC_PORT, 0); c.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.NOSASL.getAuthName()); c.set(PropertyKey.CONF_DIR, TEST_CONF_DIR.getRoot().getCanonicalPath()); c.set(PropertyKey.HUB_MANAGER_PRESTO_CONF_PATH, TEST_PRESTO_CONF_DIR.getRoot() .getCanonicalPath()); return c; } public static ManagerProcessContext getTestManagerContext() throws Exception { return getTestManagerContext(getTestConfig()); } public static ManagerProcessContext getTestManagerContext(AlluxioConfiguration conf) { return new ManagerProcessContext(conf); } }
hub/server/src/test/java/alluxio/hub/test/BaseHubTest.java
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.hub.test; import alluxio.conf.AlluxioConfiguration; import alluxio.conf.InstancedConfiguration; import alluxio.conf.PropertyKey; import alluxio.conf.ServerConfiguration; import alluxio.hub.manager.process.ManagerProcessContext; import alluxio.security.authentication.AuthType; import org.junit.ClassRule; import org.junit.rules.TemporaryFolder; public class BaseHubTest { @ClassRule public static final TemporaryFolder TEST_CONF_DIR = new TemporaryFolder(); @ClassRule public static final TemporaryFolder TEST_PRESTO_CONF_DIR = new TemporaryFolder(); protected static InstancedConfiguration getTestConfig() throws Exception { InstancedConfiguration c = new InstancedConfiguration(ServerConfiguration.global().copyProperties()); c.set(PropertyKey.HUB_MANAGER_RPC_PORT, 0); c.set(PropertyKey.HUB_MANAGER_EXECUTOR_THREADS_MIN, 0); c.set(PropertyKey.HUB_AGENT_RPC_PORT, 0); c.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.NOSASL.getAuthName()); c.set(PropertyKey.CONF_DIR, TEST_CONF_DIR.getRoot().getCanonicalPath()); c.set(PropertyKey.HUB_MANAGER_PRESTO_CONF_PATH, TEST_PRESTO_CONF_DIR.getRoot() .getCanonicalPath()); return c; } public static ManagerProcessContext getTestManagerContext() throws Exception { return getTestManagerContext(getTestConfig()); } public static ManagerProcessContext getTestManagerContext(AlluxioConfiguration conf) { return new ManagerProcessContext(conf); } }
Add Hub property keys to fix and speed up tests ### What changes are proposed in this pull request? Hub tests require Cluster ID and also reducing registration time to speed up tests. ### Why are the changes needed? See above. ### Does this PR introduce any user facing changes? No pr-link: Alluxio/alluxio#14736 change-id: cid-364b38ada04fafc9684d353f7d6f5891d5963ba1
hub/server/src/test/java/alluxio/hub/test/BaseHubTest.java
Add Hub property keys to fix and speed up tests
<ide><path>ub/server/src/test/java/alluxio/hub/test/BaseHubTest.java <ide> protected static InstancedConfiguration getTestConfig() throws Exception { <ide> InstancedConfiguration c = <ide> new InstancedConfiguration(ServerConfiguration.global().copyProperties()); <add> c.set(PropertyKey.HUB_CLUSTER_ID, "0000"); <add> c.set(PropertyKey.HUB_MANAGER_REGISTER_RETRY_TIME, "1sec"); <ide> c.set(PropertyKey.HUB_MANAGER_RPC_PORT, 0); <ide> c.set(PropertyKey.HUB_MANAGER_EXECUTOR_THREADS_MIN, 0); <ide> c.set(PropertyKey.HUB_AGENT_RPC_PORT, 0);
Java
mit
error: pathspec 'server/src/main/java/ge/edu/freeuni/taxi/dispatcher/OrderMessageListener.java' did not match any file(s) known to git
a47095cb2afa473d40704ec5a9963d3c4a68b043
1
freeuni-sdp/FreeUni-SDP-2014-Final-Project,freeuni-sdp/FreeUni-SDP-2014-Final-Project
package ge.edu.freeuni.taxi.dispatcher; import java.util.Date; import ge.edu.freeuni.taxi.Passenger; import ge.edu.freeuni.taxi.PassengerOrder; import ge.edu.freeuni.taxi.core.Message; import ge.edu.freeuni.taxi.core.MessageType; import ge.edu.freeuni.taxi.manager.OrderManager; public class OrderMessageListener implements IncomingMessageListener{ @Override public void onIncomingMessage(Message message) { if(message.getMessageType() == MessageType.CLIENT_ORDERED){ // TODO OrderManager manager = OrderManager.getInstance(); PassengerOrder order = new PassengerOrder(); order.setCreateTime(new Date()); Passenger p = new Passenger(); p.setName(message.getSender()); order.setPassenger(p); manager.updateOrder(order); } } }
server/src/main/java/ge/edu/freeuni/taxi/dispatcher/OrderMessageListener.java
#26 create and save order after receiving a message from twitter post
server/src/main/java/ge/edu/freeuni/taxi/dispatcher/OrderMessageListener.java
#26 create and save order after receiving a message from twitter post
<ide><path>erver/src/main/java/ge/edu/freeuni/taxi/dispatcher/OrderMessageListener.java <add>package ge.edu.freeuni.taxi.dispatcher; <add> <add>import java.util.Date; <add> <add>import ge.edu.freeuni.taxi.Passenger; <add>import ge.edu.freeuni.taxi.PassengerOrder; <add>import ge.edu.freeuni.taxi.core.Message; <add>import ge.edu.freeuni.taxi.core.MessageType; <add>import ge.edu.freeuni.taxi.manager.OrderManager; <add> <add>public class OrderMessageListener implements IncomingMessageListener{ <add> <add> @Override <add> public void onIncomingMessage(Message message) { <add> if(message.getMessageType() == MessageType.CLIENT_ORDERED){ <add> // TODO <add> OrderManager manager = OrderManager.getInstance(); <add> PassengerOrder order = new PassengerOrder(); <add> order.setCreateTime(new Date()); <add> Passenger p = new Passenger(); <add> p.setName(message.getSender()); <add> order.setPassenger(p); <add> manager.updateOrder(order); <add> } <add> <add> } <add> <add>}
Java
apache-2.0
a3103689932e2b650d1aa8891fcc484fbd04c021
0
akihito104/UdonRoad
/* * Copyright (c) 2016. Matsuda, Akihit (akihito104) * * 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.freshdigitable.udonroad; import android.content.Context; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; 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 com.freshdigitable.udonroad.databinding.FragmentUserInfoBinding; import com.freshdigitable.udonroad.datastore.TypedCache; import com.freshdigitable.udonroad.module.InjectionUtil; import com.freshdigitable.udonroad.module.twitter.TwitterApi; import com.freshdigitable.udonroad.subscriber.ConfigRequestWorker; import com.freshdigitable.udonroad.subscriber.RequestWorkerBase; import com.freshdigitable.udonroad.subscriber.UserRequestWorker; import com.squareup.picasso.Picasso; import javax.inject.Inject; import rx.Subscription; import rx.functions.Action0; import rx.functions.Action1; import twitter4j.RateLimitStatus; import twitter4j.Relationship; import twitter4j.User; /** * UserInfoFragment wraps UserInfoView. * * Created by akihit on 2016/02/07. */ public class UserInfoFragment extends Fragment { private static final String LOADINGTAG_USER_INFO_IMAGES = "UserInfoImages"; private FragmentUserInfoBinding binding; private Subscription subscription; @Inject TwitterApi twitterApi; @Override public void onAttach(Context context) { super.onAttach(context); InjectionUtil.getComponent(this).inject(this); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_user_info, container, false); return binding.getRoot(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); final long userId = getUserId(); twitterApi.showFriendship(userId) .doOnNext(updateRelationship()) .subscribe(RequestWorkerBase.<Relationship>nopSubscriber()); } @Override public void onStart() { super.onStart(); userRequestWorker.open(); configRequestWorker.open(); final long userId = getUserId(); final TypedCache<User> userCache = userRequestWorker.getCache(); final User user = userCache.find(userId); showUserInfo(user); subscription = userCache.observeById(userId) .subscribe(new Action1<User>() { @Override public void call(User user) { showUserInfo(user); } }); } @Override public void onStop() { super.onStop(); if (subscription != null && !subscription.isUnsubscribed()) { subscription.unsubscribe(); } dismissUserInfo(); userRequestWorker.close(); configRequestWorker.close(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.user_info, menu); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (relationship != null) { switchVisibility(relationship.isSourceFollowingTarget(), R.id.action_unfollow, R.id.action_follow, menu); switchVisibility(relationship.isSourceBlockingTarget(), R.id.action_unblock, R.id.action_block, menu); switchVisibility(relationship.isSourceMutingTarget(), R.id.action_unmute, R.id.action_mute, menu); switchVisibility(relationship.isSourceWantRetweets(), R.id.action_block_retweet, R.id.action_unblock_retweet, menu); } } private static void switchVisibility(boolean cond, @IdRes int actionOnIfTrue, @IdRes int actionOffIfFalse, @NonNull Menu menu) { menu.findItem(actionOnIfTrue).setVisible(cond); menu.findItem(actionOffIfFalse).setVisible(!cond); } @Inject UserRequestWorker<TypedCache<User>> userRequestWorker; @Inject ConfigRequestWorker configRequestWorker; @Override public boolean onOptionsItemSelected(MenuItem item) { final int itemId = item.getItemId(); final long userId = getUserId(); if (itemId == R.id.action_follow) { userRequestWorker.observeCreateFriendship(userId) .doOnCompleted(updateFollowing(true)) .subscribe(RequestWorkerBase.<User>nopSubscriber()); } else if (itemId == R.id.action_unfollow) { userRequestWorker.observeDestroyFriendship(userId) .doOnCompleted(updateFollowing(false)) .subscribe(RequestWorkerBase.<User>nopSubscriber()); } else if (itemId == R.id.action_block) { configRequestWorker.observeCreateBlock(userId) .doOnCompleted(updateBlocking(true)) .subscribe(RequestWorkerBase.<User>nopSubscriber()); } else if (itemId == R.id.action_unblock) { configRequestWorker.observeDestroyBlock(userId) .doOnCompleted(updateBlocking(false)) .subscribe(RequestWorkerBase.<User>nopSubscriber()); } else if (itemId == R.id.action_block_retweet) { configRequestWorker.observeBlockRetweet(relationship) .doOnNext(updateRelationship()) .subscribe(RequestWorkerBase.<Relationship>nopSubscriber()); } else if (itemId == R.id.action_unblock_retweet) { configRequestWorker.observeUnblockRetweet(relationship) .doOnNext(updateRelationship()) .subscribe(RequestWorkerBase.<Relationship>nopSubscriber()); } else if (itemId == R.id.action_mute) { configRequestWorker.observeCreateMute(userId) .doOnCompleted(updateMuting(true)) .subscribe(RequestWorkerBase.<User>nopSubscriber()); } else if (itemId == R.id.action_unmute) { configRequestWorker.observeDestroyMute(userId) .doOnCompleted(updateMuting(false)) .subscribe(RequestWorkerBase.<User>nopSubscriber()); } else if (itemId == R.id.action_r4s) { configRequestWorker.reportSpam(userId); } return false; } private void showUserInfo(User user) { if (user == null) { return; } Picasso.with(getContext()) .load(user.getProfileImageURLHttps()) .tag(LOADINGTAG_USER_INFO_IMAGES) .into(binding.userInfoUserInfoView.getIcon()); Picasso.with(getContext()) .load(user.getProfileBannerMobileURL()) .fit() .tag(LOADINGTAG_USER_INFO_IMAGES) .into(binding.userInfoUserInfoView.getBanner()); binding.userInfoUserInfoView.bindData(user); } private void dismissUserInfo() { Picasso.with(getContext()).cancelTag(LOADINGTAG_USER_INFO_IMAGES); binding.userInfoUserInfoView.getBanner().setImageDrawable(null); binding.userInfoUserInfoView.getIcon().setImageDrawable(null); } public static UserInfoFragment create(long userId) { final UserInfoFragment userInfoAppbarFragment = new UserInfoFragment(); final Bundle args = new Bundle(); args.putLong("userId", userId); userInfoAppbarFragment.setArguments(args); return userInfoAppbarFragment; } private long getUserId() { final Bundle arguments = getArguments(); return arguments.getLong("userId"); } private RelationshipImpl relationship; private void setRelationship(RelationshipImpl relationship) { this.relationship = relationship; notifyRelationshipChanged(); } private void notifyRelationshipChanged() { binding.userInfoUserInfoView.bindRelationship(relationship); getActivity().supportInvalidateOptionsMenu(); } @NonNull private Action0 updateFollowing(final boolean following) { return new Action0() { @Override public void call() { relationship.setFollowing(following); notifyRelationshipChanged(); } }; } @NonNull private Action0 updateBlocking(final boolean blocking) { return new Action0() { @Override public void call() { relationship.setBlocking(blocking); notifyRelationshipChanged(); } }; } @NonNull private Action0 updateMuting(final boolean muting) { return new Action0() { @Override public void call() { relationship.setMuting(muting); notifyRelationshipChanged(); } }; } private Action1<Relationship> updateRelationship() { return new Action1<Relationship>() { @Override public void call(Relationship relationship) { setRelationship(new RelationshipImpl(relationship)); } }; } private static class RelationshipImpl implements Relationship { private final Relationship relationship; RelationshipImpl(Relationship relationship) { this.relationship = relationship; this.following = relationship.isSourceFollowingTarget(); this.blocking = relationship.isSourceBlockingTarget(); this.muting = relationship.isSourceMutingTarget(); } private boolean blocking; @Override public boolean isSourceBlockingTarget() { return blocking; } void setBlocking(boolean blocking) { this.blocking = blocking; } private boolean muting; @Override public boolean isSourceMutingTarget() { return muting; } void setMuting(boolean muting) { this.muting = muting; } private boolean following; @Override public boolean isSourceFollowingTarget() { return following; } void setFollowing(boolean following) { this.following = following; } @Override public long getSourceUserId() { return relationship.getSourceUserId(); } @Override public long getTargetUserId() { return relationship.getTargetUserId(); } @Override public String getSourceUserScreenName() { return relationship.getSourceUserScreenName(); } @Override public String getTargetUserScreenName() { return relationship.getTargetUserScreenName(); } @Override public boolean isTargetFollowingSource() { return relationship.isTargetFollowingSource(); } @Override public boolean isSourceFollowedByTarget() { return relationship.isSourceFollowedByTarget(); } @Override public boolean isTargetFollowedBySource() { return following; } @Override public boolean canSourceDm() { return relationship.canSourceDm(); } @Override public boolean isSourceNotificationsEnabled() { return relationship.isSourceNotificationsEnabled(); } @Override public boolean isSourceWantRetweets() { return relationship.isSourceWantRetweets(); } @Override public RateLimitStatus getRateLimitStatus() { return relationship.getRateLimitStatus(); } @Override public int getAccessLevel() { return relationship.getAccessLevel(); } } }
app/src/main/java/com/freshdigitable/udonroad/UserInfoFragment.java
/* * Copyright (c) 2016. Matsuda, Akihit (akihito104) * * 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.freshdigitable.udonroad; import android.content.Context; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; 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 com.freshdigitable.udonroad.databinding.FragmentUserInfoBinding; import com.freshdigitable.udonroad.datastore.TypedCache; import com.freshdigitable.udonroad.module.InjectionUtil; import com.freshdigitable.udonroad.module.twitter.TwitterApi; import com.freshdigitable.udonroad.subscriber.ConfigRequestWorker; import com.freshdigitable.udonroad.subscriber.RequestWorkerBase; import com.freshdigitable.udonroad.subscriber.UserRequestWorker; import com.squareup.picasso.Picasso; import javax.inject.Inject; import rx.Observable; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action0; import rx.functions.Action1; import twitter4j.RateLimitStatus; import twitter4j.Relationship; import twitter4j.User; /** * UserInfoFragment wraps UserInfoView. * * Created by akihit on 2016/02/07. */ public class UserInfoFragment extends Fragment { private static final String LOADINGTAG_USER_INFO_IMAGES = "UserInfoImages"; private FragmentUserInfoBinding binding; private Subscription subscription; @Inject TwitterApi twitterApi; @Override public void onAttach(Context context) { super.onAttach(context); InjectionUtil.getComponent(this).inject(this); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_user_info, container, false); return binding.getRoot(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); final long userId = getUserId(); observeUpdateRelationship(twitterApi.showFriendship(userId)); } @Override public void onStart() { super.onStart(); userRequestWorker.open(); configRequestWorker.open(); final long userId = getUserId(); final TypedCache<User> userCache = userRequestWorker.getCache(); final User user = userCache.find(userId); showUserInfo(user); subscription = userCache.observeById(userId) .subscribe(new Action1<User>() { @Override public void call(User user) { showUserInfo(user); } }); } @Override public void onStop() { super.onStop(); if (subscription != null && !subscription.isUnsubscribed()) { subscription.unsubscribe(); } dismissUserInfo(); userRequestWorker.close(); configRequestWorker.close(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.user_info, menu); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (relationship != null) { switchVisibility(relationship.isSourceFollowingTarget(), R.id.action_unfollow, R.id.action_follow, menu); switchVisibility(relationship.isSourceBlockingTarget(), R.id.action_unblock, R.id.action_block, menu); switchVisibility(relationship.isSourceMutingTarget(), R.id.action_unmute, R.id.action_mute, menu); switchVisibility(relationship.isSourceWantRetweets(), R.id.action_block_retweet, R.id.action_unblock_retweet, menu); } } private static void switchVisibility(boolean cond, @IdRes int actionOnIfTrue, @IdRes int actionOffIfFalse, @NonNull Menu menu) { menu.findItem(actionOnIfTrue).setVisible(cond); menu.findItem(actionOffIfFalse).setVisible(!cond); } @Inject UserRequestWorker<TypedCache<User>> userRequestWorker; @Inject ConfigRequestWorker configRequestWorker; @Override public boolean onOptionsItemSelected(MenuItem item) { final int itemId = item.getItemId(); final long userId = getUserId(); if (itemId == R.id.action_follow) { userRequestWorker.observeCreateFriendship(userId) .doOnCompleted(new Action0() { @Override public void call() { relationship.setFollowing(true); notifyRelationshipChanged(); } }).subscribe(RequestWorkerBase.<User>nopSubscriber()); } else if (itemId == R.id.action_unfollow) { userRequestWorker.observeDestroyFriendship(userId) .doOnCompleted(new Action0() { @Override public void call() { relationship.setFollowing(false); notifyRelationshipChanged(); } }).subscribe(RequestWorkerBase.<User>nopSubscriber()); } else if (itemId == R.id.action_block) { configRequestWorker.observeCreateBlock(userId) .doOnCompleted(new Action0() { @Override public void call() { relationship.setBlocking(true); notifyRelationshipChanged(); } }).subscribe(RequestWorkerBase.<User>nopSubscriber()); } else if (itemId == R.id.action_unblock) { configRequestWorker.observeDestroyBlock(userId) .doOnCompleted(new Action0() { @Override public void call() { relationship.setBlocking(false); notifyRelationshipChanged(); } }).subscribe(RequestWorkerBase.<User>nopSubscriber()); } else if (itemId == R.id.action_block_retweet) { observeUpdateRelationship(configRequestWorker.observeBlockRetweet(relationship)); } else if (itemId == R.id.action_unblock_retweet) { observeUpdateRelationship(configRequestWorker.observeUnblockRetweet(relationship)); } else if (itemId == R.id.action_mute) { configRequestWorker.observeCreateMute(userId) .doOnCompleted(new Action0() { @Override public void call() { relationship.setMuting(true); notifyRelationshipChanged(); } }).subscribe(RequestWorkerBase.<User>nopSubscriber()); } else if (itemId == R.id.action_unmute) { configRequestWorker.observeDestroyMute(userId) .doOnCompleted(new Action0() { @Override public void call() { relationship.setMuting(false); notifyRelationshipChanged(); } }) .subscribe(RequestWorkerBase.<User>nopSubscriber()); } else if (itemId == R.id.action_r4s) { configRequestWorker.reportSpam(userId); } return false; } private void showUserInfo(User user) { if (user == null) { return; } Picasso.with(getContext()) .load(user.getProfileImageURLHttps()) .tag(LOADINGTAG_USER_INFO_IMAGES) .into(binding.userInfoUserInfoView.getIcon()); Picasso.with(getContext()) .load(user.getProfileBannerMobileURL()) .fit() .tag(LOADINGTAG_USER_INFO_IMAGES) .into(binding.userInfoUserInfoView.getBanner()); binding.userInfoUserInfoView.bindData(user); } private void dismissUserInfo() { Picasso.with(getContext()).cancelTag(LOADINGTAG_USER_INFO_IMAGES); binding.userInfoUserInfoView.getBanner().setImageDrawable(null); binding.userInfoUserInfoView.getIcon().setImageDrawable(null); } public static UserInfoFragment create(long userId) { final UserInfoFragment userInfoAppbarFragment = new UserInfoFragment(); final Bundle args = new Bundle(); args.putLong("userId", userId); userInfoAppbarFragment.setArguments(args); return userInfoAppbarFragment; } private long getUserId() { final Bundle arguments = getArguments(); return arguments.getLong("userId"); } private RelationshipImpl relationship; private void setRelationship(RelationshipImpl relationship) { this.relationship = relationship; notifyRelationshipChanged(); } private void notifyRelationshipChanged() { binding.userInfoUserInfoView.bindRelationship(relationship); getActivity().supportInvalidateOptionsMenu(); } private void observeUpdateRelationship(Observable<Relationship> relationshipObservable) { relationshipObservable.observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Relationship>() { @Override public void call(Relationship relationship) { setRelationship(new RelationshipImpl(relationship)); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { //nop } }); } private static class RelationshipImpl implements Relationship { private final Relationship relationship; RelationshipImpl(Relationship relationship) { this.relationship = relationship; this.following = relationship.isSourceFollowingTarget(); this.blocking = relationship.isSourceBlockingTarget(); this.muting = relationship.isSourceMutingTarget(); } @Override public long getSourceUserId() { return relationship.getSourceUserId(); } @Override public long getTargetUserId() { return relationship.getTargetUserId(); } private boolean blocking; @Override public boolean isSourceBlockingTarget() { return blocking; } void setBlocking(boolean blocking) { this.blocking = blocking; } private boolean muting; @Override public boolean isSourceMutingTarget() { return muting; } void setMuting(boolean muting) { this.muting = muting; } @Override public String getSourceUserScreenName() { return relationship.getSourceUserScreenName(); } @Override public String getTargetUserScreenName() { return relationship.getTargetUserScreenName(); } private boolean following; @Override public boolean isSourceFollowingTarget() { return following; } void setFollowing(boolean following) { this.following = following; } @Override public boolean isTargetFollowingSource() { return relationship.isTargetFollowingSource(); } @Override public boolean isSourceFollowedByTarget() { return relationship.isSourceFollowedByTarget(); } @Override public boolean isTargetFollowedBySource() { return following; } @Override public boolean canSourceDm() { return relationship.canSourceDm(); } @Override public boolean isSourceNotificationsEnabled() { return relationship.isSourceNotificationsEnabled(); } @Override public boolean isSourceWantRetweets() { return relationship.isSourceWantRetweets(); } @Override public RateLimitStatus getRateLimitStatus() { return relationship.getRateLimitStatus(); } @Override public int getAccessLevel() { return relationship.getAccessLevel(); } } }
refactored to update Relationship
app/src/main/java/com/freshdigitable/udonroad/UserInfoFragment.java
refactored to update Relationship
<ide><path>pp/src/main/java/com/freshdigitable/udonroad/UserInfoFragment.java <ide> <ide> import javax.inject.Inject; <ide> <del>import rx.Observable; <ide> import rx.Subscription; <del>import rx.android.schedulers.AndroidSchedulers; <ide> import rx.functions.Action0; <ide> import rx.functions.Action1; <ide> import twitter4j.RateLimitStatus; <ide> public void onActivityCreated(@Nullable Bundle savedInstanceState) { <ide> super.onActivityCreated(savedInstanceState); <ide> final long userId = getUserId(); <del> observeUpdateRelationship(twitterApi.showFriendship(userId)); <add> twitterApi.showFriendship(userId) <add> .doOnNext(updateRelationship()) <add> .subscribe(RequestWorkerBase.<Relationship>nopSubscriber()); <ide> } <ide> <ide> @Override <ide> final long userId = getUserId(); <ide> if (itemId == R.id.action_follow) { <ide> userRequestWorker.observeCreateFriendship(userId) <del> .doOnCompleted(new Action0() { <del> @Override <del> public void call() { <del> relationship.setFollowing(true); <del> notifyRelationshipChanged(); <del> } <del> }).subscribe(RequestWorkerBase.<User>nopSubscriber()); <add> .doOnCompleted(updateFollowing(true)) <add> .subscribe(RequestWorkerBase.<User>nopSubscriber()); <ide> } else if (itemId == R.id.action_unfollow) { <ide> userRequestWorker.observeDestroyFriendship(userId) <del> .doOnCompleted(new Action0() { <del> @Override <del> public void call() { <del> relationship.setFollowing(false); <del> notifyRelationshipChanged(); <del> } <del> }).subscribe(RequestWorkerBase.<User>nopSubscriber()); <add> .doOnCompleted(updateFollowing(false)) <add> .subscribe(RequestWorkerBase.<User>nopSubscriber()); <ide> } else if (itemId == R.id.action_block) { <ide> configRequestWorker.observeCreateBlock(userId) <del> .doOnCompleted(new Action0() { <del> @Override <del> public void call() { <del> relationship.setBlocking(true); <del> notifyRelationshipChanged(); <del> } <del> }).subscribe(RequestWorkerBase.<User>nopSubscriber()); <add> .doOnCompleted(updateBlocking(true)) <add> .subscribe(RequestWorkerBase.<User>nopSubscriber()); <ide> } else if (itemId == R.id.action_unblock) { <ide> configRequestWorker.observeDestroyBlock(userId) <del> .doOnCompleted(new Action0() { <del> @Override <del> public void call() { <del> relationship.setBlocking(false); <del> notifyRelationshipChanged(); <del> } <del> }).subscribe(RequestWorkerBase.<User>nopSubscriber()); <add> .doOnCompleted(updateBlocking(false)) <add> .subscribe(RequestWorkerBase.<User>nopSubscriber()); <ide> } else if (itemId == R.id.action_block_retweet) { <del> observeUpdateRelationship(configRequestWorker.observeBlockRetweet(relationship)); <add> configRequestWorker.observeBlockRetweet(relationship) <add> .doOnNext(updateRelationship()) <add> .subscribe(RequestWorkerBase.<Relationship>nopSubscriber()); <ide> } else if (itemId == R.id.action_unblock_retweet) { <del> observeUpdateRelationship(configRequestWorker.observeUnblockRetweet(relationship)); <add> configRequestWorker.observeUnblockRetweet(relationship) <add> .doOnNext(updateRelationship()) <add> .subscribe(RequestWorkerBase.<Relationship>nopSubscriber()); <ide> } else if (itemId == R.id.action_mute) { <ide> configRequestWorker.observeCreateMute(userId) <del> .doOnCompleted(new Action0() { <del> @Override <del> public void call() { <del> relationship.setMuting(true); <del> notifyRelationshipChanged(); <del> } <del> }).subscribe(RequestWorkerBase.<User>nopSubscriber()); <add> .doOnCompleted(updateMuting(true)) <add> .subscribe(RequestWorkerBase.<User>nopSubscriber()); <ide> } else if (itemId == R.id.action_unmute) { <ide> configRequestWorker.observeDestroyMute(userId) <del> .doOnCompleted(new Action0() { <del> @Override <del> public void call() { <del> relationship.setMuting(false); <del> notifyRelationshipChanged(); <del> } <del> }) <add> .doOnCompleted(updateMuting(false)) <ide> .subscribe(RequestWorkerBase.<User>nopSubscriber()); <ide> } else if (itemId == R.id.action_r4s) { <ide> configRequestWorker.reportSpam(userId); <ide> getActivity().supportInvalidateOptionsMenu(); <ide> } <ide> <del> private void observeUpdateRelationship(Observable<Relationship> relationshipObservable) { <del> relationshipObservable.observeOn(AndroidSchedulers.mainThread()) <del> .subscribe(new Action1<Relationship>() { <del> @Override <del> public void call(Relationship relationship) { <del> setRelationship(new RelationshipImpl(relationship)); <del> } <del> }, new Action1<Throwable>() { <del> @Override <del> public void call(Throwable throwable) { <del> //nop <del> } <del> }); <add> @NonNull <add> private Action0 updateFollowing(final boolean following) { <add> return new Action0() { <add> @Override <add> public void call() { <add> relationship.setFollowing(following); <add> notifyRelationshipChanged(); <add> } <add> }; <add> } <add> <add> @NonNull <add> private Action0 updateBlocking(final boolean blocking) { <add> return new Action0() { <add> @Override <add> public void call() { <add> relationship.setBlocking(blocking); <add> notifyRelationshipChanged(); <add> } <add> }; <add> } <add> <add> @NonNull <add> private Action0 updateMuting(final boolean muting) { <add> return new Action0() { <add> @Override <add> public void call() { <add> relationship.setMuting(muting); <add> notifyRelationshipChanged(); <add> } <add> }; <add> } <add> <add> private Action1<Relationship> updateRelationship() { <add> return new Action1<Relationship>() { <add> @Override <add> public void call(Relationship relationship) { <add> setRelationship(new RelationshipImpl(relationship)); <add> } <add> }; <ide> } <ide> <ide> private static class RelationshipImpl implements Relationship { <ide> this.blocking = relationship.isSourceBlockingTarget(); <ide> this.muting = relationship.isSourceMutingTarget(); <ide> } <add> private boolean blocking; <add> <add> @Override <add> public boolean isSourceBlockingTarget() { <add> return blocking; <add> } <add> <add> void setBlocking(boolean blocking) { <add> this.blocking = blocking; <add> } <add> <add> private boolean muting; <add> <add> @Override <add> public boolean isSourceMutingTarget() { <add> return muting; <add> } <add> <add> void setMuting(boolean muting) { <add> this.muting = muting; <add> } <add> <add> private boolean following; <add> <add> @Override <add> public boolean isSourceFollowingTarget() { <add> return following; <add> } <add> <add> void setFollowing(boolean following) { <add> this.following = following; <add> } <ide> <ide> @Override <ide> public long getSourceUserId() { <ide> return relationship.getTargetUserId(); <ide> } <ide> <del> private boolean blocking; <del> <del> @Override <del> public boolean isSourceBlockingTarget() { <del> return blocking; <del> } <del> <del> void setBlocking(boolean blocking) { <del> this.blocking = blocking; <del> } <del> <del> private boolean muting; <del> <del> @Override <del> public boolean isSourceMutingTarget() { <del> return muting; <del> } <del> <del> void setMuting(boolean muting) { <del> this.muting = muting; <del> } <del> <ide> @Override <ide> public String getSourceUserScreenName() { <ide> return relationship.getSourceUserScreenName(); <ide> return relationship.getTargetUserScreenName(); <ide> } <ide> <del> private boolean following; <del> <del> @Override <del> public boolean isSourceFollowingTarget() { <del> return following; <del> } <del> <del> void setFollowing(boolean following) { <del> this.following = following; <del> } <del> <ide> @Override <ide> public boolean isTargetFollowingSource() { <ide> return relationship.isTargetFollowingSource();
Java
apache-2.0
fad1c6594554975e40cd5ac018d0f4c0813b1d5c
0
mtransitapps/mtransit-for-android,mtransitapps/mtransit-for-android,mtransitapps/mtransit-for-android
package org.mtransit.android.ui.fragment; import java.util.ArrayList; import org.mtransit.android.R; import org.mtransit.android.commons.BundleUtils; import org.mtransit.android.commons.MTLog; import org.mtransit.android.commons.PreferenceUtils; import org.mtransit.android.commons.api.SupportFactory; import org.mtransit.android.commons.data.Route; import org.mtransit.android.commons.ui.widget.MTArrayAdapter; import org.mtransit.android.data.AgencyProperties; import org.mtransit.android.data.DataSourceProvider; import org.mtransit.android.data.JPaths; import org.mtransit.android.data.POIManager; import org.mtransit.android.task.RTSAgencyRoutesLoader; import org.mtransit.android.ui.MainActivity; import org.mtransit.android.ui.view.MTJPathsView; import org.mtransit.android.ui.view.MTOnItemClickListener; import org.mtransit.android.util.LoaderUtils; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.StateListDrawable; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v7.widget.SwitchCompat; import android.text.TextUtils; import android.util.StateSet; 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.ViewStub; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.CompoundButton; import android.widget.TextView; public class RTSAgencyRoutesFragment extends MTFragmentV4 implements AgencyTypeFragment.AgencyFragment, LoaderManager.LoaderCallbacks<ArrayList<Route>>, AdapterView.OnItemClickListener, CompoundButton.OnCheckedChangeListener { private static final String TAG = RTSAgencyRoutesFragment.class.getSimpleName(); private String tag = TAG; @Override public String getLogTag() { return this.tag; } public void setLogTag(String tag) { this.tag = TAG + "-" + tag; } private static final String EXTRA_AGENCY_AUTHORITY = "extra_agency_authority"; private static final String EXTRA_COLOR_INT = "extra_color_int"; private static final String EXTRA_FRAGMENT_POSITION = "extra_fragment_position"; private static final String EXTRA_LAST_VISIBLE_FRAGMENT_POSITION = "extra_last_visible_fragment_position"; public static RTSAgencyRoutesFragment newInstance(int fragmentPosition, int lastVisibleFragmentPosition, String agencyAuthority, Integer optColorInt) { RTSAgencyRoutesFragment f = new RTSAgencyRoutesFragment(); Bundle args = new Bundle(); args.putString(EXTRA_AGENCY_AUTHORITY, agencyAuthority); f.authority = agencyAuthority; if (optColorInt != null) { args.putInt(EXTRA_COLOR_INT, optColorInt); f.colorInt = optColorInt; } if (fragmentPosition >= 0) { args.putInt(EXTRA_FRAGMENT_POSITION, fragmentPosition); f.fragmentPosition = fragmentPosition; } if (lastVisibleFragmentPosition >= 0) { args.putInt(EXTRA_LAST_VISIBLE_FRAGMENT_POSITION, lastVisibleFragmentPosition); f.lastVisibleFragmentPosition = lastVisibleFragmentPosition; } f.setArguments(args); return f; } private int fragmentPosition = -1; private int lastVisibleFragmentPosition = -1; private boolean fragmentVisible = false; private RTSAgencyRouteArrayAdapter adapter; private String emptyText = null; private String authority; private Integer colorInt; @Override public String getAgencyAuthority() { return this.authority; } @Override public void onAttach(Activity activity) { super.onAttach(activity); initAdapters(activity); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); restoreInstanceState(savedInstanceState, getArguments()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_rts_agency_routes, container, false); setupView(view); return view; } @Override public void onSaveInstanceState(Bundle outState) { if (!TextUtils.isEmpty(this.authority)) { outState.putString(EXTRA_AGENCY_AUTHORITY, this.authority); } if (this.colorInt != null) { outState.putInt(EXTRA_COLOR_INT, this.colorInt); } if (this.fragmentPosition >= 0) { outState.putInt(EXTRA_FRAGMENT_POSITION, this.fragmentPosition); } if (this.lastVisibleFragmentPosition >= 0) { outState.putInt(EXTRA_LAST_VISIBLE_FRAGMENT_POSITION, this.lastVisibleFragmentPosition); } super.onSaveInstanceState(outState); } private void restoreInstanceState(Bundle... bundles) { String newAuthority = BundleUtils.getString(EXTRA_AGENCY_AUTHORITY, bundles); if (!TextUtils.isEmpty(newAuthority) && !newAuthority.equals(this.authority)) { this.authority = newAuthority; } Integer newColorInt = BundleUtils.getInt(EXTRA_COLOR_INT, bundles); if (newColorInt != null) { this.colorInt = newColorInt; } Integer fragmentPosition = BundleUtils.getInt(EXTRA_FRAGMENT_POSITION, bundles); if (fragmentPosition != null) { if (fragmentPosition >= 0) { this.fragmentPosition = fragmentPosition; } else { this.fragmentPosition = -1; } } Integer newLastVisibleFragmentPosition = BundleUtils.getInt(EXTRA_LAST_VISIBLE_FRAGMENT_POSITION, bundles); if (newLastVisibleFragmentPosition != null) { if (newLastVisibleFragmentPosition >= 0) { this.lastVisibleFragmentPosition = newLastVisibleFragmentPosition; } else { this.lastVisibleFragmentPosition = -1; } } this.adapter.setAuthority(this.authority); } private void initAdapters(Activity activity) { this.adapter = new RTSAgencyRouteArrayAdapter(activity, this.authority, isShowingListInsteadOfGrid()); } private void setupView(View view) { if (view == null) { return; } AbsListView absListView = (AbsListView) view.findViewById(isShowingListInsteadOfGrid() ? R.id.list : R.id.grid); linkAdapterWithListView(absListView); absListView.setOnItemClickListener(this); switchView(view); } private void linkAdapterWithListView(View view) { if (view == null || this.adapter == null) { return; } View listView = view.findViewById(isShowingListInsteadOfGrid() ? R.id.list : R.id.grid); if (listView != null) { ((AbsListView) listView).setAdapter(this.adapter); } } private Boolean showingListInsteadOfGrid = null; private boolean isShowingListInsteadOfGrid() { if (this.showingListInsteadOfGrid == null) { this.showingListInsteadOfGrid = isShowingListInsteadOfGridPref(); if (!TextUtils.isEmpty(this.authority)) { PreferenceUtils.savePrefDefault(getActivity(), PreferenceUtils.getPREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID(this.authority), this.showingListInsteadOfGrid, true); } } return this.showingListInsteadOfGrid; } private void checkIfShowingListInsteadOfGridChanged() { if (this.showingListInsteadOfGrid == null) { return; } boolean newShowingListInsteadOfGrid = isShowingListInsteadOfGridPref(); if (newShowingListInsteadOfGrid != this.showingListInsteadOfGrid) { setShowingListInsteadOfGrid(newShowingListInsteadOfGrid); } } private boolean isShowingListInsteadOfGridPref() { boolean showingListInsteadOfGridLastSet = PreferenceUtils.getPrefDefault(getActivity(), PreferenceUtils.PREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID_LAST_SET, PreferenceUtils.PREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID_DEFAULT); if (TextUtils.isEmpty(this.authority)) { return showingListInsteadOfGridLastSet; } return PreferenceUtils.getPrefDefault(getActivity(), PreferenceUtils.getPREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID(this.authority), showingListInsteadOfGridLastSet); } private void setShowingListInsteadOfGrid(boolean newShowingListInsteadOfGrid) { if (this.showingListInsteadOfGrid != null && this.showingListInsteadOfGrid == newShowingListInsteadOfGrid) { return; // nothing changed } this.showingListInsteadOfGrid = newShowingListInsteadOfGrid; // switching to grid PreferenceUtils.savePrefDefault(getActivity(), PreferenceUtils.PREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID_LAST_SET, this.showingListInsteadOfGrid, false); if (!TextUtils.isEmpty(this.authority)) { PreferenceUtils.savePrefDefault(getActivity(), PreferenceUtils.getPREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID(this.authority), this.showingListInsteadOfGrid, false); } if (this.adapter != null) { this.adapter.seShowingListInsteadOfGrid(this.showingListInsteadOfGrid); this.adapter.notifyDataSetChanged(); setupView(getView()); switchView(getView()); } updateListGridToggleMenuItem(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { MTOnItemClickListener.onItemClickS(parent, view, position, id, new MTOnItemClickListener() { @Override public void onItemClickMT(AdapterView<?> parent, View view, int position, long id) { Activity activity = getActivity(); if (activity == null) { return; } if (TextUtils.isEmpty(RTSAgencyRoutesFragment.this.authority)) { return; } Route selectedRoute = RTSAgencyRoutesFragment.this.adapter == null ? null : RTSAgencyRoutesFragment.this.adapter.getItem(position); if (selectedRoute == null) { return; } ((MainActivity) activity).addFragmentToStack(RTSRouteFragment.newInstance(RTSAgencyRoutesFragment.this.authority, selectedRoute.getId(), null, null, selectedRoute)); } }); } @Override public void setFragmentPosition(int fragmentPosition) { this.fragmentPosition = fragmentPosition; setFragmentVisibleAtPosition(this.lastVisibleFragmentPosition); // force reset visibility } @Override public void setFragmentVisibleAtPosition(int visibleFragmentPosition) { if (this.lastVisibleFragmentPosition == visibleFragmentPosition // && (// (this.fragmentPosition == visibleFragmentPosition && this.fragmentVisible) // || // (this.fragmentPosition != visibleFragmentPosition && !this.fragmentVisible) // ) // ) { return; } this.lastVisibleFragmentPosition = visibleFragmentPosition; if (this.fragmentPosition < 0) { return; } if (this.fragmentPosition == visibleFragmentPosition) { onFragmentVisible(); } else { onFragmentInvisible(); } } private void onFragmentInvisible() { if (!this.fragmentVisible) { return; // already invisible } this.fragmentVisible = false; } @Override public boolean isFragmentVisible() { return this.fragmentVisible; } private void onFragmentVisible() { if (this.fragmentVisible) { return; // already visible } if (!isResumed()) { return; } this.fragmentVisible = true; switchView(getView()); if (this.adapter == null || !this.adapter.isInitialized()) { LoaderUtils.restartLoader(this, ROUTES_LOADER, null, this); } checkIfShowingListInsteadOfGridChanged(); getActivity().supportInvalidateOptionsMenu(); // initialize action bar list/grid switch icon updateListGridToggleMenuItem(); } private static final int ROUTES_LOADER = 0; @Override public Loader<ArrayList<Route>> onCreateLoader(int id, Bundle args) { switch (id) { case ROUTES_LOADER: if (TextUtils.isEmpty(this.authority) || getActivity() == null) { return null; } return new RTSAgencyRoutesLoader(getActivity(), this.authority); default: MTLog.w(this, "Loader ID '%s' unknown!", id); return null; } } @Override public void onLoaderReset(Loader<ArrayList<Route>> loader) { if (this.adapter != null) { this.adapter.clear(); } } @Override public void onLoadFinished(Loader<ArrayList<Route>> loader, ArrayList<Route> data) { this.adapter.setRoutes(data); switchView(getView()); } @Override public void onPause() { super.onPause(); onFragmentInvisible(); } @Override public void onResume() { super.onResume(); if (this.fragmentPosition >= 0 && this.fragmentPosition == this.lastVisibleFragmentPosition) { onFragmentVisible(); } // ELSE would be call later } @Override public void onDestroy() { super.onDestroy(); if (this.adapter != null) { this.adapter.onDestroy(); } } private void switchView(View view) { if (view == null) { return; } if (this.adapter == null || !this.adapter.isInitialized()) { showLoading(view); } else if (this.adapter.getCount() == 0) { showEmpty(view); } else { showList(view); } } private void showList(View view) { if (view.findViewById(R.id.loading) != null) { // IF inflated/present DO view.findViewById(R.id.loading).setVisibility(View.GONE); // hide } if (view.findViewById(R.id.empty) != null) { // IF inflated/present DO view.findViewById(R.id.empty).setVisibility(View.GONE); // hide } view.findViewById(isShowingListInsteadOfGrid() ? R.id.grid : R.id.list).setVisibility(View.GONE); // hide view.findViewById(isShowingListInsteadOfGrid() ? R.id.list : R.id.grid).setVisibility(View.VISIBLE); // show } private void showLoading(View view) { if (view.findViewById(R.id.list) != null) { // IF inflated/present DO view.findViewById(R.id.list).setVisibility(View.GONE); // hide } if (view.findViewById(R.id.grid) != null) { // IF inflated/present DO view.findViewById(R.id.grid).setVisibility(View.GONE); // hide } if (view.findViewById(R.id.empty) != null) { // IF inflated/present DO view.findViewById(R.id.empty).setVisibility(View.GONE); // hide } view.findViewById(R.id.loading).setVisibility(View.VISIBLE); // show } private void showEmpty(View view) { if (view.findViewById(R.id.list) != null) { // IF inflated/present DO view.findViewById(R.id.list).setVisibility(View.GONE); // hide } if (view.findViewById(R.id.grid) != null) { // IF inflated/present DO view.findViewById(R.id.grid).setVisibility(View.GONE); // hide } if (view.findViewById(R.id.loading) != null) { // IF inflated/present DO view.findViewById(R.id.loading).setVisibility(View.GONE); // hide } if (view.findViewById(R.id.empty) == null) { // IF NOT present/inflated DO ((ViewStub) view.findViewById(R.id.empty_stub)).inflate(); // inflate } if (!TextUtils.isEmpty(this.emptyText)) { ((TextView) view.findViewById(R.id.empty_text)).setText(this.emptyText); } view.findViewById(R.id.empty).setVisibility(View.VISIBLE); // show } private MenuItem listGridToggleMenuItem; private SwitchCompat listGridSwitchMenuItem; @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); if (this.fragmentVisible) { if (menu.findItem(R.id.menu_toggle_list_grid) == null) { inflater.inflate(R.menu.menu_rts_agency_routes, menu); } this.listGridToggleMenuItem = menu.findItem(R.id.menu_toggle_list_grid); this.listGridSwitchMenuItem = (SwitchCompat) this.listGridToggleMenuItem.getActionView().findViewById(R.id.action_bar_switch_list_grid); this.listGridSwitchMenuItem.setThumbDrawable(getListGridToggleSelector()); } else { if (this.listGridSwitchMenuItem != null) { this.listGridSwitchMenuItem.setOnCheckedChangeListener(null); this.listGridSwitchMenuItem.setVisibility(View.GONE); this.listGridSwitchMenuItem = null; } if (this.listGridToggleMenuItem != null) { this.listGridToggleMenuItem.setVisible(false); this.listGridToggleMenuItem = null; } } updateListGridToggleMenuItem(); } private StateListDrawable listGridToggleSelector = null; @NonNull private StateListDrawable getListGridToggleSelector() { if (listGridToggleSelector == null) { listGridToggleSelector = new StateListDrawable(); LayerDrawable listLayerDrawable = (LayerDrawable) SupportFactory.get().getResourcesDrawable(getResources(), R.drawable.switch_thumb_list, null); GradientDrawable listOvalShape = (GradientDrawable) listLayerDrawable.findDrawableByLayerId(R.id.switch_list_oval_shape); if (this.colorInt != null) { listOvalShape.setColor(this.colorInt); } listGridToggleSelector.addState(new int[]{android.R.attr.state_checked}, listLayerDrawable); LayerDrawable gridLayerDrawable = (LayerDrawable) SupportFactory.get().getResourcesDrawable(getResources(), R.drawable.switch_thumb_grid, null); GradientDrawable gridOvalShape = (GradientDrawable) gridLayerDrawable.findDrawableByLayerId(R.id.switch_grid_oval_shape); if (this.colorInt != null) { gridOvalShape.setColor(this.colorInt); } listGridToggleSelector.addState(StateSet.WILD_CARD, gridLayerDrawable); } return this.listGridToggleSelector; } private void updateListGridToggleMenuItem() { if (!this.fragmentVisible) { return; } if (this.listGridToggleMenuItem == null) { return; } if (this.listGridSwitchMenuItem == null) { return; } this.listGridSwitchMenuItem.setChecked(isShowingListInsteadOfGrid()); this.listGridSwitchMenuItem.setOnCheckedChangeListener(this); this.listGridSwitchMenuItem.setVisibility(View.VISIBLE); this.listGridToggleMenuItem.setVisible(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (!this.fragmentVisible) { return false; // not handled } switch (item.getItemId()) { case R.id.menu_toggle_list_grid: setShowingListInsteadOfGrid(!isShowingListInsteadOfGrid()); // switching return true; // handled } return super.onOptionsItemSelected(item); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (!this.fragmentVisible) { return; } if (buttonView.getId() == R.id.action_bar_switch_list_grid) { setShowingListInsteadOfGrid(isChecked); } } private static class RTSAgencyRouteArrayAdapter extends MTArrayAdapter<Route> implements MTLog.Loggable { private static final String TAG = RTSAgencyRouteArrayAdapter.class.getSimpleName(); @Override public String getLogTag() { return TAG; } private ArrayList<Route> routes = null; private LayoutInflater layoutInflater; private String authority; private boolean showingListInsteadOfGrid; public RTSAgencyRouteArrayAdapter(Context context, String authority, boolean showingListInsteadOfGrid) { super(context, -1); this.layoutInflater = LayoutInflater.from(context); this.authority = authority; this.showingListInsteadOfGrid = showingListInsteadOfGrid; } public void seShowingListInsteadOfGrid(boolean showingListInsteadOfGrid) { this.showingListInsteadOfGrid = showingListInsteadOfGrid; } public void setAuthority(String authority) { this.authority = authority; } public void setRoutes(ArrayList<Route> routes) { this.routes = routes; } public boolean isInitialized() { return this.routes != null; } @Override public int getCount() { return this.routes == null ? 0 : this.routes.size(); } @Override public int getItemViewType(int position) { return this.showingListInsteadOfGrid ? 0 : 1; } @Override public int getViewTypeCount() { return 2; } @Override public Route getItem(int position) { return this.routes == null ? null : this.routes.get(position); } @Override public View getView(int position, View convertView, ViewGroup parent) { return getRouteView(position, convertView, parent); } private View getRouteView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = this.layoutInflater.inflate(this.showingListInsteadOfGrid ? R.layout.layout_rts_route_list_item : R.layout.layout_rts_route_grid_item, parent, false); RouteViewHolder holder = new RouteViewHolder(); holder.routeFL = convertView.findViewById(R.id.route); holder.routeShortNameTv = (TextView) convertView.findViewById(R.id.route_short_name); holder.routeTypeImg = (MTJPathsView) convertView.findViewById(R.id.route_type_img); holder.routeLongNameTv = (TextView) convertView.findViewById(R.id.route_long_name); convertView.setTag(holder); } updateRouteView(position, convertView); return convertView; } private View updateRouteView(int position, View convertView) { Route route = getItem(position); if (convertView == null) { return null; } RouteViewHolder holder = (RouteViewHolder) convertView.getTag(); if (route == null) { holder.routeFL.setVisibility(View.GONE); } else { if (TextUtils.isEmpty(route.getShortName())) { holder.routeShortNameTv.setVisibility(View.INVISIBLE); if (holder.routeTypeImg.hasPaths() && this.authority.equals(holder.routeTypeImg.getTag())) { holder.routeTypeImg.setVisibility(View.VISIBLE); } else { AgencyProperties agency = DataSourceProvider.get(getContext()).getAgency(getContext(), this.authority); JPaths rtsRouteLogo = agency == null ? null : agency.getLogo(getContext()); if (rtsRouteLogo != null) { holder.routeTypeImg.setJSON(rtsRouteLogo); holder.routeTypeImg.setTag(this.authority); holder.routeTypeImg.setVisibility(View.VISIBLE); } else { holder.routeTypeImg.setVisibility(View.GONE); } } } else { holder.routeTypeImg.setVisibility(View.GONE); holder.routeShortNameTv.setText(Route.setShortNameSize(route.getShortName())); holder.routeShortNameTv.setVisibility(View.VISIBLE); } if (holder.routeLongNameTv != null) { if (TextUtils.isEmpty(route.getLongName())) { holder.routeLongNameTv.setVisibility(View.GONE); } else { holder.routeLongNameTv.setText(route.getLongName()); holder.routeLongNameTv.setVisibility(View.VISIBLE); } } holder.routeFL.setBackgroundColor(POIManager.getRouteColor(getContext(), route, this.authority, Color.BLACK)); holder.routeFL.setVisibility(View.VISIBLE); } return convertView; } public void onDestroy() { if (this.routes != null) { this.routes.clear(); this.routes = null; } } public static class RouteViewHolder { TextView routeShortNameTv; View routeFL; MTJPathsView routeTypeImg; TextView routeLongNameTv; } } }
src/org/mtransit/android/ui/fragment/RTSAgencyRoutesFragment.java
package org.mtransit.android.ui.fragment; import java.util.ArrayList; import org.mtransit.android.R; import org.mtransit.android.commons.BundleUtils; import org.mtransit.android.commons.MTLog; import org.mtransit.android.commons.PreferenceUtils; import org.mtransit.android.commons.api.SupportFactory; import org.mtransit.android.commons.data.Route; import org.mtransit.android.commons.ui.widget.MTArrayAdapter; import org.mtransit.android.data.AgencyProperties; import org.mtransit.android.data.DataSourceProvider; import org.mtransit.android.data.JPaths; import org.mtransit.android.data.POIManager; import org.mtransit.android.task.RTSAgencyRoutesLoader; import org.mtransit.android.ui.MainActivity; import org.mtransit.android.ui.view.MTJPathsView; import org.mtransit.android.ui.view.MTOnItemClickListener; import org.mtransit.android.util.LoaderUtils; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.StateListDrawable; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v7.widget.SwitchCompat; import android.text.TextUtils; import android.util.StateSet; 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.ViewStub; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.CompoundButton; import android.widget.TextView; public class RTSAgencyRoutesFragment extends MTFragmentV4 implements AgencyTypeFragment.AgencyFragment, LoaderManager.LoaderCallbacks<ArrayList<Route>>, AdapterView.OnItemClickListener, CompoundButton.OnCheckedChangeListener { private static final String TAG = RTSAgencyRoutesFragment.class.getSimpleName(); private String tag = TAG; @Override public String getLogTag() { return this.tag; } public void setLogTag(String tag) { this.tag = TAG + "-" + tag; } private static final String EXTRA_AGENCY_AUTHORITY = "extra_agency_authority"; private static final String EXTRA_COLOR_INT = "extra_color_int"; private static final String EXTRA_FRAGMENT_POSITION = "extra_fragment_position"; private static final String EXTRA_LAST_VISIBLE_FRAGMENT_POSITION = "extra_last_visible_fragment_position"; public static RTSAgencyRoutesFragment newInstance(int fragmentPosition, int lastVisibleFragmentPosition, String agencyAuthority, Integer optColorInt) { RTSAgencyRoutesFragment f = new RTSAgencyRoutesFragment(); Bundle args = new Bundle(); args.putString(EXTRA_AGENCY_AUTHORITY, agencyAuthority); f.authority = agencyAuthority; if (optColorInt != null) { args.putInt(EXTRA_COLOR_INT, optColorInt); f.colorInt = optColorInt; } if (fragmentPosition >= 0) { args.putInt(EXTRA_FRAGMENT_POSITION, fragmentPosition); f.fragmentPosition = fragmentPosition; } if (lastVisibleFragmentPosition >= 0) { args.putInt(EXTRA_LAST_VISIBLE_FRAGMENT_POSITION, lastVisibleFragmentPosition); f.lastVisibleFragmentPosition = lastVisibleFragmentPosition; } f.setArguments(args); return f; } private int fragmentPosition = -1; private int lastVisibleFragmentPosition = -1; private boolean fragmentVisible = false; private RTSAgencyRouteArrayAdapter adapter; private String emptyText = null; private String authority; private Integer colorInt; @Override public String getAgencyAuthority() { return this.authority; } @Override public void onAttach(Activity activity) { super.onAttach(activity); initAdapters(activity); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); restoreInstanceState(savedInstanceState, getArguments()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_rts_agency_routes, container, false); setupView(view); return view; } @Override public void onSaveInstanceState(Bundle outState) { if (!TextUtils.isEmpty(this.authority)) { outState.putString(EXTRA_AGENCY_AUTHORITY, this.authority); } if (this.colorInt != null) { outState.putInt(EXTRA_COLOR_INT, this.colorInt); } if (this.fragmentPosition >= 0) { outState.putInt(EXTRA_FRAGMENT_POSITION, this.fragmentPosition); } if (this.lastVisibleFragmentPosition >= 0) { outState.putInt(EXTRA_LAST_VISIBLE_FRAGMENT_POSITION, this.lastVisibleFragmentPosition); } super.onSaveInstanceState(outState); } private void restoreInstanceState(Bundle... bundles) { String newAuthority = BundleUtils.getString(EXTRA_AGENCY_AUTHORITY, bundles); if (!TextUtils.isEmpty(newAuthority) && !newAuthority.equals(this.authority)) { this.authority = newAuthority; } Integer newColorInt = BundleUtils.getInt(EXTRA_COLOR_INT, bundles); if (newColorInt != null) { this.colorInt = newColorInt; } Integer fragmentPosition = BundleUtils.getInt(EXTRA_FRAGMENT_POSITION, bundles); if (fragmentPosition != null) { if (fragmentPosition >= 0) { this.fragmentPosition = fragmentPosition; } else { this.fragmentPosition = -1; } } Integer newLastVisibleFragmentPosition = BundleUtils.getInt(EXTRA_LAST_VISIBLE_FRAGMENT_POSITION, bundles); if (newLastVisibleFragmentPosition != null) { if (newLastVisibleFragmentPosition >= 0) { this.lastVisibleFragmentPosition = newLastVisibleFragmentPosition; } else { this.lastVisibleFragmentPosition = -1; } } this.adapter.setAuthority(this.authority); } private void initAdapters(Activity activity) { this.adapter = new RTSAgencyRouteArrayAdapter(activity, this.authority, isShowingListInsteadOfGrid()); } private void setupView(View view) { if (view == null) { return; } AbsListView absListView = (AbsListView) view.findViewById(isShowingListInsteadOfGrid() ? R.id.list : R.id.grid); linkAdapterWithListView(absListView); absListView.setOnItemClickListener(this); switchView(view); } private void linkAdapterWithListView(View view) { if (view == null || this.adapter == null) { return; } View listView = view.findViewById(isShowingListInsteadOfGrid() ? R.id.list : R.id.grid); if (listView != null) { ((AbsListView) listView).setAdapter(this.adapter); } } private Boolean showingListInsteadOfGrid = null; private boolean isShowingListInsteadOfGrid() { if (this.showingListInsteadOfGrid == null) { this.showingListInsteadOfGrid = isShowingListInsteadOfGridPref(); if (!TextUtils.isEmpty(this.authority)) { PreferenceUtils.savePrefDefault(getActivity(), PreferenceUtils.getPREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID(this.authority), this.showingListInsteadOfGrid, true); } } return this.showingListInsteadOfGrid; } private void checkIfShowingListInsteadOfGridChanged() { if (this.showingListInsteadOfGrid == null) { return; } boolean newShowingListInsteadOfGrid = isShowingListInsteadOfGridPref(); if (newShowingListInsteadOfGrid != this.showingListInsteadOfGrid) { setShowingListInsteadOfGrid(newShowingListInsteadOfGrid); } } private boolean isShowingListInsteadOfGridPref() { boolean showingListInsteadOfGridLastSet = PreferenceUtils.getPrefDefault(getActivity(), PreferenceUtils.PREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID_LAST_SET, PreferenceUtils.PREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID_DEFAULT); if (TextUtils.isEmpty(this.authority)) { return showingListInsteadOfGridLastSet; } return PreferenceUtils.getPrefDefault(getActivity(), PreferenceUtils.getPREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID(this.authority), showingListInsteadOfGridLastSet); } private void setShowingListInsteadOfGrid(boolean newShowingListInsteadOfGrid) { if (this.showingListInsteadOfGrid != null && this.showingListInsteadOfGrid == newShowingListInsteadOfGrid) { return; // nothing changed } this.showingListInsteadOfGrid = newShowingListInsteadOfGrid; // switching to grid PreferenceUtils.savePrefDefault(getActivity(), PreferenceUtils.PREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID_LAST_SET, this.showingListInsteadOfGrid, false); if (!TextUtils.isEmpty(this.authority)) { PreferenceUtils.savePrefDefault(getActivity(), PreferenceUtils.getPREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID(this.authority), this.showingListInsteadOfGrid, false); } if (this.adapter != null) { this.adapter.seShowingListInsteadOfGrid(this.showingListInsteadOfGrid); this.adapter.notifyDataSetChanged(); setupView(getView()); switchView(getView()); } updateListGridToggleMenuItem(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { MTOnItemClickListener.onItemClickS(parent, view, position, id, new MTOnItemClickListener() { @Override public void onItemClickMT(AdapterView<?> parent, View view, int position, long id) { Activity activity = getActivity(); if (activity == null) { return; } if (TextUtils.isEmpty(RTSAgencyRoutesFragment.this.authority)) { return; } Route selectedRoute = RTSAgencyRoutesFragment.this.adapter == null ? null : RTSAgencyRoutesFragment.this.adapter.getItem(position); if (selectedRoute == null) { return; } ((MainActivity) activity).addFragmentToStack(RTSRouteFragment.newInstance(RTSAgencyRoutesFragment.this.authority, selectedRoute.getId(), null, null, selectedRoute)); } }); } @Override public void setFragmentPosition(int fragmentPosition) { this.fragmentPosition = fragmentPosition; setFragmentVisibleAtPosition(this.lastVisibleFragmentPosition); // force reset visibility } @Override public void setFragmentVisibleAtPosition(int visibleFragmentPosition) { if (this.lastVisibleFragmentPosition == visibleFragmentPosition // && (// (this.fragmentPosition == visibleFragmentPosition && this.fragmentVisible) // || // (this.fragmentPosition != visibleFragmentPosition && !this.fragmentVisible) // ) // ) { return; } this.lastVisibleFragmentPosition = visibleFragmentPosition; if (this.fragmentPosition < 0) { return; } if (this.fragmentPosition == visibleFragmentPosition) { onFragmentVisible(); } else { onFragmentInvisible(); } } private void onFragmentInvisible() { if (!this.fragmentVisible) { return; // already invisible } this.fragmentVisible = false; } @Override public boolean isFragmentVisible() { return this.fragmentVisible; } private void onFragmentVisible() { if (this.fragmentVisible) { return; // already visible } if (!isResumed()) { return; } this.fragmentVisible = true; switchView(getView()); if (this.adapter == null || !this.adapter.isInitialized()) { LoaderUtils.restartLoader(this, ROUTES_LOADER, null, this); } checkIfShowingListInsteadOfGridChanged(); getActivity().supportInvalidateOptionsMenu(); // initialize action bar list/grid switch icon updateListGridToggleMenuItem(); } private static final int ROUTES_LOADER = 0; @Override public Loader<ArrayList<Route>> onCreateLoader(int id, Bundle args) { switch (id) { case ROUTES_LOADER: if (TextUtils.isEmpty(this.authority) || getActivity() == null) { return null; } return new RTSAgencyRoutesLoader(getActivity(), this.authority); default: MTLog.w(this, "Loader ID '%s' unknown!", id); return null; } } @Override public void onLoaderReset(Loader<ArrayList<Route>> loader) { if (this.adapter != null) { this.adapter.clear(); } } @Override public void onLoadFinished(Loader<ArrayList<Route>> loader, ArrayList<Route> data) { this.adapter.setRoutes(data); switchView(getView()); } @Override public void onPause() { super.onPause(); onFragmentInvisible(); } @Override public void onResume() { super.onResume(); if (this.fragmentPosition >= 0 && this.fragmentPosition == this.lastVisibleFragmentPosition) { onFragmentVisible(); } // ELSE would be call later } @Override public void onDestroy() { super.onDestroy(); if (this.adapter != null) { this.adapter.onDestroy(); } } private void switchView(View view) { if (view == null) { return; } if (this.adapter == null || !this.adapter.isInitialized()) { showLoading(view); } else if (this.adapter.getCount() == 0) { showEmpty(view); } else { showList(view); } } private void showList(View view) { if (view.findViewById(R.id.loading) != null) { // IF inflated/present DO view.findViewById(R.id.loading).setVisibility(View.GONE); // hide } if (view.findViewById(R.id.empty) != null) { // IF inflated/present DO view.findViewById(R.id.empty).setVisibility(View.GONE); // hide } view.findViewById(isShowingListInsteadOfGrid() ? R.id.grid : R.id.list).setVisibility(View.GONE); // hide view.findViewById(isShowingListInsteadOfGrid() ? R.id.list : R.id.grid).setVisibility(View.VISIBLE); // show } private void showLoading(View view) { if (view.findViewById(R.id.list) != null) { // IF inflated/present DO view.findViewById(R.id.list).setVisibility(View.GONE); // hide } if (view.findViewById(R.id.grid) != null) { // IF inflated/present DO view.findViewById(R.id.grid).setVisibility(View.GONE); // hide } if (view.findViewById(R.id.empty) != null) { // IF inflated/present DO view.findViewById(R.id.empty).setVisibility(View.GONE); // hide } view.findViewById(R.id.loading).setVisibility(View.VISIBLE); // show } private void showEmpty(View view) { if (view.findViewById(R.id.list) != null) { // IF inflated/present DO view.findViewById(R.id.list).setVisibility(View.GONE); // hide } if (view.findViewById(R.id.grid) != null) { // IF inflated/present DO view.findViewById(R.id.grid).setVisibility(View.GONE); // hide } if (view.findViewById(R.id.loading) != null) { // IF inflated/present DO view.findViewById(R.id.loading).setVisibility(View.GONE); // hide } if (view.findViewById(R.id.empty) == null) { // IF NOT present/inflated DO ((ViewStub) view.findViewById(R.id.empty_stub)).inflate(); // inflate } if (!TextUtils.isEmpty(this.emptyText)) { ((TextView) view.findViewById(R.id.empty_text)).setText(this.emptyText); } view.findViewById(R.id.empty).setVisibility(View.VISIBLE); // show } private MenuItem listGridToggleMenuItem; @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); if (this.fragmentVisible) { if (menu.findItem(R.id.menu_toggle_list_grid) == null) { inflater.inflate(R.menu.menu_rts_agency_routes, menu); } this.listGridToggleMenuItem = menu.findItem(R.id.menu_toggle_list_grid); this.listGridSwitchMenuItem = (SwitchCompat) this.listGridToggleMenuItem.getActionView().findViewById(R.id.action_bar_switch_list_grid); this.listGridSwitchMenuItem.setThumbDrawable(getListGridToggleSelector()); } else { if (this.listGridSwitchMenuItem != null) { this.listGridSwitchMenuItem.setOnCheckedChangeListener(null); this.listGridSwitchMenuItem.setVisibility(View.GONE); this.listGridSwitchMenuItem = null; } if (this.listGridToggleMenuItem != null) { this.listGridToggleMenuItem.setVisible(false); this.listGridToggleMenuItem = null; } } updateListGridToggleMenuItem(); } private StateListDrawable listGridToggleSelector = null; @NonNull private StateListDrawable getListGridToggleSelector() { if (listGridToggleSelector == null) { listGridToggleSelector = new StateListDrawable(); LayerDrawable listLayerDrawable = (LayerDrawable) SupportFactory.get().getResourcesDrawable(getResources(), R.drawable.switch_thumb_list, null); GradientDrawable listOvalShape = (GradientDrawable) listLayerDrawable.findDrawableByLayerId(R.id.switch_list_oval_shape); if (this.colorInt != null) { listOvalShape.setColor(this.colorInt); } listGridToggleSelector.addState(new int[]{android.R.attr.state_checked}, listLayerDrawable); LayerDrawable gridLayerDrawable = (LayerDrawable) SupportFactory.get().getResourcesDrawable(getResources(), R.drawable.switch_thumb_grid, null); GradientDrawable gridOvalShape = (GradientDrawable) gridLayerDrawable.findDrawableByLayerId(R.id.switch_grid_oval_shape); if (this.colorInt != null) { gridOvalShape.setColor(this.colorInt); } listGridToggleSelector.addState(StateSet.WILD_CARD, gridLayerDrawable); } return this.listGridToggleSelector; } private void updateListGridToggleMenuItem() { if (!this.fragmentVisible) { return; } if (this.listGridToggleMenuItem == null) { return; } if (this.listGridSwitchMenuItem == null) { return; } this.listGridSwitchMenuItem.setChecked(isShowingListInsteadOfGrid()); this.listGridSwitchMenuItem.setOnCheckedChangeListener(this); this.listGridSwitchMenuItem.setVisibility(View.VISIBLE); this.listGridToggleMenuItem.setVisible(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (!this.fragmentVisible) { return false; // not handled } switch (item.getItemId()) { case R.id.menu_toggle_list_grid: setShowingListInsteadOfGrid(!isShowingListInsteadOfGrid()); // switching return true; // handled } return super.onOptionsItemSelected(item); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (!this.fragmentVisible) { return; } if (buttonView.getId() == R.id.action_bar_switch_list_grid) { setShowingListInsteadOfGrid(isChecked); } } private static class RTSAgencyRouteArrayAdapter extends MTArrayAdapter<Route> implements MTLog.Loggable { private static final String TAG = RTSAgencyRouteArrayAdapter.class.getSimpleName(); @Override public String getLogTag() { return TAG; } private ArrayList<Route> routes = null; private LayoutInflater layoutInflater; private String authority; private boolean showingListInsteadOfGrid; public RTSAgencyRouteArrayAdapter(Context context, String authority, boolean showingListInsteadOfGrid) { super(context, -1); this.layoutInflater = LayoutInflater.from(context); this.authority = authority; this.showingListInsteadOfGrid = showingListInsteadOfGrid; } public void seShowingListInsteadOfGrid(boolean showingListInsteadOfGrid) { this.showingListInsteadOfGrid = showingListInsteadOfGrid; } public void setAuthority(String authority) { this.authority = authority; } public void setRoutes(ArrayList<Route> routes) { this.routes = routes; } public boolean isInitialized() { return this.routes != null; } @Override public int getCount() { return this.routes == null ? 0 : this.routes.size(); } @Override public int getItemViewType(int position) { return this.showingListInsteadOfGrid ? 0 : 1; } @Override public int getViewTypeCount() { return 2; } @Override public Route getItem(int position) { return this.routes == null ? null : this.routes.get(position); } @Override public View getView(int position, View convertView, ViewGroup parent) { return getRouteView(position, convertView, parent); } private View getRouteView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = this.layoutInflater.inflate(this.showingListInsteadOfGrid ? R.layout.layout_rts_route_list_item : R.layout.layout_rts_route_grid_item, parent, false); RouteViewHolder holder = new RouteViewHolder(); holder.routeFL = convertView.findViewById(R.id.route); holder.routeShortNameTv = (TextView) convertView.findViewById(R.id.route_short_name); holder.routeTypeImg = (MTJPathsView) convertView.findViewById(R.id.route_type_img); holder.routeLongNameTv = (TextView) convertView.findViewById(R.id.route_long_name); convertView.setTag(holder); } updateRouteView(position, convertView); return convertView; } private View updateRouteView(int position, View convertView) { Route route = getItem(position); if (convertView == null) { return null; } RouteViewHolder holder = (RouteViewHolder) convertView.getTag(); if (route == null) { holder.routeFL.setVisibility(View.GONE); } else { if (TextUtils.isEmpty(route.getShortName())) { holder.routeShortNameTv.setVisibility(View.INVISIBLE); if (holder.routeTypeImg.hasPaths() && this.authority.equals(holder.routeTypeImg.getTag())) { holder.routeTypeImg.setVisibility(View.VISIBLE); } else { AgencyProperties agency = DataSourceProvider.get(getContext()).getAgency(getContext(), this.authority); JPaths rtsRouteLogo = agency == null ? null : agency.getLogo(getContext()); if (rtsRouteLogo != null) { holder.routeTypeImg.setJSON(rtsRouteLogo); holder.routeTypeImg.setTag(this.authority); holder.routeTypeImg.setVisibility(View.VISIBLE); } else { holder.routeTypeImg.setVisibility(View.GONE); } } } else { holder.routeTypeImg.setVisibility(View.GONE); holder.routeShortNameTv.setText(Route.setShortNameSize(route.getShortName())); holder.routeShortNameTv.setVisibility(View.VISIBLE); } if (holder.routeLongNameTv != null) { if (TextUtils.isEmpty(route.getLongName())) { holder.routeLongNameTv.setVisibility(View.GONE); } else { holder.routeLongNameTv.setText(route.getLongName()); holder.routeLongNameTv.setVisibility(View.VISIBLE); } } holder.routeFL.setBackgroundColor(POIManager.getRouteColor(getContext(), route, this.authority, Color.BLACK)); holder.routeFL.setVisibility(View.VISIBLE); } return convertView; } public void onDestroy() { if (this.routes != null) { this.routes.clear(); this.routes = null; } } public static class RouteViewHolder { TextView routeShortNameTv; View routeFL; MTJPathsView routeTypeImg; TextView routeLongNameTv; } } }
Use Switch instead of icons for list/grid & list/map toggles in toolbar.
src/org/mtransit/android/ui/fragment/RTSAgencyRoutesFragment.java
Use Switch instead of icons for list/grid & list/map toggles in toolbar.
<ide><path>rc/org/mtransit/android/ui/fragment/RTSAgencyRoutesFragment.java <ide> } <ide> <ide> private MenuItem listGridToggleMenuItem; <add> private SwitchCompat listGridSwitchMenuItem; <ide> <ide> @Override <ide> public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
Java
apache-2.0
1b7985773ad3a4290a27a00c4c6d38f76c9db900
0
apache/logging-log4j2,apache/logging-log4j2,apache/logging-log4j2
/* * 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.logging.log4j; import java.io.Serializable; import java.util.Collection; import java.util.Locale; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.logging.log4j.spi.StandardLevel; import org.apache.logging.log4j.util.Strings; /** * Levels used for identifying the severity of an event. Levels are organized from most specific to least: * <table> * <tr> * <th>Name</th> * <th>Description</th> * </tr> * <tr> * <td>{@link #OFF}</td> * <td>No events will be logged.</td> * </tr> * <tr> * <td>{@link #FATAL}</td> * <td>A fatal event that will prevent the application from continuing.</td> * </tr> * <tr> * <td>{@link #ERROR}</td> * <td>An error in the application, possibly recoverable.</td> * </tr> * <tr> * <td>{@link #WARN}</td> * <td>An event that might possible lead to an error.</td> * </tr> * <tr> * <td>{@link #INFO}</td> * <td>An event for informational purposes.</td> * </tr> * <tr> * <td>{@link #DEBUG}</td> * <td>A general debugging event.</td> * </tr> * <tr> * <td>{@link #TRACE}</td> * <td>A fine-grained debug message, typically capturing the flow through the application.</td> * </tr> * <tr> * <td>{@link #ALL}</td> * <td>All events should be logged.</td> * </tr> * </table> * <p> * Typically, configuring a level in a filter or on a logger will cause logging events of that level and those that are * more specific to pass through the filter. A special level, {@link #ALL}, is guaranteed to capture all levels when * used in logging configurations. * </p> */ public final class Level implements Comparable<Level>, Serializable { private static final ConcurrentMap<String, Level> LEVELS = new ConcurrentHashMap<>(); // SUPPRESS CHECKSTYLE /** * No events will be logged. */ public static final Level OFF = new Level("OFF", StandardLevel.OFF.intLevel()); /** * A fatal event that will prevent the application from continuing. */ public static final Level FATAL = new Level("FATAL", StandardLevel.FATAL.intLevel()); /** * An error in the application, possibly recoverable. */ public static final Level ERROR = new Level("ERROR", StandardLevel.ERROR.intLevel()); /** * An event that might possible lead to an error. */ public static final Level WARN = new Level("WARN", StandardLevel.WARN.intLevel()); /** * An event for informational purposes. */ public static final Level INFO = new Level("INFO", StandardLevel.INFO.intLevel()); /** * A general debugging event. */ public static final Level DEBUG = new Level("DEBUG", StandardLevel.DEBUG.intLevel()); /** * A fine-grained debug message, typically capturing the flow through the application. */ public static final Level TRACE = new Level("TRACE", StandardLevel.TRACE.intLevel()); /** * All events should be logged. */ public static final Level ALL = new Level("ALL", StandardLevel.ALL.intLevel()); /** * @since 2.1 */ public static final String CATEGORY = "Level"; private static final long serialVersionUID = 1581082L; private final String name; private final int intLevel; private final StandardLevel standardLevel; private Level(final String name, final int intLevel) { if (Strings.isEmpty(name)) { throw new IllegalArgumentException("Illegal null or empty Level name."); } if (intLevel < 0) { throw new IllegalArgumentException("Illegal Level int less than zero."); } this.name = name; this.intLevel = intLevel; this.standardLevel = StandardLevel.getStandardLevel(intLevel); if (LEVELS.putIfAbsent(name, this) != null) { throw new IllegalStateException("Level " + name + " has already been defined."); } } /** * Gets the integral value of this Level. * * @return the value of this Level. */ public int intLevel() { return this.intLevel; } /** * Gets the standard Level values as an enum. * * @return an enum of the standard Levels. */ public StandardLevel getStandardLevel() { return standardLevel; } /** * Compares this level against the levels passed as arguments and returns true if this level is in between the given * levels. * * @param minLevel The minimum level to test. * @param maxLevel The maximum level to test. * @return True true if this level is in between the given levels * @since 2.4 */ public boolean isInRange(final Level minLevel, final Level maxLevel) { return this.intLevel >= minLevel.intLevel && this.intLevel <= maxLevel.intLevel; } /** * Compares this level against the level passed as an argument and returns true if this level is the same or is less * specific. * <p> * Concretely, {@link #ALL} is less specific than {@link #TRACE}, which is less specific than {@link #DEBUG}, which * is less specific than {@link #INFO}, which is less specific than {@link #WARN}, which is less specific than * {@link #ERROR}, which is less specific than {@link #FATAL}, and finally {@link #OFF}, which is the most specific * standard level. * </p> * * @param level * The level to test. * @return True if this level Level is less specific or the same as the given Level. */ public boolean isLessSpecificThan(final Level level) { return this.intLevel >= level.intLevel; } /** * Compares this level against the level passed as an argument and returns true if this level is the same or is more * specific. * <p> * Concretely, {@link #FATAL} is more specific than {@link #ERROR}, which is more specific than {@link #WARN}, * etc., until {@link #TRACE}, and finally {@link #ALL}, which is the least specific standard level. * The most specific level is {@link #OFF}. * </p> * * @param level The level to test. * @return True if this level Level is more specific or the same as the given Level. */ public boolean isMoreSpecificThan(final Level level) { return this.intLevel <= level.intLevel; } @Override @SuppressWarnings("CloneDoesntCallSuperClone") // CHECKSTYLE:OFF public Level clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } // CHECKSTYLE:ON @Override public int compareTo(final Level other) { return intLevel < other.intLevel ? -1 : (intLevel > other.intLevel ? 1 : 0); } @Override public boolean equals(final Object other) { return other instanceof Level && other == this; } public Class<Level> getDeclaringClass() { return Level.class; } @Override public int hashCode() { return this.name.hashCode(); } /** * Gets the symbolic name of this Level. Equivalent to calling {@link #toString()}. * * @return the name of this Level. */ public String name() { return this.name; } @Override public String toString() { return this.name; } /** * Retrieves an existing Level or creates on if it didn't previously exist. * * @param name The name of the level. * @param intValue The integer value for the Level. If the level was previously created this value is ignored. * @return The Level. * @throws java.lang.IllegalArgumentException if the name is null or intValue is less than zero. */ public static Level forName(final String name, final int intValue) { final Level level = LEVELS.get(name); if (level != null) { return level; } try { return new Level(name, intValue); } catch (final IllegalStateException ex) { // The level was added by something else so just return that one. return LEVELS.get(name); } } /** * Return the Level associated with the name or null if the Level cannot be found. * * @param name The name of the Level. * @return The Level or null. */ public static Level getLevel(final String name) { return LEVELS.get(name); } /** * Converts the string passed as argument to a level. If the conversion fails, then this method returns * {@link #DEBUG}. * * @param level The name of the desired Level. * @return The Level associated with the String. */ public static Level toLevel(final String level) { return toLevel(level, Level.DEBUG); } /** * Converts the string passed as argument to a level. If the conversion fails, then this method returns the value of * <code>defaultLevel</code>. * * @param name The name of the desired Level. * @param defaultLevel The Level to use if the String is invalid. * @return The Level associated with the String. */ public static Level toLevel(final String name, final Level defaultLevel) { if (name == null) { return defaultLevel; } final Level level = LEVELS.get(toUpperCase(name.trim())); return level == null ? defaultLevel : level; } private static String toUpperCase(final String name) { return name.toUpperCase(Locale.ENGLISH); } /** * Return an array of all the Levels that have been registered. * * @return An array of Levels. */ public static Level[] values() { return Level.LEVELS.values().toArray(new Level[Level.LEVELS.values().size()]); } /** * Return the Level associated with the name. * * @param name The name of the Level to return. * @return The Level. * @throws java.lang.NullPointerException if the Level name is {@code null}. * @throws java.lang.IllegalArgumentException if the Level name is not registered. */ public static Level valueOf(final String name) { Objects.requireNonNull(name, "No level name given."); final String levelName = toUpperCase(name.trim()); final Level level = LEVELS.get(levelName); if (level != null) { return level; } throw new IllegalArgumentException("Unknown level constant [" + levelName + "]."); } /** * Returns the enum constant of the specified enum type with the specified name. The name must match exactly an * identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.) * * @param enumType the {@code Class} object of the enum type from which to return a constant * @param name the name of the constant to return * @param <T> The enum type whose constant is to be returned * @return the enum constant of the specified enum type with the specified name * @throws java.lang.IllegalArgumentException if the specified enum type has no constant with the specified name, or * the specified class object does not represent an enum type * @throws java.lang.NullPointerException if {@code enumType} or {@code name} are {@code null} * @see java.lang.Enum#valueOf(Class, String) */ public static <T extends Enum<T>> T valueOf(final Class<T> enumType, final String name) { return Enum.valueOf(enumType, name); } // for deserialization protected Object readResolve() { return Level.valueOf(this.name); } }
log4j-api/src/main/java/org/apache/logging/log4j/Level.java
/* * 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.logging.log4j; import java.io.Serializable; import java.util.Collection; import java.util.Locale; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.logging.log4j.spi.StandardLevel; import org.apache.logging.log4j.util.Strings; /** * Levels used for identifying the severity of an event. Levels are organized from most specific to least: * <table> * <tr> * <th>Name</th> * <th>Description</th> * </tr> * <tr> * <td>{@link #OFF}</td> * <td>No events will be logged.</td> * </tr> * <tr> * <td>{@link #FATAL}</td> * <td>A fatal event that will prevent the application from continuing.</td> * </tr> * <tr> * <td>{@link #ERROR}</td> * <td>An error in the application, possibly recoverable.</td> * </tr> * <tr> * <td>{@link #WARN}</td> * <td>An event that might possible lead to an error.</td> * </tr> * <tr> * <td>{@link #INFO}</td> * <td>An event for informational purposes.</td> * </tr> * <tr> * <td>{@link #DEBUG}</td> * <td>A general debugging event.</td> * </tr> * <tr> * <td>{@link #TRACE}</td> * <td>A fine-grained debug message, typically capturing the flow through the application.</td> * </tr> * <tr> * <td>{@link #ALL}</td> * <td>All events should be logged.</td> * </tr> * </table> * <p> * Typically, configuring a level in a filter or on a logger will cause logging events of that level and those that are * more specific to pass through the filter. A special level, {@link #ALL}, is guaranteed to capture all levels when * used in logging configurations. * </p> */ public final class Level implements Comparable<Level>, Serializable { private static final ConcurrentMap<String, Level> LEVELS = new ConcurrentHashMap<>(); // SUPPRESS CHECKSTYLE /** * No events will be logged. */ public static final Level OFF = new Level("OFF", StandardLevel.OFF.intLevel()); /** * A fatal event that will prevent the application from continuing. */ public static final Level FATAL = new Level("FATAL", StandardLevel.FATAL.intLevel()); /** * An error in the application, possibly recoverable. */ public static final Level ERROR = new Level("ERROR", StandardLevel.ERROR.intLevel()); /** * An event that might possible lead to an error. */ public static final Level WARN = new Level("WARN", StandardLevel.WARN.intLevel()); /** * An event for informational purposes. */ public static final Level INFO = new Level("INFO", StandardLevel.INFO.intLevel()); /** * A general debugging event. */ public static final Level DEBUG = new Level("DEBUG", StandardLevel.DEBUG.intLevel()); /** * A fine-grained debug message, typically capturing the flow through the application. */ public static final Level TRACE = new Level("TRACE", StandardLevel.TRACE.intLevel()); /** * All events should be logged. */ public static final Level ALL = new Level("ALL", StandardLevel.ALL.intLevel()); /** * @since 2.1 */ public static final String CATEGORY = "Level"; private static final long serialVersionUID = 1581082L; private final String name; private final int intLevel; private final StandardLevel standardLevel; private Level(final String name, final int intLevel) { if (Strings.isEmpty(name)) { throw new IllegalArgumentException("Illegal null or empty Level name."); } if (intLevel < 0) { throw new IllegalArgumentException("Illegal Level int less than zero."); } this.name = name; this.intLevel = intLevel; this.standardLevel = StandardLevel.getStandardLevel(intLevel); if (LEVELS.putIfAbsent(name, this) != null) { throw new IllegalStateException("Level " + name + " has already been defined."); } } /** * Gets the integral value of this Level. * * @return the value of this Level. */ public int intLevel() { return this.intLevel; } /** * Gets the standard Level values as an enum. * * @return an enum of the standard Levels. */ public StandardLevel getStandardLevel() { return standardLevel; } /** * Compares this level against the levels passed as arguments and returns true if this level is in between the given * levels. * * @param minLevel The minimum level to test. * @param maxLevel The maximum level to test. * @return True true if this level is in between the given levels * @since 2.4 */ public boolean isInRange(final Level minLevel, final Level maxLevel) { return this.intLevel >= minLevel.intLevel && this.intLevel <= maxLevel.intLevel; } /** * Compares this level against the level passed as an argument and returns true if this level is the same or is less * specific. * <p> * Concretely, {@link #ALL} is less specific than {@link #TRACE}, which is less specific than {@link #DEBUG}, which * is less specific than {@link #INFO}, which is less specific than {@link #WARN}, which is less specific than * {@link #ERROR}, which is less specific than {@link #FATAL}, and finally {@link #OFF}, which is the most specific * standard level. * </p> * * @param level * The level to test. * @return True if this level Level is less specific or the same as the given Level. */ public boolean isLessSpecificThan(final Level level) { return this.intLevel >= level.intLevel; } /** * Compares this level against the level passed as an argument and returns true if this level is the same or is more * specific. * <p> * Concretely, {@link #FATAL} is more specific than {@link #ERROR}, which is more specific than {@link #WARN}, * etc., until {@link #TRACE}, and finally {@link #ALL}, which is the least specific standard level. * The most specific level is {@link #OFF}. * </p> * * @param level The level to test. * @return True if this level Level is more specific or the same as the given Level. */ public boolean isMoreSpecificThan(final Level level) { return this.intLevel <= level.intLevel; } @Override @SuppressWarnings("CloneDoesntCallSuperClone") // CHECKSTYLE:OFF public Level clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } // CHECKSTYLE:ON @Override public int compareTo(final Level other) { return intLevel < other.intLevel ? -1 : (intLevel > other.intLevel ? 1 : 0); } @Override public boolean equals(final Object other) { return other instanceof Level && other == this; } public Class<Level> getDeclaringClass() { return Level.class; } @Override public int hashCode() { return this.name.hashCode(); } /** * Gets the symbolic name of this Level. Equivalent to calling {@link #toString()}. * * @return the name of this Level. */ public String name() { return this.name; } @Override public String toString() { return this.name; } /** * Retrieves an existing Level or creates on if it didn't previously exist. * * @param name The name of the level. * @param intValue The integer value for the Level. If the level was previously created this value is ignored. * @return The Level. * @throws java.lang.IllegalArgumentException if the name is null or intValue is less than zero. */ public static Level forName(final String name, final int intValue) { final Level level = LEVELS.get(name); if (level != null) { return level; } try { return new Level(name, intValue); } catch (final IllegalStateException ex) { // The level was added by something else so just return that one. return LEVELS.get(name); } } /** * Return the Level associated with the name or null if the Level cannot be found. * * @param name The name of the Level. * @return The Level or null. */ public static Level getLevel(final String name) { return LEVELS.get(name); } /** * Converts the string passed as argument to a level. If the conversion fails, then this method returns * {@link #DEBUG}. * * @param level The name of the desired Level. * @return The Level associated with the String. */ public static Level toLevel(final String level) { return toLevel(level, Level.DEBUG); } /** * Converts the string passed as argument to a level. If the conversion fails, then this method returns the value of * <code>defaultLevel</code>. * * @param name The name of the desired Level. * @param defaultLevel The Level to use if the String is invalid. * @return The Level associated with the String. */ public static Level toLevel(final String name, final Level defaultLevel) { if (name == null) { return defaultLevel; } final Level level = LEVELS.get(toUpperCase(name.trim())); return level == null ? defaultLevel : level; } private static String toUpperCase(final String name) { return name.toUpperCase(Locale.ENGLISH); } /** * Return an array of all the Levels that have been registered. * * @return An array of Levels. */ public static Level[] values() { final Collection<Level> values = Level.LEVELS.values(); return values.toArray(new Level[values.size()]); } /** * Return the Level associated with the name. * * @param name The name of the Level to return. * @return The Level. * @throws java.lang.NullPointerException if the Level name is {@code null}. * @throws java.lang.IllegalArgumentException if the Level name is not registered. */ public static Level valueOf(final String name) { Objects.requireNonNull(name, "No level name given."); final String levelName = toUpperCase(name.trim()); final Level level = LEVELS.get(levelName); if (level != null) { return level; } throw new IllegalArgumentException("Unknown level constant [" + levelName + "]."); } /** * Returns the enum constant of the specified enum type with the specified name. The name must match exactly an * identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.) * * @param enumType the {@code Class} object of the enum type from which to return a constant * @param name the name of the constant to return * @param <T> The enum type whose constant is to be returned * @return the enum constant of the specified enum type with the specified name * @throws java.lang.IllegalArgumentException if the specified enum type has no constant with the specified name, or * the specified class object does not represent an enum type * @throws java.lang.NullPointerException if {@code enumType} or {@code name} are {@code null} * @see java.lang.Enum#valueOf(Class, String) */ public static <T extends Enum<T>> T valueOf(final Class<T> enumType, final String name) { return Enum.valueOf(enumType, name); } // for deserialization protected Object readResolve() { return Level.valueOf(this.name); } }
In-line single-use local variable.
log4j-api/src/main/java/org/apache/logging/log4j/Level.java
In-line single-use local variable.
<ide><path>og4j-api/src/main/java/org/apache/logging/log4j/Level.java <ide> * @return An array of Levels. <ide> */ <ide> public static Level[] values() { <del> final Collection<Level> values = Level.LEVELS.values(); <del> return values.toArray(new Level[values.size()]); <add> return Level.LEVELS.values().toArray(new Level[Level.LEVELS.values().size()]); <ide> } <ide> <ide> /**
Java
mit
error: pathspec 'src/main/java/com/blankstyle/vertx/php/http/HttpServerResponse.java' did not match any file(s) known to git
067c6a055757dc58ba915017d0512a713da0e803
1
vert-x/mod-lang-php,alwinmark/vertx-php,khasinski/mod-lang-php,khasinski/mod-lang-php,vert-x/mod-lang-php,khasinski/mod-lang-php,alwinmark/vertx-php
package com.blankstyle.vertx.php.http; import com.blankstyle.vertx.php.Handler; import com.blankstyle.vertx.php.streams.ExceptionSupport; import com.blankstyle.vertx.php.streams.WriteStream; import com.caucho.quercus.annotation.Optional; import com.caucho.quercus.env.BooleanValue; import com.caucho.quercus.env.Callback; import com.caucho.quercus.env.Env; import com.caucho.quercus.env.NumberValue; import com.caucho.quercus.env.StringValue; import com.caucho.quercus.env.Value; /** * A PHP compatible implementation of the Vert.x HttpServerResponse. * * @author Jordan Halterman */ public class HttpServerResponse implements WriteStream, ExceptionSupport { private org.vertx.java.core.http.HttpServerResponse response; public HttpServerResponse(org.vertx.java.core.http.HttpServerResponse response) { this.response = response; } public HttpServerResponse(Env env, org.vertx.java.core.http.HttpServerResponse response) { this.response = response; } /** * Returns the response status code. */ public Value getStatusCode(Env env) { return env.wrapJava(response.getStatusCode()); } /** * Sets the response status code. */ public Value setStatusCode(Env env, NumberValue statusCode) { response.setStatusCode(statusCode.toInt()); return env.wrapJava(this); } /** * Returns the response status message. */ public Value getStatusMessage(Env env) { return env.createString(response.getStatusMessage()); } /** * Sets the response status message. */ public Value setStatusMessage(Env env, StringValue message) { response.setStatusMessage(message.toString()); return env.wrapJava(this); } /** * Returns response headers. */ public Value headers(Env env) { return env.wrapJava(response.headers()); } /** * Returns response trailers. */ public Value trailers(Env env) { return env.wrapJava(response.trailers()); } /** * Puts an HTTP header. */ public Value putHeader(Env env, StringValue name, Value value) { response.putHeader(name.toString(), value.toString()); return env.wrapJava(this); } /** * Sends a file to the client. */ public Value sendFile(Env env, StringValue filename) { response.sendFile(filename.toString()); return env.wrapJava(this); } @Override public Value write(Env env, Value data, @Optional StringValue enc) { if (enc != null && !enc.isDefault()) { response.write(data.toString(), enc.toString()); } else { response.write(data.toString()); } return env.wrapJava(this); } public void end() { response.end(); } public void end(Env env) { end(); } public void end(Env env, Value data) { response.end(data.toString()); } @Override public Value drainHandler(Env env, Callback handler) { response.drainHandler(new Handler<Void>(env, handler)); return env.wrapJava(this); } public Value closeHandler(Env env, Callback handler) { response.closeHandler(new Handler<Void>(env, handler)); return env.wrapJava(this); } public Value setChunked(Env env, BooleanValue chunked) { response.setChunked(chunked.toBoolean()); return env.wrapJava(this); } public BooleanValue isChunked(Env env) { return BooleanValue.create(response.isChunked()); } @Override public Value setWriteQueueMaxSize(Env env, NumberValue size) { response.setWriteQueueMaxSize(size.toInt()); return env.wrapJava(this); } @Override public BooleanValue writeQueueFull(Env env) { return BooleanValue.create(response.writeQueueFull()); } @Override public Value exceptionHandler(Env env, Callback handler) { response.exceptionHandler(new Handler<Throwable>(env, handler)); return env.wrapJava(this); } }
src/main/java/com/blankstyle/vertx/php/http/HttpServerResponse.java
Add HTTP server response handler.
src/main/java/com/blankstyle/vertx/php/http/HttpServerResponse.java
Add HTTP server response handler.
<ide><path>rc/main/java/com/blankstyle/vertx/php/http/HttpServerResponse.java <add>package com.blankstyle.vertx.php.http; <add> <add>import com.blankstyle.vertx.php.Handler; <add>import com.blankstyle.vertx.php.streams.ExceptionSupport; <add>import com.blankstyle.vertx.php.streams.WriteStream; <add>import com.caucho.quercus.annotation.Optional; <add>import com.caucho.quercus.env.BooleanValue; <add>import com.caucho.quercus.env.Callback; <add>import com.caucho.quercus.env.Env; <add>import com.caucho.quercus.env.NumberValue; <add>import com.caucho.quercus.env.StringValue; <add>import com.caucho.quercus.env.Value; <add> <add>/** <add> * A PHP compatible implementation of the Vert.x HttpServerResponse. <add> * <add> * @author Jordan Halterman <add> */ <add>public class HttpServerResponse implements WriteStream, ExceptionSupport { <add> <add> private org.vertx.java.core.http.HttpServerResponse response; <add> <add> public HttpServerResponse(org.vertx.java.core.http.HttpServerResponse response) { <add> this.response = response; <add> } <add> <add> public HttpServerResponse(Env env, org.vertx.java.core.http.HttpServerResponse response) { <add> this.response = response; <add> } <add> <add> /** <add> * Returns the response status code. <add> */ <add> public Value getStatusCode(Env env) { <add> return env.wrapJava(response.getStatusCode()); <add> } <add> <add> /** <add> * Sets the response status code. <add> */ <add> public Value setStatusCode(Env env, NumberValue statusCode) { <add> response.setStatusCode(statusCode.toInt()); <add> return env.wrapJava(this); <add> } <add> <add> /** <add> * Returns the response status message. <add> */ <add> public Value getStatusMessage(Env env) { <add> return env.createString(response.getStatusMessage()); <add> } <add> <add> /** <add> * Sets the response status message. <add> */ <add> public Value setStatusMessage(Env env, StringValue message) { <add> response.setStatusMessage(message.toString()); <add> return env.wrapJava(this); <add> } <add> <add> /** <add> * Returns response headers. <add> */ <add> public Value headers(Env env) { <add> return env.wrapJava(response.headers()); <add> } <add> <add> /** <add> * Returns response trailers. <add> */ <add> public Value trailers(Env env) { <add> return env.wrapJava(response.trailers()); <add> } <add> <add> /** <add> * Puts an HTTP header. <add> */ <add> public Value putHeader(Env env, StringValue name, Value value) { <add> response.putHeader(name.toString(), value.toString()); <add> return env.wrapJava(this); <add> } <add> <add> /** <add> * Sends a file to the client. <add> */ <add> public Value sendFile(Env env, StringValue filename) { <add> response.sendFile(filename.toString()); <add> return env.wrapJava(this); <add> } <add> <add> @Override <add> public Value write(Env env, Value data, @Optional StringValue enc) { <add> if (enc != null && !enc.isDefault()) { <add> response.write(data.toString(), enc.toString()); <add> } <add> else { <add> response.write(data.toString()); <add> } <add> return env.wrapJava(this); <add> } <add> <add> public void end() { <add> response.end(); <add> } <add> <add> public void end(Env env) { <add> end(); <add> } <add> <add> public void end(Env env, Value data) { <add> response.end(data.toString()); <add> } <add> <add> @Override <add> public Value drainHandler(Env env, Callback handler) { <add> response.drainHandler(new Handler<Void>(env, handler)); <add> return env.wrapJava(this); <add> } <add> <add> public Value closeHandler(Env env, Callback handler) { <add> response.closeHandler(new Handler<Void>(env, handler)); <add> return env.wrapJava(this); <add> } <add> <add> public Value setChunked(Env env, BooleanValue chunked) { <add> response.setChunked(chunked.toBoolean()); <add> return env.wrapJava(this); <add> } <add> <add> public BooleanValue isChunked(Env env) { <add> return BooleanValue.create(response.isChunked()); <add> } <add> <add> @Override <add> public Value setWriteQueueMaxSize(Env env, NumberValue size) { <add> response.setWriteQueueMaxSize(size.toInt()); <add> return env.wrapJava(this); <add> } <add> <add> @Override <add> public BooleanValue writeQueueFull(Env env) { <add> return BooleanValue.create(response.writeQueueFull()); <add> } <add> <add> @Override <add> public Value exceptionHandler(Env env, Callback handler) { <add> response.exceptionHandler(new Handler<Throwable>(env, handler)); <add> return env.wrapJava(this); <add> } <add> <add>}
Java
apache-2.0
7584bf7d5660e72c2658bae1eb9eeeceabbf7c8f
0
jackylk/incubator-carbondata,ravipesala/incubator-carbondata,manishgupta88/incubator-carbondata,ravipesala/incubator-carbondata,zzcclp/carbondata,manishgupta88/carbondata,manishgupta88/incubator-carbondata,jackylk/incubator-carbondata,ravipesala/incubator-carbondata,zzcclp/carbondata,manishgupta88/incubator-carbondata,zzcclp/carbondata,manishgupta88/carbondata,manishgupta88/incubator-carbondata,manishgupta88/carbondata,jackylk/incubator-carbondata,zzcclp/carbondata,manishgupta88/carbondata,jackylk/incubator-carbondata,ravipesala/incubator-carbondata,zzcclp/carbondata
/* * 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.carbondata.core.scan.result.iterator; import java.util.List; import org.apache.carbondata.common.CarbonIterator; import org.apache.carbondata.core.scan.result.RowBatch; /** * Iterator over row result */ public class ChunkRowIterator extends CarbonIterator<Object[]> { /** * iterator over chunk result */ private CarbonIterator<RowBatch> iterator; /** * current chunk */ private RowBatch currentChunk; public ChunkRowIterator(CarbonIterator<RowBatch> iterator) { this.iterator = iterator; } /** * Returns {@code true} if the iteration has more elements. (In other words, * returns {@code true} if {@link #next} would return an element rather than * throwing an exception.) * * @return {@code true} if the iteration has more elements */ @Override public boolean hasNext() { if (currentChunk != null && currentChunk.hasNext()) { return true; } else if (iterator != null && iterator.hasNext()) { currentChunk = iterator.next(); return hasNext(); } return false; } /** * Returns the next element in the iteration. * * @return the next element in the iteration */ @Override public Object[] next() { return currentChunk.next(); } /** * read next batch * * @return list of batch result */ public List<Object[]> nextBatch() { return currentChunk.nextBatch(); } }
core/src/main/java/org/apache/carbondata/core/scan/result/iterator/ChunkRowIterator.java
/* * 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.carbondata.core.scan.result.iterator; import java.util.List; import org.apache.carbondata.common.CarbonIterator; import org.apache.carbondata.core.scan.result.RowBatch; /** * Iterator over row result */ public class ChunkRowIterator extends CarbonIterator<Object[]> { /** * iterator over chunk result */ private CarbonIterator<RowBatch> iterator; /** * current chunk */ private RowBatch currentChunk; public ChunkRowIterator(CarbonIterator<RowBatch> iterator) { this.iterator = iterator; if (iterator.hasNext()) { currentChunk = iterator.next(); } } /** * Returns {@code true} if the iteration has more elements. (In other words, * returns {@code true} if {@link #next} would return an element rather than * throwing an exception.) * * @return {@code true} if the iteration has more elements */ @Override public boolean hasNext() { if (null != currentChunk) { if ((currentChunk.hasNext())) { return true; } else if (!currentChunk.hasNext()) { while (iterator.hasNext()) { currentChunk = iterator.next(); if (currentChunk != null && currentChunk.hasNext()) { return true; } } } } return false; } /** * Returns the next element in the iteration. * * @return the next element in the iteration */ @Override public Object[] next() { return currentChunk.next(); } /** * read next batch * * @return list of batch result */ public List<Object[]> nextBatch() { return currentChunk.nextBatch(); } }
[CARBONDATA-3121] Improvement of CarbonReader build time CarbonReader builder is taking huge time. Reason Initialization of ChunkRowIterator is triggering actual I/O operation, and thus huge build time. Solution remove CarbonIterator.hasNext() and CarbonIterator.next() from build. This closes #2942
core/src/main/java/org/apache/carbondata/core/scan/result/iterator/ChunkRowIterator.java
[CARBONDATA-3121] Improvement of CarbonReader build time
<ide><path>ore/src/main/java/org/apache/carbondata/core/scan/result/iterator/ChunkRowIterator.java <ide> <ide> public ChunkRowIterator(CarbonIterator<RowBatch> iterator) { <ide> this.iterator = iterator; <del> if (iterator.hasNext()) { <del> currentChunk = iterator.next(); <del> } <ide> } <ide> <ide> /** <ide> * @return {@code true} if the iteration has more elements <ide> */ <ide> @Override public boolean hasNext() { <del> if (null != currentChunk) { <del> if ((currentChunk.hasNext())) { <del> return true; <del> } else if (!currentChunk.hasNext()) { <del> while (iterator.hasNext()) { <del> currentChunk = iterator.next(); <del> if (currentChunk != null && currentChunk.hasNext()) { <del> return true; <del> } <del> } <del> } <add> if (currentChunk != null && currentChunk.hasNext()) { <add> return true; <add> } else if (iterator != null && iterator.hasNext()) { <add> currentChunk = iterator.next(); <add> return hasNext(); <ide> } <ide> return false; <ide> }
Java
apache-2.0
0d40bffe3e6f2df4810f1b025e25fb907f5b7aaf
0
statsbiblioteket/newspaper-batch-metadata-checker,statsbiblioteket/newspaper-batch-metadata-checker,statsbiblioteket/newspaper-batch-metadata-checker
package dk.statsbiblioteket.newspaper.metadatachecker; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URISyntaxException; import java.util.Properties; import dk.statsbiblioteket.medieplatform.autonomous.Batch; import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector; import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.TreeIterator; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventHandlerFactory; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventRunner; import dk.statsbiblioteket.medieplatform.autonomous.iterator.filesystem.transforming.TransformingIteratorForFileSystems; import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.ConfigurationProperties; import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.MfPakConfiguration; import dk.statsbiblioteket.newspaper.mfpakintegration.database.MfPakDAO; import dk.statsbiblioteket.util.Streams; import dk.statsbiblioteket.util.xml.DOM; import org.testng.annotations.Test; import org.w3c.dom.Document; import static org.testng.Assert.assertTrue; /** */ public class MetadataCheckerComponentIT { private final static String TEST_BATCH_ID = "400022028241"; /** Tests that the BatchStructureChecker can parse a production like batch. */ @Test(groups = "integrationTest") public void testMetadataCheck() throws Exception { String pathToProperties = System.getProperty("integration.test.newspaper.properties"); Properties properties = new Properties(); properties.load(new FileInputStream(pathToProperties)); TreeIterator iterator = getIterator(); EventRunner batchStructureChecker = new EventRunner(iterator); ResultCollector resultCollector = new ResultCollector("Batch Structure Checker", "v0.1"); Batch batch = new Batch(); batch.setBatchID(TEST_BATCH_ID); batch.setRoundTripNumber(1); InputStream batchXmlStructureStream = retrieveBatchStructure(batch); if (batchXmlStructureStream == null) { throw new RuntimeException("Failed to resolve batch manifest from data collector"); } ByteArrayOutputStream temp = new ByteArrayOutputStream(); Streams.pipe(batchXmlStructureStream, temp); Document batchXmlManifest = DOM.streamToDOM(batchXmlStructureStream); MfPakConfiguration mfPakConfiguration = new MfPakConfiguration(); mfPakConfiguration.setDatabaseUrl(properties.getProperty(ConfigurationProperties.DATABASE_URL)); mfPakConfiguration.setDatabaseUser(properties.getProperty(ConfigurationProperties.DATABASE_USER)); mfPakConfiguration.setDatabasePassword(properties.getProperty(ConfigurationProperties.DATABASE_PASSWORD)); EventHandlerFactory eventHandlerFactory = new MetadataChecksFactory( resultCollector, true, getBatchFolder().getParentFile().getAbsolutePath(), getJpylyzerPath(), null, new MfPakDAO(mfPakConfiguration), batch, batchXmlManifest); batchStructureChecker.runEvents(eventHandlerFactory.createEventHandlers()); System.out.println(resultCollector.toReport()); assertTrue(resultCollector.isSuccess()); //Assert.fail(); } private InputStream retrieveBatchStructure(Batch batch) { return Thread.currentThread().getContextClassLoader().getResourceAsStream("assumed-valid-structure.xml"); } private String getJpylyzerPath() { return "src/main/extras/jpylyzer-1.10.1/jpylyzer.py"; } /** * Creates and returns a iteration based on the test batch file structure found in the test/ressources folder. * * @return A iterator the the test batch * @throws URISyntaxException */ public TreeIterator getIterator() throws URISyntaxException { File file = getBatchFolder(); System.out.println(file); return new TransformingIteratorForFileSystems(file, "\\.", ".*\\.jp2$", ".md5"); } private File getBatchFolder() { String pathToTestBatch = System.getProperty("integration.test.newspaper.testdata"); return new File(pathToTestBatch, "small-test-batch/B" + TEST_BATCH_ID + "-RT1"); } }
src/test/java/dk/statsbiblioteket/newspaper/metadatachecker/MetadataCheckerComponentIT.java
package dk.statsbiblioteket.newspaper.metadatachecker; import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.ConfigurationProperties; import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.MfPakConfiguration; import dk.statsbiblioteket.newspaper.mfpakintegration.database.MfPakDAO; import dk.statsbiblioteket.util.Streams; import org.testng.annotations.Test; import dk.statsbiblioteket.medieplatform.autonomous.Batch; import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector; import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.TreeIterator; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventHandlerFactory; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventRunner; import dk.statsbiblioteket.medieplatform.autonomous.iterator.filesystem.transforming.TransformingIteratorForFileSystems; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URISyntaxException; import java.util.Properties; import static org.testng.Assert.assertTrue; /** */ public class MetadataCheckerComponentIT { private final static String TEST_BATCH_ID = "400022028241"; /** Tests that the BatchStructureChecker can parse a production like batch. */ @Test(groups = "integrationTest") public void testMetadataCheck() throws Exception { String pathToProperties = System.getProperty("integration.test.newspaper.properties"); Properties properties = new Properties(); properties.load(new FileInputStream(pathToProperties)); TreeIterator iterator = getIterator(); EventRunner batchStructureChecker = new EventRunner(iterator); ResultCollector resultCollector = new ResultCollector("Batch Structure Checker", "v0.1"); Batch batch = new Batch(); batch.setBatchID(TEST_BATCH_ID); batch.setRoundTripNumber(1); InputStream batchXmlStructureStream = retrieveBatchStructure(batch); if (batchXmlStructureStream == null) { throw new RuntimeException("Failed to resolve batch manifest from data collector"); } ByteArrayOutputStream temp = new ByteArrayOutputStream(); Streams.pipe(batchXmlStructureStream, temp); String batchXmlManifest = new String(temp.toByteArray(), "UTF-8"); MfPakConfiguration mfPakConfiguration = new MfPakConfiguration(); mfPakConfiguration.setDatabaseUrl(properties.getProperty(ConfigurationProperties.DATABASE_URL)); mfPakConfiguration.setDatabaseUser(properties.getProperty(ConfigurationProperties.DATABASE_USER)); mfPakConfiguration.setDatabasePassword(properties.getProperty(ConfigurationProperties.DATABASE_PASSWORD)); EventHandlerFactory eventHandlerFactory = new MetadataChecksFactory(resultCollector, true, getBatchFolder().getParentFile() .getAbsolutePath(), getJpylyzerPath(), null, new MfPakDAO(mfPakConfiguration), batch, batchXmlManifest); batchStructureChecker.runEvents(eventHandlerFactory.createEventHandlers()); System.out.println(resultCollector.toReport()); assertTrue(resultCollector.isSuccess()); //Assert.fail(); } private InputStream retrieveBatchStructure(Batch batch) { return Thread.currentThread().getContextClassLoader().getResourceAsStream("assumed-valid-structure.xml"); } private String getJpylyzerPath() { return "src/main/extras/jpylyzer-1.10.1/jpylyzer.py"; } /** * Creates and returns a iteration based on the test batch file structure found in the test/ressources folder. * * @return A iterator the the test batch * @throws URISyntaxException */ public TreeIterator getIterator() throws URISyntaxException { File file = getBatchFolder(); System.out.println(file); return new TransformingIteratorForFileSystems(file, "\\.", ".*\\.jp2$", ".md5"); } private File getBatchFolder() { String pathToTestBatch = System.getProperty("integration.test.newspaper.testdata"); return new File(pathToTestBatch, "small-test-batch/B" + TEST_BATCH_ID + "-RT1"); } }
Fixe test compile error
src/test/java/dk/statsbiblioteket/newspaper/metadatachecker/MetadataCheckerComponentIT.java
Fixe test compile error
<ide><path>rc/test/java/dk/statsbiblioteket/newspaper/metadatachecker/MetadataCheckerComponentIT.java <ide> package dk.statsbiblioteket.newspaper.metadatachecker; <ide> <del>import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.ConfigurationProperties; <del>import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.MfPakConfiguration; <del>import dk.statsbiblioteket.newspaper.mfpakintegration.database.MfPakDAO; <del>import dk.statsbiblioteket.util.Streams; <del>import org.testng.annotations.Test; <add>import java.io.ByteArrayOutputStream; <add>import java.io.File; <add>import java.io.FileInputStream; <add>import java.io.InputStream; <add>import java.net.URISyntaxException; <add>import java.util.Properties; <ide> <ide> import dk.statsbiblioteket.medieplatform.autonomous.Batch; <ide> import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector; <ide> import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventHandlerFactory; <ide> import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventRunner; <ide> import dk.statsbiblioteket.medieplatform.autonomous.iterator.filesystem.transforming.TransformingIteratorForFileSystems; <del> <del>import java.io.ByteArrayOutputStream; <del>import java.io.File; <del>import java.io.FileInputStream; <del>import java.io.InputStream; <del>import java.net.URISyntaxException; <del>import java.util.Properties; <add>import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.ConfigurationProperties; <add>import dk.statsbiblioteket.newspaper.mfpakintegration.configuration.MfPakConfiguration; <add>import dk.statsbiblioteket.newspaper.mfpakintegration.database.MfPakDAO; <add>import dk.statsbiblioteket.util.Streams; <add>import dk.statsbiblioteket.util.xml.DOM; <add>import org.testng.annotations.Test; <add>import org.w3c.dom.Document; <ide> <ide> import static org.testng.Assert.assertTrue; <ide> <ide> } <ide> ByteArrayOutputStream temp = new ByteArrayOutputStream(); <ide> Streams.pipe(batchXmlStructureStream, temp); <del> String batchXmlManifest = new String(temp.toByteArray(), "UTF-8"); <add> <add> Document batchXmlManifest = DOM.streamToDOM(batchXmlStructureStream); <ide> <ide> MfPakConfiguration mfPakConfiguration = new MfPakConfiguration(); <ide> mfPakConfiguration.setDatabaseUrl(properties.getProperty(ConfigurationProperties.DATABASE_URL)); <ide> mfPakConfiguration.setDatabaseUser(properties.getProperty(ConfigurationProperties.DATABASE_USER)); <ide> mfPakConfiguration.setDatabasePassword(properties.getProperty(ConfigurationProperties.DATABASE_PASSWORD)); <del> EventHandlerFactory eventHandlerFactory = new MetadataChecksFactory(resultCollector, <del> true, <del> getBatchFolder().getParentFile() <del> .getAbsolutePath(), <del> getJpylyzerPath(), <del> null, <del> new MfPakDAO(mfPakConfiguration), <del> batch, <del> batchXmlManifest); <add> EventHandlerFactory eventHandlerFactory = new MetadataChecksFactory( <add> resultCollector, <add> true, <add> getBatchFolder().getParentFile().getAbsolutePath(), <add> getJpylyzerPath(), <add> null, <add> new MfPakDAO(mfPakConfiguration), <add> batch, <add> batchXmlManifest); <ide> batchStructureChecker.runEvents(eventHandlerFactory.createEventHandlers()); <ide> System.out.println(resultCollector.toReport()); <ide> assertTrue(resultCollector.isSuccess());
Java
apache-2.0
87f946db8fd567ecf404fc4a77134f4b61f64fa0
0
icecondor/android,icecondor/android
package com.icecondor.nest; import java.io.IOException; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import net.oauth.OAuth; import net.oauth.OAuthAccessor; import net.oauth.OAuthException; import net.oauth.OAuthMessage; import net.oauth.client.OAuthClient; import net.oauth.client.httpclient4.HttpClient4; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.params.AllClientPNames; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.media.MediaPlayer; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.RemoteException; import android.os.Process; import android.preference.PreferenceManager; import android.util.Log; import com.icecondor.nest.db.GeoRss; import com.icecondor.nest.db.LocationStorageProviders; import com.icecondor.nest.types.Gps; //look at android.permission.RECEIVE_BOOT_COMPLETED public class Pigeon extends Service implements Constants, LocationListener, SharedPreferences.OnSharedPreferenceChangeListener, Handler.Callback { private Timer heartbeat_timer; private Timer rss_timer; private Timer push_queue_timer; //private Timer wifi_scan_timer = new Timer(); boolean on_switch = false; private Location last_recorded_fix, last_pushed_fix, last_local_fix; long last_pushed_time; int last_fix_http_status; Notification ongoing_notification; NotificationManager notificationManager; LocationManager locationManager; WifiManager wifiManager; PendingIntent contentIntent; SharedPreferences settings; GeoRss rssdb; MediaPlayer mp; private TimerTask heartbeatTask; DefaultHttpClient httpClient; OAuthClient oclient; private int last_battery_level; BatteryReceiver battery_receiver; WidgetReceiver widget_receiver; private boolean ac_power; ApiSocket apiSocket; Handler pigeonHandler; long reconnectLastTry; public void onCreate() { Log.i(APP_TAG, "*** Pigeon service created. "+ "\""+Thread.currentThread().getName()+"\""+" tid:"+Thread.currentThread().getId()+ " uid:"+Process.myUid()); super.onCreate(); /* Database */ rssdb = new GeoRss(this); rssdb.open(); rssdb.log("Pigon created"); /* GPS */ locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); rssdb.log("GPS provider enabled: "+locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)); last_local_fix = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); rssdb.log("NETWORK provider enabled: "+locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)); Location last_network_fix = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (last_local_fix == null) { if(last_network_fix != null) { last_local_fix = last_network_fix; // fall back onto the network location rssdb.log("Last known NETWORK fix: "+last_network_fix+" "+ Util.DateTimeIso8601(last_network_fix.getTime())); } } else { rssdb.log("Last known GPS fix: "+last_local_fix+" "+ Util.DateTimeIso8601(last_local_fix.getTime())); } Cursor oldest; if ((oldest = rssdb.oldestPushedLocationQueue()).getCount() > 0) { rssdb.log("Oldest pushed fix found"); last_pushed_fix = Gps.fromJson(oldest.getString( oldest.getColumnIndex(GeoRss.POSITION_QUEUE_JSON))).getLocation(); } oldest.close(); /* WIFI */ wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); /* Notifications */ notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Start.class), 0); CharSequence text = getText(R.string.status_started); ongoing_notification = new Notification(R.drawable.condorhead_statusbar, text, System .currentTimeMillis()); ongoing_notification.flags = ongoing_notification.flags ^ Notification.FLAG_ONGOING_EVENT; ongoing_notification.setLatestEventInfo(this, "IceCondor", "", contentIntent); /* Preferences */ settings = PreferenceManager.getDefaultSharedPreferences(this); settings.registerOnSharedPreferenceChangeListener(this); on_switch = settings.getBoolean(SETTING_PIGEON_TRANSMITTING, false); if (on_switch) { //startForeground(1, ongoing_notification); startLocationUpdates(); sendBroadcast(new Intent("com.icecondor.nest.WIDGET_ON")); } /* Sound */ mp = MediaPlayer.create(this, R.raw.beep); /* Timers */ startHeartbeatTimer(); //startRssTimer(); startPushQueueTimer(); /* Apache HTTP Monstrosity*/ httpClient = new DefaultHttpClient(); httpClient.getParams().setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 15 *1000); httpClient.getParams().setIntParameter(AllClientPNames.SO_TIMEOUT, 30 *1000); oclient = new OAuthClient(new HttpClient4()); /* Battery */ battery_receiver = new BatteryReceiver(); registerReceiver(battery_receiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); registerReceiver(battery_receiver, new IntentFilter(Intent.ACTION_POWER_CONNECTED)); registerReceiver(battery_receiver, new IntentFilter(Intent.ACTION_POWER_DISCONNECTED)); widget_receiver = new WidgetReceiver(); registerReceiver(widget_receiver, new IntentFilter("com.icecondor.nest.PIGEON_OFF")); registerReceiver(widget_receiver, new IntentFilter("com.icecondor.nest.PIGEON_ON")); registerReceiver(widget_receiver, new IntentFilter("com.icecondor.nest.PIGEON_INQUIRE")); /* Callbacks from the API Communication Thread */ pigeonHandler = new Handler(this); } protected void apiReconnect() { if (reconnectLastTry < (System.currentTimeMillis()-(30*1000))) { reconnectLastTry = System.currentTimeMillis(); rssdb.log("apiReconnect() "+ "\""+Thread.currentThread().getName()+"\""+" #"+Thread.currentThread().getId() ); if(apiSocket != null && apiSocket.isConnected()) { try { apiSocket.close(); } catch (IOException e) { } rssdb.log("Warning: Closing connected apiSocket"); } try { apiSocket = new ApiSocket(ICECONDOR_API_URL, pigeonHandler, "token"); apiSocket.connect(); pushQueue(); } catch (URISyntaxException e) { e.printStackTrace(); } } else { rssdb.log("apiReconnect() ignored. last try is "+ (System.currentTimeMillis()-reconnectLastTry)/1000+" sec ago "+ "\""+Thread.currentThread().getName()+"\""+" #"+Thread.currentThread().getId() ); } } public void onStart(Intent start, int key) { super.onStart(start,key); apiReconnect(); rssdb.log("Pigon started"); broadcastGpsFix(last_local_fix); } public void onDestroy() { unregisterReceiver(battery_receiver); unregisterReceiver(widget_receiver); stop_background(); rssdb.log("Pigon destroyed"); rssdb.close(); } private void notificationStatusUpdate(String msg) { ongoing_notification.setLatestEventInfo(this, "IceCondor", msg, contentIntent); ongoing_notification.when = System.currentTimeMillis(); notificationManager.notify(1, ongoing_notification); } private void notification(String msg) { Notification notification = new Notification(R.drawable.condorhead_statusbar, msg, System.currentTimeMillis()); // a contentView error is thrown if this line is not here notification.setLatestEventInfo(this, "IceCondor Notice", msg, contentIntent); notificationManager.notify(2, notification); } private void notificationFlash(String msg) { notification(msg); notificationManager.cancel(2); } private void startLocationUpdates() { long record_frequency = Long.decode(settings.getString(SETTING_TRANSMISSION_FREQUENCY, "300000")); rssdb.log("requesting Location Updates every "+ Util.millisecondsToWords(record_frequency)); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, record_frequency, 0.0F, this); locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, record_frequency, 0.0F, this); // Log.i(APP_TAG, "kicking off wifi scan timer"); // wifi_scan_timer.scheduleAtFixedRate( // new TimerTask() { // public void run() { // Log.i(APP_TAG, "wifi: start scan (enabled:"+wifiManager.isWifiEnabled()+")"); // wifiManager.startScan(); // } // }, 0, 60000); } private void stopLocationUpdates() { rssdb.log("pigeon: stopping location updates"); locationManager.removeUpdates(this); } @Override public IBinder onBind(Intent intent) { Log.i(APP_TAG,"onBind for "+intent.getExtras()); return pigeonBinder; } @Override public void onRebind(Intent intent) { Log.i(APP_TAG, "onReBind for "+intent.toString()); } @Override public void onLowMemory() { rssdb.log("Pigeon: onLowMemory"); } @Override public boolean onUnbind(Intent intent) { Log.i(APP_TAG, "Pigeon: onUnbind for "+intent.toString()); return false; } public void pushQueue() { Timer push_queue_timer_single = new Timer("Push Queue Single Timer"); push_queue_timer_single.schedule(new PushQueueTask(), 0); } class PushQueueTask extends TimerTask { public void run() { Cursor oldest; rssdb.log("** queue push size "+rssdb.countPositionQueueRemaining()+" \""+Thread.currentThread().getName()+"\""+" tid:"+Thread.currentThread().getId() ); if ((oldest = rssdb.oldestUnpushedLocationQueue()).getCount() > 0) { int id = oldest.getInt(oldest.getColumnIndex("_id")); rssdb.log("PushQueueTask oldest unpushed id "+id); Gps fix = Gps.fromJson(oldest.getString( oldest.getColumnIndex(GeoRss.POSITION_QUEUE_JSON))); rssdb.log("PushQueueTask after Gps.fromJson"); boolean status = pushLocationApi(fix); if (status == true) { rssdb.log("queue push #"+id+" OK"); rssdb.mark_as_pushed(id); last_pushed_fix = fix.getLocation(); last_pushed_time = System.currentTimeMillis(); broadcastBirdFix(fix.getLocation()); } else { rssdb.log("queue push #"+id+" FAIL "+status); } } oldest.close(); } } public boolean pushLocationApi(Gps gps) { rssdb.log("pushLocationApi: loading access token"); String[] token_and_secret = LocationStorageProviders.getDefaultAccessToken(this); JSONObject json = gps.toJson(); try { json.put("oauth_token", token_and_secret[0]); json.put("username", token_and_secret[1]); rssdb.log("pushLocationApi: "+json.toString()+" isConnected():"+apiSocket.isConnected()); boolean pass = apiSocket.emit(json.toString()); if(pass == false) { apiReconnect(); } return pass; } catch (JSONException e) { rssdb.log("pushLocationApi: JSONException "+e); } return false; } public int pushLocationRest(Gps gps) { Location fix = gps.getLocation(); Log.i(APP_TAG, "sending id: "+settings.getString(SETTING_OPENID,"")+ " fix: " +fix.getLatitude()+" long: "+fix.getLongitude()+ " alt: "+fix.getAltitude() + " time: " + Util.DateTimeIso8601(fix.getTime()) + " acc: "+fix.getAccuracy()); rssdb.log("pushing fix "+" time: " + Util.DateTimeIso8601(fix.getTime()) + "("+fix.getTime()+") acc: "+fix.getAccuracy()); if (settings.getBoolean(SETTING_BEEP_ON_FIX, false)) { play_fix_beep(); } //ArrayList <NameValuePair> params = new ArrayList <NameValuePair>(); ArrayList<Map.Entry<String, String>> params = new ArrayList<Map.Entry<String, String>>(); addPostParameters(params, fix, gps.getBattery()); OAuthAccessor accessor = LocationStorageProviders.defaultAccessor(this); String[] token_and_secret = LocationStorageProviders.getDefaultAccessToken(this); params.add(new OAuth.Parameter("oauth_token", token_and_secret[0])); accessor.tokenSecret = token_and_secret[1]; try { OAuthMessage omessage; Log.d(APP_TAG, "invoke("+accessor+", POST, "+ICECONDOR_WRITE_URL+", "+params); omessage = oclient.invoke(accessor, "POST", ICECONDOR_WRITE_URL, params); omessage.getHeader("Result"); last_fix_http_status = 200; return last_fix_http_status; } catch (OAuthException e) { rssdb.log("push OAuthException "+e); } catch (URISyntaxException e) { rssdb.log("push URISyntaxException "+e); } catch (UnknownHostException e) { rssdb.log("push UnknownHostException "+e); } catch (IOException e) { // includes host not found rssdb.log("push IOException "+e); } last_fix_http_status = 500; return last_fix_http_status; // something went wrong } private void addPostParameters(ArrayList<Map.Entry<String, String>> dict, Location fix, int lastBatteryLevel) { dict.add(new Util.Parameter("location[provider]", fix.getProvider())); dict.add(new Util.Parameter("location[latitude]", Double.toString(fix.getLatitude()))); dict.add(new Util.Parameter("location[longitude]", Double.toString(fix.getLongitude()))); dict.add(new Util.Parameter("location[altitude]", Double.toString(fix.getAltitude()))); dict.add(new Util.Parameter("client[version]", ""+ICECONDOR_VERSION)); if(fix.hasAccuracy()) { dict.add(new Util.Parameter("location[accuracy]", Double.toString(fix.getAccuracy()))); } if(fix.hasBearing()) { dict.add(new Util.Parameter("location[heading]", Double.toString(fix.getBearing()))); } if(fix.hasSpeed()) { dict.add(new Util.Parameter("location[velocity]", Double.toString(fix.getSpeed()))); } dict.add(new Util.Parameter("location[timestamp]", Util.DateTimeIso8601(fix.getTime()))); dict.add(new Util.Parameter("location[batterylevel]", Integer.toString(lastBatteryLevel))); } public void onLocationChanged(Location location) { Log.i(APP_TAG, "onLocationChanged: Thread \""+Thread.currentThread().getName()+"\""+" #"+Thread.currentThread().getId()); last_local_fix = location; long time_since_last_update = last_local_fix.getTime() - (last_recorded_fix == null?0:last_recorded_fix.getTime()); long record_frequency = Long.decode(settings.getString(SETTING_TRANSMISSION_FREQUENCY, "180000")); rssdb.log("pigeon onLocationChanged: lat:"+location.getLatitude()+ " long:"+location.getLongitude() + " acc:"+ location.getAccuracy()+" "+ (time_since_last_update/1000)+" seconds since last update"); if (on_switch) { if((last_local_fix.getAccuracy() < (last_recorded_fix == null? 500000:last_recorded_fix.getAccuracy())) || time_since_last_update > record_frequency ) { last_recorded_fix = last_local_fix; last_fix_http_status = 200; Gps gps = new Gps(); gps.setLocation(last_local_fix); gps.setBattery(last_battery_level); long id = rssdb.addPosition(gps.toJson().toString()); rssdb.log("Pigeon location queued. location #"+id); pushQueue(); broadcastGpsFix(location); } } } private void broadcastGpsFix(Location location) { Intent intent = new Intent(GPS_FIX_ACTION); intent.putExtra("location", location); sendBroadcast(intent); } private void broadcastBirdFix(Location location) { Intent intent = new Intent(BIRD_FIX_ACTION); intent.putExtra("location", location); sendBroadcast(intent); } private void play_fix_beep() { mp.start(); } public void onProviderDisabled(String provider) { rssdb.log("provider "+provider+" disabled"); } public void onProviderEnabled(String provider) { rssdb.log("provider "+provider+" enabled"); } public void onStatusChanged(String provider, int status, Bundle extras) { String status_msg = ""; if (status == LocationProvider.TEMPORARILY_UNAVAILABLE) {status_msg = "TEMPORARILY_UNAVAILABLE";} if (status == LocationProvider.OUT_OF_SERVICE) {status_msg = "OUT_OF_SERVICE";} if (status == LocationProvider.AVAILABLE) {status_msg = "AVAILABLE";} Log.i(APP_TAG, "provider "+provider+" status changed to "+status_msg); rssdb.log("GPS "+status_msg); } @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String pref_name) { Log.i(APP_TAG, "shared preference changed: "+pref_name); if (pref_name.equals(SETTING_TRANSMISSION_FREQUENCY)) { if (on_switch) { stopLocationUpdates(); startLocationUpdates(); notificationFlash("Position reporting frequency now "+Util.millisecondsToWords( Long.parseLong(prefs.getString(pref_name, "N/A")))); } } if (pref_name.equals(SETTING_RSS_READ_FREQUENCY)) { //stopRssTimer(); //startRssTimer(); notificationFlash("RSS Read frequency now "+Util.millisecondsToWords( Long.parseLong(prefs.getString(pref_name, "N/A")))); } } private void startHeartbeatTimer() { heartbeat_timer = new Timer("Heartbeat Timer"); heartbeatTask = new HeartBeatTask(); heartbeat_timer.scheduleAtFixedRate(heartbeatTask, 0, 20000); } private void stopHeartbeatTimer() { heartbeat_timer.cancel(); } private void startRssTimer() { rss_timer = new Timer("RSS Reader Timer"); long rss_read_frequency = Long.decode(settings.getString(SETTING_RSS_READ_FREQUENCY, "60000")); Log.i(APP_TAG, "starting rss timer at frequency "+rss_read_frequency); rss_timer.scheduleAtFixedRate( new TimerTask() { public void run() { Log.i(APP_TAG, "rss_timer fired"); updateRSS(); } }, 0, rss_read_frequency); } private void stopRssTimer() { rss_timer.cancel(); } private void startPushQueueTimer() { push_queue_timer = new Timer("Push Queue Timer"); push_queue_timer.scheduleAtFixedRate(new PushQueueTask(), 0, 30000); } private void stopPushQueueTimer() { push_queue_timer.cancel(); } protected void updateRSS() { new Timer().schedule( new TimerTask() { public void run() { Log.i(APP_TAG, "rss_timer fired"); Cursor geoRssUrls = rssdb.findFeeds(); while (geoRssUrls.moveToNext()) { try { rssdb.readGeoRss(geoRssUrls); } catch (ClientProtocolException e) { Log.i(APP_TAG, "http protocol exception "+e); } catch (IOException e) { Log.i(APP_TAG, "io error "+e); } } geoRssUrls.close(); } }, 0); } protected void start_background() { on_switch = true; settings.edit().putBoolean(SETTING_PIGEON_TRANSMITTING, on_switch).commit(); startLocationUpdates(); notificationStatusUpdate("Waiting for fix."); notificationFlash("Location reporting ON."); Intent intent = new Intent("com.icecondor.nest.WIDGET_ON"); sendBroadcast(intent); } protected void stop_background() { on_switch = false; //stopRssTimer(); stopLocationUpdates(); stopPushQueueTimer(); stopHeartbeatTimer(); settings.edit().putBoolean(SETTING_PIGEON_TRANSMITTING,on_switch).commit(); notificationManager.cancel(1); Intent intent = new Intent("com.icecondor.nest.WIDGET_OFF"); sendBroadcast(intent); } class HeartBeatTask extends TimerTask { public void run() { String fix_part = ""; if (on_switch) { if (last_pushed_fix != null) { String ago = Util.timeAgoInWords(last_pushed_time); String fago = Util.timeAgoInWords(last_pushed_fix.getTime()); if (last_fix_http_status != 200) { ago = "err."; } fix_part = "push "+ ago+"/"+fago+"."; } if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { fix_part = "Warning: GPS set to disabled"; } } else { fix_part = "Location reporting is off."; } String queue_part = ""+rssdb.countPositionQueueRemaining()+" queued."; String beat_part = ""; if (last_local_fix != null) { String ago = Util.timeAgoInWords(last_local_fix.getTime()); beat_part = "fix "+ago+"."; } String msg = fix_part+" "+beat_part+" "+queue_part; notificationStatusUpdate(msg); } }; private class BatteryReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals("android.intent.action.BATTERY_CHANGED")) { last_battery_level = intent.getIntExtra("level", 0); } if (action.equals("android.intent.action.ACTION_POWER_CONNECTED")) { ac_power = true; } if (action.equals("android.intent.action.ACTION_POWER_DISCONNECTED")) { ac_power = false; } } }; private class WidgetReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals("com.icecondor.nest.PIGEON_OFF")) { stopSelf(); } if (action.equals("com.icecondor.nest.PIGEON_ON")) { start_background(); } if (action.equals("com.icecondor.nest.PIGEON_INQUIRE")) { if(on_switch) { sendBroadcast(new Intent("com.icecondor.nest.WIDGET_ON")); } else { sendBroadcast(new Intent("com.icecondor.nest.WIDGET_ON")); } } } }; private final PigeonService.Stub pigeonBinder = new PigeonService.Stub() { public boolean isTransmitting() throws RemoteException { Log.i(APP_TAG, "isTransmitting => "+on_switch); return on_switch; } public void startTransmitting() throws RemoteException { if (on_switch) { Log.i(APP_TAG, "startTransmitting: already transmitting"); } else { rssdb.log("Pigeon: startTransmitting"); start_background(); } } public void stopTransmitting() throws RemoteException { rssdb.log("Pigeon: stopTransmitting"); stop_background(); } public Location getLastFix() throws RemoteException { if (last_local_fix != null) { broadcastGpsFix(last_local_fix); } return last_local_fix; } @Override public Location getLastPushedFix() throws RemoteException { if(last_pushed_fix != null) { broadcastBirdFix(last_pushed_fix); } return last_pushed_fix; } @Override public void refreshRSS() throws RemoteException { updateRSS(); } @Override public void pushFix() throws RemoteException { pushQueue(); } }; @Override public boolean handleMessage(Message msg) { rssdb.log("handleMessage: "+msg+" \""+Thread.currentThread().getName()+"\""+" #"+Thread.currentThread().getId()); return true; } }
src/com/icecondor/nest/Pigeon.java
package com.icecondor.nest; import java.io.IOException; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import net.oauth.OAuth; import net.oauth.OAuthAccessor; import net.oauth.OAuthException; import net.oauth.OAuthMessage; import net.oauth.client.OAuthClient; import net.oauth.client.httpclient4.HttpClient4; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.params.AllClientPNames; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.media.MediaPlayer; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.RemoteException; import android.os.Process; import android.preference.PreferenceManager; import android.util.Log; import com.icecondor.nest.db.GeoRss; import com.icecondor.nest.db.LocationStorageProviders; import com.icecondor.nest.types.Gps; //look at android.permission.RECEIVE_BOOT_COMPLETED public class Pigeon extends Service implements Constants, LocationListener, SharedPreferences.OnSharedPreferenceChangeListener, Handler.Callback { private Timer heartbeat_timer; private Timer rss_timer; private Timer push_queue_timer; //private Timer wifi_scan_timer = new Timer(); boolean on_switch = false; private Location last_recorded_fix, last_pushed_fix, last_local_fix; long last_pushed_time; int last_fix_http_status; Notification ongoing_notification; NotificationManager notificationManager; LocationManager locationManager; WifiManager wifiManager; PendingIntent contentIntent; SharedPreferences settings; GeoRss rssdb; MediaPlayer mp; private TimerTask heartbeatTask; DefaultHttpClient httpClient; OAuthClient oclient; private int last_battery_level; BatteryReceiver battery_receiver; WidgetReceiver widget_receiver; private boolean ac_power; ApiSocket apiSocket; Handler pigeonHandler; long reconnectLastTry; public void onCreate() { Log.i(APP_TAG, "*** Pigeon service created. "+ "\""+Thread.currentThread().getName()+"\""+" tid:"+Thread.currentThread().getId()+ " uid:"+Process.myUid()); super.onCreate(); /* Database */ rssdb = new GeoRss(this); rssdb.open(); rssdb.log("Pigon created"); /* GPS */ locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); rssdb.log("GPS provider enabled: "+locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)); last_local_fix = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); rssdb.log("NETWORK provider enabled: "+locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)); Location last_network_fix = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (last_local_fix == null) { if(last_network_fix != null) { last_local_fix = last_network_fix; // fall back onto the network location rssdb.log("Last known NETWORK fix: "+last_network_fix+" "+ Util.DateTimeIso8601(last_network_fix.getTime())); } } else { rssdb.log("Last known GPS fix: "+last_local_fix+" "+ Util.DateTimeIso8601(last_local_fix.getTime())); } Cursor oldest; if ((oldest = rssdb.oldestPushedLocationQueue()).getCount() > 0) { rssdb.log("Oldest pushed fix found"); last_pushed_fix = Gps.fromJson(oldest.getString( oldest.getColumnIndex(GeoRss.POSITION_QUEUE_JSON))).getLocation(); } oldest.close(); /* WIFI */ wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); /* Notifications */ notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Start.class), 0); CharSequence text = getText(R.string.status_started); ongoing_notification = new Notification(R.drawable.condorhead_statusbar, text, System .currentTimeMillis()); ongoing_notification.flags = ongoing_notification.flags ^ Notification.FLAG_ONGOING_EVENT; ongoing_notification.setLatestEventInfo(this, "IceCondor", "", contentIntent); /* Preferences */ settings = PreferenceManager.getDefaultSharedPreferences(this); settings.registerOnSharedPreferenceChangeListener(this); on_switch = settings.getBoolean(SETTING_PIGEON_TRANSMITTING, false); if (on_switch) { //startForeground(1, ongoing_notification); startLocationUpdates(); sendBroadcast(new Intent("com.icecondor.nest.WIDGET_ON")); } /* Sound */ mp = MediaPlayer.create(this, R.raw.beep); /* Timers */ startHeartbeatTimer(); //startRssTimer(); startPushQueueTimer(); /* Apache HTTP Monstrosity*/ httpClient = new DefaultHttpClient(); httpClient.getParams().setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 15 *1000); httpClient.getParams().setIntParameter(AllClientPNames.SO_TIMEOUT, 30 *1000); oclient = new OAuthClient(new HttpClient4()); /* Battery */ battery_receiver = new BatteryReceiver(); registerReceiver(battery_receiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); registerReceiver(battery_receiver, new IntentFilter(Intent.ACTION_POWER_CONNECTED)); registerReceiver(battery_receiver, new IntentFilter(Intent.ACTION_POWER_DISCONNECTED)); widget_receiver = new WidgetReceiver(); registerReceiver(widget_receiver, new IntentFilter("com.icecondor.nest.PIGEON_OFF")); registerReceiver(widget_receiver, new IntentFilter("com.icecondor.nest.PIGEON_ON")); registerReceiver(widget_receiver, new IntentFilter("com.icecondor.nest.PIGEON_INQUIRE")); /* Callbacks from the API Communication Thread */ pigeonHandler = new Handler(this); } protected void apiReconnect() { if (reconnectLastTry < (System.currentTimeMillis()-(30*1000))) { reconnectLastTry = System.currentTimeMillis(); rssdb.log("apiReconnect() "+ "\""+Thread.currentThread().getName()+"\""+" #"+Thread.currentThread().getId() ); if(apiSocket != null && apiSocket.isConnected()) { try { apiSocket.close(); } catch (IOException e) { } rssdb.log("Warning: Closing connected apiSocket"); } try { apiSocket = new ApiSocket(ICECONDOR_API_URL, pigeonHandler, "token"); apiSocket.connect(); } catch (URISyntaxException e) { e.printStackTrace(); } } else { rssdb.log("apiReconnect() ignored. last try is "+ (System.currentTimeMillis()-reconnectLastTry)/1000+" sec ago "+ "\""+Thread.currentThread().getName()+"\""+" #"+Thread.currentThread().getId() ); } } public void onStart(Intent start, int key) { super.onStart(start,key); apiReconnect(); rssdb.log("Pigon started"); broadcastGpsFix(last_local_fix); } public void onDestroy() { unregisterReceiver(battery_receiver); unregisterReceiver(widget_receiver); stop_background(); rssdb.log("Pigon destroyed"); rssdb.close(); } private void notificationStatusUpdate(String msg) { ongoing_notification.setLatestEventInfo(this, "IceCondor", msg, contentIntent); ongoing_notification.when = System.currentTimeMillis(); notificationManager.notify(1, ongoing_notification); } private void notification(String msg) { Notification notification = new Notification(R.drawable.condorhead_statusbar, msg, System.currentTimeMillis()); // a contentView error is thrown if this line is not here notification.setLatestEventInfo(this, "IceCondor Notice", msg, contentIntent); notificationManager.notify(2, notification); } private void notificationFlash(String msg) { notification(msg); notificationManager.cancel(2); } private void startLocationUpdates() { long record_frequency = Long.decode(settings.getString(SETTING_TRANSMISSION_FREQUENCY, "300000")); rssdb.log("requesting Location Updates every "+ Util.millisecondsToWords(record_frequency)); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, record_frequency, 0.0F, this); locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, record_frequency, 0.0F, this); // Log.i(APP_TAG, "kicking off wifi scan timer"); // wifi_scan_timer.scheduleAtFixedRate( // new TimerTask() { // public void run() { // Log.i(APP_TAG, "wifi: start scan (enabled:"+wifiManager.isWifiEnabled()+")"); // wifiManager.startScan(); // } // }, 0, 60000); } private void stopLocationUpdates() { rssdb.log("pigeon: stopping location updates"); locationManager.removeUpdates(this); } @Override public IBinder onBind(Intent intent) { Log.i(APP_TAG,"onBind for "+intent.getExtras()); return pigeonBinder; } @Override public void onRebind(Intent intent) { Log.i(APP_TAG, "onReBind for "+intent.toString()); } @Override public void onLowMemory() { rssdb.log("Pigeon: onLowMemory"); } @Override public boolean onUnbind(Intent intent) { Log.i(APP_TAG, "Pigeon: onUnbind for "+intent.toString()); return false; } public void pushQueue() { Timer push_queue_timer_single = new Timer("Push Queue Single Timer"); push_queue_timer_single.schedule(new PushQueueTask(), 0); } class PushQueueTask extends TimerTask { public void run() { Cursor oldest; rssdb.log("** queue push size "+rssdb.countPositionQueueRemaining()+" \""+Thread.currentThread().getName()+"\""+" tid:"+Thread.currentThread().getId() ); if ((oldest = rssdb.oldestUnpushedLocationQueue()).getCount() > 0) { int id = oldest.getInt(oldest.getColumnIndex("_id")); rssdb.log("PushQueueTask oldest unpushed id "+id); Gps fix = Gps.fromJson(oldest.getString( oldest.getColumnIndex(GeoRss.POSITION_QUEUE_JSON))); rssdb.log("PushQueueTask after Gps.fromJson"); boolean status = pushLocationApi(fix); if (status == true) { rssdb.log("queue push #"+id+" OK"); rssdb.mark_as_pushed(id); last_pushed_fix = fix.getLocation(); last_pushed_time = System.currentTimeMillis(); broadcastBirdFix(fix.getLocation()); } else { rssdb.log("queue push #"+id+" FAIL "+status); } } oldest.close(); } } public boolean pushLocationApi(Gps gps) { rssdb.log("pushLocationApi: loading access token"); String[] token_and_secret = LocationStorageProviders.getDefaultAccessToken(this); JSONObject json = gps.toJson(); try { json.put("oauth_token", token_and_secret[0]); json.put("username", token_and_secret[1]); rssdb.log("pushLocationApi: "+json.toString()+" isConnected():"+apiSocket.isConnected()); boolean pass = apiSocket.emit(json.toString()); if(pass == false) { apiReconnect(); } return pass; } catch (JSONException e) { rssdb.log("pushLocationApi: JSONException "+e); } return false; } public int pushLocationRest(Gps gps) { Location fix = gps.getLocation(); Log.i(APP_TAG, "sending id: "+settings.getString(SETTING_OPENID,"")+ " fix: " +fix.getLatitude()+" long: "+fix.getLongitude()+ " alt: "+fix.getAltitude() + " time: " + Util.DateTimeIso8601(fix.getTime()) + " acc: "+fix.getAccuracy()); rssdb.log("pushing fix "+" time: " + Util.DateTimeIso8601(fix.getTime()) + "("+fix.getTime()+") acc: "+fix.getAccuracy()); if (settings.getBoolean(SETTING_BEEP_ON_FIX, false)) { play_fix_beep(); } //ArrayList <NameValuePair> params = new ArrayList <NameValuePair>(); ArrayList<Map.Entry<String, String>> params = new ArrayList<Map.Entry<String, String>>(); addPostParameters(params, fix, gps.getBattery()); OAuthAccessor accessor = LocationStorageProviders.defaultAccessor(this); String[] token_and_secret = LocationStorageProviders.getDefaultAccessToken(this); params.add(new OAuth.Parameter("oauth_token", token_and_secret[0])); accessor.tokenSecret = token_and_secret[1]; try { OAuthMessage omessage; Log.d(APP_TAG, "invoke("+accessor+", POST, "+ICECONDOR_WRITE_URL+", "+params); omessage = oclient.invoke(accessor, "POST", ICECONDOR_WRITE_URL, params); omessage.getHeader("Result"); last_fix_http_status = 200; return last_fix_http_status; } catch (OAuthException e) { rssdb.log("push OAuthException "+e); } catch (URISyntaxException e) { rssdb.log("push URISyntaxException "+e); } catch (UnknownHostException e) { rssdb.log("push UnknownHostException "+e); } catch (IOException e) { // includes host not found rssdb.log("push IOException "+e); } last_fix_http_status = 500; return last_fix_http_status; // something went wrong } private void addPostParameters(ArrayList<Map.Entry<String, String>> dict, Location fix, int lastBatteryLevel) { dict.add(new Util.Parameter("location[provider]", fix.getProvider())); dict.add(new Util.Parameter("location[latitude]", Double.toString(fix.getLatitude()))); dict.add(new Util.Parameter("location[longitude]", Double.toString(fix.getLongitude()))); dict.add(new Util.Parameter("location[altitude]", Double.toString(fix.getAltitude()))); dict.add(new Util.Parameter("client[version]", ""+ICECONDOR_VERSION)); if(fix.hasAccuracy()) { dict.add(new Util.Parameter("location[accuracy]", Double.toString(fix.getAccuracy()))); } if(fix.hasBearing()) { dict.add(new Util.Parameter("location[heading]", Double.toString(fix.getBearing()))); } if(fix.hasSpeed()) { dict.add(new Util.Parameter("location[velocity]", Double.toString(fix.getSpeed()))); } dict.add(new Util.Parameter("location[timestamp]", Util.DateTimeIso8601(fix.getTime()))); dict.add(new Util.Parameter("location[batterylevel]", Integer.toString(lastBatteryLevel))); } public void onLocationChanged(Location location) { Log.i(APP_TAG, "onLocationChanged: Thread \""+Thread.currentThread().getName()+"\""+" #"+Thread.currentThread().getId()); last_local_fix = location; long time_since_last_update = last_local_fix.getTime() - (last_recorded_fix == null?0:last_recorded_fix.getTime()); long record_frequency = Long.decode(settings.getString(SETTING_TRANSMISSION_FREQUENCY, "180000")); rssdb.log("pigeon onLocationChanged: lat:"+location.getLatitude()+ " long:"+location.getLongitude() + " acc:"+ location.getAccuracy()+" "+ (time_since_last_update/1000)+" seconds since last update"); if (on_switch) { if((last_local_fix.getAccuracy() < (last_recorded_fix == null? 500000:last_recorded_fix.getAccuracy())) || time_since_last_update > record_frequency ) { last_recorded_fix = last_local_fix; last_fix_http_status = 200; Gps gps = new Gps(); gps.setLocation(last_local_fix); gps.setBattery(last_battery_level); long id = rssdb.addPosition(gps.toJson().toString()); rssdb.log("Pigeon location queued. location #"+id); pushQueue(); broadcastGpsFix(location); } } } private void broadcastGpsFix(Location location) { Intent intent = new Intent(GPS_FIX_ACTION); intent.putExtra("location", location); sendBroadcast(intent); } private void broadcastBirdFix(Location location) { Intent intent = new Intent(BIRD_FIX_ACTION); intent.putExtra("location", location); sendBroadcast(intent); } private void play_fix_beep() { mp.start(); } public void onProviderDisabled(String provider) { rssdb.log("provider "+provider+" disabled"); } public void onProviderEnabled(String provider) { rssdb.log("provider "+provider+" enabled"); } public void onStatusChanged(String provider, int status, Bundle extras) { String status_msg = ""; if (status == LocationProvider.TEMPORARILY_UNAVAILABLE) {status_msg = "TEMPORARILY_UNAVAILABLE";} if (status == LocationProvider.OUT_OF_SERVICE) {status_msg = "OUT_OF_SERVICE";} if (status == LocationProvider.AVAILABLE) {status_msg = "AVAILABLE";} Log.i(APP_TAG, "provider "+provider+" status changed to "+status_msg); rssdb.log("GPS "+status_msg); } @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String pref_name) { Log.i(APP_TAG, "shared preference changed: "+pref_name); if (pref_name.equals(SETTING_TRANSMISSION_FREQUENCY)) { if (on_switch) { stopLocationUpdates(); startLocationUpdates(); notificationFlash("Position reporting frequency now "+Util.millisecondsToWords( Long.parseLong(prefs.getString(pref_name, "N/A")))); } } if (pref_name.equals(SETTING_RSS_READ_FREQUENCY)) { //stopRssTimer(); //startRssTimer(); notificationFlash("RSS Read frequency now "+Util.millisecondsToWords( Long.parseLong(prefs.getString(pref_name, "N/A")))); } } private void startHeartbeatTimer() { heartbeat_timer = new Timer("Heartbeat Timer"); heartbeatTask = new HeartBeatTask(); heartbeat_timer.scheduleAtFixedRate(heartbeatTask, 0, 20000); } private void stopHeartbeatTimer() { heartbeat_timer.cancel(); } private void startRssTimer() { rss_timer = new Timer("RSS Reader Timer"); long rss_read_frequency = Long.decode(settings.getString(SETTING_RSS_READ_FREQUENCY, "60000")); Log.i(APP_TAG, "starting rss timer at frequency "+rss_read_frequency); rss_timer.scheduleAtFixedRate( new TimerTask() { public void run() { Log.i(APP_TAG, "rss_timer fired"); updateRSS(); } }, 0, rss_read_frequency); } private void stopRssTimer() { rss_timer.cancel(); } private void startPushQueueTimer() { push_queue_timer = new Timer("Push Queue Timer"); push_queue_timer.scheduleAtFixedRate(new PushQueueTask(), 0, 30000); } private void stopPushQueueTimer() { push_queue_timer.cancel(); } protected void updateRSS() { new Timer().schedule( new TimerTask() { public void run() { Log.i(APP_TAG, "rss_timer fired"); Cursor geoRssUrls = rssdb.findFeeds(); while (geoRssUrls.moveToNext()) { try { rssdb.readGeoRss(geoRssUrls); } catch (ClientProtocolException e) { Log.i(APP_TAG, "http protocol exception "+e); } catch (IOException e) { Log.i(APP_TAG, "io error "+e); } } geoRssUrls.close(); } }, 0); } protected void start_background() { on_switch = true; settings.edit().putBoolean(SETTING_PIGEON_TRANSMITTING, on_switch).commit(); startLocationUpdates(); notificationStatusUpdate("Waiting for fix."); notificationFlash("Location reporting ON."); Intent intent = new Intent("com.icecondor.nest.WIDGET_ON"); sendBroadcast(intent); } protected void stop_background() { on_switch = false; //stopRssTimer(); stopLocationUpdates(); stopPushQueueTimer(); stopHeartbeatTimer(); settings.edit().putBoolean(SETTING_PIGEON_TRANSMITTING,on_switch).commit(); notificationManager.cancel(1); Intent intent = new Intent("com.icecondor.nest.WIDGET_OFF"); sendBroadcast(intent); } class HeartBeatTask extends TimerTask { public void run() { String fix_part = ""; if (on_switch) { if (last_pushed_fix != null) { String ago = Util.timeAgoInWords(last_pushed_time); String fago = Util.timeAgoInWords(last_pushed_fix.getTime()); if (last_fix_http_status != 200) { ago = "err."; } fix_part = "push "+ ago+"/"+fago+"."; } if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { fix_part = "Warning: GPS set to disabled"; } } else { fix_part = "Location reporting is off."; } String queue_part = ""+rssdb.countPositionQueueRemaining()+" queued."; String beat_part = ""; if (last_local_fix != null) { String ago = Util.timeAgoInWords(last_local_fix.getTime()); beat_part = "fix "+ago+"."; } String msg = fix_part+" "+beat_part+" "+queue_part; notificationStatusUpdate(msg); } }; private class BatteryReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals("android.intent.action.BATTERY_CHANGED")) { last_battery_level = intent.getIntExtra("level", 0); } if (action.equals("android.intent.action.ACTION_POWER_CONNECTED")) { ac_power = true; } if (action.equals("android.intent.action.ACTION_POWER_DISCONNECTED")) { ac_power = false; } } }; private class WidgetReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals("com.icecondor.nest.PIGEON_OFF")) { stopSelf(); } if (action.equals("com.icecondor.nest.PIGEON_ON")) { start_background(); } if (action.equals("com.icecondor.nest.PIGEON_INQUIRE")) { if(on_switch) { sendBroadcast(new Intent("com.icecondor.nest.WIDGET_ON")); } else { sendBroadcast(new Intent("com.icecondor.nest.WIDGET_ON")); } } } }; private final PigeonService.Stub pigeonBinder = new PigeonService.Stub() { public boolean isTransmitting() throws RemoteException { Log.i(APP_TAG, "isTransmitting => "+on_switch); return on_switch; } public void startTransmitting() throws RemoteException { if (on_switch) { Log.i(APP_TAG, "startTransmitting: already transmitting"); } else { rssdb.log("Pigeon: startTransmitting"); start_background(); } } public void stopTransmitting() throws RemoteException { rssdb.log("Pigeon: stopTransmitting"); stop_background(); } public Location getLastFix() throws RemoteException { if (last_local_fix != null) { broadcastGpsFix(last_local_fix); } return last_local_fix; } @Override public Location getLastPushedFix() throws RemoteException { if(last_pushed_fix != null) { broadcastBirdFix(last_pushed_fix); } return last_pushed_fix; } @Override public void refreshRSS() throws RemoteException { updateRSS(); } @Override public void pushFix() throws RemoteException { pushQueue(); } }; @Override public boolean handleMessage(Message msg) { rssdb.log("handleMessage: "+msg+" \""+Thread.currentThread().getName()+"\""+" #"+Thread.currentThread().getId()); return true; } }
get a little more agressive about queue pushing
src/com/icecondor/nest/Pigeon.java
get a little more agressive about queue pushing
<ide><path>rc/com/icecondor/nest/Pigeon.java <ide> try { <ide> apiSocket = new ApiSocket(ICECONDOR_API_URL, pigeonHandler, "token"); <ide> apiSocket.connect(); <add> pushQueue(); <ide> } catch (URISyntaxException e) { <ide> e.printStackTrace(); <ide> }
Java
apache-2.0
error: pathspec 'src/test/java/mkl/testarea/pdfbox2/content/ArrangeText.java' did not match any file(s) known to git
5debefcb8ed476d1cfb63db67e2025d823ec443c
1
mkl-public/testarea-pdfbox2
package mkl.testarea.pdfbox2.content; import java.io.File; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDType1Font; import org.junit.BeforeClass; import org.junit.Test; /** * @author mkl */ public class ArrangeText { final static File RESULT_FOLDER = new File("target/test-outputs", "content"); @BeforeClass public static void setUpBeforeClass() throws Exception { RESULT_FOLDER.mkdirs(); } /** * <a href="https://stackoverflow.com/questions/46908322/apache-pdfbox-how-can-i-specify-the-position-of-the-texts-im-outputting"> * Apache PDFBox: How can I specify the position of the texts I'm outputting * </a> * <p> * This test shows how to arrange text pieces using relative coordinates * to move from line start to line start. * </p> */ @Test public void testArrangeTextForTeamotea() throws IOException { try (PDDocument document = new PDDocument()) { PDPage page = new PDPage(); document.addPage(page); PDFont font = PDType1Font.HELVETICA; String text = "Text 1"; String text1 = "Text 2"; String text2 = "Text 3"; String text3 = "Text 4"; String text4 = "Text 5"; String text5 = "Text 6"; try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) { contentStream.beginText(); contentStream.newLineAtOffset(175, 670); contentStream.setFont(font, 12); contentStream.setLeading(15); contentStream.showText(text); contentStream.newLine(); contentStream.showText(text1); contentStream.newLineAtOffset(225, 10); contentStream.setFont(font, 15); contentStream.showText(text2); contentStream.newLineAtOffset(-390, -175); contentStream.setFont(font, 13.5f); contentStream.setLeading(17); contentStream.showText(text3); contentStream.newLine(); contentStream.showText(text5); contentStream.newLineAtOffset(300, 13.5f); contentStream.showText(text4); contentStream.endText(); contentStream.moveTo(0, 520); contentStream.lineTo(612, 520); contentStream.stroke(); } document.save(new File(RESULT_FOLDER, "arrangedText.pdf")); } } }
src/test/java/mkl/testarea/pdfbox2/content/ArrangeText.java
New ArrangeText test focusing on the stack overflow question Apache PDFBox: How can I specify the position of the texts I'm outputting https://stackoverflow.com/questions/46908322/apache-pdfbox-how-can-i-specify-the-position-of-the-texts-im-outputting This test shows how to arrange text pieces using relative coordinates to move from line start to line start.
src/test/java/mkl/testarea/pdfbox2/content/ArrangeText.java
New ArrangeText test focusing on the stack overflow question
<ide><path>rc/test/java/mkl/testarea/pdfbox2/content/ArrangeText.java <add>package mkl.testarea.pdfbox2.content; <add> <add>import java.io.File; <add>import java.io.IOException; <add> <add>import org.apache.pdfbox.pdmodel.PDDocument; <add>import org.apache.pdfbox.pdmodel.PDPage; <add>import org.apache.pdfbox.pdmodel.PDPageContentStream; <add>import org.apache.pdfbox.pdmodel.font.PDFont; <add>import org.apache.pdfbox.pdmodel.font.PDType1Font; <add>import org.junit.BeforeClass; <add>import org.junit.Test; <add> <add>/** <add> * @author mkl <add> */ <add>public class ArrangeText { <add> final static File RESULT_FOLDER = new File("target/test-outputs", "content"); <add> <add> @BeforeClass <add> public static void setUpBeforeClass() throws Exception <add> { <add> RESULT_FOLDER.mkdirs(); <add> } <add> <add> /** <add> * <a href="https://stackoverflow.com/questions/46908322/apache-pdfbox-how-can-i-specify-the-position-of-the-texts-im-outputting"> <add> * Apache PDFBox: How can I specify the position of the texts I'm outputting <add> * </a> <add> * <p> <add> * This test shows how to arrange text pieces using relative coordinates <add> * to move from line start to line start. <add> * </p> <add> */ <add> @Test <add> public void testArrangeTextForTeamotea() throws IOException { <add> try (PDDocument document = new PDDocument()) { <add> PDPage page = new PDPage(); <add> document.addPage(page); <add> <add> PDFont font = PDType1Font.HELVETICA; <add> <add> String text = "Text 1"; <add> String text1 = "Text 2"; <add> String text2 = "Text 3"; <add> String text3 = "Text 4"; <add> String text4 = "Text 5"; <add> String text5 = "Text 6"; <add> <add> try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) { <add> contentStream.beginText(); <add> <add> contentStream.newLineAtOffset(175, 670); <add> contentStream.setFont(font, 12); <add> contentStream.setLeading(15); <add> contentStream.showText(text); <add> contentStream.newLine(); <add> contentStream.showText(text1); <add> <add> contentStream.newLineAtOffset(225, 10); <add> contentStream.setFont(font, 15); <add> contentStream.showText(text2); <add> <add> contentStream.newLineAtOffset(-390, -175); <add> contentStream.setFont(font, 13.5f); <add> contentStream.setLeading(17); <add> contentStream.showText(text3); <add> contentStream.newLine(); <add> contentStream.showText(text5); <add> <add> contentStream.newLineAtOffset(300, 13.5f); <add> contentStream.showText(text4); <add> <add> contentStream.endText(); <add> <add> contentStream.moveTo(0, 520); <add> contentStream.lineTo(612, 520); <add> contentStream.stroke(); <add> } <add> <add> document.save(new File(RESULT_FOLDER, "arrangedText.pdf")); <add> } <add> } <add> <add>}
Java
apache-2.0
3d5e8086342da1cf66be032c3fd8fe0024508dad
0
phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida
package ca.corefacility.bioinformatics.irida.model.enums; import static com.google.common.base.Preconditions.checkNotNull; import java.util.HashMap; import java.util.Map; /** * Defins a set of states that an analysis submission can be in. * * @author Aaron Petkau <[email protected]> * */ public enum AnalysisState { /** * Occurs when an analysis is first submitted. */ SUBMITTED("SUBMITTED"), /** * An analysis that is executing in the execution manager. */ RUNNING("RUNNING"), /** * An analysis that has finished running in the execution manager. */ FINISHED_RUNNING("FINISHED_RUNNING"), /** * An analysis that has completed and been loaded into IRIDA. */ COMPLETED("COMPLETED"), /** * An analysis that was not successfully able to run. */ ERROR("ERROR"); private static Map<String, AnalysisState> stateMap = new HashMap<>(); private String stateString; /** * Sets of a Map used to convert a string to a WorkflowState */ static { for (AnalysisState state : AnalysisState.values()) { stateMap.put(state.toString(), state); } } private AnalysisState(String stateString) { this.stateString = stateString; } /** * Given a string defining a state, converts this to a AnalysisState. * @param stateString The string defining the state. * @return A AnalysisState for the corresponding state. */ public static AnalysisState fromString(String stateString) { AnalysisState state = stateMap.get(stateString); checkNotNull(state, "state for string \"" + stateString + "\" does not exist"); return state; } @Override public String toString() { return stateString; } }
src/main/java/ca/corefacility/bioinformatics/irida/model/enums/AnalysisState.java
package ca.corefacility.bioinformatics.irida.model.enums; /** * Defins a set of states that an analysis submission can be in. * * @author Aaron Petkau <[email protected]> * */ public enum AnalysisState { /** * Occurs when an analysis is first submitted. */ SUBMITTED, /** * An analysis that is executing in the execution manager. */ RUNNING, /** * An analysis that has finished running in the execution manager. */ FINISHED_RUNNING, /** * An analysis that has completed and been loaded into IRIDA. */ COMPLETED, /** * An analysis that was not successfully able to run. */ ERROR; }
Modified analysis state
src/main/java/ca/corefacility/bioinformatics/irida/model/enums/AnalysisState.java
Modified analysis state
<ide><path>rc/main/java/ca/corefacility/bioinformatics/irida/model/enums/AnalysisState.java <ide> package ca.corefacility.bioinformatics.irida.model.enums; <add> <add>import static com.google.common.base.Preconditions.checkNotNull; <add> <add>import java.util.HashMap; <add>import java.util.Map; <ide> <ide> /** <ide> * Defins a set of states that an analysis submission can be in. <ide> /** <ide> * Occurs when an analysis is first submitted. <ide> */ <del> SUBMITTED, <add> SUBMITTED("SUBMITTED"), <ide> <ide> /** <ide> * An analysis that is executing in the execution manager. <ide> */ <del> RUNNING, <add> RUNNING("RUNNING"), <ide> <ide> /** <ide> * An analysis that has finished running in the execution manager. <ide> */ <del> FINISHED_RUNNING, <add> FINISHED_RUNNING("FINISHED_RUNNING"), <ide> <ide> /** <ide> * An analysis that has completed and been loaded into IRIDA. <ide> */ <del> COMPLETED, <add> COMPLETED("COMPLETED"), <ide> <ide> /** <ide> * An analysis that was not successfully able to run. <ide> */ <del> ERROR; <add> ERROR("ERROR"); <add> <add> private static Map<String, AnalysisState> stateMap = new HashMap<>(); <add> private String stateString; <add> <add> /** <add> * Sets of a Map used to convert a string to a WorkflowState <add> */ <add> static { <add> for (AnalysisState state : AnalysisState.values()) { <add> stateMap.put(state.toString(), state); <add> } <add> } <add> <add> private AnalysisState(String stateString) { <add> this.stateString = stateString; <add> } <add> <add> /** <add> * Given a string defining a state, converts this to a AnalysisState. <add> * @param stateString The string defining the state. <add> * @return A AnalysisState for the corresponding state. <add> */ <add> public static AnalysisState fromString(String stateString) { <add> AnalysisState state = stateMap.get(stateString); <add> checkNotNull(state, "state for string \"" + stateString + "\" does not exist"); <add> <add> return state; <add> } <add> <add> @Override <add> public String toString() { <add> return stateString; <add> } <ide> }
Java
apache-2.0
c83f8c757ba5c82a0e0c228998c2aaa487c4be7f
0
real-logic/benchmarks,real-logic/benchmarks,real-logic/benchmarks
/* * Copyright 2015 Real Logic 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 uk.co.real_logic.benchmarks.latency; public class Configuration { public static final int MAX_THREAD_COUNT = 4; public static final int SEND_QUEUE_CAPACITY = 64 * 1024; public static final int RESPONSE_QUEUE_CAPACITY = 32 * 1024; }
src/jmh/java/uk/co/real_logic/benchmarks/latency/Configuration.java
/* * Copyright 2015 Real Logic 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 uk.co.real_logic.benchmarks.latency; public class Configuration { public static final int MAX_THREAD_COUNT = 4; public static final int SEND_QUEUE_CAPACITY = 64 * 1024; public static final int RESPONSE_QUEUE_CAPACITY = 4 * 1024; }
Increase size of response queue.
src/jmh/java/uk/co/real_logic/benchmarks/latency/Configuration.java
Increase size of response queue.
<ide><path>rc/jmh/java/uk/co/real_logic/benchmarks/latency/Configuration.java <ide> { <ide> public static final int MAX_THREAD_COUNT = 4; <ide> public static final int SEND_QUEUE_CAPACITY = 64 * 1024; <del> public static final int RESPONSE_QUEUE_CAPACITY = 4 * 1024; <add> public static final int RESPONSE_QUEUE_CAPACITY = 32 * 1024; <ide> }
Java
apache-2.0
3abed5ddc9c1f568347ca16b6bed87a927d15fa0
0
gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa
package uk.ac.ebi.gxa.loader.service; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Iterators; import com.google.common.collect.ListMultimap; import uk.ac.ebi.arrayexpress2.magetab.datamodel.IDF; import uk.ac.ebi.gxa.loader.AtlasLoaderException; import uk.ac.ebi.gxa.loader.DefaultAtlasLoader; import uk.ac.ebi.gxa.loader.UpdateNetCDFForExperimentCommand; import uk.ac.ebi.gxa.loader.datamatrix.DataMatrixStorage; import uk.ac.ebi.gxa.netcdf.generator.NetCDFCreator; import uk.ac.ebi.gxa.netcdf.generator.NetCDFCreatorException; import uk.ac.ebi.gxa.netcdf.reader.NetCDFProxy; import uk.ac.ebi.gxa.utils.EfvTree; import uk.ac.ebi.gxa.utils.Maker; import uk.ac.ebi.gxa.utils.Pair; import uk.ac.ebi.microarray.atlas.model.*; import javax.annotation.Nonnull; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; import static com.google.common.collect.Collections2.transform; import static com.google.common.collect.Iterators.concat; import static com.google.common.collect.Iterators.filter; import static com.google.common.io.Closeables.closeQuietly; import static com.google.common.primitives.Floats.asList; import static uk.ac.ebi.gxa.utils.CountIterator.zeroTo; import static uk.ac.ebi.gxa.utils.FileUtil.extension; /** * NetCDF updater service which preserves expression values information, but updates all properties * * @author pashky */ public class AtlasNetCDFUpdaterService extends AtlasLoaderService { private static final Function<File, String> GET_NAME = new Function<File, String>() { public String apply(@Nonnull File file) { return file.getName(); } }; public AtlasNetCDFUpdaterService(DefaultAtlasLoader atlasLoader) { super(atlasLoader); } private static class CBitSet extends BitSet implements Comparable<CBitSet> { private CBitSet(int nbits) { super(nbits); } public int compareTo(CBitSet o) { for (int i = 0; i < Math.max(size(), o.size()); ++i) { boolean b1 = get(i); boolean b2 = o.get(i); if (b1 != b2) return b1 ? 1 : -1; } return 0; } } private static class CPair<T1 extends Comparable<T1>, T2 extends Comparable<T2>> extends Pair<T1, T2> implements Comparable<CPair<T1, T2>> { private CPair(T1 first, T2 second) { super(first, second); } public int compareTo(CPair<T1, T2> o) { int d = getFirst().compareTo(o.getFirst()); return d != 0 ? d : getSecond().compareTo(o.getSecond()); } } private EfvTree<CPair<String, String>> matchEfvs(EfvTree<CBitSet> from, EfvTree<CBitSet> to) { final List<EfvTree.Ef<CBitSet>> fromTree = matchEfvsSort(from); final List<EfvTree.Ef<CBitSet>> toTree = matchEfvsSort(to); EfvTree<CPair<String, String>> result = new EfvTree<CPair<String, String>>(); for (EfvTree.Ef<CBitSet> toEf : toTree) { boolean matched = false; for (EfvTree.Ef<CBitSet> fromEf : fromTree) if (fromEf.getEfvs().size() == toEf.getEfvs().size()) { int i; for (i = 0; i < fromEf.getEfvs().size(); ++i) if (!fromEf.getEfvs().get(i).getPayload().equals(toEf.getEfvs().get(i).getPayload())) break; if (i == fromEf.getEfvs().size()) { for (i = 0; i < fromEf.getEfvs().size(); ++i) result.put(toEf.getEf(), toEf.getEfvs().get(i).getEfv(), new CPair<String, String>(fromEf.getEf(), fromEf.getEfvs().get(i).getEfv())); matched = true; } } if (!matched) return null; } return result; } private List<EfvTree.Ef<CBitSet>> matchEfvsSort(EfvTree<CBitSet> from) { final List<EfvTree.Ef<CBitSet>> fromTree = from.getNameSortedTree(); for (EfvTree.Ef<CBitSet> ef : fromTree) { Collections.sort(ef.getEfvs(), new Comparator<EfvTree.Efv<CBitSet>>() { public int compare(EfvTree.Efv<CBitSet> o1, EfvTree.Efv<CBitSet> o2) { return o1.getPayload().compareTo(o2.getPayload()); } }); } return fromTree; } private EfvTree<CBitSet> getEfvPatternsFromAssays(final List<Assay> assays) { Set<String> efs = new HashSet<String>(); for (Assay assay : assays) for (Property prop : assay.getProperties()) efs.add(prop.getName()); EfvTree<CBitSet> efvTree = new EfvTree<CBitSet>(); int i = 0; for (Assay assay : assays) { for (final String propName : efs) { String value = assay.getPropertySummary(propName); efvTree.getOrCreate(propName, value, new Maker<CBitSet>() { public CBitSet make() { return new CBitSet(assays.size()); } }).set(i, true); } ++i; } return efvTree; } public void process(UpdateNetCDFForExperimentCommand cmd, AtlasLoaderServiceListener listener) throws AtlasLoaderException { String experimentAccession = cmd.getAccession(); listener.setAccession(experimentAccession); List<Assay> assays = getAtlasDAO().getAssaysByExperimentAccession(experimentAccession); ListMultimap<String, Assay> assaysByArrayDesign = ArrayListMultimap.create(); for (Assay assay : assays) { String adAcc = assay.getArrayDesignAccession(); if (null != adAcc) assaysByArrayDesign.put(adAcc, assay); } Experiment experiment = getAtlasDAO().getExperimentByAccession(experimentAccession); final String version = "NetCDF Updater"; for (String arrayDesignAccession : assaysByArrayDesign.keySet()) { ArrayDesign arrayDesign = getAtlasDAO().getArrayDesignByAccession(arrayDesignAccession); // TODO: keep the knowledge about filename's meaning in ONE place final File originalNetCDF = new File(getAtlasNetCDFDirectory(experimentAccession), experiment.getExperimentID() + "_" + arrayDesign.getArrayDesignID() + ".nc"); listener.setProgress("Reading existing NetCDF"); final List<Assay> arrayDesignAssays = assaysByArrayDesign.get(arrayDesignAccession); getLog().info("Starting NetCDF for " + experimentAccession + " and " + arrayDesignAccession + " (" + arrayDesignAssays.size() + " assays)"); // TODO: create an entity encapsulating the following values: it is what we read from NetCDF EfvTree<CPair<String, String>> matchedEfvs = null; final List<Assay> leaveAssays; DataMatrixStorage storage; String[] uEFVs; NetCDFProxy reader = null; try { reader = new NetCDFProxy(originalNetCDF); leaveAssays = new ArrayList<Assay>(arrayDesignAssays.size()); final long[] oldAssays = reader.getAssays(); for (int i = 0; i < oldAssays.length; ++i) { for (Assay assay : arrayDesignAssays) if (assay.getAssayID() == oldAssays[i]) { leaveAssays.add(assay); oldAssays[i] = -1; // mark it as used for later filtering break; } } if (oldAssays.length == leaveAssays.size()) { EfvTree<CBitSet> oldEfvPats = new EfvTree<CBitSet>(); for (String ef : reader.getFactors()) { String[] efvs = reader.getFactorValues(ef); for (String efv : new HashSet<String>(Arrays.asList(efvs))) { CBitSet pattern = new CBitSet(efvs.length); for (int i = 0; i < efvs.length; ++i) pattern.set(i, efvs[i].equals(efv)); oldEfvPats.put(ef, efv, pattern); } } EfvTree<CBitSet> newEfvPats = getEfvPatternsFromAssays(leaveAssays); matchedEfvs = matchEfvs(oldEfvPats, newEfvPats); } uEFVs = reader.getUniqueFactorValues(); String[] deAccessions = reader.getDesignElementAccessions(); storage = new DataMatrixStorage( leaveAssays.size() + (matchedEfvs != null ? uEFVs.length * 2 : 0), // expressions + pvals + tstats deAccessions.length, 1); for (int i = 0; i < deAccessions.length; ++i) { final float[] values = reader.getExpressionDataForDesignElementAtIndex(i); final float[] pval = reader.getPValuesForDesignElement(i); final float[] tstat = reader.getTStatisticsForDesignElement(i); storage.add(deAccessions[i], concat( Iterators.transform( filter( zeroTo(values.length), new Predicate<Integer>() { public boolean apply(@Nonnull Integer j) { return oldAssays[j] == -1; // skips deleted assays } }), new Function<Integer, Float>() { public Float apply(@Nonnull Integer j) { return values[j]; } }), asList(pval).iterator(), asList(tstat).iterator())); } } catch (IOException e) { getLog().error("Error reading NetCDF for " + experimentAccession + " and " + arrayDesignAccession); throw new AtlasLoaderException(e); } finally { closeQuietly(reader); } try { if (!originalNetCDF.delete()) throw new AtlasLoaderException("Can't delete original NetCDF file " + originalNetCDF); listener.setProgress("Writing new NetCDF"); NetCDFCreator netCdfCreator = new NetCDFCreator(); netCdfCreator.setAssays(leaveAssays); for (Assay assay : leaveAssays) for (Sample sample : getAtlasDAO().getSamplesByAssayAccession(experimentAccession, assay.getAccession())) netCdfCreator.setSample(assay, sample); Map<String, DataMatrixStorage.ColumnRef> dataMap = new HashMap<String, DataMatrixStorage.ColumnRef>(); for (int i = 0; i < leaveAssays.size(); ++i) dataMap.put(leaveAssays.get(i).getAccession(), new DataMatrixStorage.ColumnRef(storage, i)); netCdfCreator.setAssayDataMap(dataMap); if (matchedEfvs != null) { Map<Pair<String, String>, DataMatrixStorage.ColumnRef> pvalMap = new HashMap<Pair<String, String>, DataMatrixStorage.ColumnRef>(); Map<Pair<String, String>, DataMatrixStorage.ColumnRef> tstatMap = new HashMap<Pair<String, String>, DataMatrixStorage.ColumnRef>(); for (EfvTree.EfEfv<CPair<String, String>> efEfv : matchedEfvs.getNameSortedList()) { final int oldPos = Arrays.asList(uEFVs).indexOf(efEfv.getPayload().getFirst() + "||" + efEfv.getPayload().getSecond()); pvalMap.put(Pair.create(efEfv.getEf(), efEfv.getEfv()), new DataMatrixStorage.ColumnRef(storage, leaveAssays.size() + oldPos)); tstatMap.put(Pair.create(efEfv.getEf(), efEfv.getEfv()), new DataMatrixStorage.ColumnRef(storage, leaveAssays.size() + uEFVs.length + oldPos)); } netCdfCreator.setPvalDataMap(pvalMap); netCdfCreator.setTstatDataMap(tstatMap); } netCdfCreator.setArrayDesign(arrayDesign); netCdfCreator.setExperiment(experiment); netCdfCreator.setVersion(version); netCdfCreator.createNetCdf(getAtlasNetCDFDirectory(experimentAccession)); getLog().info("Successfully finished NetCDF for " + experimentAccession + " and " + arrayDesignAccession); if (matchedEfvs != null) listener.setRecomputeAnalytics(false); } catch (NetCDFCreatorException e) { getLog().error("Error writing NetCDF for " + experimentAccession + " and " + arrayDesignAccession); throw new AtlasLoaderException(e); } } //create or update idf file // BufferedWriter idfWriter = null; try { File experimentFolder = getAtlasNetCDFDirectory(experimentAccession); IDF idf = new IDF(); idf.addComment("ArrayExpressAccession", experiment.getAccession()); idf.netCDFFile = findNetcdfFiles(experimentFolder); idf.sdrfFile = findOrCreateSdrfFiles(experimentFolder); idfWriter = new BufferedWriter(new FileWriter(findOrCreateIdfFile(experimentAccession))); idfWriter.write(idf.toString()); } catch (Exception ex) { throw new AtlasLoaderException(ex); } finally { closeQuietly(idfWriter); } } private Collection<String> findOrCreateSdrfFiles(File experimentFolder) throws IOException { File[] allSdrfFiles = experimentFolder.listFiles(extension("sdrf", true)); Collection<String> sdrfFiles = transform(Arrays.asList(allSdrfFiles), GET_NAME); if (sdrfFiles.isEmpty()) { File emptySdrfFile = new File(experimentFolder, "empty.sdrf"); emptySdrfFile.createNewFile(); FileWriter writer = new FileWriter(emptySdrfFile); writer.write("hello"); writer.close(); sdrfFiles.add("empty.sdrf"); } return sdrfFiles; } private Collection<String> findNetcdfFiles(File experimentFolder) { File[] allNcdfFiles = experimentFolder.listFiles(extension("nc", false)); return transform(Arrays.asList(allNcdfFiles), GET_NAME); } private File findOrCreateIdfFile(String experimentAccession) throws IOException { File experimentFolder = getAtlasNetCDFDirectory(experimentAccession); File idfFile = getIdfFile(experimentFolder); if (null == idfFile) { idfFile = new File(experimentFolder, experimentAccession + ".idf"); idfFile.createNewFile(); } return idfFile; } private File getIdfFile(File experimentFolder) { File[] allIdfFiles = experimentFolder.listFiles(extension("idf", true)); return allIdfFiles.length == 0 ? null : allIdfFiles[0]; } }
atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/service/AtlasNetCDFUpdaterService.java
package uk.ac.ebi.gxa.loader.service; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Iterators; import com.google.common.collect.ListMultimap; import uk.ac.ebi.arrayexpress2.magetab.datamodel.IDF; import uk.ac.ebi.gxa.loader.AtlasLoaderException; import uk.ac.ebi.gxa.loader.DefaultAtlasLoader; import uk.ac.ebi.gxa.loader.UpdateNetCDFForExperimentCommand; import uk.ac.ebi.gxa.loader.datamatrix.DataMatrixStorage; import uk.ac.ebi.gxa.netcdf.generator.NetCDFCreator; import uk.ac.ebi.gxa.netcdf.generator.NetCDFCreatorException; import uk.ac.ebi.gxa.netcdf.reader.NetCDFProxy; import uk.ac.ebi.gxa.utils.EfvTree; import uk.ac.ebi.gxa.utils.Maker; import uk.ac.ebi.gxa.utils.Pair; import uk.ac.ebi.microarray.atlas.model.*; import javax.annotation.Nonnull; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; import static com.google.common.collect.Collections2.transform; import static com.google.common.collect.Iterators.concat; import static com.google.common.collect.Iterators.filter; import static com.google.common.io.Closeables.closeQuietly; import static com.google.common.primitives.Floats.asList; import static uk.ac.ebi.gxa.utils.CountIterator.zeroTo; import static uk.ac.ebi.gxa.utils.FileUtil.extension; /** * NetCDF updater service which preserves expression values information, but updates all properties * * @author pashky */ public class AtlasNetCDFUpdaterService extends AtlasLoaderService { private static final Function<File, String> GET_NAME = new Function<File, String>() { public String apply(@Nonnull File file) { return file.getName(); } }; public AtlasNetCDFUpdaterService(DefaultAtlasLoader atlasLoader) { super(atlasLoader); } private static class CBitSet extends BitSet implements Comparable<CBitSet> { private CBitSet(int nbits) { super(nbits); } public int compareTo(CBitSet o) { for (int i = 0; i < Math.max(size(), o.size()); ++i) { boolean b1 = get(i); boolean b2 = o.get(i); if (b1 != b2) return b1 ? 1 : -1; } return 0; } } private static class CPair<T1 extends Comparable<T1>, T2 extends Comparable<T2>> extends Pair<T1, T2> implements Comparable<CPair<T1, T2>> { private CPair(T1 first, T2 second) { super(first, second); } public int compareTo(CPair<T1, T2> o) { int d = getFirst().compareTo(o.getFirst()); return d != 0 ? d : getSecond().compareTo(o.getSecond()); } } private EfvTree<CPair<String, String>> matchEfvs(EfvTree<CBitSet> from, EfvTree<CBitSet> to) { final List<EfvTree.Ef<CBitSet>> fromTree = matchEfvsSort(from); final List<EfvTree.Ef<CBitSet>> toTree = matchEfvsSort(to); EfvTree<CPair<String, String>> result = new EfvTree<CPair<String, String>>(); for (EfvTree.Ef<CBitSet> toEf : toTree) { boolean matched = false; for (EfvTree.Ef<CBitSet> fromEf : fromTree) if (fromEf.getEfvs().size() == toEf.getEfvs().size()) { int i; for (i = 0; i < fromEf.getEfvs().size(); ++i) if (!fromEf.getEfvs().get(i).getPayload().equals(toEf.getEfvs().get(i).getPayload())) break; if (i == fromEf.getEfvs().size()) { for (i = 0; i < fromEf.getEfvs().size(); ++i) result.put(toEf.getEf(), toEf.getEfvs().get(i).getEfv(), new CPair<String, String>(fromEf.getEf(), fromEf.getEfvs().get(i).getEfv())); matched = true; } } if (!matched) return null; } return result; } private List<EfvTree.Ef<CBitSet>> matchEfvsSort(EfvTree<CBitSet> from) { final List<EfvTree.Ef<CBitSet>> fromTree = from.getNameSortedTree(); for (EfvTree.Ef<CBitSet> ef : fromTree) { Collections.sort(ef.getEfvs(), new Comparator<EfvTree.Efv<CBitSet>>() { public int compare(EfvTree.Efv<CBitSet> o1, EfvTree.Efv<CBitSet> o2) { return o1.getPayload().compareTo(o2.getPayload()); } }); } return fromTree; } private EfvTree<CBitSet> getEfvPatternsFromAssays(final List<Assay> assays) { Set<String> efs = new HashSet<String>(); for (Assay assay : assays) for (Property prop : assay.getProperties()) efs.add(prop.getName()); EfvTree<CBitSet> efvTree = new EfvTree<CBitSet>(); int i = 0; for (Assay assay : assays) { for (final String propName : efs) { String value = assay.getPropertySummary(propName); efvTree.getOrCreate(propName, value, new Maker<CBitSet>() { public CBitSet make() { return new CBitSet(assays.size()); } }).set(i, true); } ++i; } return efvTree; } public void process(UpdateNetCDFForExperimentCommand cmd, AtlasLoaderServiceListener listener) throws AtlasLoaderException { String experimentAccession = cmd.getAccession(); listener.setAccession(experimentAccession); List<Assay> assays = getAtlasDAO().getAssaysByExperimentAccession(experimentAccession); ListMultimap<String, Assay> assaysByArrayDesign = ArrayListMultimap.create(); for (Assay assay : assays) { String adAcc = assay.getArrayDesignAccession(); if (null != adAcc) assaysByArrayDesign.put(adAcc, assay); } Experiment experiment = getAtlasDAO().getExperimentByAccession(experimentAccession); final String version = "NetCDF Updater"; for (String arrayDesignAccession : assaysByArrayDesign.keySet()) { ArrayDesign arrayDesign = getAtlasDAO().getArrayDesignByAccession(arrayDesignAccession); // TODO: keep the knowledge about filename's meaning in ONE place final File originalNetCDF = new File(getAtlasNetCDFDirectory(experimentAccession), experiment.getExperimentID() + "_" + arrayDesign.getArrayDesignID() + ".nc"); listener.setProgress("Reading existing NetCDF"); final List<Assay> arrayDesignAssays = assaysByArrayDesign.get(arrayDesignAccession); getLog().info("Starting NetCDF for " + experimentAccession + " and " + arrayDesignAccession + " (" + arrayDesignAssays.size() + " assays)"); // TODO: create an entity encapsulating the following values: it is what we read from NetCDF EfvTree<CPair<String, String>> matchedEfvs = null; final List<Assay> leaveAssays; DataMatrixStorage storage; String[] uEFVs; NetCDFProxy reader = null; try { reader = new NetCDFProxy(originalNetCDF); leaveAssays = new ArrayList<Assay>(arrayDesignAssays.size()); final long[] oldAssays = reader.getAssays(); for (int i = 0; i < oldAssays.length; ++i) { for (Assay assay : arrayDesignAssays) if (assay.getAssayID() == oldAssays[i]) { leaveAssays.add(assay); oldAssays[i] = -1; // mark it as used for later filtering break; } } if (oldAssays.length == leaveAssays.size()) { EfvTree<CBitSet> oldEfvPats = new EfvTree<CBitSet>(); for (String ef : reader.getFactors()) { String[] efvs = reader.getFactorValues(ef); for (String efv : new HashSet<String>(Arrays.asList(efvs))) { CBitSet pattern = new CBitSet(efvs.length); for (int i = 0; i < efvs.length; ++i) pattern.set(i, efvs[i].equals(efv)); oldEfvPats.put(ef, efv, pattern); } } EfvTree<CBitSet> newEfvPats = getEfvPatternsFromAssays(leaveAssays); matchedEfvs = matchEfvs(oldEfvPats, newEfvPats); } uEFVs = reader.getUniqueFactorValues(); String[] deAccessions = reader.getDesignElementAccessions(); storage = new DataMatrixStorage( leaveAssays.size() + (matchedEfvs != null ? uEFVs.length * 2 : 0), // expressions + pvals + tstats deAccessions.length, 1); for (int i = 0; i < deAccessions.length; ++i) { final float[] values = reader.getExpressionDataForDesignElementAtIndex(i); final float[] pval = reader.getPValuesForDesignElement(i); final float[] tstat = reader.getTStatisticsForDesignElement(i); storage.add(deAccessions[i], concat( Iterators.transform( filter( zeroTo(values.length), new Predicate<Integer>() { public boolean apply(@Nonnull Integer j) { return oldAssays[j] == -1; // skips deleted assays } }), new Function<Integer, Float>() { public Float apply(@Nonnull Integer j) { return values[j]; } }), asList(pval).iterator(), asList(tstat).iterator())); } } catch (IOException e) { getLog().error("Error reading NetCDF for " + experimentAccession + " and " + arrayDesignAccession); throw new AtlasLoaderException(e); } finally { closeQuietly(reader); } try { if (!originalNetCDF.delete()) throw new AtlasLoaderException("Can't delete original NetCDF file " + originalNetCDF); listener.setProgress("Writing new NetCDF"); NetCDFCreator netCdfCreator = new NetCDFCreator(); netCdfCreator.setAssays(leaveAssays); for (Assay assay : leaveAssays) for (Sample sample : getAtlasDAO().getSamplesByAssayAccession(experimentAccession, assay.getAccession())) netCdfCreator.setSample(assay, sample); Map<String, DataMatrixStorage.ColumnRef> dataMap = new HashMap<String, DataMatrixStorage.ColumnRef>(); for (int i = 0; i < leaveAssays.size(); ++i) dataMap.put(leaveAssays.get(i).getAccession(), new DataMatrixStorage.ColumnRef(storage, i)); netCdfCreator.setAssayDataMap(dataMap); if (matchedEfvs != null) { Map<Pair<String, String>, DataMatrixStorage.ColumnRef> pvalMap = new HashMap<Pair<String, String>, DataMatrixStorage.ColumnRef>(); Map<Pair<String, String>, DataMatrixStorage.ColumnRef> tstatMap = new HashMap<Pair<String, String>, DataMatrixStorage.ColumnRef>(); for (EfvTree.EfEfv<CPair<String, String>> efEfv : matchedEfvs.getNameSortedList()) { final int oldPos = Arrays.asList(uEFVs).indexOf(efEfv.getPayload().getFirst() + "||" + efEfv.getPayload().getSecond()); pvalMap.put(Pair.create(efEfv.getEf(), efEfv.getEfv()), new DataMatrixStorage.ColumnRef(storage, leaveAssays.size() + oldPos)); tstatMap.put(Pair.create(efEfv.getEf(), efEfv.getEfv()), new DataMatrixStorage.ColumnRef(storage, leaveAssays.size() + uEFVs.length + oldPos)); } netCdfCreator.setPvalDataMap(pvalMap); netCdfCreator.setTstatDataMap(tstatMap); } netCdfCreator.setArrayDesign(arrayDesign); netCdfCreator.setExperiment(experiment); netCdfCreator.setVersion(version); netCdfCreator.createNetCdf(getAtlasNetCDFDirectory(experimentAccession)); getLog().info("Successfully finished NetCDF for " + experimentAccession + " and " + arrayDesignAccession); if (matchedEfvs != null) listener.setRecomputeAnalytics(false); } catch (NetCDFCreatorException e) { getLog().error("Error writing NetCDF for " + experimentAccession + " and " + arrayDesignAccession); throw new AtlasLoaderException(e); } } //create or update idf file // try { File idfFile = findOrCreateIdfFile(experimentAccession); File experimentFolder = getAtlasNetCDFDirectory(experimentAccession); IDF idf = new IDF(); idf.addComment("ArrayExpressAccession", experiment.getAccession()); idf.netCDFFile = findNetcdfFiles(experimentFolder); idf.sdrfFile = findOrCreateSdrfFiles(experimentFolder); BufferedWriter idfWriter = new BufferedWriter(new FileWriter(idfFile)); idfWriter.write(idf.toString()); idfWriter.close(); } catch (Exception ex) { throw new AtlasLoaderException(ex); } } private Collection<String> findOrCreateSdrfFiles(File experimentFolder) throws IOException { File[] allSdrfFiles = experimentFolder.listFiles(extension("sdrf", true)); Collection<String> sdrfFiles = transform(Arrays.asList(allSdrfFiles), GET_NAME); if (sdrfFiles.isEmpty()) { File emptySdrfFile = new File(experimentFolder, "empty.sdrf"); emptySdrfFile.createNewFile(); FileWriter writer = new FileWriter(emptySdrfFile); writer.write("hello"); writer.close(); sdrfFiles.add("empty.sdrf"); } return sdrfFiles; } private Collection<String> findNetcdfFiles(File experimentFolder) { File[] allNcdfFiles = experimentFolder.listFiles(extension("nc", false)); return transform(Arrays.asList(allNcdfFiles), GET_NAME); } private File findOrCreateIdfFile(String experimentAccession) throws IOException { File experimentFolder = getAtlasNetCDFDirectory(experimentAccession); File idfFile = getIdfFile(experimentFolder); if (null == idfFile) { idfFile = new File(experimentFolder, experimentAccession + ".idf"); idfFile.createNewFile(); } return idfFile; } private File getIdfFile(File experimentFolder) { File[] allIdfFiles = experimentFolder.listFiles(extension("idf", true)); return allIdfFiles.length == 0 ? null : allIdfFiles[0]; } }
Resource management
atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/service/AtlasNetCDFUpdaterService.java
Resource management
<ide><path>tlas-loader/src/main/java/uk/ac/ebi/gxa/loader/service/AtlasNetCDFUpdaterService.java <ide> <ide> //create or update idf file <ide> // <add> BufferedWriter idfWriter = null; <ide> try { <del> File idfFile = findOrCreateIdfFile(experimentAccession); <del> <del> <ide> File experimentFolder = getAtlasNetCDFDirectory(experimentAccession); <ide> <ide> IDF idf = new IDF(); <ide> idf.netCDFFile = findNetcdfFiles(experimentFolder); <ide> idf.sdrfFile = findOrCreateSdrfFiles(experimentFolder); <ide> <del> BufferedWriter idfWriter = new BufferedWriter(new FileWriter(idfFile)); <add> idfWriter = new BufferedWriter(new FileWriter(findOrCreateIdfFile(experimentAccession))); <ide> idfWriter.write(idf.toString()); <del> idfWriter.close(); <ide> } catch (Exception ex) { <ide> throw new AtlasLoaderException(ex); <del> } <del> <add> } finally { <add> closeQuietly(idfWriter); <add> } <ide> } <ide> <ide> private Collection<String> findOrCreateSdrfFiles(File experimentFolder) throws IOException {
JavaScript
mit
a1a63e9ba12df96752492e4b62d1d9e999ae49d9
0
ratecity/keystone,Adam14Four/keystone,Yaska/keystone,w01fgang/keystone,ONode/keystone,michaelerobertsjr/keystone,trentmillar/keystone,qwales1/keystone,Tangcuyu/keystone,snowkeeper/keystone,xyzteam2016/keystone,alobodig/keystone,brianjd/keystone,w01fgang/keystone,jacargentina/keystone,codevlabs/keystone,Tangcuyu/keystone,brianjd/keystone,creynders/keystone,pswoodworth/keystone,sendyhalim/keystone,dvdcastro/keystone,andrewlinfoot/keystone,jstockwin/keystone,wmertens/keystone,Adam14Four/keystone,andreufirefly/keystone,alobodig/keystone,rafmsou/keystone,benkroeger/keystone,naustudio/keystone,everisARQ/keystone,frontyard/keystone,vokal/keystone,suryagh/keystone,mikaoelitiana/keystone,Redmart/keystone,suryagh/keystone,danielmahon/keystone,pr1ntr/keystone,concoursbyappointment/keystoneRedux,Ftonso/keystone,snowkeeper/keystone,danielmahon/keystone,naustudio/keystone,michaelerobertsjr/keystone,webteckie/keystone,creynders/keystone,andrewlinfoot/keystone,wmertens/keystone,dvdcastro/keystone,pr1ntr/keystone,dryna/keystone-twoje-urodziny,concoursbyappointment/keystoneRedux,Pop-Code/keystone,linhanyang/keystone,joerter/keystone,naustudio/keystone,ratecity/keystone,matthewstyers/keystone,efernandesng/keystone,matthewstyers/keystone,matthieugayon/keystone,trentmillar/keystone,ONode/keystone,tony2cssc/keystone,jacargentina/keystone,andreufirefly/keystone,danielmahon/keystone,sendyhalim/keystone,codevlabs/keystone,tony2cssc/keystone,matthewstyers/keystone,riyadhalnur/keystone,dryna/keystone-twoje-urodziny,vokal/keystone,xyzteam2016/keystone,joerter/keystone,nickhsine/keystone,everisARQ/keystone,frontyard/keystone,Ftonso/keystone,efernandesng/keystone,jstockwin/keystone,benkroeger/keystone,Yaska/keystone,pswoodworth/keystone,nickhsine/keystone,benkroeger/keystone,vokal/keystone,webteckie/keystone,Yaska/keystone,Redmart/keystone,qwales1/keystone,trentmillar/keystone,matthieugayon/keystone,frontyard/keystone,riyadhalnur/keystone,rafmsou/keystone,mikaoelitiana/keystone,Pop-Code/keystone,cermati/keystone,andrewlinfoot/keystone,cermati/keystone
'use strict'; import classnames from 'classnames'; import React from 'react'; import ReactDOM from 'react-dom'; import SessionStore from '../stores/SessionStore'; import { Alert, Button, Form, FormField, FormInput } from 'elemental'; import { createHistory } from 'history'; var history = createHistory(); var SigninView = React.createClass({ getInitialState () { return { email: '', password: '', isAnimating: false, isInvalid: false, invalidMessage: '', signedOut: window.location.search === '?signedout' }; }, componentDidMount () { if (this.state.signedOut && window.history.replaceState) { history.replaceState({}, window.location.pathname); } if (this.refs.email) { React.findDOMNode(this.refs.email).select(); } }, handleInputChange (e) { let newState = {}; newState[e.target.name] = e.target.value; this.setState(newState); }, handleSubmit (e) { e.preventDefault(); if (!this.state.email || !this.state.password) { return this.displayError('Please enter an email address and password to sign in.'); } SessionStore.signin({ email: this.state.email, password: this.state.password }, (err, data) => { if (err || data && data.error) { this.displayError('The email and password you entered are not valid.'); } else { // TODO: Handle custom signin redirections top.location.href = '/keystone'; } }); }, displayError (message) { this.setState({ isAnimating: true, isInvalid: true, invalidMessage: message }); setTimeout(this.finishAnimation, 750); }, finishAnimation () { if (!this.isMounted()) return; if (this.refs.email) { React.findDOMNode(this.refs.email).select(); } this.setState({ isAnimating: false }); }, renderBrand () { let logo = { src: '/keystone/images/logo.png', width: 205, height: 68 }; if (this.props.logo) { logo = typeof this.props.logo === 'string' ? { src: this.props.logo } : this.props.logo; // TODO: Deprecate this if (Array.isArray(logo)) { logo = { src: logo[0], width: logo[1], height: logo[2] }; } } return ( <div className="auth-box__col"> <div className="auth-box__brand"> <a href="/" className="auth-box__brand__logo"> <img src={logo.src} width={logo.width ? logo.width : null} height={logo.height ? logo.height : null} alt={this.props.brand} /> </a> </div> </div> ); }, renderUserInfo () { if (!this.props.user) return null; let openKeystoneButton = this.props.userCanAccessKeystone ? <Button href="/keystone" type="primary">Open Keystone</Button> : null; return ( <div className="auth-box__col"> <p>Hi {this.props.user.name.first},</p> <p>You're already signed in.</p> {openKeystoneButton} <Button href="/keystone/signout" type="link-cancel">Sign Out</Button> </div> ); }, renderAlert () { if (this.state.isInvalid) { return <Alert key="error" type="danger" style={{ textAlign: 'center' }}>{this.state.invalidMessage}</Alert>; } else if (this.state.signedOut) { return <Alert key="signed-out" type="info" style={{ textAlign: 'center' }}>You have been signed out.</Alert>; } else { /* eslint-disable react/self-closing-comp */ // TODO: This probably isn't the best way to do this, we // shouldn't be using Elemental classNames instead of components return <div key="fake" className="Alert Alert--placeholder">&nbsp;</div>; /* eslint-enable */ } }, renderForm () { if (this.props.user) return null; return ( <div className="auth-box__col"> <Form method="post" onSubmit={this.handleSubmit} noValidate> <FormField label="Email" htmlFor="email"> <FormInput type="email" name="email" onChange={this.handleInputChange} value={this.state.email} ref="email" /> </FormField> <FormField label="Password" htmlFor="password"> <FormInput type="password" name="password" onChange={this.handleInputChange} value={this.state.password} ref="password" /> </FormField> <Button disabled={this.state.animating} type="primary" submit>Sign In</Button> {/*<Button disabled={this.state.animating} type="link-text">Forgot Password?</Button>*/} </Form> </div> ); }, render () { let boxClassname = classnames('auth-box', { 'auth-box--has-errors': this.state.isAnimating }); return ( <div className="auth-wrapper"> {this.renderAlert()} <div className={boxClassname}> <h1 className="u-hidden-visually">{this.props.brand ? this.props.brand : 'Keystone'} Sign In </h1> <div className="auth-box__inner"> {this.renderBrand()} {this.renderUserInfo()} {this.renderForm()} </div> </div> <div className="auth-footer"> <span>Powered by </span> <a href="http://keystonejs.com" target="_blank" title="The Node.js CMS and web application platform (new window)">KeystoneJS</a> </div> </div> ); } }); ReactDOM.render(<SigninView brand={Keystone.brand} logo={Keystone.logo} user={Keystone.user} userCanAccessKeystone={Keystone.userCanAccessKeystone} />, document.getElementById('signin-view'));
admin/client/views/signin.js
'use strict'; import classnames from 'classnames'; import React from 'react'; import ReactDOM from 'react-dom'; import SessionStore from '../stores/SessionStore'; import { Alert, Button, Form, FormField, FormInput } from 'elemental'; import { createHistory } from 'history'; var history = createHistory(); var SigninView = React.createClass({ getInitialState () { return { email: '', password: '', isAnimating: false, isInvalid: false, invalidMessage: '', signedOut: window.location.search === '?signedout' }; }, componentDidMount () { if (this.state.signedOut && window.history.replaceState) { history.replaceState({}, window.location.pathname); } if (this.refs.email) { React.findDOMNode(this.refs.email).select(); } }, handleInputChange (e) { let newState = {}; newState[e.target.name] = e.target.value; this.setState(newState); }, handleSubmit (e) { e.preventDefault(); if (!this.state.email || !this.state.password) { return this.displayError('Please enter an email address and password to sign in.'); } SessionStore.signin({ email: this.state.email, password: this.state.password }, (err, data) => { if (err) { this.displayError('The email and password you entered are not valid.'); } else { // TODO: Handle custom signin redirections top.location.href = '/keystone'; } }); }, displayError (message) { this.setState({ isAnimating: true, isInvalid: true, invalidMessage: message }); setTimeout(this.finishAnimation, 750); }, finishAnimation () { if (!this.isMounted()) return; if (this.refs.email) { React.findDOMNode(this.refs.email).select(); } this.setState({ isAnimating: false }); }, renderBrand () { let logo = { src: '/keystone/images/logo.png', width: 205, height: 68 }; if (this.props.logo) { logo = typeof this.props.logo === 'string' ? { src: this.props.logo } : this.props.logo; // TODO: Deprecate this if (Array.isArray(logo)) { logo = { src: logo[0], width: logo[1], height: logo[2] }; } } return ( <div className="auth-box__col"> <div className="auth-box__brand"> <a href="/" className="auth-box__brand__logo"> <img src={logo.src} width={logo.width ? logo.width : null} height={logo.height ? logo.height : null} alt={this.props.brand} /> </a> </div> </div> ); }, renderUserInfo () { if (!this.props.user) return null; let openKeystoneButton = this.props.userCanAccessKeystone ? <Button href="/keystone" type="primary">Open Keystone</Button> : null; return ( <div className="auth-box__col"> <p>Hi {this.props.user.name.first},</p> <p>You're already signed in.</p> {openKeystoneButton} <Button href="/keystone/signout" type="link-cancel">Sign Out</Button> </div> ); }, renderAlert () { if (this.state.isInvalid) { return <Alert key="error" type="danger" style={{ textAlign: 'center' }}>{this.state.invalidMessage}</Alert>; } else if (this.state.signedOut) { return <Alert key="signed-out" type="info" style={{ textAlign: 'center' }}>You have been signed out.</Alert>; } else { /* eslint-disable react/self-closing-comp */ // TODO: This probably isn't the best way to do this, we // shouldn't be using Elemental classNames instead of components return <div key="fake" className="Alert Alert--placeholder">&nbsp;</div>; /* eslint-enable */ } }, renderForm () { if (this.props.user) return null; return ( <div className="auth-box__col"> <Form method="post" onSubmit={this.handleSubmit} noValidate> <FormField label="Email" htmlFor="email"> <FormInput type="email" name="email" onChange={this.handleInputChange} value={this.state.email} ref="email" /> </FormField> <FormField label="Password" htmlFor="password"> <FormInput type="password" name="password" onChange={this.handleInputChange} value={this.state.password} ref="password" /> </FormField> <Button disabled={this.state.animating} type="primary" submit>Sign In</Button> {/*<Button disabled={this.state.animating} type="link-text">Forgot Password?</Button>*/} </Form> </div> ); }, render () { let boxClassname = classnames('auth-box', { 'auth-box--has-errors': this.state.isAnimating }); return ( <div className="auth-wrapper"> {this.renderAlert()} <div className={boxClassname}> <h1 className="u-hidden-visually">{this.props.brand ? this.props.brand : 'Keystone'} Sign In </h1> <div className="auth-box__inner"> {this.renderBrand()} {this.renderUserInfo()} {this.renderForm()} </div> </div> <div className="auth-footer"> <span>Powered by </span> <a href="http://keystonejs.com" target="_blank" title="The Node.js CMS and web application platform (new window)">KeystoneJS</a> </div> </div> ); } }); ReactDOM.render(<SigninView brand={Keystone.brand} logo={Keystone.logo} user={Keystone.user} userCanAccessKeystone={Keystone.userCanAccessKeystone} />, document.getElementById('signin-view'));
Signin: more robust error handling @JedWatson look into status code returned by SessionStore
admin/client/views/signin.js
Signin: more robust error handling
<ide><path>dmin/client/views/signin.js <ide> email: this.state.email, <ide> password: this.state.password <ide> }, (err, data) => { <del> if (err) { <add> if (err || data && data.error) { <ide> this.displayError('The email and password you entered are not valid.'); <ide> } else { <ide> // TODO: Handle custom signin redirections
Java
lgpl-2.1
3d1ebb5e64c8025cf7546b8a454bc91ef749a624
0
smily77/Arduino,ikbelkirasan/Arduino,wayoda/Arduino,ari-analytics/Arduino,vbextreme/Arduino,tannewt/Arduino,HCastano/Arduino,steamboating/Arduino,381426068/Arduino,karlitxo/Arduino,arunkuttiyara/Arduino,OpenDevice/Arduino,mateuszdw/Arduino,snargledorf/Arduino,chaveiro/Arduino,Ramoonus/Arduino,tbowmo/Arduino,vbextreme/Arduino,brianonn/Energia,NaSymbol/Arduino,eddyst/Arduino-SourceCode,fungxu/Arduino,HCastano/Arduino,koltegirish/Arduino,jaej-dev/Arduino,pdNor/Arduino,spapadim/Arduino,vigneshmanix/Energia,zenmanenergy/Arduino,damellis/Arduino,nandojve/Arduino,pdNor/Arduino,plinioseniore/Arduino,diydrones/Arduino,zederson/Arduino,laylthe/Arduino,jaej-dev/Arduino,ccoenen/Arduino,danielchalef/Arduino,dvdvideo1234/Energia,ms-iot/Arduino,ssvs111/Arduino,nkolban/Arduino,eggfly/arduino,paulmand3l/Arduino,kidswong999/Arduino,shannonshsu/Arduino,garci66/Arduino,nkolban/Arduino,PaintYourDragon/Arduino,danielohh/Energia,Cloudino/Arduino,karlitxo/Arduino,danielchalef/Arduino,wayoda/Arduino,koltegirish/Arduino,drpjk/Arduino,gestrem/Arduino,spapadim/Arduino,toddtreece/esp8266-Arduino,PaintYourDragon/Arduino,damellis/Arduino,tbowmo/Arduino,probonopd/Arduino,eduardocasarin/Arduino,381426068/Arduino,bobintornado/Energia,damellis/Arduino,ikbelkirasan/Arduino,fungxu/Arduino,wilhelmryan/Arduino,jabezGit/Arduino,stickbreaker/Arduino,NeuralSpaz/Arduino,ntruchsess/Arduino-1,aichi/Arduino-2,gonium/Arduino,SmartArduino/Arduino-1,weera00/Arduino,aichi/Arduino-2,ThoughtWorksIoTGurgaon/Arduino,koltegirish/Arduino,raimohanska/Arduino,xxxajk/Arduino-1,myrtleTree33/Arduino,nkolban/Arduino,andrealmeidadomingues/Arduino,niggor/Arduino_cc,bsmr-arduino/Arduino,karlitxo/Arduino,henningpohl/Arduino,piersoft/esp8266-Arduino,ogferreiro/Arduino,eeijcea/Arduino-1,eddyst/Arduino-SourceCode,superboonie/Arduino,bsmr-arduino/Arduino,jabezGit/Arduino,niggor/Arduino_cc,mc-hamster/esp8266-Arduino,mangelajo/Arduino,vigneshmanix/Energia,wayoda/Arduino,ogahara/Arduino,ntruchsess/Arduino-1,danielohh/Energia,NaSymbol/Arduino,spapadim/Arduino,eduardocasarin/Arduino,ms-iot/Arduino,stickbreaker/Arduino,martianmartin/Energia,jmgonzalez00449/Arduino,kidswong999/Arduino,andrealmeidadomingues/Arduino,stevemarple/Arduino-org,aichi/Arduino-2,acosinwork/Arduino,eddyst/Arduino-SourceCode,jadonk/Energia,ogferreiro/Arduino,PaoloP74/Arduino,adafruit/ESP8266-Arduino,ashwin713/Arduino,raimohanska/Arduino,probonopd/Arduino,bigjosh/Arduino,superboonie/Arduino,cscenter/Arduino,ektor5/Arduino,tomkrus007/Arduino,OpenDevice/Arduino,scdls/Arduino,DavidUser/Energia,SmartArduino/Arduino-1,me-no-dev/Arduino-1,superboonie/Arduino,jamesrob4/Arduino,nkolban/Arduino,arduino-org/Arduino,stevemarple/Arduino,ogahara/Arduino,stevemarple/Arduino,tommyli2014/Arduino,cevatbostancioglu/Energia,spapadim/Arduino,shannonshsu/Arduino,shiitakeo/Arduino,lulufei/Arduino,zederson/Arduino,jaehong/Xmegaduino,snargledorf/Arduino,01org/Arduino,tbowmo/Arduino,vigneshmanix/Energia,Ramoonus/Arduino,nandojve/Arduino,NoPinky/Energia,fungxu/Arduino,Alfredynho/AgroSis,talhaburak/Arduino,sanyaade-iot/Energia,sanyaade-iot/Arduino-1,weera00/Arduino,bigjosh/Arduino,zacinaction/Energia,Cloudino/Cloudino-Arduino-IDE,scdls/Arduino,noahchense/Arduino-1,381426068/Arduino,eduardocasarin/Arduino,nandojve/Arduino,tomkrus007/Arduino,odbol/Arduino,rcook/DesignLab,raimohanska/Arduino,weera00/Arduino,bigjosh/Arduino,cevatbostancioglu/Energia,eggfly/arduino,Cloudino/Cloudino-Arduino-IDE,drpjk/Arduino,KlaasDeNys/Arduino,OpenDevice/Arduino,scdls/Arduino,talhaburak/Arduino,arduino-org/Arduino,drpjk/Arduino,xxxajk/Arduino-1,ntruchsess/Arduino-1,Alfredynho/AgroSis,bugobliterator/BUAGI,brianonn/Energia,myrtleTree33/Arduino,tannewt/Arduino,diydrones/Arduino,stevemayhew/Arduino,jaehong/Xmegaduino,381426068/Arduino,stevemarple/Arduino-org,Chris--A/Arduino,mboufos/esp8266-Arduino,ashwin713/Arduino,bigjosh/Arduino,adamkh/Arduino,jabezGit/Arduino,danielchalef/Arduino,croberts15/Energia,PeterVH/Arduino,weera00/Arduino,plinioseniore/Arduino,leftbrainstrain/Arduino-ESP8266,fungxu/Arduino,laylthe/Arduino,wdoganowski/Arduino,radiolok/Energia,stevemayhew/Arduino,stevemayhew/Arduino,steamboating/Arduino,gberl001/Arduino,chaveiro/Arduino,pasky/Energia,qtonthat/Energia,ssvs111/Arduino,arduino-org/Arduino,lulufei/Arduino,paulo-raca/ESP8266-Arduino,ForestNymph/Arduino_sources,zenmanenergy/Arduino,majenkotech/Arduino,andyvand/Arduino-1,linino/Arduino,talhaburak/Arduino,odbol/Arduino,adamkh/Arduino,probonopd/Arduino,NoPinky/Energia,rodibot/Arduino,championswimmer/Arduino,gberl001/Arduino,wilhelmryan/Arduino,arunkuttiyara/Arduino,diydrones/Arduino,gberl001/Arduino,ms-iot/Arduino,dvdvideo1234/Energia,croberts15/Energia,381426068/Arduino,shiitakeo/Arduino,raimohanska/Arduino,shannonshsu/Arduino,bugobliterator/BUAGI,wilhelmryan/Arduino,rodibot/Arduino,jamesrob4/Arduino,jabezGit/Arduino,Alfredynho/AgroSis,i--storm/Energia,diydrones/Arduino,NoPinky/Energia,mangelajo/Arduino,SmartArduino/Arduino-1,acosinwork/Arduino,NeuralSpaz/Arduino,bobintornado/Energia,croberts15/Energia,eddyst/Arduino-SourceCode,zaiexx/Arduino,lukeWal/Arduino,ashwin713/Arduino,andyvand/Arduino-1,wayoda/Arduino,andyvand/Arduino-1,Cloudino/Arduino,jaimemaretoli/Arduino,tbowmo/Arduino,ccoenen/Arduino,stickbreaker/Arduino,NaSymbol/Arduino,PeterVH/Arduino,mateuszdw/Arduino,garci66/Arduino,plaintea/esp8266-Arduino,cscenter/Arduino,adamkh/Arduino,me-no-dev/Arduino-1,meanbot/Energia,ari-analytics/Arduino,stevemarple/Arduino,PaoloP74/Arduino,pasky/Energia,odbol/Arduino,Cloudino/Arduino,PaoloP74/Arduino,eeijcea/Arduino-1,benwolfe/esp8266-Arduino,steamboating/Arduino,bugobliterator/BUAGI,piersoft/esp8266-Arduino,stevemarple/Arduino-org,jomolinare/Arduino,ektor5/Arduino,zederson/Arduino,jmgonzalez00449/Arduino,jamesrob4/Arduino,DavidUser/Energia,i--storm/Energia,ForestNymph/Arduino_sources,eeijcea/Arduino-1,adafruit/ESP8266-Arduino,linino/Arduino,NoPinky/Energia,mboufos/esp8266-Arduino,ogferreiro/Arduino,pasky/Energia,kidswong999/Arduino,PaoloP74/Arduino,OpenDevice/Arduino,adamkh/Arduino,jaehong/Xmegaduino,me-no-dev/Arduino-1,andyvand/Arduino-1,bsmr-arduino/Arduino,myrtleTree33/Arduino,jaimemaretoli/Arduino,ssvs111/Arduino,paulo-raca/ESP8266-Arduino,rcook/DesignLab,tskurauskas/Arduino,PaoloP74/Arduino,me-no-dev/Arduino-1,battosai30/Energia,noahchense/Arduino-1,mattvenn/Arduino,HCastano/Arduino,rcook/DesignLab,UDOOboard/Arduino,tskurauskas/Arduino,paulo-raca/ESP8266-Arduino,i--storm/Energia,zaiexx/Arduino,shannonshsu/Arduino,wayoda/Arduino,ikbelkirasan/Arduino,ssvs111/Arduino,Protoneer/Arduino,Chris--A/Arduino,me-no-dev/Arduino-1,chaveiro/Arduino,sanyaade-iot/Arduino-1,wdoganowski/Arduino,shiitakeo/Arduino,andyvand/Arduino-1,mangelajo/Arduino,jamesrob4/Arduino,arduino-org/Arduino,drpjk/Arduino,zenmanenergy/Arduino,lukeWal/Arduino,arduino-org/Arduino,niggor/Arduino_cc,NicoHood/Arduino,vigneshmanix/Energia,PaoloP74/Arduino,gestrem/Arduino,piersoft/esp8266-Arduino,zenmanenergy/Arduino,bsmr-arduino/Arduino,jaimemaretoli/Arduino,stickbreaker/Arduino,benwolfe/esp8266-Arduino,jabezGit/Arduino,byran/Arduino,Chris--A/Arduino,bigjosh/Arduino,myrtleTree33/Arduino,mangelajo/Arduino,probonopd/Arduino,radiolok/Energia,KlaasDeNys/Arduino,eduardocasarin/Arduino,lukeWal/Arduino,EmuxEvans/Arduino,byran/Arduino,stevemayhew/Arduino,myrtleTree33/Arduino,henningpohl/Arduino,PeterVH/Arduino,zederson/Arduino,eddyst/Arduino-SourceCode,ogferreiro/Arduino,SmartArduino/Arduino-1,henningpohl/Arduino,zederson/Arduino,andrealmeidadomingues/Arduino,eggfly/arduino,kidswong999/Arduino,tommyli2014/Arduino,PeterVH/Arduino,onovy/Arduino,vbextreme/Arduino,radut/Arduino,croberts15/Energia,nandojve/Arduino,NeuralSpaz/Arduino,henningpohl/Arduino,battosai30/Energia,brianonn/Energia,danielohh/Energia,tomkrus007/Arduino,zaiexx/Arduino,dvdvideo1234/Energia,tommyli2014/Arduino,majenkotech/Arduino,jaej-dev/Arduino,byran/Arduino,qtonthat/Energia,NoPinky/Energia,mangelajo/Arduino,ssvs111/Arduino,mangelajo/Arduino,snargledorf/Arduino,linino/Arduino,majenkotech/Arduino,Protoneer/Arduino,Gourav2906/Arduino,PaintYourDragon/Arduino,me-no-dev/Arduino-1,NicoHood/Arduino,nandojve/Arduino,croberts15/Energia,NoPinky/Energia,eeijcea/Arduino-1,jaej-dev/Arduino,wilhelmryan/Arduino,ms-iot/Arduino,jaehong/Xmegaduino,paulo-raca/ESP8266-Arduino,talhaburak/Arduino,gestrem/Arduino,EmuxEvans/Arduino,championswimmer/Arduino,ari-analytics/Arduino,ThoughtWorksIoTGurgaon/Arduino,acosinwork/Arduino,pdNor/Arduino,damellis/Arduino,linino/Arduino,EmuxEvans/Arduino,onovy/Arduino,PaintYourDragon/Arduino,bobintornado/Energia,sanyaade-iot/Arduino-1,laylthe/Arduino,pdNor/Arduino,benwolfe/esp8266-Arduino,myrtleTree33/Arduino,HCastano/Arduino,ari-analytics/Arduino,battosai30/Energia,paulo-raca/ESP8266-Arduino,zenmanenergy/Arduino,tbowmo/Arduino,jaimemaretoli/Arduino,tskurauskas/Arduino,01org/Arduino,Ramoonus/Arduino,steamboating/Arduino,gurbrinder/Arduino,garci66/Arduino,stickbreaker/Arduino,byran/Arduino,jomolinare/Arduino,battosai30/Energia,leftbrainstrain/Arduino-ESP8266,cevatbostancioglu/Energia,aichi/Arduino-2,radut/Arduino,sanyaade-iot/Arduino-1,Orthogonal-Systems/arduino-libs,scdls/Arduino,ogferreiro/Arduino,wayoda/Arduino,mc-hamster/esp8266-Arduino,tannewt/Arduino,gberl001/Arduino,garci66/Arduino,majenkotech/Arduino,smily77/Arduino,championswimmer/Arduino,tskurauskas/Arduino,jadonk/Energia,smily77/Arduino,benwolfe/esp8266-Arduino,wdoganowski/Arduino,vigneshmanix/Energia,paulo-raca/ESP8266-Arduino,noahchense/Arduino-1,wilhelmryan/Arduino,martianmartin/Energia,leftbrainstrain/Arduino-ESP8266,Cloudino/Arduino,Protoneer/Arduino,danielohh/Energia,shannonshsu/Arduino,myrtleTree33/Arduino,Cloudino/Cloudino-Arduino-IDE,gonium/Arduino,piersoft/esp8266-Arduino,ashwin713/Arduino,bugobliterator/BUAGI,superboonie/Arduino,jaimemaretoli/Arduino,odbol/Arduino,NaSymbol/Arduino,toddtreece/esp8266-Arduino,ogahara/Arduino,jadonk/Energia,i--storm/Energia,gurbrinder/Arduino,jomolinare/Arduino,mc-hamster/esp8266-Arduino,sanyaade-iot/Energia,HCastano/Arduino,radiolok/Energia,bobintornado/Energia,OpenDevice/Arduino,Cloudino/Cloudino-Arduino-IDE,Ramoonus/Arduino,vbextreme/Arduino,cscenter/Arduino,pdNor/Arduino,tskurauskas/Arduino,paulmand3l/Arduino,bsmr-arduino/Arduino,nandojve/Arduino,NicoHood/Arduino,niggor/Arduino_cc,damellis/Arduino,brianonn/Energia,Protoneer/Arduino,acosinwork/Arduino,majenkotech/Arduino,eddyst/Arduino-SourceCode,vbextreme/Arduino,tbowmo/Arduino,mboufos/esp8266-Arduino,garci66/Arduino,jmgonzalez00449/Arduino,cscenter/Arduino,paulmand3l/Arduino,ForestNymph/Arduino_sources,ForestNymph/Arduino_sources,PeterVH/Arduino,adafruit/ESP8266-Arduino,fungxu/Arduino,ricklon/Arduino,EmuxEvans/Arduino,Gourav2906/Arduino,tannewt/Arduino,tannewt/Arduino,linino/Arduino,381426068/Arduino,snargledorf/Arduino,andyvand/Arduino-1,tbowmo/Arduino,jmgonzalez00449/Arduino,gestrem/Arduino,eggfly/arduino,battosai30/Energia,lulufei/Arduino,laylthe/Arduino,snargledorf/Arduino,mateuszdw/Arduino,danielchalef/Arduino,karlitxo/Arduino,mateuszdw/Arduino,bigjosh/Arduino,wdoganowski/Arduino,andrealmeidadomingues/Arduino,championswimmer/Arduino,ThoughtWorksIoTGurgaon/Arduino,weera00/Arduino,mc-hamster/esp8266-Arduino,jabezGit/Arduino,kidswong999/Arduino,adafruit/ESP8266-Arduino,fungxu/Arduino,stevemayhew/Arduino,pasky/Energia,sanyaade-iot/Energia,Alfredynho/AgroSis,paulo-raca/ESP8266-Arduino,jomolinare/Arduino,01org/Arduino,cevatbostancioglu/Energia,mattvenn/Arduino,eduardocasarin/Arduino,ikbelkirasan/Arduino,zacinaction/Energia,adafruit/ESP8266-Arduino,bobintornado/Energia,gioblu/ArduOpen,Alfredynho/AgroSis,weera00/Arduino,Alfredynho/AgroSis,raimohanska/Arduino,UDOOboard/Arduino,bsmr-arduino/Arduino,koltegirish/Arduino,rcook/DesignLab,battosai30/Energia,Protoneer/Arduino,jomolinare/Arduino,plaintea/esp8266-Arduino,majenkotech/Arduino,drpjk/Arduino,superboonie/Arduino,henningpohl/Arduino,DavidUser/Energia,ogahara/Arduino,mboufos/esp8266-Arduino,KlaasDeNys/Arduino,ogahara/Arduino,onovy/Arduino,Gourav2906/Arduino,smily77/Arduino,tskurauskas/Arduino,toddtreece/esp8266-Arduino,NeuralSpaz/Arduino,niggor/Arduino_cc,gurbrinder/Arduino,wdoganowski/Arduino,vbextreme/Arduino,plaintea/esp8266-Arduino,wdoganowski/Arduino,stevemarple/Arduino-org,jaehong/Xmegaduino,jaimemaretoli/Arduino,superboonie/Arduino,aichi/Arduino-2,martianmartin/Energia,nkolban/Arduino,stevemarple/Arduino,bigjosh/Arduino,Orthogonal-Systems/arduino-libs,ashwin713/Arduino,lukeWal/Arduino,ogahara/Arduino,pdNor/Arduino,danielchalef/Arduino,shiitakeo/Arduino,ntruchsess/Arduino-1,Ramoonus/Arduino,ccoenen/Arduino,steamboating/Arduino,jmgonzalez00449/Arduino,leftbrainstrain/Arduino-ESP8266,sanyaade-iot/Arduino-1,jadonk/Energia,arduino-org/Arduino,ricklon/Arduino,gurbrinder/Arduino,NeuralSpaz/Arduino,gioblu/ArduOpen,jmgonzalez00449/Arduino,Gourav2906/Arduino,mateuszdw/Arduino,ricklon/Arduino,Orthogonal-Systems/arduino-libs,gestrem/Arduino,ashwin713/Arduino,ektor5/Arduino,NicoHood/Arduino,mattvenn/Arduino,jamesrob4/Arduino,adamkh/Arduino,talhaburak/Arduino,radut/Arduino,ari-analytics/Arduino,brianonn/Energia,ccoenen/Arduino,lukeWal/Arduino,koltegirish/Arduino,vigneshmanix/Energia,qtonthat/Energia,KlaasDeNys/Arduino,me-no-dev/Arduino-1,spapadim/Arduino,radut/Arduino,ForestNymph/Arduino_sources,lulufei/Arduino,bsmr-arduino/Arduino,DavidUser/Energia,jaimemaretoli/Arduino,smily77/Arduino,ssvs111/Arduino,scdls/Arduino,lulufei/Arduino,bobintornado/Energia,stevemayhew/Arduino,stevemayhew/Arduino,stevemayhew/Arduino,eduardocasarin/Arduino,piersoft/esp8266-Arduino,OpenDevice/Arduino,scdls/Arduino,tomkrus007/Arduino,sanyaade-iot/Energia,ntruchsess/Arduino-1,ms-iot/Arduino,chaveiro/Arduino,smily77/Arduino,onovy/Arduino,steamboating/Arduino,i--storm/Energia,ssvs111/Arduino,shiitakeo/Arduino,zenmanenergy/Arduino,zaiexx/Arduino,zenmanenergy/Arduino,01org/Arduino,Chris--A/Arduino,lukeWal/Arduino,andyvand/Arduino-1,majenkotech/Arduino,gberl001/Arduino,NaSymbol/Arduino,mateuszdw/Arduino,Cloudino/Cloudino-Arduino-IDE,damellis/Arduino,gioblu/ArduOpen,acosinwork/Arduino,HCastano/Arduino,NoPinky/Energia,talhaburak/Arduino,radut/Arduino,Gourav2906/Arduino,Cloudino/Cloudino-Arduino-IDE,zederson/Arduino,rodibot/Arduino,odbol/Arduino,ms-iot/Arduino,vbextreme/Arduino,scdls/Arduino,dvdvideo1234/Energia,lulufei/Arduino,leftbrainstrain/Arduino-ESP8266,ashwin713/Arduino,martianmartin/Energia,wilhelmryan/Arduino,vigneshmanix/Energia,shiitakeo/Arduino,meanbot/Energia,danielohh/Energia,ntruchsess/Arduino-1,Cloudino/Arduino,NaSymbol/Arduino,cscenter/Arduino,381426068/Arduino,meanbot/Energia,Gourav2906/Arduino,pdNor/Arduino,bugobliterator/BUAGI,linino/Arduino,shiitakeo/Arduino,acosinwork/Arduino,danielohh/Energia,probonopd/Arduino,championswimmer/Arduino,gioblu/ArduOpen,onovy/Arduino,laylthe/Arduino,battosai30/Energia,byran/Arduino,gurbrinder/Arduino,Cloudino/Arduino,stevemarple/Arduino,ricklon/Arduino,jomolinare/Arduino,ccoenen/Arduino,Gourav2906/Arduino,eeijcea/Arduino-1,probonopd/Arduino,pdNor/Arduino,gurbrinder/Arduino,dvdvideo1234/Energia,sanyaade-iot/Arduino-1,andrealmeidadomingues/Arduino,Gourav2906/Arduino,PeterVH/Arduino,snargledorf/Arduino,mangelajo/Arduino,NaSymbol/Arduino,karlitxo/Arduino,ThoughtWorksIoTGurgaon/Arduino,eeijcea/Arduino-1,qtonthat/Energia,karlitxo/Arduino,tannewt/Arduino,ikbelkirasan/Arduino,EmuxEvans/Arduino,wilhelmryan/Arduino,DavidUser/Energia,byran/Arduino,eggfly/arduino,PeterVH/Arduino,eggfly/arduino,spapadim/Arduino,plinioseniore/Arduino,plinioseniore/Arduino,gestrem/Arduino,stevemarple/Arduino-org,Chris--A/Arduino,lukeWal/Arduino,mattvenn/Arduino,jomolinare/Arduino,paulmand3l/Arduino,championswimmer/Arduino,mattvenn/Arduino,PaintYourDragon/Arduino,ektor5/Arduino,jamesrob4/Arduino,tommyli2014/Arduino,jaimemaretoli/Arduino,tbowmo/Arduino,stevemarple/Arduino,NeuralSpaz/Arduino,meanbot/Energia,henningpohl/Arduino,PaoloP74/Arduino,mc-hamster/esp8266-Arduino,gioblu/ArduOpen,rodibot/Arduino,eggfly/arduino,stevemarple/Arduino,henningpohl/Arduino,raimohanska/Arduino,adafruit/ESP8266-Arduino,nandojve/Arduino,bugobliterator/BUAGI,ogferreiro/Arduino,01org/Arduino,dvdvideo1234/Energia,jaej-dev/Arduino,sanyaade-iot/Energia,wayoda/Arduino,radiolok/Energia,tommyli2014/Arduino,niggor/Arduino_cc,KlaasDeNys/Arduino,tommyli2014/Arduino,martianmartin/Energia,cscenter/Arduino,mboufos/esp8266-Arduino,KlaasDeNys/Arduino,jmgonzalez00449/Arduino,jaehong/Xmegaduino,zaiexx/Arduino,noahchense/Arduino-1,snargledorf/Arduino,gonium/Arduino,jaej-dev/Arduino,bigjosh/Arduino,i--storm/Energia,bsmr-arduino/Arduino,ashwin713/Arduino,chaveiro/Arduino,ThoughtWorksIoTGurgaon/Arduino,radut/Arduino,gestrem/Arduino,niggor/Arduino_cc,aichi/Arduino-2,adamkh/Arduino,tomkrus007/Arduino,paulmand3l/Arduino,raimohanska/Arduino,ForestNymph/Arduino_sources,stickbreaker/Arduino,eggfly/arduino,tannewt/Arduino,kidswong999/Arduino,jmgonzalez00449/Arduino,onovy/Arduino,SmartArduino/Arduino-1,gonium/Arduino,arunkuttiyara/Arduino,ntruchsess/Arduino-1,diydrones/Arduino,ForestNymph/Arduino_sources,HCastano/Arduino,smily77/Arduino,PeterVH/Arduino,andrealmeidadomingues/Arduino,adafruit/ESP8266-Arduino,danielohh/Energia,xxxajk/Arduino-1,NicoHood/Arduino,jaej-dev/Arduino,ricklon/Arduino,nkolban/Arduino,gberl001/Arduino,tommyli2014/Arduino,danielchalef/Arduino,benwolfe/esp8266-Arduino,jadonk/Energia,jamesrob4/Arduino,UDOOboard/Arduino,pasky/Energia,koltegirish/Arduino,ari-analytics/Arduino,cscenter/Arduino,kidswong999/Arduino,NicoHood/Arduino,garci66/Arduino,xxxajk/Arduino-1,rodibot/Arduino,croberts15/Energia,koltegirish/Arduino,chaveiro/Arduino,rcook/DesignLab,cevatbostancioglu/Energia,NaSymbol/Arduino,superboonie/Arduino,jaehong/Xmegaduino,OpenDevice/Arduino,plaintea/esp8266-Arduino,Ramoonus/Arduino,adamkh/Arduino,croberts15/Energia,Cloudino/Arduino,drpjk/Arduino,niggor/Arduino_cc,ccoenen/Arduino,gonium/Arduino,laylthe/Arduino,stevemarple/Arduino-org,leftbrainstrain/Arduino-ESP8266,probonopd/Arduino,Alfredynho/AgroSis,pasky/Energia,tomkrus007/Arduino,Chris--A/Arduino,noahchense/Arduino-1,martianmartin/Energia,me-no-dev/Arduino-1,stevemarple/Arduino-org,gonium/Arduino,steamboating/Arduino,KlaasDeNys/Arduino,shannonshsu/Arduino,sanyaade-iot/Arduino-1,odbol/Arduino,Chris--A/Arduino,plinioseniore/Arduino,ikbelkirasan/Arduino,ccoenen/Arduino,nkolban/Arduino,ogferreiro/Arduino,rodibot/Arduino,lulufei/Arduino,garci66/Arduino,ari-analytics/Arduino,arduino-org/Arduino,radiolok/Energia,byran/Arduino,UDOOboard/Arduino,UDOOboard/Arduino,vbextreme/Arduino,sanyaade-iot/Energia,radiolok/Energia,PaoloP74/Arduino,tskurauskas/Arduino,dvdvideo1234/Energia,radut/Arduino,shannonshsu/Arduino,stevemarple/Arduino-org,arunkuttiyara/Arduino,xxxajk/Arduino-1,adamkh/Arduino,odbol/Arduino,fungxu/Arduino,qtonthat/Energia,NicoHood/Arduino,plinioseniore/Arduino,xxxajk/Arduino-1,laylthe/Arduino,jabezGit/Arduino,mattvenn/Arduino,drpjk/Arduino,radiolok/Energia,qtonthat/Energia,UDOOboard/Arduino,mateuszdw/Arduino,ikbelkirasan/Arduino,zederson/Arduino,leftbrainstrain/Arduino-ESP8266,i--storm/Energia,cevatbostancioglu/Energia,henningpohl/Arduino,EmuxEvans/Arduino,ektor5/Arduino,ThoughtWorksIoTGurgaon/Arduino,niggor/Arduino_cc,danielchalef/Arduino,ikbelkirasan/Arduino,andrealmeidadomingues/Arduino,byran/Arduino,gurbrinder/Arduino,NeuralSpaz/Arduino,DavidUser/Energia,chaveiro/Arduino,ektor5/Arduino,Cloudino/Cloudino-Arduino-IDE,jabezGit/Arduino,rcook/DesignLab,talhaburak/Arduino,ThoughtWorksIoTGurgaon/Arduino,paulmand3l/Arduino,gonium/Arduino,DavidUser/Energia,UDOOboard/Arduino,zacinaction/Energia,ricklon/Arduino,meanbot/Energia,paulmand3l/Arduino,KlaasDeNys/Arduino,ricklon/Arduino,Protoneer/Arduino,SmartArduino/Arduino-1,zacinaction/Energia,karlitxo/Arduino,SmartArduino/Arduino-1,01org/Arduino,diydrones/Arduino,acosinwork/Arduino,cscenter/Arduino,garci66/Arduino,eduardocasarin/Arduino,jadonk/Energia,PaintYourDragon/Arduino,noahchense/Arduino-1,talhaburak/Arduino,chaveiro/Arduino,EmuxEvans/Arduino,martianmartin/Energia,ccoenen/Arduino,superboonie/Arduino,brianonn/Energia,eeijcea/Arduino-1,lukeWal/Arduino,plinioseniore/Arduino,aichi/Arduino-2,brianonn/Energia,shannonshsu/Arduino,wayoda/Arduino,Protoneer/Arduino,acosinwork/Arduino,ThoughtWorksIoTGurgaon/Arduino,onovy/Arduino,kidswong999/Arduino,arduino-org/Arduino,tomkrus007/Arduino,cevatbostancioglu/Energia,ntruchsess/Arduino-1,zacinaction/Energia,wdoganowski/Arduino,damellis/Arduino,sanyaade-iot/Energia,nandojve/Arduino,arunkuttiyara/Arduino,tskurauskas/Arduino,HCastano/Arduino,eddyst/Arduino-SourceCode,zaiexx/Arduino,zaiexx/Arduino,plaintea/esp8266-Arduino,eddyst/Arduino-SourceCode,gberl001/Arduino,xxxajk/Arduino-1,bobintornado/Energia,ogahara/Arduino,Chris--A/Arduino,ari-analytics/Arduino,mattvenn/Arduino,arunkuttiyara/Arduino,rcook/DesignLab,tomkrus007/Arduino,NicoHood/Arduino,zaiexx/Arduino,qtonthat/Energia,zacinaction/Energia,noahchense/Arduino-1,meanbot/Energia,spapadim/Arduino,arunkuttiyara/Arduino,xxxajk/Arduino-1,stickbreaker/Arduino,weera00/Arduino
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* AvrdudeUploader - uploader implementation using avrdude Part of the Arduino project - http://www.arduino.cc/ Copyright (c) 2004-05 Hernando Barragan 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 $Id$ */ package processing.app; import java.io.*; import java.util.*; import java.util.zip.*; import javax.swing.*; import gnu.io.*; public class AvrdudeUploader extends Uploader { public AvrdudeUploader() { } public boolean uploadUsingPreferences(String buildPath, String className) throws RunnerException { List commandDownloader = new ArrayList(); // avrdude doesn't want to read device signatures (it always gets // 0x000000); force it to continue uploading anyway commandDownloader.add("-F"); String programmer = Preferences.get("upload.programmer"); // avrdude wants "stk500v1" to distinguish it from stk500v2 if (programmer.equals("stk500")) programmer = "stk500v1"; commandDownloader.add("-c" + programmer); if (Preferences.get("upload.programmer").equals("dapa")) { // avrdude doesn't need to be told the address of the parallel port //commandDownloader.add("-dlpt=" + Preferences.get("parallel.port")); } else { commandDownloader.add( "-P" + (Base.isWindows() ? "/dev/" + Preferences.get("serial.port").toLowerCase() : Preferences.get("serial.port"))); commandDownloader.add( "-b" + Preferences.getInteger("serial.download_rate")); } if (Preferences.getBoolean("upload.erase")) commandDownloader.add("-e"); else commandDownloader.add("-D"); if (!Preferences.getBoolean("upload.verify")) commandDownloader.add("-V"); commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i"); return uisp(commandDownloader); } public boolean burnBootloaderAVRISP(String target) throws RunnerException { List commandDownloader = new ArrayList(); commandDownloader.add("-c" + Preferences.get("bootloader." + target + ".programmer")); if (Preferences.get("bootloader." + target + ".communication").equals("usb")) { commandDownloader.add("-Pusb"); } else { commandDownloader.add( "-P" + (Base.isWindows() ? "/dev/" + Preferences.get("serial.port").toLowerCase() : Preferences.get("serial.port"))); } commandDownloader.add("-b" + Preferences.get("serial.burn_rate")); return burnBootloader(target, commandDownloader); } public boolean burnBootloaderParallel(String target) throws RunnerException { List commandDownloader = new ArrayList(); commandDownloader.add("-dprog=dapa"); commandDownloader.add("-dlpt=" + Preferences.get("parallel.port")); return burnBootloader(target, commandDownloader); } protected boolean burnBootloader(String target, Collection params) throws RunnerException { return // unlock bootloader segment of flash memory and write fuses uisp(params, Arrays.asList(new String[] { "-e", "-Ulock:w:" + Preferences.get("bootloader." + target + ".unlock_bits") + ":m", "-Uefuse:w:" + Preferences.get("bootloader." + target + ".extended_fuses") + ":m", "-Uhfuse:w:" + Preferences.get("bootloader." + target + ".high_fuses") + ":m", "-Ulfuse:w:" + Preferences.get("bootloader." + target + ".low_fuses") + ":m", })) && // upload bootloader and lock bootloader segment uisp(params, Arrays.asList(new String[] { "-Uflash:w:" + Preferences.get("bootloader." + target + ".path") + File.separator + Preferences.get("bootloader." + target + ".file") + ":i", "-Ulock:w:" + Preferences.get("bootloader." + target + ".lock_bits") + ":m" })); } public boolean uisp(Collection p1, Collection p2) throws RunnerException { ArrayList p = new ArrayList(p1); p.addAll(p2); return uisp(p); } public boolean uisp(Collection params) throws RunnerException { flushSerialBuffer(); List commandDownloader = new ArrayList(); commandDownloader.add("avrdude"); // On Windows and the Mac, we need to point avrdude at its config file // since it's getting installed in an unexpected location (i.e. a // sub-directory of wherever the user happens to stick Arduino). On Linux, // avrdude will have been properly installed by the distribution's package // manager and should be able to find its config file. if(Base.isMacOS()) { commandDownloader.add("-C" + "tools/avr/etc/avrdude.conf"); } else if(Base.isWindows()) { String userdir = System.getProperty("user.dir") + File.separator; commandDownloader.add("-C" + userdir + "tools/avr/etc/avrdude.conf"); } if (Preferences.getBoolean("upload.verbose")) { commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); } else { commandDownloader.add("-q"); commandDownloader.add("-q"); } // XXX: quick hack to chop the "atmega" off of "atmega8" and "atmega168", // then shove an "m" at the beginning. won't work for attiny's, etc. commandDownloader.add("-pm" + Preferences.get("build.mcu").substring(6)); commandDownloader.addAll(params); return executeUploadCommand(commandDownloader); } }
app/AvrdudeUploader.java
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* AvrdudeUploader - uploader implementation using avrdude Part of the Arduino project - http://www.arduino.cc/ Copyright (c) 2004-05 Hernando Barragan 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 $Id$ */ package processing.app; import java.io.*; import java.util.*; import java.util.zip.*; import javax.swing.*; import gnu.io.*; public class AvrdudeUploader extends Uploader { public AvrdudeUploader() { } public boolean uploadUsingPreferences(String buildPath, String className) throws RunnerException { List commandDownloader = new ArrayList(); // avrdude doesn't want to read device signatures (it always gets // 0x000000); force it to continue uploading anyway commandDownloader.add("-F"); String programmer = Preferences.get("upload.programmer"); // avrdude wants "stk500v1" to distinguish it from stk500v2 if (programmer.equals("stk500")) programmer = "stk500v1"; commandDownloader.add("-c" + programmer); if (Preferences.get("upload.programmer").equals("dapa")) { // avrdude doesn't need to be told the address of the parallel port //commandDownloader.add("-dlpt=" + Preferences.get("parallel.port")); } else { commandDownloader.add( "-P" + (Base.isWindows() ? "/dev/" + Preferences.get("serial.port").toLowerCase() : Preferences.get("serial.port"))); commandDownloader.add( "-b" + Preferences.getInteger("serial.download_rate")); } if (Preferences.getBoolean("upload.erase")) commandDownloader.add("-e"); else commandDownloader.add("-D"); if (!Preferences.getBoolean("upload.verify")) commandDownloader.add("-V"); commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex"); return uisp(commandDownloader); } public boolean burnBootloaderAVRISP(String target) throws RunnerException { List commandDownloader = new ArrayList(); commandDownloader.add("-c" + Preferences.get("bootloader." + target + ".programmer")); if (Preferences.get("bootloader." + target + ".communication").equals("usb")) { commandDownloader.add("-Pusb"); } else { commandDownloader.add( "-P" + (Base.isWindows() ? "/dev/" + Preferences.get("serial.port").toLowerCase() : Preferences.get("serial.port"))); } commandDownloader.add("-b" + Preferences.get("serial.burn_rate")); return burnBootloader(target, commandDownloader); } public boolean burnBootloaderParallel(String target) throws RunnerException { List commandDownloader = new ArrayList(); commandDownloader.add("-dprog=dapa"); commandDownloader.add("-dlpt=" + Preferences.get("parallel.port")); return burnBootloader(target, commandDownloader); } protected boolean burnBootloader(String target, Collection params) throws RunnerException { return // unlock bootloader segment of flash memory and write fuses uisp(params, Arrays.asList(new String[] { "-e", "-Ulock:w:" + Preferences.get("bootloader." + target + ".unlock_bits") + ":m", "-Uefuse:w:" + Preferences.get("bootloader." + target + ".extended_fuses") + ":m", "-Uhfuse:w:" + Preferences.get("bootloader." + target + ".high_fuses") + ":m", "-Ulfuse:w:" + Preferences.get("bootloader." + target + ".low_fuses") + ":m", })) && // upload bootloader and lock bootloader segment uisp(params, Arrays.asList(new String[] { "-Uflash:w:" + Preferences.get("bootloader." + target + ".path") + File.separator + Preferences.get("bootloader." + target + ".file") + ":i", "-Ulock:w:" + Preferences.get("bootloader." + target + ".lock_bits") + ":m" })); } public boolean uisp(Collection p1, Collection p2) throws RunnerException { ArrayList p = new ArrayList(p1); p.addAll(p2); return uisp(p); } public boolean uisp(Collection params) throws RunnerException { flushSerialBuffer(); List commandDownloader = new ArrayList(); commandDownloader.add("avrdude"); // On Windows and the Mac, we need to point avrdude at its config file // since it's getting installed in an unexpected location (i.e. a // sub-directory of wherever the user happens to stick Arduino). On Linux, // avrdude will have been properly installed by the distribution's package // manager and should be able to find its config file. if(Base.isMacOS()) { commandDownloader.add("-C" + "tools/avr/etc/avrdude.conf"); } else if(Base.isWindows()) { String userdir = System.getProperty("user.dir") + File.separator; commandDownloader.add("-C" + userdir + "tools/avr/etc/avrdude.conf"); } if (Preferences.getBoolean("upload.verbose")) { commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); } else { commandDownloader.add("-q"); commandDownloader.add("-q"); } // XXX: quick hack to chop the "atmega" off of "atmega8" and "atmega168", // then shove an "m" at the beginning. won't work for attiny's, etc. commandDownloader.add("-pm" + Preferences.get("build.mcu").substring(6)); commandDownloader.addAll(params); return executeUploadCommand(commandDownloader); } }
Explicitly specifying intel hex to avrdude so it's not confused by paths with :'s in them from Windows drive letters
app/AvrdudeUploader.java
Explicitly specifying intel hex to avrdude so it's not confused by paths with :'s in them from Windows drive letters
<ide><path>pp/AvrdudeUploader.java <ide> commandDownloader.add("-D"); <ide> if (!Preferences.getBoolean("upload.verify")) <ide> commandDownloader.add("-V"); <del> commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex"); <add> commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i"); <ide> return uisp(commandDownloader); <ide> } <ide>
Java
mit
68b0ff6daee80d239046dc014f30750dec1b68b8
0
AlmasB/FXGL,AlmasB/FXGL,AlmasB/FXGL,AlmasB/FXGL
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.physics.box2d.collision; import com.almasb.fxgl.core.math.Vec2; import com.almasb.fxgl.physics.box2d.collision.Distance.SimplexCache; import com.almasb.fxgl.physics.box2d.collision.Manifold.ManifoldType; import com.almasb.fxgl.physics.box2d.collision.shapes.CircleShape; import com.almasb.fxgl.physics.box2d.collision.shapes.EdgeShape; import com.almasb.fxgl.physics.box2d.collision.shapes.PolygonShape; import com.almasb.fxgl.physics.box2d.collision.shapes.Shape; import com.almasb.fxgl.physics.box2d.common.JBoxSettings; import com.almasb.fxgl.physics.box2d.common.Rotation; import com.almasb.fxgl.physics.box2d.common.Transform; import com.almasb.fxgl.physics.box2d.pooling.IWorldPool; /** * Functions used for computing contact points, distance queries, and TOI queries. * Collision methods are non-static for pooling speed, retrieve a collision object from the {@link IWorldPool}. * Should not be constructed. * * @author Daniel Murphy */ public final class Collision { private final IWorldPool pool; public Collision(IWorldPool pool) { incidentEdge[0] = new ClipVertex(); incidentEdge[1] = new ClipVertex(); clipPoints1[0] = new ClipVertex(); clipPoints1[1] = new ClipVertex(); clipPoints2[0] = new ClipVertex(); clipPoints2[1] = new ClipVertex(); this.pool = pool; } private final DistanceInput input = new DistanceInput(); private final SimplexCache cache = new SimplexCache(); private final DistanceOutput output = new DistanceOutput(); /** * Determine if two generic shapes overlap. */ public boolean testOverlap(Shape shapeA, int indexA, Shape shapeB, int indexB, Transform xfA, Transform xfB) { input.proxyA.set(shapeA, indexA); input.proxyB.set(shapeB, indexB); input.transformA.set(xfA); input.transformB.set(xfB); input.useRadii = true; cache.count = 0; pool.getDistance().distance(output, cache, input); // djm note: anything significant about 10.0f? return output.distance < 10.0f * JBoxSettings.EPSILON; } /** * Clipping for contact manifolds. * Sutherland-Hodgman clipping. */ public static int clipSegmentToLine(ClipVertex[] vOut, ClipVertex[] vIn, Vec2 normal, float offset, int vertexIndexA) { // Start with no output points int numOut = 0; final ClipVertex vIn0 = vIn[0]; final ClipVertex vIn1 = vIn[1]; final Vec2 vIn0v = vIn0.v; final Vec2 vIn1v = vIn1.v; // Calculate the distance of end points to the line float distance0 = Vec2.dot(normal, vIn0v) - offset; float distance1 = Vec2.dot(normal, vIn1v) - offset; // If the points are behind the plane if (distance0 <= 0.0f) { vOut[numOut++].set(vIn0); } if (distance1 <= 0.0f) { vOut[numOut++].set(vIn1); } // If the points are on different sides of the plane if (distance0 * distance1 < 0.0f) { // Find intersection point of edge and plane float interp = distance0 / (distance0 - distance1); ClipVertex vOutNO = vOut[numOut]; // vOut[numOut].v = vIn[0].v + interp * (vIn[1].v - vIn[0].v); vOutNO.v.x = vIn0v.x + interp * (vIn1v.x - vIn0v.x); vOutNO.v.y = vIn0v.y + interp * (vIn1v.y - vIn0v.y); // VertexA is hitting edgeB. vOutNO.id.indexA = (byte) vertexIndexA; vOutNO.id.indexB = vIn0.id.indexB; vOutNO.id.typeA = (byte) ContactID.Type.VERTEX.ordinal(); vOutNO.id.typeB = (byte) ContactID.Type.FACE.ordinal(); ++numOut; } return numOut; } // #### COLLISION STUFF (not from collision.h or collision.cpp) #### // djm pooling private static Vec2 d = new Vec2(); /** * Compute the collision manifold between two circles. */ @SuppressWarnings("PMD.UselessParentheses") public void collideCircles(Manifold manifold, CircleShape circle1, Transform xfA, CircleShape circle2, Transform xfB) { manifold.pointCount = 0; // before inline: // Transform.mulToOut(xfA, circle1.m_p, pA); // Transform.mulToOut(xfB, circle2.m_p, pB); // d.set(pB).subLocal(pA); // float distSqr = d.x * d.x + d.y * d.y; // after inline: Vec2 circle1p = circle1.center; Vec2 circle2p = circle2.center; float pAx = (xfA.q.c * circle1p.x - xfA.q.s * circle1p.y) + xfA.p.x; float pAy = (xfA.q.s * circle1p.x + xfA.q.c * circle1p.y) + xfA.p.y; float pBx = (xfB.q.c * circle2p.x - xfB.q.s * circle2p.y) + xfB.p.x; float pBy = (xfB.q.s * circle2p.x + xfB.q.c * circle2p.y) + xfB.p.y; float dx = pBx - pAx; float dy = pBy - pAy; float distSqr = dx * dx + dy * dy; // end inline final float radius = circle1.getRadius() + circle2.getRadius(); if (distSqr > radius * radius) { return; } manifold.type = ManifoldType.CIRCLES; manifold.localPoint.set(circle1p); manifold.localNormal.setZero(); manifold.pointCount = 1; manifold.points[0].localPoint.set(circle2p); manifold.points[0].id.zero(); } /** * Compute the collision manifold between a polygon and a circle. * * @param manifold * @param polygon * @param xfA * @param circle * @param xfB */ @SuppressWarnings("PMD.UselessParentheses") public void collidePolygonAndCircle(Manifold manifold, final PolygonShape polygon, final Transform xfA, final CircleShape circle, final Transform xfB) { manifold.pointCount = 0; // Vec2 v = circle.m_p; // Compute circle position in the frame of the polygon. // before inline: // Transform.mulToOutUnsafe(xfB, circle.m_p, c); // Transform.mulTransToOut(xfA, c, cLocal); // final float cLocalx = cLocal.x; // final float cLocaly = cLocal.y; // after inline: final Vec2 circlep = circle.center; final Rotation xfBq = xfB.q; final Rotation xfAq = xfA.q; final float cx = (xfBq.c * circlep.x - xfBq.s * circlep.y) + xfB.p.x; final float cy = (xfBq.s * circlep.x + xfBq.c * circlep.y) + xfB.p.y; final float px = cx - xfA.p.x; final float py = cy - xfA.p.y; final float cLocalx = (xfAq.c * px + xfAq.s * py); final float cLocaly = (-xfAq.s * px + xfAq.c * py); // end inline // Find the min separating edge. int normalIndex = 0; float separation = -Float.MAX_VALUE; final float radius = polygon.getRadius() + circle.getRadius(); final int vertexCount = polygon.getVertexCount(); float s; final Vec2[] vertices = polygon.m_vertices; final Vec2[] normals = polygon.m_normals; for (int i = 0; i < vertexCount; i++) { // before inline // temp.set(cLocal).subLocal(vertices[i]); // float s = Vec2.dot(normals[i], temp); // after inline final Vec2 vertex = vertices[i]; final float tempx = cLocalx - vertex.x; final float tempy = cLocaly - vertex.y; s = normals[i].x * tempx + normals[i].y * tempy; if (s > radius) { // early out return; } if (s > separation) { separation = s; normalIndex = i; } } // Vertices that subtend the incident face. final int vertIndex1 = normalIndex; final int vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; final Vec2 v1 = vertices[vertIndex1]; final Vec2 v2 = vertices[vertIndex2]; // If the center is inside the polygon ... if (separation < JBoxSettings.EPSILON) { manifold.pointCount = 1; manifold.type = ManifoldType.FACE_A; // before inline: // manifold.localNormal.set(normals[normalIndex]); // manifold.localPoint.set(v1).addLocal(v2).mulLocal(.5f); // manifold.points[0].localPoint.set(circle.m_p); // after inline: final Vec2 normal = normals[normalIndex]; manifold.localNormal.x = normal.x; manifold.localNormal.y = normal.y; manifold.localPoint.x = (v1.x + v2.x) * .5f; manifold.localPoint.y = (v1.y + v2.y) * .5f; final ManifoldPoint mpoint = manifold.points[0]; mpoint.localPoint.x = circlep.x; mpoint.localPoint.y = circlep.y; mpoint.id.zero(); // end inline return; } // Compute barycentric coordinates // before inline: // temp.set(cLocal).subLocal(v1); // temp2.set(v2).subLocal(v1); // float u1 = Vec2.dot(temp, temp2); // temp.set(cLocal).subLocal(v2); // temp2.set(v1).subLocal(v2); // float u2 = Vec2.dot(temp, temp2); // after inline: final float tempX = cLocalx - v1.x; final float tempY = cLocaly - v1.y; final float temp2X = v2.x - v1.x; final float temp2Y = v2.y - v1.y; final float u1 = tempX * temp2X + tempY * temp2Y; final float temp3X = cLocalx - v2.x; final float temp3Y = cLocaly - v2.y; final float temp4X = v1.x - v2.x; final float temp4Y = v1.y - v2.y; final float u2 = temp3X * temp4X + temp3Y * temp4Y; // end inline if (u1 <= 0f) { // inlined final float dx = cLocalx - v1.x; final float dy = cLocaly - v1.y; if (dx * dx + dy * dy > radius * radius) { return; } manifold.pointCount = 1; manifold.type = ManifoldType.FACE_A; // before inline: // manifold.localNormal.set(cLocal).subLocal(v1); // after inline: manifold.localNormal.x = cLocalx - v1.x; manifold.localNormal.y = cLocaly - v1.y; // end inline manifold.localNormal.getLengthAndNormalize(); manifold.localPoint.set(v1); manifold.points[0].localPoint.set(circlep); manifold.points[0].id.zero(); } else if (u2 <= 0.0f) { // inlined final float dx = cLocalx - v2.x; final float dy = cLocaly - v2.y; if (dx * dx + dy * dy > radius * radius) { return; } manifold.pointCount = 1; manifold.type = ManifoldType.FACE_A; // before inline: // manifold.localNormal.set(cLocal).subLocal(v2); // after inline: manifold.localNormal.x = cLocalx - v2.x; manifold.localNormal.y = cLocaly - v2.y; // end inline manifold.localNormal.getLengthAndNormalize(); manifold.localPoint.set(v2); manifold.points[0].localPoint.set(circlep); manifold.points[0].id.zero(); } else { // Vec2 faceCenter = 0.5f * (v1 + v2); // (temp is faceCenter) // before inline: // temp.set(v1).addLocal(v2).mulLocal(.5f); // // temp2.set(cLocal).subLocal(temp); // separation = Vec2.dot(temp2, normals[vertIndex1]); // if (separation > radius) { // return; // } // after inline: final float fcx = (v1.x + v2.x) * .5f; final float fcy = (v1.y + v2.y) * .5f; final float tx = cLocalx - fcx; final float ty = cLocaly - fcy; final Vec2 normal = normals[vertIndex1]; separation = tx * normal.x + ty * normal.y; if (separation > radius) { return; } // end inline manifold.pointCount = 1; manifold.type = ManifoldType.FACE_A; manifold.localNormal.set(normals[vertIndex1]); manifold.localPoint.x = fcx; // (faceCenter) manifold.localPoint.y = fcy; manifold.points[0].localPoint.set(circlep); manifold.points[0].id.zero(); } } // djm pooling, and from above private final Vec2 temp = new Vec2(); @SuppressWarnings("PMD.UselessParentheses") public void findIncidentEdge(final ClipVertex[] c, final PolygonShape poly1, final Transform xf1, int edge1, final PolygonShape poly2, final Transform xf2) { int count1 = poly1.getVertexCount(); final Vec2[] normals1 = poly1.m_normals; int count2 = poly2.getVertexCount(); final Vec2[] vertices2 = poly2.m_vertices; final Vec2[] normals2 = poly2.m_normals; assert 0 <= edge1 && edge1 < count1; final ClipVertex c0 = c[0]; final ClipVertex c1 = c[1]; final Rotation xf1q = xf1.q; final Rotation xf2q = xf2.q; // Get the normal of the reference edge in poly2's frame. // Vec2 normal1 = MulT(xf2.R, Mul(xf1.R, normals1[edge1])); // before inline: // Rot.mulToOutUnsafe(xf1.q, normals1[edge1], normal1); // temporary // Rot.mulTrans(xf2.q, normal1, normal1); // after inline: final Vec2 v = normals1[edge1]; final float tempx = xf1q.c * v.x - xf1q.s * v.y; final float tempy = xf1q.s * v.x + xf1q.c * v.y; final float normal1x = xf2q.c * tempx + xf2q.s * tempy; final float normal1y = -xf2q.s * tempx + xf2q.c * tempy; // end inline // Find the incident edge on poly2. int index = 0; float minDot = Float.MAX_VALUE; for (int i = 0; i < count2; ++i) { Vec2 b = normals2[i]; float dot = normal1x * b.x + normal1y * b.y; if (dot < minDot) { minDot = dot; index = i; } } // Build the clip vertices for the incident edge. int i1 = index; int i2 = i1 + 1 < count2 ? i1 + 1 : 0; // c0.v = Mul(xf2, vertices2[i1]); Vec2 v1 = vertices2[i1]; Vec2 out = c0.v; out.x = (xf2q.c * v1.x - xf2q.s * v1.y) + xf2.p.x; out.y = (xf2q.s * v1.x + xf2q.c * v1.y) + xf2.p.y; c0.id.indexA = (byte) edge1; c0.id.indexB = (byte) i1; c0.id.typeA = (byte) ContactID.Type.FACE.ordinal(); c0.id.typeB = (byte) ContactID.Type.VERTEX.ordinal(); // c1.v = Mul(xf2, vertices2[i2]); Vec2 v2 = vertices2[i2]; Vec2 out1 = c1.v; out1.x = (xf2q.c * v2.x - xf2q.s * v2.y) + xf2.p.x; out1.y = (xf2q.s * v2.x + xf2q.c * v2.y) + xf2.p.y; c1.id.indexA = (byte) edge1; c1.id.indexB = (byte) i2; c1.id.typeA = (byte) ContactID.Type.FACE.ordinal(); c1.id.typeB = (byte) ContactID.Type.VERTEX.ordinal(); } private final EdgeResults results1 = new EdgeResults(); private final EdgeResults results2 = new EdgeResults(); private final ClipVertex[] incidentEdge = new ClipVertex[2]; private final Vec2 localTangent = new Vec2(); private final Vec2 localNormal = new Vec2(); private final Vec2 planePoint = new Vec2(); private final Vec2 tangent = new Vec2(); private final Vec2 v11 = new Vec2(); private final Vec2 v12 = new Vec2(); private final ClipVertex[] clipPoints1 = new ClipVertex[2]; private final ClipVertex[] clipPoints2 = new ClipVertex[2]; /** * Compute the collision manifold between two polygons. */ @SuppressWarnings("PMD.UselessParentheses") public void collidePolygons(Manifold manifold, final PolygonShape polyA, final Transform xfA, final PolygonShape polyB, final Transform xfB) { // Find edge normal of max separation on A - return if separating axis is found // Find edge normal of max separation on B - return if separation axis is found // Choose reference edge as min(minA, minB) // Find incident edge // Clip // The normal points from 1 to 2 manifold.pointCount = 0; float totalRadius = polyA.getRadius() + polyB.getRadius(); findMaxSeparation(results1, polyA, xfA, polyB, xfB); if (results1.separation > totalRadius) { return; } findMaxSeparation(results2, polyB, xfB, polyA, xfA); if (results2.separation > totalRadius) { return; } final PolygonShape poly1; // reference polygon final PolygonShape poly2; // incident polygon Transform xf1, xf2; int edge1; // reference edge boolean flip; final float k_tol = 0.1f * JBoxSettings.linearSlop; if (results2.separation > results1.separation + k_tol) { poly1 = polyB; poly2 = polyA; xf1 = xfB; xf2 = xfA; edge1 = results2.edgeIndex; manifold.type = ManifoldType.FACE_B; flip = true; } else { poly1 = polyA; poly2 = polyB; xf1 = xfA; xf2 = xfB; edge1 = results1.edgeIndex; manifold.type = ManifoldType.FACE_A; flip = false; } final Rotation xf1q = xf1.q; findIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); int count1 = poly1.getVertexCount(); final Vec2[] vertices1 = poly1.m_vertices; final int iv1 = edge1; final int iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0; v11.set(vertices1[iv1]); v12.set(vertices1[iv2]); localTangent.x = v12.x - v11.x; localTangent.y = v12.y - v11.y; localTangent.getLengthAndNormalize(); // Vec2 localNormal = Vec2.cross(dv, 1.0f); localNormal.x = 1f * localTangent.y; localNormal.y = -1f * localTangent.x; // Vec2 planePoint = 0.5f * (v11+ v12); planePoint.x = (v11.x + v12.x) * .5f; planePoint.y = (v11.y + v12.y) * .5f; // Rot.mulToOutUnsafe(xf1.q, localTangent, tangent); tangent.x = xf1q.c * localTangent.x - xf1q.s * localTangent.y; tangent.y = xf1q.s * localTangent.x + xf1q.c * localTangent.y; // Vec2.crossToOutUnsafe(tangent, 1f, normal); final float normalx = 1f * tangent.y; final float normaly = -1f * tangent.x; Transform.mulToOut(xf1, v11, v11); Transform.mulToOut(xf1, v12, v12); // v11 = Mul(xf1, v11); // v12 = Mul(xf1, v12); // Face offset // float frontOffset = Vec2.dot(normal, v11); float frontOffset = normalx * v11.x + normaly * v11.y; // Side offsets, extended by polytope skin thickness. // float sideOffset1 = -Vec2.dot(tangent, v11) + totalRadius; // float sideOffset2 = Vec2.dot(tangent, v12) + totalRadius; float sideOffset1 = -(tangent.x * v11.x + tangent.y * v11.y) + totalRadius; float sideOffset2 = tangent.x * v12.x + tangent.y * v12.y + totalRadius; // Clip incident edge against extruded edge1 side edges. // ClipVertex clipPoints1[2]; // ClipVertex clipPoints2[2]; int np; // Clip to box side 1 // np = ClipSegmentToLine(clipPoints1, incidentEdge, -sideNormal, sideOffset1); tangent.negateLocal(); np = clipSegmentToLine(clipPoints1, incidentEdge, tangent, sideOffset1, iv1); tangent.negateLocal(); if (np < 2) { return; } // Clip to negative box side 1 np = clipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); if (np < 2) { return; } // Now clipPoints2 contains the clipped points. manifold.localNormal.set(localNormal); manifold.localPoint.set(planePoint); int pointCount = 0; for (int i = 0; i < JBoxSettings.maxManifoldPoints; ++i) { // float separation = Vec2.dot(normal, clipPoints2[i].v) - frontOffset; float separation = normalx * clipPoints2[i].v.x + normaly * clipPoints2[i].v.y - frontOffset; if (separation <= totalRadius) { ManifoldPoint cp = manifold.points[pointCount]; // cp.m_localPoint = MulT(xf2, clipPoints2[i].v); Vec2 out = cp.localPoint; final float px = clipPoints2[i].v.x - xf2.p.x; final float py = clipPoints2[i].v.y - xf2.p.y; out.x = (xf2.q.c * px + xf2.q.s * py); out.y = (-xf2.q.s * px + xf2.q.c * py); cp.id.set(clipPoints2[i].id); if (flip) { // Swap features cp.id.flip(); } ++pointCount; } } manifold.pointCount = pointCount; } private final Transform xf = new Transform(); private final Vec2 n = new Vec2(); private final Vec2 v1 = new Vec2(); /** * Find the max separation between poly1 and poly2 using edge normals from poly1. */ public void findMaxSeparation(EdgeResults results, PolygonShape poly1, Transform xf1, PolygonShape poly2, Transform xf2) { int count1 = poly1.getVertexCount(); int count2 = poly2.getVertexCount(); Vec2[] n1s = poly1.m_normals; Vec2[] v1s = poly1.m_vertices; Vec2[] v2s = poly2.m_vertices; Transform.mulTransToOutUnsafe(xf2, xf1, xf); final Rotation xfq = xf.q; int bestIndex = 0; float maxSeparation = -Float.MAX_VALUE; for (int i = 0; i < count1; i++) { // Get poly1 normal in frame2. Rotation.mulToOutUnsafe(xfq, n1s[i], n); Transform.mulToOutUnsafe(xf, v1s[i], v1); // Find deepest point for normal i. float si = Float.MAX_VALUE; for (int j = 0; j < count2; ++j) { Vec2 v2sj = v2s[j]; float sij = n.x * (v2sj.x - v1.x) + n.y * (v2sj.y - v1.y); if (sij < si) { si = sij; } } if (si > maxSeparation) { maxSeparation = si; bestIndex = i; } } results.edgeIndex = bestIndex; results.separation = maxSeparation; } private final Vec2 Q = new Vec2(); private final Vec2 e = new Vec2(); private final ContactID cf = new ContactID(); private final Vec2 e1 = new Vec2(); private final Vec2 P = new Vec2(); // Compute contact points for edge versus circle. // This accounts for edge connectivity. public void collideEdgeAndCircle(Manifold manifold, final EdgeShape edgeA, final Transform xfA, final CircleShape circleB, final Transform xfB) { manifold.pointCount = 0; // Compute circle in frame of edge // Vec2 Q = MulT(xfA, Mul(xfB, circleB.m_p)); Transform.mulToOutUnsafe(xfB, circleB.center, temp); Transform.mulTransToOutUnsafe(xfA, temp, Q); final Vec2 A = edgeA.m_vertex1; final Vec2 B = edgeA.m_vertex2; e.set(B).subLocal(A); // Barycentric coordinates float u = Vec2.dot(e, temp.set(B).subLocal(Q)); float v = Vec2.dot(e, temp.set(Q).subLocal(A)); float radius = edgeA.getRadius() + circleB.getRadius(); // ContactFeature cf; cf.indexB = 0; cf.typeB = (byte) ContactID.Type.VERTEX.ordinal(); // Region A if (v <= 0.0f) { final Vec2 P = A; d.set(Q).subLocal(P); float dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } // Is there an edge connected to A? if (edgeA.m_hasVertex0) { final Vec2 A1 = edgeA.m_vertex0; final Vec2 B1 = A; e1.set(B1).subLocal(A1); float u1 = Vec2.dot(e1, temp.set(B1).subLocal(Q)); // Is the circle in Region AB of the previous edge? if (u1 > 0.0f) { return; } } cf.indexA = 0; cf.typeA = (byte) ContactID.Type.VERTEX.ordinal(); manifold.pointCount = 1; manifold.type = Manifold.ManifoldType.CIRCLES; manifold.localNormal.setZero(); manifold.localPoint.set(P); // manifold.points[0].id.key = 0; manifold.points[0].id.set(cf); manifold.points[0].localPoint.set(circleB.center); return; } // Region B if (u <= 0.0f) { Vec2 P = B; d.set(Q).subLocal(P); float dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } // Is there an edge connected to B? if (edgeA.m_hasVertex3) { final Vec2 B2 = edgeA.m_vertex3; final Vec2 A2 = B; final Vec2 e2 = e1; e2.set(B2).subLocal(A2); float v2 = Vec2.dot(e2, temp.set(Q).subLocal(A2)); // Is the circle in Region AB of the next edge? if (v2 > 0.0f) { return; } } cf.indexA = 1; cf.typeA = (byte) ContactID.Type.VERTEX.ordinal(); manifold.pointCount = 1; manifold.type = Manifold.ManifoldType.CIRCLES; manifold.localNormal.setZero(); manifold.localPoint.set(P); // manifold.points[0].id.key = 0; manifold.points[0].id.set(cf); manifold.points[0].localPoint.set(circleB.center); return; } // Region AB float den = Vec2.dot(e, e); assert den > 0.0f; // Vec2 P = (1.0f / den) * (u * A + v * B); P.set(A).mulLocal(u).addLocal(temp.set(B).mulLocal(v)); P.mulLocal(1.0f / den); d.set(Q).subLocal(P); float dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } n.x = -e.y; n.y = e.x; if (Vec2.dot(n, temp.set(Q).subLocal(A)) < 0.0f) { n.set(-n.x, -n.y); } n.getLengthAndNormalize(); cf.indexA = 0; cf.typeA = (byte) ContactID.Type.FACE.ordinal(); manifold.pointCount = 1; manifold.type = Manifold.ManifoldType.FACE_A; manifold.localNormal.set(n); manifold.localPoint.set(A); // manifold.points[0].id.key = 0; manifold.points[0].id.set(cf); manifold.points[0].localPoint.set(circleB.center); } private final EPCollider collider = new EPCollider(); public void collideEdgeAndPolygon(Manifold manifold, final EdgeShape edgeA, final Transform xfA, final PolygonShape polygonB, final Transform xfB) { collider.collide(manifold, edgeA, xfA, polygonB, xfB); } /** * Java-specific class for returning edge results */ private static class EdgeResults { float separation; int edgeIndex; } /** * Used for computing contact manifolds. */ private static class ClipVertex { public final Vec2 v = new Vec2(); public final ContactID id = new ContactID(); public void set(final ClipVertex cv) { Vec2 v1 = cv.v; v.x = v1.x; v.y = v1.y; ContactID c = cv.id; id.indexA = c.indexA; id.indexB = c.indexB; id.typeA = c.typeA; id.typeB = c.typeB; } } /** * This structure is used to keep track of the best separating axis. */ private static class EPAxis { enum Type { UNKNOWN, EDGE_A, EDGE_B } Type type; int index; float separation; } /** * This holds polygon B expressed in frame A. */ private static class TempPolygon { final Vec2[] vertices = new Vec2[JBoxSettings.maxPolygonVertices]; final Vec2[] normals = new Vec2[JBoxSettings.maxPolygonVertices]; int count; TempPolygon() { for (int i = 0; i < vertices.length; i++) { vertices[i] = new Vec2(); normals[i] = new Vec2(); } } } /** * Reference face used for clipping */ private static class ReferenceFace { int i1, i2; final Vec2 v1 = new Vec2(); final Vec2 v2 = new Vec2(); final Vec2 normal = new Vec2(); final Vec2 sideNormal1 = new Vec2(); float sideOffset1; final Vec2 sideNormal2 = new Vec2(); float sideOffset2; } /** * This class collides and edge and a polygon, taking into account edge adjacency. */ private static class EPCollider { final TempPolygon m_polygonB = new TempPolygon(); final Transform m_xf = new Transform(); final Vec2 m_centroidB = new Vec2(); Vec2 m_v0 = new Vec2(); Vec2 m_v1 = new Vec2(); Vec2 m_v2 = new Vec2(); Vec2 m_v3 = new Vec2(); final Vec2 m_normal0 = new Vec2(); final Vec2 m_normal1 = new Vec2(); final Vec2 m_normal2 = new Vec2(); final Vec2 m_normal = new Vec2(); final Vec2 m_lowerLimit = new Vec2(); final Vec2 m_upperLimit = new Vec2(); float m_radius; boolean m_front; EPCollider() { for (int i = 0; i < 2; i++) { ie[i] = new ClipVertex(); clipPoints1[i] = new ClipVertex(); clipPoints2[i] = new ClipVertex(); } } private final Vec2 edge1 = new Vec2(); private final Vec2 temp = new Vec2(); private final Vec2 edge0 = new Vec2(); private final Vec2 edge2 = new Vec2(); private final ClipVertex[] ie = new ClipVertex[2]; private final ClipVertex[] clipPoints1 = new ClipVertex[2]; private final ClipVertex[] clipPoints2 = new ClipVertex[2]; private final ReferenceFace rf = new ReferenceFace(); private final EPAxis edgeAxis = new EPAxis(); private final EPAxis polygonAxis = new EPAxis(); public void collide(Manifold manifold, final EdgeShape edgeA, final Transform xfA, final PolygonShape polygonB, final Transform xfB) { Transform.mulTransToOutUnsafe(xfA, xfB, m_xf); Transform.mulToOutUnsafe(m_xf, polygonB.m_centroid, m_centroidB); m_v0 = edgeA.m_vertex0; m_v1 = edgeA.m_vertex1; m_v2 = edgeA.m_vertex2; m_v3 = edgeA.m_vertex3; boolean hasVertex0 = edgeA.m_hasVertex0; boolean hasVertex3 = edgeA.m_hasVertex3; edge1.set(m_v2).subLocal(m_v1); edge1.getLengthAndNormalize(); m_normal1.set(edge1.y, -edge1.x); float offset1 = Vec2.dot(m_normal1, temp.set(m_centroidB).subLocal(m_v1)); float offset0 = 0.0f, offset2 = 0.0f; boolean convex1 = false, convex2 = false; // Is there a preceding edge? if (hasVertex0) { edge0.set(m_v1).subLocal(m_v0); edge0.getLengthAndNormalize(); m_normal0.set(edge0.y, -edge0.x); convex1 = Vec2.cross(edge0, edge1) >= 0.0f; offset0 = Vec2.dot(m_normal0, temp.set(m_centroidB).subLocal(m_v0)); } // Is there a following edge? if (hasVertex3) { edge2.set(m_v3).subLocal(m_v2); edge2.getLengthAndNormalize(); m_normal2.set(edge2.y, -edge2.x); convex2 = Vec2.cross(edge1, edge2) > 0.0f; offset2 = Vec2.dot(m_normal2, temp.set(m_centroidB).subLocal(m_v2)); } // Determine front or back collision. Determine collision normal limits. if (hasVertex0 && hasVertex3) { if (convex1 && convex2) { m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = m_normal0.x; m_lowerLimit.y = m_normal0.y; m_upperLimit.x = m_normal2.x; m_upperLimit.y = m_normal2.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = -m_normal1.x; m_lowerLimit.y = -m_normal1.y; m_upperLimit.x = -m_normal1.x; m_upperLimit.y = -m_normal1.y; } } else if (convex1) { m_front = offset0 >= 0.0f || offset1 >= 0.0f && offset2 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = m_normal0.x; m_lowerLimit.y = m_normal0.y; m_upperLimit.x = m_normal1.x; m_upperLimit.y = m_normal1.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = -m_normal2.x; m_lowerLimit.y = -m_normal2.y; m_upperLimit.x = -m_normal1.x; m_upperLimit.y = -m_normal1.y; } } else if (convex2) { m_front = offset2 >= 0.0f || offset0 >= 0.0f && offset1 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = m_normal1.x; m_lowerLimit.y = m_normal1.y; m_upperLimit.x = m_normal2.x; m_upperLimit.y = m_normal2.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = -m_normal1.x; m_lowerLimit.y = -m_normal1.y; m_upperLimit.x = -m_normal0.x; m_upperLimit.y = -m_normal0.y; } } else { m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = m_normal1.x; m_lowerLimit.y = m_normal1.y; m_upperLimit.x = m_normal1.x; m_upperLimit.y = m_normal1.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = -m_normal2.x; m_lowerLimit.y = -m_normal2.y; m_upperLimit.x = -m_normal0.x; m_upperLimit.y = -m_normal0.y; } } } else if (hasVertex0) { if (convex1) { m_front = offset0 >= 0.0f || offset1 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = m_normal0.x; m_lowerLimit.y = m_normal0.y; m_upperLimit.x = -m_normal1.x; m_upperLimit.y = -m_normal1.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = m_normal1.x; m_lowerLimit.y = m_normal1.y; m_upperLimit.x = -m_normal1.x; m_upperLimit.y = -m_normal1.y; } } else { m_front = offset0 >= 0.0f && offset1 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = m_normal1.x; m_lowerLimit.y = m_normal1.y; m_upperLimit.x = -m_normal1.x; m_upperLimit.y = -m_normal1.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = m_normal1.x; m_lowerLimit.y = m_normal1.y; m_upperLimit.x = -m_normal0.x; m_upperLimit.y = -m_normal0.y; } } } else if (hasVertex3) { if (convex2) { m_front = offset1 >= 0.0f || offset2 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = -m_normal1.x; m_lowerLimit.y = -m_normal1.y; m_upperLimit.x = m_normal2.x; m_upperLimit.y = m_normal2.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = -m_normal1.x; m_lowerLimit.y = -m_normal1.y; m_upperLimit.x = m_normal1.x; m_upperLimit.y = m_normal1.y; } } else { m_front = offset1 >= 0.0f && offset2 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = -m_normal1.x; m_lowerLimit.y = -m_normal1.y; m_upperLimit.x = m_normal1.x; m_upperLimit.y = m_normal1.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = -m_normal2.x; m_lowerLimit.y = -m_normal2.y; m_upperLimit.x = m_normal1.x; m_upperLimit.y = m_normal1.y; } } } else { m_front = offset1 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = -m_normal1.x; m_lowerLimit.y = -m_normal1.y; m_upperLimit.x = -m_normal1.x; m_upperLimit.y = -m_normal1.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = m_normal1.x; m_lowerLimit.y = m_normal1.y; m_upperLimit.x = m_normal1.x; m_upperLimit.y = m_normal1.y; } } // Get polygonB in frameA m_polygonB.count = polygonB.getVertexCount(); for (int i = 0; i < polygonB.getVertexCount(); ++i) { Transform.mulToOutUnsafe(m_xf, polygonB.m_vertices[i], m_polygonB.vertices[i]); Rotation.mulToOutUnsafe(m_xf.q, polygonB.m_normals[i], m_polygonB.normals[i]); } m_radius = 2.0f * JBoxSettings.polygonRadius; manifold.pointCount = 0; computeEdgeSeparation(edgeAxis); // If no valid normal can be found than this edge should not collide. if (edgeAxis.type == EPAxis.Type.UNKNOWN) { return; } if (edgeAxis.separation > m_radius) { return; } computePolygonSeparation(polygonAxis); if (polygonAxis.type != EPAxis.Type.UNKNOWN && polygonAxis.separation > m_radius) { return; } // Use hysteresis for jitter reduction. final float k_relativeTol = 0.98f; final float k_absoluteTol = 0.001f; EPAxis primaryAxis; if (polygonAxis.type == EPAxis.Type.UNKNOWN) { primaryAxis = edgeAxis; } else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) { primaryAxis = polygonAxis; } else { primaryAxis = edgeAxis; } final ClipVertex ie0 = ie[0]; final ClipVertex ie1 = ie[1]; if (primaryAxis.type == EPAxis.Type.EDGE_A) { manifold.type = Manifold.ManifoldType.FACE_A; // Search for the polygon normal that is most anti-parallel to the edge normal. int bestIndex = 0; float bestValue = Vec2.dot(m_normal, m_polygonB.normals[0]); for (int i = 1; i < m_polygonB.count; ++i) { float value = Vec2.dot(m_normal, m_polygonB.normals[i]); if (value < bestValue) { bestValue = value; bestIndex = i; } } int i1 = bestIndex; int i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0; ie0.v.set(m_polygonB.vertices[i1]); ie0.id.indexA = 0; ie0.id.indexB = (byte) i1; ie0.id.typeA = (byte) ContactID.Type.FACE.ordinal(); ie0.id.typeB = (byte) ContactID.Type.VERTEX.ordinal(); ie1.v.set(m_polygonB.vertices[i2]); ie1.id.indexA = 0; ie1.id.indexB = (byte) i2; ie1.id.typeA = (byte) ContactID.Type.FACE.ordinal(); ie1.id.typeB = (byte) ContactID.Type.VERTEX.ordinal(); if (m_front) { rf.i1 = 0; rf.i2 = 1; rf.v1.set(m_v1); rf.v2.set(m_v2); rf.normal.set(m_normal1); } else { rf.i1 = 1; rf.i2 = 0; rf.v1.set(m_v2); rf.v2.set(m_v1); rf.normal.set(m_normal1).negateLocal(); } } else { manifold.type = Manifold.ManifoldType.FACE_B; ie0.v.set(m_v1); ie0.id.indexA = 0; ie0.id.indexB = (byte) primaryAxis.index; ie0.id.typeA = (byte) ContactID.Type.VERTEX.ordinal(); ie0.id.typeB = (byte) ContactID.Type.FACE.ordinal(); ie1.v.set(m_v2); ie1.id.indexA = 0; ie1.id.indexB = (byte) primaryAxis.index; ie1.id.typeA = (byte) ContactID.Type.VERTEX.ordinal(); ie1.id.typeB = (byte) ContactID.Type.FACE.ordinal(); rf.i1 = primaryAxis.index; rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0; rf.v1.set(m_polygonB.vertices[rf.i1]); rf.v2.set(m_polygonB.vertices[rf.i2]); rf.normal.set(m_polygonB.normals[rf.i1]); } rf.sideNormal1.set(rf.normal.y, -rf.normal.x); rf.sideNormal2.set(rf.sideNormal1).negateLocal(); rf.sideOffset1 = Vec2.dot(rf.sideNormal1, rf.v1); rf.sideOffset2 = Vec2.dot(rf.sideNormal2, rf.v2); // Clip incident edge against extruded edge1 side edges. int np; // Clip to box side 1 np = clipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); if (np < JBoxSettings.maxManifoldPoints) { return; } // Clip to negative box side 1 np = clipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); if (np < JBoxSettings.maxManifoldPoints) { return; } // Now clipPoints2 contains the clipped points. if (primaryAxis.type == EPAxis.Type.EDGE_A) { manifold.localNormal.set(rf.normal); manifold.localPoint.set(rf.v1); } else { manifold.localNormal.set(polygonB.m_normals[rf.i1]); manifold.localPoint.set(polygonB.m_vertices[rf.i1]); } int pointCount = 0; for (int i = 0; i < JBoxSettings.maxManifoldPoints; ++i) { float separation; separation = Vec2.dot(rf.normal, temp.set(clipPoints2[i].v).subLocal(rf.v1)); if (separation <= m_radius) { ManifoldPoint cp = manifold.points[pointCount]; if (primaryAxis.type == EPAxis.Type.EDGE_A) { // cp.localPoint = MulT(m_xf, clipPoints2[i].v); Transform.mulTransToOutUnsafe(m_xf, clipPoints2[i].v, cp.localPoint); cp.id.set(clipPoints2[i].id); } else { cp.localPoint.set(clipPoints2[i].v); cp.id.typeA = clipPoints2[i].id.typeB; cp.id.typeB = clipPoints2[i].id.typeA; cp.id.indexA = clipPoints2[i].id.indexB; cp.id.indexB = clipPoints2[i].id.indexA; } ++pointCount; } } manifold.pointCount = pointCount; } public void computeEdgeSeparation(EPAxis axis) { axis.type = EPAxis.Type.EDGE_A; axis.index = m_front ? 0 : 1; axis.separation = Float.MAX_VALUE; float nx = m_normal.x; float ny = m_normal.y; for (int i = 0; i < m_polygonB.count; ++i) { Vec2 v = m_polygonB.vertices[i]; float tempx = v.x - m_v1.x; float tempy = v.y - m_v1.y; float s = nx * tempx + ny * tempy; if (s < axis.separation) { axis.separation = s; } } } private final Vec2 perp = new Vec2(); private final Vec2 n = new Vec2(); public void computePolygonSeparation(EPAxis axis) { axis.type = EPAxis.Type.UNKNOWN; axis.index = -1; axis.separation = -Float.MAX_VALUE; perp.x = -m_normal.y; perp.y = m_normal.x; for (int i = 0; i < m_polygonB.count; ++i) { Vec2 normalB = m_polygonB.normals[i]; Vec2 vB = m_polygonB.vertices[i]; n.x = -normalB.x; n.y = -normalB.y; // float s1 = Vec2.dot(n, temp.set(vB).subLocal(m_v1)); // float s2 = Vec2.dot(n, temp.set(vB).subLocal(m_v2)); float tempx = vB.x - m_v1.x; float tempy = vB.y - m_v1.y; float s1 = n.x * tempx + n.y * tempy; tempx = vB.x - m_v2.x; tempy = vB.y - m_v2.y; float s2 = n.x * tempx + n.y * tempy; float s = Math.min(s1, s2); if (s > m_radius) { // No collision axis.type = EPAxis.Type.EDGE_B; axis.index = i; axis.separation = s; return; } // Adjacency if (n.x * perp.x + n.y * perp.y >= 0.0f) { if (Vec2.dot(temp.set(n).subLocal(m_upperLimit), m_normal) < -JBoxSettings.angularSlop) { continue; } } else { if (Vec2.dot(temp.set(n).subLocal(m_lowerLimit), m_normal) < -JBoxSettings.angularSlop) { continue; } } if (s > axis.separation) { axis.type = EPAxis.Type.EDGE_B; axis.index = i; axis.separation = s; } } } } }
fxgl-entity/src/main/java/com/almasb/fxgl/physics/box2d/collision/Collision.java
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.physics.box2d.collision; import com.almasb.fxgl.core.math.Vec2; import com.almasb.fxgl.physics.box2d.collision.Distance.SimplexCache; import com.almasb.fxgl.physics.box2d.collision.Manifold.ManifoldType; import com.almasb.fxgl.physics.box2d.collision.shapes.CircleShape; import com.almasb.fxgl.physics.box2d.collision.shapes.EdgeShape; import com.almasb.fxgl.physics.box2d.collision.shapes.PolygonShape; import com.almasb.fxgl.physics.box2d.collision.shapes.Shape; import com.almasb.fxgl.physics.box2d.common.JBoxSettings; import com.almasb.fxgl.physics.box2d.common.Rotation; import com.almasb.fxgl.physics.box2d.common.Transform; import com.almasb.fxgl.physics.box2d.pooling.IWorldPool; /** * Functions used for computing contact points, distance queries, and TOI queries. * Collision methods are non-static for pooling speed, retrieve a collision object from the {@link IWorldPool}. * Should not be constructed. * * @author Daniel Murphy */ public final class Collision { private final IWorldPool pool; public Collision(IWorldPool pool) { incidentEdge[0] = new ClipVertex(); incidentEdge[1] = new ClipVertex(); clipPoints1[0] = new ClipVertex(); clipPoints1[1] = new ClipVertex(); clipPoints2[0] = new ClipVertex(); clipPoints2[1] = new ClipVertex(); this.pool = pool; } private final DistanceInput input = new DistanceInput(); private final SimplexCache cache = new SimplexCache(); private final DistanceOutput output = new DistanceOutput(); /** * Determine if two generic shapes overlap. */ public boolean testOverlap(Shape shapeA, int indexA, Shape shapeB, int indexB, Transform xfA, Transform xfB) { input.proxyA.set(shapeA, indexA); input.proxyB.set(shapeB, indexB); input.transformA.set(xfA); input.transformB.set(xfB); input.useRadii = true; cache.count = 0; pool.getDistance().distance(output, cache, input); // djm note: anything significant about 10.0f? return output.distance < 10.0f * JBoxSettings.EPSILON; } /** * Clipping for contact manifolds. * Sutherland-Hodgman clipping. */ public static int clipSegmentToLine(ClipVertex[] vOut, ClipVertex[] vIn, Vec2 normal, float offset, int vertexIndexA) { // Start with no output points int numOut = 0; final ClipVertex vIn0 = vIn[0]; final ClipVertex vIn1 = vIn[1]; final Vec2 vIn0v = vIn0.v; final Vec2 vIn1v = vIn1.v; // Calculate the distance of end points to the line float distance0 = Vec2.dot(normal, vIn0v) - offset; float distance1 = Vec2.dot(normal, vIn1v) - offset; // If the points are behind the plane if (distance0 <= 0.0f) { vOut[numOut++].set(vIn0); } if (distance1 <= 0.0f) { vOut[numOut++].set(vIn1); } // If the points are on different sides of the plane if (distance0 * distance1 < 0.0f) { // Find intersection point of edge and plane float interp = distance0 / (distance0 - distance1); ClipVertex vOutNO = vOut[numOut]; // vOut[numOut].v = vIn[0].v + interp * (vIn[1].v - vIn[0].v); vOutNO.v.x = vIn0v.x + interp * (vIn1v.x - vIn0v.x); vOutNO.v.y = vIn0v.y + interp * (vIn1v.y - vIn0v.y); // VertexA is hitting edgeB. vOutNO.id.indexA = (byte) vertexIndexA; vOutNO.id.indexB = vIn0.id.indexB; vOutNO.id.typeA = (byte) ContactID.Type.VERTEX.ordinal(); vOutNO.id.typeB = (byte) ContactID.Type.FACE.ordinal(); ++numOut; } return numOut; } // #### COLLISION STUFF (not from collision.h or collision.cpp) #### // djm pooling private static Vec2 d = new Vec2(); /** * Compute the collision manifold between two circles. */ @SuppressWarnings("PMD.UselessParentheses") public void collideCircles(Manifold manifold, CircleShape circle1, Transform xfA, CircleShape circle2, Transform xfB) { manifold.pointCount = 0; // before inline: // Transform.mulToOut(xfA, circle1.m_p, pA); // Transform.mulToOut(xfB, circle2.m_p, pB); // d.set(pB).subLocal(pA); // float distSqr = d.x * d.x + d.y * d.y; // after inline: Vec2 circle1p = circle1.center; Vec2 circle2p = circle2.center; float pAx = (xfA.q.c * circle1p.x - xfA.q.s * circle1p.y) + xfA.p.x; float pAy = (xfA.q.s * circle1p.x + xfA.q.c * circle1p.y) + xfA.p.y; float pBx = (xfB.q.c * circle2p.x - xfB.q.s * circle2p.y) + xfB.p.x; float pBy = (xfB.q.s * circle2p.x + xfB.q.c * circle2p.y) + xfB.p.y; float dx = pBx - pAx; float dy = pBy - pAy; float distSqr = dx * dx + dy * dy; // end inline final float radius = circle1.getRadius() + circle2.getRadius(); if (distSqr > radius * radius) { return; } manifold.type = ManifoldType.CIRCLES; manifold.localPoint.set(circle1p); manifold.localNormal.setZero(); manifold.pointCount = 1; manifold.points[0].localPoint.set(circle2p); manifold.points[0].id.zero(); } /** * Compute the collision manifold between a polygon and a circle. * * @param manifold * @param polygon * @param xfA * @param circle * @param xfB */ @SuppressWarnings("PMD.UselessParentheses") public void collidePolygonAndCircle(Manifold manifold, final PolygonShape polygon, final Transform xfA, final CircleShape circle, final Transform xfB) { manifold.pointCount = 0; // Vec2 v = circle.m_p; // Compute circle position in the frame of the polygon. // before inline: // Transform.mulToOutUnsafe(xfB, circle.m_p, c); // Transform.mulTransToOut(xfA, c, cLocal); // final float cLocalx = cLocal.x; // final float cLocaly = cLocal.y; // after inline: final Vec2 circlep = circle.center; final Rotation xfBq = xfB.q; final Rotation xfAq = xfA.q; final float cx = (xfBq.c * circlep.x - xfBq.s * circlep.y) + xfB.p.x; final float cy = (xfBq.s * circlep.x + xfBq.c * circlep.y) + xfB.p.y; final float px = cx - xfA.p.x; final float py = cy - xfA.p.y; final float cLocalx = (xfAq.c * px + xfAq.s * py); final float cLocaly = (-xfAq.s * px + xfAq.c * py); // end inline // Find the min separating edge. int normalIndex = 0; float separation = -Float.MAX_VALUE; final float radius = polygon.getRadius() + circle.getRadius(); final int vertexCount = polygon.getVertexCount(); float s; final Vec2[] vertices = polygon.m_vertices; final Vec2[] normals = polygon.m_normals; for (int i = 0; i < vertexCount; i++) { // before inline // temp.set(cLocal).subLocal(vertices[i]); // float s = Vec2.dot(normals[i], temp); // after inline final Vec2 vertex = vertices[i]; final float tempx = cLocalx - vertex.x; final float tempy = cLocaly - vertex.y; s = normals[i].x * tempx + normals[i].y * tempy; if (s > radius) { // early out return; } if (s > separation) { separation = s; normalIndex = i; } } // Vertices that subtend the incident face. final int vertIndex1 = normalIndex; final int vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; final Vec2 v1 = vertices[vertIndex1]; final Vec2 v2 = vertices[vertIndex2]; // If the center is inside the polygon ... if (separation < JBoxSettings.EPSILON) { manifold.pointCount = 1; manifold.type = ManifoldType.FACE_A; // before inline: // manifold.localNormal.set(normals[normalIndex]); // manifold.localPoint.set(v1).addLocal(v2).mulLocal(.5f); // manifold.points[0].localPoint.set(circle.m_p); // after inline: final Vec2 normal = normals[normalIndex]; manifold.localNormal.x = normal.x; manifold.localNormal.y = normal.y; manifold.localPoint.x = (v1.x + v2.x) * .5f; manifold.localPoint.y = (v1.y + v2.y) * .5f; final ManifoldPoint mpoint = manifold.points[0]; mpoint.localPoint.x = circlep.x; mpoint.localPoint.y = circlep.y; mpoint.id.zero(); // end inline return; } // Compute barycentric coordinates // before inline: // temp.set(cLocal).subLocal(v1); // temp2.set(v2).subLocal(v1); // float u1 = Vec2.dot(temp, temp2); // temp.set(cLocal).subLocal(v2); // temp2.set(v1).subLocal(v2); // float u2 = Vec2.dot(temp, temp2); // after inline: final float tempX = cLocalx - v1.x; final float tempY = cLocaly - v1.y; final float temp2X = v2.x - v1.x; final float temp2Y = v2.y - v1.y; final float u1 = tempX * temp2X + tempY * temp2Y; final float temp3X = cLocalx - v2.x; final float temp3Y = cLocaly - v2.y; final float temp4X = v1.x - v2.x; final float temp4Y = v1.y - v2.y; final float u2 = temp3X * temp4X + temp3Y * temp4Y; // end inline if (u1 <= 0f) { // inlined final float dx = cLocalx - v1.x; final float dy = cLocaly - v1.y; if (dx * dx + dy * dy > radius * radius) { return; } manifold.pointCount = 1; manifold.type = ManifoldType.FACE_A; // before inline: // manifold.localNormal.set(cLocal).subLocal(v1); // after inline: manifold.localNormal.x = cLocalx - v1.x; manifold.localNormal.y = cLocaly - v1.y; // end inline manifold.localNormal.getLengthAndNormalize(); manifold.localPoint.set(v1); manifold.points[0].localPoint.set(circlep); manifold.points[0].id.zero(); } else if (u2 <= 0.0f) { // inlined final float dx = cLocalx - v2.x; final float dy = cLocaly - v2.y; if (dx * dx + dy * dy > radius * radius) { return; } manifold.pointCount = 1; manifold.type = ManifoldType.FACE_A; // before inline: // manifold.localNormal.set(cLocal).subLocal(v2); // after inline: manifold.localNormal.x = cLocalx - v2.x; manifold.localNormal.y = cLocaly - v2.y; // end inline manifold.localNormal.getLengthAndNormalize(); manifold.localPoint.set(v2); manifold.points[0].localPoint.set(circlep); manifold.points[0].id.zero(); } else { // Vec2 faceCenter = 0.5f * (v1 + v2); // (temp is faceCenter) // before inline: // temp.set(v1).addLocal(v2).mulLocal(.5f); // // temp2.set(cLocal).subLocal(temp); // separation = Vec2.dot(temp2, normals[vertIndex1]); // if (separation > radius) { // return; // } // after inline: final float fcx = (v1.x + v2.x) * .5f; final float fcy = (v1.y + v2.y) * .5f; final float tx = cLocalx - fcx; final float ty = cLocaly - fcy; final Vec2 normal = normals[vertIndex1]; separation = tx * normal.x + ty * normal.y; if (separation > radius) { return; } // end inline manifold.pointCount = 1; manifold.type = ManifoldType.FACE_A; manifold.localNormal.set(normals[vertIndex1]); manifold.localPoint.x = fcx; // (faceCenter) manifold.localPoint.y = fcy; manifold.points[0].localPoint.set(circlep); manifold.points[0].id.zero(); } } // djm pooling, and from above private final Vec2 temp = new Vec2(); @SuppressWarnings("PMD.UselessParentheses") public void findIncidentEdge(final ClipVertex[] c, final PolygonShape poly1, final Transform xf1, int edge1, final PolygonShape poly2, final Transform xf2) { int count1 = poly1.getVertexCount(); final Vec2[] normals1 = poly1.m_normals; int count2 = poly2.getVertexCount(); final Vec2[] vertices2 = poly2.m_vertices; final Vec2[] normals2 = poly2.m_normals; assert 0 <= edge1 && edge1 < count1; final ClipVertex c0 = c[0]; final ClipVertex c1 = c[1]; final Rotation xf1q = xf1.q; final Rotation xf2q = xf2.q; // Get the normal of the reference edge in poly2's frame. // Vec2 normal1 = MulT(xf2.R, Mul(xf1.R, normals1[edge1])); // before inline: // Rot.mulToOutUnsafe(xf1.q, normals1[edge1], normal1); // temporary // Rot.mulTrans(xf2.q, normal1, normal1); // after inline: final Vec2 v = normals1[edge1]; final float tempx = xf1q.c * v.x - xf1q.s * v.y; final float tempy = xf1q.s * v.x + xf1q.c * v.y; final float normal1x = xf2q.c * tempx + xf2q.s * tempy; final float normal1y = -xf2q.s * tempx + xf2q.c * tempy; // end inline // Find the incident edge on poly2. int index = 0; float minDot = Float.MAX_VALUE; for (int i = 0; i < count2; ++i) { Vec2 b = normals2[i]; float dot = normal1x * b.x + normal1y * b.y; if (dot < minDot) { minDot = dot; index = i; } } // Build the clip vertices for the incident edge. int i1 = index; int i2 = i1 + 1 < count2 ? i1 + 1 : 0; // c0.v = Mul(xf2, vertices2[i1]); Vec2 v1 = vertices2[i1]; Vec2 out = c0.v; out.x = (xf2q.c * v1.x - xf2q.s * v1.y) + xf2.p.x; out.y = (xf2q.s * v1.x + xf2q.c * v1.y) + xf2.p.y; c0.id.indexA = (byte) edge1; c0.id.indexB = (byte) i1; c0.id.typeA = (byte) ContactID.Type.FACE.ordinal(); c0.id.typeB = (byte) ContactID.Type.VERTEX.ordinal(); // c1.v = Mul(xf2, vertices2[i2]); Vec2 v2 = vertices2[i2]; Vec2 out1 = c1.v; out1.x = (xf2q.c * v2.x - xf2q.s * v2.y) + xf2.p.x; out1.y = (xf2q.s * v2.x + xf2q.c * v2.y) + xf2.p.y; c1.id.indexA = (byte) edge1; c1.id.indexB = (byte) i2; c1.id.typeA = (byte) ContactID.Type.FACE.ordinal(); c1.id.typeB = (byte) ContactID.Type.VERTEX.ordinal(); } private final EdgeResults results1 = new EdgeResults(); private final EdgeResults results2 = new EdgeResults(); private final ClipVertex[] incidentEdge = new ClipVertex[2]; private final Vec2 localTangent = new Vec2(); private final Vec2 localNormal = new Vec2(); private final Vec2 planePoint = new Vec2(); private final Vec2 tangent = new Vec2(); private final Vec2 v11 = new Vec2(); private final Vec2 v12 = new Vec2(); private final ClipVertex[] clipPoints1 = new ClipVertex[2]; private final ClipVertex[] clipPoints2 = new ClipVertex[2]; /** * Compute the collision manifold between two polygons. */ @SuppressWarnings("PMD.UselessParentheses") public void collidePolygons(Manifold manifold, final PolygonShape polyA, final Transform xfA, final PolygonShape polyB, final Transform xfB) { // Find edge normal of max separation on A - return if separating axis is found // Find edge normal of max separation on B - return if separation axis is found // Choose reference edge as min(minA, minB) // Find incident edge // Clip // The normal points from 1 to 2 manifold.pointCount = 0; float totalRadius = polyA.getRadius() + polyB.getRadius(); findMaxSeparation(results1, polyA, xfA, polyB, xfB); if (results1.separation > totalRadius) { return; } findMaxSeparation(results2, polyB, xfB, polyA, xfA); if (results2.separation > totalRadius) { return; } final PolygonShape poly1; // reference polygon final PolygonShape poly2; // incident polygon Transform xf1, xf2; int edge1; // reference edge boolean flip; final float k_tol = 0.1f * JBoxSettings.linearSlop; if (results2.separation > results1.separation + k_tol) { poly1 = polyB; poly2 = polyA; xf1 = xfB; xf2 = xfA; edge1 = results2.edgeIndex; manifold.type = ManifoldType.FACE_B; flip = true; } else { poly1 = polyA; poly2 = polyB; xf1 = xfA; xf2 = xfB; edge1 = results1.edgeIndex; manifold.type = ManifoldType.FACE_A; flip = false; } final Rotation xf1q = xf1.q; findIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); int count1 = poly1.getVertexCount(); final Vec2[] vertices1 = poly1.m_vertices; final int iv1 = edge1; final int iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0; v11.set(vertices1[iv1]); v12.set(vertices1[iv2]); localTangent.x = v12.x - v11.x; localTangent.y = v12.y - v11.y; localTangent.getLengthAndNormalize(); // Vec2 localNormal = Vec2.cross(dv, 1.0f); localNormal.x = 1f * localTangent.y; localNormal.y = -1f * localTangent.x; // Vec2 planePoint = 0.5f * (v11+ v12); planePoint.x = (v11.x + v12.x) * .5f; planePoint.y = (v11.y + v12.y) * .5f; // Rot.mulToOutUnsafe(xf1.q, localTangent, tangent); tangent.x = xf1q.c * localTangent.x - xf1q.s * localTangent.y; tangent.y = xf1q.s * localTangent.x + xf1q.c * localTangent.y; // Vec2.crossToOutUnsafe(tangent, 1f, normal); final float normalx = 1f * tangent.y; final float normaly = -1f * tangent.x; Transform.mulToOut(xf1, v11, v11); Transform.mulToOut(xf1, v12, v12); // v11 = Mul(xf1, v11); // v12 = Mul(xf1, v12); // Face offset // float frontOffset = Vec2.dot(normal, v11); float frontOffset = normalx * v11.x + normaly * v11.y; // Side offsets, extended by polytope skin thickness. // float sideOffset1 = -Vec2.dot(tangent, v11) + totalRadius; // float sideOffset2 = Vec2.dot(tangent, v12) + totalRadius; float sideOffset1 = -(tangent.x * v11.x + tangent.y * v11.y) + totalRadius; float sideOffset2 = tangent.x * v12.x + tangent.y * v12.y + totalRadius; // Clip incident edge against extruded edge1 side edges. // ClipVertex clipPoints1[2]; // ClipVertex clipPoints2[2]; int np; // Clip to box side 1 // np = ClipSegmentToLine(clipPoints1, incidentEdge, -sideNormal, sideOffset1); tangent.negateLocal(); np = clipSegmentToLine(clipPoints1, incidentEdge, tangent, sideOffset1, iv1); tangent.negateLocal(); if (np < 2) { return; } // Clip to negative box side 1 np = clipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); if (np < 2) { return; } // Now clipPoints2 contains the clipped points. manifold.localNormal.set(localNormal); manifold.localPoint.set(planePoint); int pointCount = 0; for (int i = 0; i < JBoxSettings.maxManifoldPoints; ++i) { // float separation = Vec2.dot(normal, clipPoints2[i].v) - frontOffset; float separation = normalx * clipPoints2[i].v.x + normaly * clipPoints2[i].v.y - frontOffset; if (separation <= totalRadius) { ManifoldPoint cp = manifold.points[pointCount]; // cp.m_localPoint = MulT(xf2, clipPoints2[i].v); Vec2 out = cp.localPoint; final float px = clipPoints2[i].v.x - xf2.p.x; final float py = clipPoints2[i].v.y - xf2.p.y; out.x = (xf2.q.c * px + xf2.q.s * py); out.y = (-xf2.q.s * px + xf2.q.c * py); cp.id.set(clipPoints2[i].id); if (flip) { // Swap features cp.id.flip(); } ++pointCount; } } manifold.pointCount = pointCount; } private final Transform xf = new Transform(); private final Vec2 n = new Vec2(); private final Vec2 v1 = new Vec2(); /** * Find the max separation between poly1 and poly2 using edge normals from poly1. */ public void findMaxSeparation(EdgeResults results, PolygonShape poly1, Transform xf1, PolygonShape poly2, Transform xf2) { int count1 = poly1.getVertexCount(); int count2 = poly2.getVertexCount(); Vec2[] n1s = poly1.m_normals; Vec2[] v1s = poly1.m_vertices; Vec2[] v2s = poly2.m_vertices; Transform.mulTransToOutUnsafe(xf2, xf1, xf); final Rotation xfq = xf.q; int bestIndex = 0; float maxSeparation = -Float.MAX_VALUE; for (int i = 0; i < count1; i++) { // Get poly1 normal in frame2. Rotation.mulToOutUnsafe(xfq, n1s[i], n); Transform.mulToOutUnsafe(xf, v1s[i], v1); // Find deepest point for normal i. float si = Float.MAX_VALUE; for (int j = 0; j < count2; ++j) { Vec2 v2sj = v2s[j]; float sij = n.x * (v2sj.x - v1.x) + n.y * (v2sj.y - v1.y); if (sij < si) { si = sij; } } if (si > maxSeparation) { maxSeparation = si; bestIndex = i; } } results.edgeIndex = bestIndex; results.separation = maxSeparation; } private final Vec2 Q = new Vec2(); private final Vec2 e = new Vec2(); private final ContactID cf = new ContactID(); private final Vec2 e1 = new Vec2(); private final Vec2 P = new Vec2(); // Compute contact points for edge versus circle. // This accounts for edge connectivity. public void collideEdgeAndCircle(Manifold manifold, final EdgeShape edgeA, final Transform xfA, final CircleShape circleB, final Transform xfB) { manifold.pointCount = 0; // Compute circle in frame of edge // Vec2 Q = MulT(xfA, Mul(xfB, circleB.m_p)); Transform.mulToOutUnsafe(xfB, circleB.center, temp); Transform.mulTransToOutUnsafe(xfA, temp, Q); final Vec2 A = edgeA.m_vertex1; final Vec2 B = edgeA.m_vertex2; e.set(B).subLocal(A); // Barycentric coordinates float u = Vec2.dot(e, temp.set(B).subLocal(Q)); float v = Vec2.dot(e, temp.set(Q).subLocal(A)); float radius = edgeA.getRadius() + circleB.getRadius(); // ContactFeature cf; cf.indexB = 0; cf.typeB = (byte) ContactID.Type.VERTEX.ordinal(); // Region A if (v <= 0.0f) { final Vec2 P = A; d.set(Q).subLocal(P); float dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } // Is there an edge connected to A? if (edgeA.m_hasVertex0) { final Vec2 A1 = edgeA.m_vertex0; final Vec2 B1 = A; e1.set(B1).subLocal(A1); float u1 = Vec2.dot(e1, temp.set(B1).subLocal(Q)); // Is the circle in Region AB of the previous edge? if (u1 > 0.0f) { return; } } cf.indexA = 0; cf.typeA = (byte) ContactID.Type.VERTEX.ordinal(); manifold.pointCount = 1; manifold.type = Manifold.ManifoldType.CIRCLES; manifold.localNormal.setZero(); manifold.localPoint.set(P); // manifold.points[0].id.key = 0; manifold.points[0].id.set(cf); manifold.points[0].localPoint.set(circleB.center); return; } // Region B if (u <= 0.0f) { Vec2 P = B; d.set(Q).subLocal(P); float dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } // Is there an edge connected to B? if (edgeA.m_hasVertex3) { final Vec2 B2 = edgeA.m_vertex3; final Vec2 A2 = B; final Vec2 e2 = e1; e2.set(B2).subLocal(A2); float v2 = Vec2.dot(e2, temp.set(Q).subLocal(A2)); // Is the circle in Region AB of the next edge? if (v2 > 0.0f) { return; } } cf.indexA = 1; cf.typeA = (byte) ContactID.Type.VERTEX.ordinal(); manifold.pointCount = 1; manifold.type = Manifold.ManifoldType.CIRCLES; manifold.localNormal.setZero(); manifold.localPoint.set(P); // manifold.points[0].id.key = 0; manifold.points[0].id.set(cf); manifold.points[0].localPoint.set(circleB.center); return; } // Region AB float den = Vec2.dot(e, e); assert den > 0.0f; // Vec2 P = (1.0f / den) * (u * A + v * B); P.set(A).mulLocal(u).addLocal(temp.set(B).mulLocal(v)); P.mulLocal(1.0f / den); d.set(Q).subLocal(P); float dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } n.x = -e.y; n.y = e.x; if (Vec2.dot(n, temp.set(Q).subLocal(A)) < 0.0f) { n.set(-n.x, -n.y); } n.getLengthAndNormalize(); cf.indexA = 0; cf.typeA = (byte) ContactID.Type.FACE.ordinal(); manifold.pointCount = 1; manifold.type = Manifold.ManifoldType.FACE_A; manifold.localNormal.set(n); manifold.localPoint.set(A); // manifold.points[0].id.key = 0; manifold.points[0].id.set(cf); manifold.points[0].localPoint.set(circleB.center); } private final EPCollider collider = new EPCollider(); public void collideEdgeAndPolygon(Manifold manifold, final EdgeShape edgeA, final Transform xfA, final PolygonShape polygonB, final Transform xfB) { collider.collide(manifold, edgeA, xfA, polygonB, xfB); } /** * Java-specific class for returning edge results */ private static class EdgeResults { float separation; int edgeIndex; } /** * Used for computing contact manifolds. */ private static class ClipVertex { public final Vec2 v; public final ContactID id; public ClipVertex() { v = new Vec2(); id = new ContactID(); } public void set(final ClipVertex cv) { Vec2 v1 = cv.v; v.x = v1.x; v.y = v1.y; ContactID c = cv.id; id.indexA = c.indexA; id.indexB = c.indexB; id.typeA = c.typeA; id.typeB = c.typeB; } } /** * This structure is used to keep track of the best separating axis. */ private static class EPAxis { enum Type { UNKNOWN, EDGE_A, EDGE_B } Type type; int index; float separation; } /** * This holds polygon B expressed in frame A. */ private static class TempPolygon { final Vec2[] vertices = new Vec2[JBoxSettings.maxPolygonVertices]; final Vec2[] normals = new Vec2[JBoxSettings.maxPolygonVertices]; int count; TempPolygon() { for (int i = 0; i < vertices.length; i++) { vertices[i] = new Vec2(); normals[i] = new Vec2(); } } } /** * Reference face used for clipping */ private static class ReferenceFace { int i1, i2; final Vec2 v1 = new Vec2(); final Vec2 v2 = new Vec2(); final Vec2 normal = new Vec2(); final Vec2 sideNormal1 = new Vec2(); float sideOffset1; final Vec2 sideNormal2 = new Vec2(); float sideOffset2; } /** * This class collides and edge and a polygon, taking into account edge adjacency. */ private static class EPCollider { final TempPolygon m_polygonB = new TempPolygon(); final Transform m_xf = new Transform(); final Vec2 m_centroidB = new Vec2(); Vec2 m_v0 = new Vec2(); Vec2 m_v1 = new Vec2(); Vec2 m_v2 = new Vec2(); Vec2 m_v3 = new Vec2(); final Vec2 m_normal0 = new Vec2(); final Vec2 m_normal1 = new Vec2(); final Vec2 m_normal2 = new Vec2(); final Vec2 m_normal = new Vec2(); final Vec2 m_lowerLimit = new Vec2(); final Vec2 m_upperLimit = new Vec2(); float m_radius; boolean m_front; EPCollider() { for (int i = 0; i < 2; i++) { ie[i] = new ClipVertex(); clipPoints1[i] = new ClipVertex(); clipPoints2[i] = new ClipVertex(); } } private final Vec2 edge1 = new Vec2(); private final Vec2 temp = new Vec2(); private final Vec2 edge0 = new Vec2(); private final Vec2 edge2 = new Vec2(); private final ClipVertex[] ie = new ClipVertex[2]; private final ClipVertex[] clipPoints1 = new ClipVertex[2]; private final ClipVertex[] clipPoints2 = new ClipVertex[2]; private final ReferenceFace rf = new ReferenceFace(); private final EPAxis edgeAxis = new EPAxis(); private final EPAxis polygonAxis = new EPAxis(); public void collide(Manifold manifold, final EdgeShape edgeA, final Transform xfA, final PolygonShape polygonB, final Transform xfB) { Transform.mulTransToOutUnsafe(xfA, xfB, m_xf); Transform.mulToOutUnsafe(m_xf, polygonB.m_centroid, m_centroidB); m_v0 = edgeA.m_vertex0; m_v1 = edgeA.m_vertex1; m_v2 = edgeA.m_vertex2; m_v3 = edgeA.m_vertex3; boolean hasVertex0 = edgeA.m_hasVertex0; boolean hasVertex3 = edgeA.m_hasVertex3; edge1.set(m_v2).subLocal(m_v1); edge1.getLengthAndNormalize(); m_normal1.set(edge1.y, -edge1.x); float offset1 = Vec2.dot(m_normal1, temp.set(m_centroidB).subLocal(m_v1)); float offset0 = 0.0f, offset2 = 0.0f; boolean convex1 = false, convex2 = false; // Is there a preceding edge? if (hasVertex0) { edge0.set(m_v1).subLocal(m_v0); edge0.getLengthAndNormalize(); m_normal0.set(edge0.y, -edge0.x); convex1 = Vec2.cross(edge0, edge1) >= 0.0f; offset0 = Vec2.dot(m_normal0, temp.set(m_centroidB).subLocal(m_v0)); } // Is there a following edge? if (hasVertex3) { edge2.set(m_v3).subLocal(m_v2); edge2.getLengthAndNormalize(); m_normal2.set(edge2.y, -edge2.x); convex2 = Vec2.cross(edge1, edge2) > 0.0f; offset2 = Vec2.dot(m_normal2, temp.set(m_centroidB).subLocal(m_v2)); } // Determine front or back collision. Determine collision normal limits. if (hasVertex0 && hasVertex3) { if (convex1 && convex2) { m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = m_normal0.x; m_lowerLimit.y = m_normal0.y; m_upperLimit.x = m_normal2.x; m_upperLimit.y = m_normal2.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = -m_normal1.x; m_lowerLimit.y = -m_normal1.y; m_upperLimit.x = -m_normal1.x; m_upperLimit.y = -m_normal1.y; } } else if (convex1) { m_front = offset0 >= 0.0f || offset1 >= 0.0f && offset2 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = m_normal0.x; m_lowerLimit.y = m_normal0.y; m_upperLimit.x = m_normal1.x; m_upperLimit.y = m_normal1.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = -m_normal2.x; m_lowerLimit.y = -m_normal2.y; m_upperLimit.x = -m_normal1.x; m_upperLimit.y = -m_normal1.y; } } else if (convex2) { m_front = offset2 >= 0.0f || offset0 >= 0.0f && offset1 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = m_normal1.x; m_lowerLimit.y = m_normal1.y; m_upperLimit.x = m_normal2.x; m_upperLimit.y = m_normal2.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = -m_normal1.x; m_lowerLimit.y = -m_normal1.y; m_upperLimit.x = -m_normal0.x; m_upperLimit.y = -m_normal0.y; } } else { m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = m_normal1.x; m_lowerLimit.y = m_normal1.y; m_upperLimit.x = m_normal1.x; m_upperLimit.y = m_normal1.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = -m_normal2.x; m_lowerLimit.y = -m_normal2.y; m_upperLimit.x = -m_normal0.x; m_upperLimit.y = -m_normal0.y; } } } else if (hasVertex0) { if (convex1) { m_front = offset0 >= 0.0f || offset1 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = m_normal0.x; m_lowerLimit.y = m_normal0.y; m_upperLimit.x = -m_normal1.x; m_upperLimit.y = -m_normal1.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = m_normal1.x; m_lowerLimit.y = m_normal1.y; m_upperLimit.x = -m_normal1.x; m_upperLimit.y = -m_normal1.y; } } else { m_front = offset0 >= 0.0f && offset1 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = m_normal1.x; m_lowerLimit.y = m_normal1.y; m_upperLimit.x = -m_normal1.x; m_upperLimit.y = -m_normal1.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = m_normal1.x; m_lowerLimit.y = m_normal1.y; m_upperLimit.x = -m_normal0.x; m_upperLimit.y = -m_normal0.y; } } } else if (hasVertex3) { if (convex2) { m_front = offset1 >= 0.0f || offset2 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = -m_normal1.x; m_lowerLimit.y = -m_normal1.y; m_upperLimit.x = m_normal2.x; m_upperLimit.y = m_normal2.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = -m_normal1.x; m_lowerLimit.y = -m_normal1.y; m_upperLimit.x = m_normal1.x; m_upperLimit.y = m_normal1.y; } } else { m_front = offset1 >= 0.0f && offset2 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = -m_normal1.x; m_lowerLimit.y = -m_normal1.y; m_upperLimit.x = m_normal1.x; m_upperLimit.y = m_normal1.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = -m_normal2.x; m_lowerLimit.y = -m_normal2.y; m_upperLimit.x = m_normal1.x; m_upperLimit.y = m_normal1.y; } } } else { m_front = offset1 >= 0.0f; if (m_front) { m_normal.x = m_normal1.x; m_normal.y = m_normal1.y; m_lowerLimit.x = -m_normal1.x; m_lowerLimit.y = -m_normal1.y; m_upperLimit.x = -m_normal1.x; m_upperLimit.y = -m_normal1.y; } else { m_normal.x = -m_normal1.x; m_normal.y = -m_normal1.y; m_lowerLimit.x = m_normal1.x; m_lowerLimit.y = m_normal1.y; m_upperLimit.x = m_normal1.x; m_upperLimit.y = m_normal1.y; } } // Get polygonB in frameA m_polygonB.count = polygonB.getVertexCount(); for (int i = 0; i < polygonB.getVertexCount(); ++i) { Transform.mulToOutUnsafe(m_xf, polygonB.m_vertices[i], m_polygonB.vertices[i]); Rotation.mulToOutUnsafe(m_xf.q, polygonB.m_normals[i], m_polygonB.normals[i]); } m_radius = 2.0f * JBoxSettings.polygonRadius; manifold.pointCount = 0; computeEdgeSeparation(edgeAxis); // If no valid normal can be found than this edge should not collide. if (edgeAxis.type == EPAxis.Type.UNKNOWN) { return; } if (edgeAxis.separation > m_radius) { return; } computePolygonSeparation(polygonAxis); if (polygonAxis.type != EPAxis.Type.UNKNOWN && polygonAxis.separation > m_radius) { return; } // Use hysteresis for jitter reduction. final float k_relativeTol = 0.98f; final float k_absoluteTol = 0.001f; EPAxis primaryAxis; if (polygonAxis.type == EPAxis.Type.UNKNOWN) { primaryAxis = edgeAxis; } else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) { primaryAxis = polygonAxis; } else { primaryAxis = edgeAxis; } final ClipVertex ie0 = ie[0]; final ClipVertex ie1 = ie[1]; if (primaryAxis.type == EPAxis.Type.EDGE_A) { manifold.type = Manifold.ManifoldType.FACE_A; // Search for the polygon normal that is most anti-parallel to the edge normal. int bestIndex = 0; float bestValue = Vec2.dot(m_normal, m_polygonB.normals[0]); for (int i = 1; i < m_polygonB.count; ++i) { float value = Vec2.dot(m_normal, m_polygonB.normals[i]); if (value < bestValue) { bestValue = value; bestIndex = i; } } int i1 = bestIndex; int i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0; ie0.v.set(m_polygonB.vertices[i1]); ie0.id.indexA = 0; ie0.id.indexB = (byte) i1; ie0.id.typeA = (byte) ContactID.Type.FACE.ordinal(); ie0.id.typeB = (byte) ContactID.Type.VERTEX.ordinal(); ie1.v.set(m_polygonB.vertices[i2]); ie1.id.indexA = 0; ie1.id.indexB = (byte) i2; ie1.id.typeA = (byte) ContactID.Type.FACE.ordinal(); ie1.id.typeB = (byte) ContactID.Type.VERTEX.ordinal(); if (m_front) { rf.i1 = 0; rf.i2 = 1; rf.v1.set(m_v1); rf.v2.set(m_v2); rf.normal.set(m_normal1); } else { rf.i1 = 1; rf.i2 = 0; rf.v1.set(m_v2); rf.v2.set(m_v1); rf.normal.set(m_normal1).negateLocal(); } } else { manifold.type = Manifold.ManifoldType.FACE_B; ie0.v.set(m_v1); ie0.id.indexA = 0; ie0.id.indexB = (byte) primaryAxis.index; ie0.id.typeA = (byte) ContactID.Type.VERTEX.ordinal(); ie0.id.typeB = (byte) ContactID.Type.FACE.ordinal(); ie1.v.set(m_v2); ie1.id.indexA = 0; ie1.id.indexB = (byte) primaryAxis.index; ie1.id.typeA = (byte) ContactID.Type.VERTEX.ordinal(); ie1.id.typeB = (byte) ContactID.Type.FACE.ordinal(); rf.i1 = primaryAxis.index; rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0; rf.v1.set(m_polygonB.vertices[rf.i1]); rf.v2.set(m_polygonB.vertices[rf.i2]); rf.normal.set(m_polygonB.normals[rf.i1]); } rf.sideNormal1.set(rf.normal.y, -rf.normal.x); rf.sideNormal2.set(rf.sideNormal1).negateLocal(); rf.sideOffset1 = Vec2.dot(rf.sideNormal1, rf.v1); rf.sideOffset2 = Vec2.dot(rf.sideNormal2, rf.v2); // Clip incident edge against extruded edge1 side edges. int np; // Clip to box side 1 np = clipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); if (np < JBoxSettings.maxManifoldPoints) { return; } // Clip to negative box side 1 np = clipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); if (np < JBoxSettings.maxManifoldPoints) { return; } // Now clipPoints2 contains the clipped points. if (primaryAxis.type == EPAxis.Type.EDGE_A) { manifold.localNormal.set(rf.normal); manifold.localPoint.set(rf.v1); } else { manifold.localNormal.set(polygonB.m_normals[rf.i1]); manifold.localPoint.set(polygonB.m_vertices[rf.i1]); } int pointCount = 0; for (int i = 0; i < JBoxSettings.maxManifoldPoints; ++i) { float separation; separation = Vec2.dot(rf.normal, temp.set(clipPoints2[i].v).subLocal(rf.v1)); if (separation <= m_radius) { ManifoldPoint cp = manifold.points[pointCount]; if (primaryAxis.type == EPAxis.Type.EDGE_A) { // cp.localPoint = MulT(m_xf, clipPoints2[i].v); Transform.mulTransToOutUnsafe(m_xf, clipPoints2[i].v, cp.localPoint); cp.id.set(clipPoints2[i].id); } else { cp.localPoint.set(clipPoints2[i].v); cp.id.typeA = clipPoints2[i].id.typeB; cp.id.typeB = clipPoints2[i].id.typeA; cp.id.indexA = clipPoints2[i].id.indexB; cp.id.indexB = clipPoints2[i].id.indexA; } ++pointCount; } } manifold.pointCount = pointCount; } public void computeEdgeSeparation(EPAxis axis) { axis.type = EPAxis.Type.EDGE_A; axis.index = m_front ? 0 : 1; axis.separation = Float.MAX_VALUE; float nx = m_normal.x; float ny = m_normal.y; for (int i = 0; i < m_polygonB.count; ++i) { Vec2 v = m_polygonB.vertices[i]; float tempx = v.x - m_v1.x; float tempy = v.y - m_v1.y; float s = nx * tempx + ny * tempy; if (s < axis.separation) { axis.separation = s; } } } private final Vec2 perp = new Vec2(); private final Vec2 n = new Vec2(); public void computePolygonSeparation(EPAxis axis) { axis.type = EPAxis.Type.UNKNOWN; axis.index = -1; axis.separation = -Float.MAX_VALUE; perp.x = -m_normal.y; perp.y = m_normal.x; for (int i = 0; i < m_polygonB.count; ++i) { Vec2 normalB = m_polygonB.normals[i]; Vec2 vB = m_polygonB.vertices[i]; n.x = -normalB.x; n.y = -normalB.y; // float s1 = Vec2.dot(n, temp.set(vB).subLocal(m_v1)); // float s2 = Vec2.dot(n, temp.set(vB).subLocal(m_v2)); float tempx = vB.x - m_v1.x; float tempy = vB.y - m_v1.y; float s1 = n.x * tempx + n.y * tempy; tempx = vB.x - m_v2.x; tempy = vB.y - m_v2.y; float s2 = n.x * tempx + n.y * tempy; float s = Math.min(s1, s2); if (s > m_radius) { // No collision axis.type = EPAxis.Type.EDGE_B; axis.index = i; axis.separation = s; return; } // Adjacency if (n.x * perp.x + n.y * perp.y >= 0.0f) { if (Vec2.dot(temp.set(n).subLocal(m_upperLimit), m_normal) < -JBoxSettings.angularSlop) { continue; } } else { if (Vec2.dot(temp.set(n).subLocal(m_lowerLimit), m_normal) < -JBoxSettings.angularSlop) { continue; } } if (s > axis.separation) { axis.type = EPAxis.Type.EDGE_B; axis.index = i; axis.separation = s; } } } } }
refactor
fxgl-entity/src/main/java/com/almasb/fxgl/physics/box2d/collision/Collision.java
refactor
<ide><path>xgl-entity/src/main/java/com/almasb/fxgl/physics/box2d/collision/Collision.java <ide> * Used for computing contact manifolds. <ide> */ <ide> private static class ClipVertex { <del> public final Vec2 v; <del> public final ContactID id; <del> <del> public ClipVertex() { <del> v = new Vec2(); <del> id = new ContactID(); <del> } <add> public final Vec2 v = new Vec2(); <add> public final ContactID id = new ContactID(); <ide> <ide> public void set(final ClipVertex cv) { <ide> Vec2 v1 = cv.v;
Java
apache-2.0
f61242e97e2f260451bd57ef3f51cf5dd0a04d11
0
ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,allotria/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,jagguli/intellij-community,holmes/intellij-community,consulo/consulo,nicolargo/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,signed/intellij-community,fitermay/intellij-community,adedayo/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,fnouama/intellij-community,dslomov/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,kool79/intellij-community,retomerz/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,ibinti/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,amith01994/intellij-community,amith01994/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,retomerz/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,supersven/intellij-community,suncycheng/intellij-community,da1z/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,signed/intellij-community,holmes/intellij-community,suncycheng/intellij-community,da1z/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,xfournet/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,caot/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,gnuhub/intellij-community,izonder/intellij-community,xfournet/intellij-community,kdwink/intellij-community,caot/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,signed/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,petteyg/intellij-community,semonte/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,izonder/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,allotria/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,robovm/robovm-studio,FHannes/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,fitermay/intellij-community,blademainer/intellij-community,diorcety/intellij-community,ibinti/intellij-community,kdwink/intellij-community,apixandru/intellij-community,allotria/intellij-community,da1z/intellij-community,joewalnes/idea-community,retomerz/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,caot/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,fnouama/intellij-community,kool79/intellij-community,amith01994/intellij-community,samthor/intellij-community,amith01994/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,caot/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,samthor/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,holmes/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,slisson/intellij-community,hurricup/intellij-community,xfournet/intellij-community,ryano144/intellij-community,da1z/intellij-community,diorcety/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,clumsy/intellij-community,adedayo/intellij-community,hurricup/intellij-community,diorcety/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,amith01994/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,asedunov/intellij-community,kdwink/intellij-community,kool79/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,caot/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,adedayo/intellij-community,ernestp/consulo,salguarnieri/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,robovm/robovm-studio,hurricup/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ernestp/consulo,idea4bsd/idea4bsd,caot/intellij-community,jagguli/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,holmes/intellij-community,jexp/idea2,gnuhub/intellij-community,ernestp/consulo,vladmm/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,holmes/intellij-community,jexp/idea2,ivan-fedorov/intellij-community,robovm/robovm-studio,supersven/intellij-community,izonder/intellij-community,orekyuu/intellij-community,kool79/intellij-community,supersven/intellij-community,signed/intellij-community,fitermay/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,supersven/intellij-community,jagguli/intellij-community,kdwink/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,samthor/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,ibinti/intellij-community,samthor/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,holmes/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,allotria/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,da1z/intellij-community,signed/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,jagguli/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,signed/intellij-community,nicolargo/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,da1z/intellij-community,vladmm/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,amith01994/intellij-community,da1z/intellij-community,tmpgit/intellij-community,jexp/idea2,fnouama/intellij-community,jexp/idea2,supersven/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,holmes/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,ahb0327/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,robovm/robovm-studio,samthor/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,ryano144/intellij-community,blademainer/intellij-community,clumsy/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,nicolargo/intellij-community,consulo/consulo,ftomassetti/intellij-community,diorcety/intellij-community,dslomov/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,jexp/idea2,pwoodworth/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,kool79/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,slisson/intellij-community,jexp/idea2,mglukhikh/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,joewalnes/idea-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,apixandru/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,FHannes/intellij-community,signed/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,apixandru/intellij-community,caot/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,vladmm/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,vladmm/intellij-community,da1z/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,signed/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,allotria/intellij-community,caot/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,adedayo/intellij-community,jexp/idea2,alphafoobar/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,youdonghai/intellij-community,joewalnes/idea-community,supersven/intellij-community,asedunov/intellij-community,diorcety/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,jagguli/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,da1z/intellij-community,clumsy/intellij-community,retomerz/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,samthor/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,jexp/idea2,joewalnes/idea-community,fnouama/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,joewalnes/idea-community,da1z/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,semonte/intellij-community,semonte/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,allotria/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,supersven/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,consulo/consulo,allotria/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,clumsy/intellij-community,supersven/intellij-community,tmpgit/intellij-community,ernestp/consulo,semonte/intellij-community,signed/intellij-community,vladmm/intellij-community,hurricup/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,caot/intellij-community,semonte/intellij-community,supersven/intellij-community,asedunov/intellij-community,signed/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,semonte/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,ernestp/consulo,ol-loginov/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,clumsy/intellij-community,dslomov/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,semonte/intellij-community,hurricup/intellij-community,allotria/intellij-community,ahb0327/intellij-community,slisson/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,wreckJ/intellij-community,consulo/consulo,FHannes/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,asedunov/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,signed/intellij-community,samthor/intellij-community,xfournet/intellij-community,kool79/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,ibinti/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,blademainer/intellij-community,consulo/consulo,michaelgallacher/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,ahb0327/intellij-community
/* * Copyright (c) 2000-2007 JetBrains s.r.o. All Rights Reserved. */ package com.intellij.psi; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.intellij.lang.ASTNode; import com.intellij.psi.meta.PsiMetaBaseOwner; import com.intellij.psi.meta.PsiMetaDataBase; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.scope.BaseScopeProcessor; import com.intellij.psi.scope.util.PsiScopesUtil; import com.intellij.psi.impl.source.resolve.ResolveCache; import com.intellij.psi.impl.source.resolve.ResolveUtil; import com.intellij.psi.impl.source.tree.ChangeUtil; import com.intellij.psi.impl.source.tree.CompositeElement; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.impl.source.codeStyle.ReferenceAdjuster; import com.intellij.psi.impl.CheckUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.ObjectUtils; import com.intellij.openapi.util.TextRange; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NonNls; import java.util.Set; import java.util.LinkedHashSet; /** * @author peter */ public abstract class AbstractQualifiedReference<T extends AbstractQualifiedReference<T>> extends ASTWrapperPsiElement implements PsiPolyVariantReference, PsiQualifiedReference { private static final ResolveCache.PolyVariantResolver<AbstractQualifiedReference> MY_RESOLVER = new ResolveCache.PolyVariantResolver<AbstractQualifiedReference>() { public ResolveResult[] resolve(final AbstractQualifiedReference expression, final boolean incompleteCode) { return expression.resolveInner(); } }; public AbstractQualifiedReference(@NotNull final ASTNode node) { super(node); } public final PsiReference getReference() { return this; } public final PsiElement getElement() { return this; } protected abstract ResolveResult[] resolveInner(); @NotNull public final ResolveResult[] multiResolve(final boolean incompleteCode) { return getManager().getResolveCache().resolveWithCaching(this, MY_RESOLVER, false, false); } @Nullable public final PsiElement resolve() { final ResolveResult[] results = multiResolve(false); return results.length == 1 ? results[0].getElement() : null; } protected boolean processVariantsInner(PsiScopeProcessor processor) { final T qualifier = getQualifier(); if (qualifier == null) { return processUnqualifiedVariants(processor); } final PsiElement psiElement = qualifier.resolve(); return psiElement == null || psiElement.processDeclarations(processor, PsiSubstitutor.EMPTY, null, this); } protected boolean processUnqualifiedVariants(final PsiScopeProcessor processor) { return PsiScopesUtil.treeWalkUp(processor, this, null); } public final String getCanonicalText() { return getText(); } @SuppressWarnings({"unchecked"}) @Nullable public T getQualifier() { return (T)findChildByClass(getClass()); } public final PsiElement handleElementRename(final String newElementName) throws IncorrectOperationException { CheckUtil.checkWritable(this); final PsiElement firstChildNode = ObjectUtils.assertNotNull(getFirstChild()); final PsiElement firstInIdentifier = getClass().isInstance(firstChildNode) ? ObjectUtils.assertNotNull(firstChildNode.getNextSibling()).getNextSibling() : firstChildNode; ChangeUtil.removeChildren((CompositeElement)getNode(), (TreeElement)firstInIdentifier, null); final PsiElement referenceName = ObjectUtils.assertNotNull(parseReference(newElementName).getReferenceNameElement()); ChangeUtil.addChild((CompositeElement)getNode(), (TreeElement)referenceName.getNode(), null); return this; } public final PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException { CheckUtil.checkWritable(this); if (isReferenceTo(element)) return this; if (element instanceof PsiMethod) { final PsiMethod method = (PsiMethod)element; final String methodName = method.getName(); if (isDirectlyVisible(method)) return replaceReference(methodName); final AbstractQualifiedReference result = replaceReference(method.getContainingClass().getQualifiedName() + "." + methodName); final AbstractQualifiedReference qualifier = result.getQualifier(); assert qualifier != null; qualifier.shortenReferences(); return result; } if (element instanceof PsiClass) { return replaceReference(((PsiClass)element).getQualifiedName()).shortenReferences(); } if (element instanceof PsiPackage) { return replaceReference(((PsiPackage)element).getQualifiedName()); } if (element instanceof PsiMetaBaseOwner) { final PsiMetaDataBase metaData = ((PsiMetaBaseOwner)element).getMetaData(); if (metaData != null) { final String name = metaData.getName(this); if (name != null) { return replaceReference(name); } } } return this; } private boolean isDirectlyVisible(final PsiMethod method) { final AbstractQualifiedReferenceResolvingProcessor processor = new AbstractQualifiedReferenceResolvingProcessor() { protected void process(final PsiElement element) { if (getManager().areElementsEquivalent(element, method) && isAccessible(element)) { setFound(); } } }; processUnqualifiedVariants(processor); return processor.isFound(); } private AbstractQualifiedReference replaceReference(final String newText) { final ASTNode newNode = parseReference(newText).getNode(); getNode().getTreeParent().replaceChild(getNode(), newNode); return (AbstractQualifiedReference)newNode.getPsi(); } @NotNull protected abstract T parseReference(String newText); protected final boolean isAccessible(final PsiElement element) { if (element instanceof PsiMember) { final PsiMember member = (PsiMember)element; return ResolveUtil.isAccessible(member, member.getContainingClass(), member.getModifierList(), this, null, null); } return true; } @NotNull private AbstractQualifiedReference shortenReferences() { final PsiElement refElement = resolve(); if (refElement instanceof PsiClass) { final PsiQualifiedReference reference = ReferenceAdjuster.getClassReferenceToShorten((PsiClass)refElement, false, this); if (reference instanceof AbstractQualifiedReference) { ((AbstractQualifiedReference)reference).dequalify(); } } return this; } private void dequalify() { final AbstractQualifiedReference qualifier = getQualifier(); if (qualifier != null) { getNode().removeChild(qualifier.getNode()); final PsiElement separator = getSeparator(); if (separator != null) { final ASTNode separatorNode = separator.getNode(); if (separatorNode != null) { getNode().removeChild(separatorNode); } } } } public boolean isReferenceTo(final PsiElement element) { final PsiManager manager = getManager(); for (final ResolveResult result : multiResolve(false)) { if (manager.areElementsEquivalent(element, result.getElement())) return true; } return false; } @Nullable protected abstract PsiElement getSeparator(); @Nullable protected abstract PsiElement getReferenceNameElement(); public final TextRange getRangeInElement() { final PsiElement element = getSeparator(); final int length = getTextLength(); return element == null ? TextRange.from(0, length) : new TextRange(element.getStartOffsetInParent() + element.getTextLength(), length); } @Nullable @NonNls public final String getReferenceName() { final PsiElement element = getReferenceNameElement(); return element == null ? null : element.getText(); } public final boolean isSoft() { return false; } protected abstract static class AbstractQualifiedReferenceResolvingProcessor extends BaseScopeProcessor { private boolean myFound = false; private final Set<ResolveResult> myResults = new LinkedHashSet<ResolveResult>(); public boolean execute(final PsiElement element, final PsiSubstitutor substitutor) { if (isFound()) return false; process(element); return true; } protected final void addResult(ResolveResult resolveResult) { myResults.add(resolveResult); } private boolean isFound() { return myFound; } public void handleEvent(final Event event, final Object associated) { if ((event == Event.SET_CURRENT_FILE_CONTEXT || event == Event.SET_DECLARATION_HOLDER) && !myResults.isEmpty()) { setFound(); } super.handleEvent(event, associated); } protected final void setFound() { myFound = true; } protected abstract void process(PsiElement element); public Set<ResolveResult> getResults() { return myResults; } } }
codeInsight/impl/com/intellij/psi/AbstractQualifiedReference.java
/* * Copyright (c) 2000-2007 JetBrains s.r.o. All Rights Reserved. */ package com.intellij.psi; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.intellij.lang.ASTNode; import com.intellij.psi.meta.PsiMetaBaseOwner; import com.intellij.psi.meta.PsiMetaDataBase; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.scope.BaseScopeProcessor; import com.intellij.psi.scope.util.PsiScopesUtil; import com.intellij.psi.impl.source.resolve.ResolveCache; import com.intellij.psi.impl.source.resolve.ResolveUtil; import com.intellij.psi.impl.source.tree.ChangeUtil; import com.intellij.psi.impl.source.tree.CompositeElement; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.impl.source.codeStyle.ReferenceAdjuster; import com.intellij.psi.impl.CheckUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.ObjectUtils; import com.intellij.openapi.util.TextRange; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NonNls; import java.util.Set; import java.util.LinkedHashSet; /** * @author peter */ public abstract class AbstractQualifiedReference<T extends AbstractQualifiedReference<T>> extends ASTWrapperPsiElement implements PsiPolyVariantReference, PsiQualifiedReference { private static final ResolveCache.PolyVariantResolver<AbstractQualifiedReference> MY_RESOLVER = new ResolveCache.PolyVariantResolver<AbstractQualifiedReference>() { public ResolveResult[] resolve(final AbstractQualifiedReference expression, final boolean incompleteCode) { return expression.resolveInner(); } }; public AbstractQualifiedReference(@NotNull final ASTNode node) { super(node); } public final PsiReference getReference() { return this; } public final PsiElement getElement() { return this; } protected abstract ResolveResult[] resolveInner(); @NotNull public final ResolveResult[] multiResolve(final boolean incompleteCode) { return getManager().getResolveCache().resolveWithCaching(this, MY_RESOLVER, false, false); } @Nullable public final PsiElement resolve() { final ResolveResult[] results = multiResolve(false); return results.length == 1 ? results[0].getElement() : null; } protected boolean processVariantsInner(PsiScopeProcessor processor) { final T qualifier = getQualifier(); if (qualifier == null) { return processUnqualifiedVariants(processor); } final PsiElement psiElement = qualifier.resolve(); return psiElement == null || psiElement.processDeclarations(processor, PsiSubstitutor.EMPTY, null, this); } protected boolean processUnqualifiedVariants(final PsiScopeProcessor processor) { return PsiScopesUtil.treeWalkUp(processor, this, null); } public final String getCanonicalText() { return getText(); } @SuppressWarnings({"unchecked"}) @Nullable public T getQualifier() { return (T)findChildByClass(getClass()); } public final PsiElement handleElementRename(final String newElementName) throws IncorrectOperationException { CheckUtil.checkWritable(this); final PsiElement firstChildNode = ObjectUtils.assertNotNull(getFirstChild()); final PsiElement firstInIdentifier = getClass().isInstance(firstChildNode) ? ObjectUtils.assertNotNull(firstChildNode.getNextSibling()).getNextSibling() : firstChildNode; ChangeUtil.removeChildren((CompositeElement)getNode(), (TreeElement)firstInIdentifier, null); final PsiElement referenceName = ObjectUtils.assertNotNull(parseReference(newElementName).getReferenceNameElement()); ChangeUtil.addChild((CompositeElement)getNode(), (TreeElement)referenceName.getNode(), null); return this; } public final PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException { CheckUtil.checkWritable(this); if (isReferenceTo(element)) return this; if (element instanceof PsiMethod) { final PsiMethod method = (PsiMethod)element; final String methodName = method.getName(); if (isDirectlyVisible(method)) return replaceReference(methodName); final AbstractQualifiedReference result = replaceReference(method.getContainingClass().getQualifiedName() + "." + methodName); final AbstractQualifiedReference qualifier = result.getQualifier(); assert qualifier != null; qualifier.shortenReferences(); return result; } if (element instanceof PsiClass) { return replaceReference(((PsiClass)element).getQualifiedName()).shortenReferences(); } if (element instanceof PsiPackage) { return replaceReference(((PsiPackage)element).getQualifiedName()); } if (element instanceof PsiMetaBaseOwner) { final PsiMetaDataBase metaData = ((PsiMetaBaseOwner)element).getMetaData(); if (metaData != null) { final String name = metaData.getName(this); if (name != null) { return replaceReference(name); } } } return this; } private boolean isDirectlyVisible(final PsiMethod method) { final AbstractQualifiedReferenceResolvingProcessor processor = new AbstractQualifiedReferenceResolvingProcessor() { protected void process(final PsiElement element) { if (getManager().areElementsEquivalent(element, method) && isAccessible(element)) { setFound(); } } }; processUnqualifiedVariants(processor); return processor.isFound(); } private AbstractQualifiedReference replaceReference(final String newText) { final ASTNode newNode = parseReference(newText).getNode(); getNode().getTreeParent().replaceChild(getNode(), newNode); return (AbstractQualifiedReference)newNode.getPsi(); } @NotNull protected abstract T parseReference(String newText); protected final boolean isAccessible(final PsiElement element) { if (element instanceof PsiMember) { final PsiMember member = (PsiMember)element; return ResolveUtil.isAccessible(member, member.getContainingClass(), member.getModifierList(), this, null, null); } return true; } @NotNull private AbstractQualifiedReference shortenReferences() { final PsiElement refElement = resolve(); if (refElement instanceof PsiClass) { final PsiQualifiedReference reference = ReferenceAdjuster.getClassReferenceToShorten((PsiClass)refElement, false, this); if (reference instanceof AbstractQualifiedReference) { ((AbstractQualifiedReference)reference).dequalify(); } } return this; } private void dequalify() { final AbstractQualifiedReference qualifier = getQualifier(); if (qualifier != null) { getNode().removeChild(qualifier.getNode()); final PsiElement separator = getSeparator(); if (separator != null) { final ASTNode separatorNode = separator.getNode(); if (separatorNode != null) { getNode().removeChild(separatorNode); } } } } public boolean isReferenceTo(final PsiElement element) { final PsiManager manager = getManager(); for (final ResolveResult result : multiResolve(false)) { if (manager.areElementsEquivalent(element, result.getElement())) return true; } return false; } @Nullable protected abstract PsiElement getSeparator(); @Nullable protected abstract PsiElement getReferenceNameElement(); public final TextRange getRangeInElement() { final PsiElement element = getSeparator(); final int length = getTextLength(); return element == null ? TextRange.from(0, length) : new TextRange(element.getStartOffsetInParent() + element.getTextLength(), length); } @Nullable @NonNls public final String getReferenceName() { final PsiElement element = getReferenceNameElement(); return element == null ? null : element.getText(); } public final boolean isSoft() { return false; } protected abstract static class AbstractQualifiedReferenceResolvingProcessor extends BaseScopeProcessor { private boolean myFound = false; private final Set<ResolveResult> myResults = new LinkedHashSet<ResolveResult>(); public boolean execute(final PsiElement element, final PsiSubstitutor substitutor) { if (isFound()) return false; process(element); return true; } protected final void addResult(ResolveResult resolveResult) { myResults.add(resolveResult); } private boolean isFound() { return myFound; } public void handleEvent(final Event event, final Object associated) { if (event == Event.SET_CURRENT_FILE_CONTEXT && !myResults.isEmpty()) { setFound(); } super.handleEvent(event, associated); } protected final void setFound() { myFound = true; } protected abstract void process(PsiElement element); public Set<ResolveResult> getResults() { return myResults; } } }
IDEADEV-17519 Spring + aop: the implementation method name in execution expression used in @Pointcut is not resolved
codeInsight/impl/com/intellij/psi/AbstractQualifiedReference.java
IDEADEV-17519 Spring + aop: the implementation method name in execution expression used in @Pointcut is not resolved
<ide><path>odeInsight/impl/com/intellij/psi/AbstractQualifiedReference.java <ide> } <ide> <ide> public void handleEvent(final Event event, final Object associated) { <del> if (event == Event.SET_CURRENT_FILE_CONTEXT && !myResults.isEmpty()) { <add> if ((event == Event.SET_CURRENT_FILE_CONTEXT || event == Event.SET_DECLARATION_HOLDER) && !myResults.isEmpty()) { <ide> setFound(); <ide> } <ide> super.handleEvent(event, associated);
Java
apache-2.0
3f53007af6f2b4a7bcfcedd732a3e273c1ba1122
0
99soft/meiyo
/* * Copyright 2010 The Meiyo Team * * 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.commons.meiyo.classpath.builder; import java.io.File; import org.nnsoft.commons.meiyo.classpath.ClassPath; import org.nnsoft.commons.meiyo.classpath.ErrorHandler; /** * TODO fill me */ public final class ClassPathBuilder { private static final String JAVA_CLASS_PATH = "java.class.path"; /** * This class can't be instantiated. */ private ClassPathBuilder() { // do nothing } public static ClassPath createClassPathByDefaultSettings() { return createClassPathFromJVM() .usingDefaultClassLoader() .usingDefaultErrorHandler(); } public static ClassLoaderBuilder createClassPathFromJVM() { return createClassPathFromPath(System.getProperty(JAVA_CLASS_PATH)); } public static ClassLoaderBuilder createClassPathFromPath(final String classpath) { if (classpath == null || classpath.length() == 0) { throw new IllegalArgumentException("Parameter 'classpath' must not be empty"); } return createClassPathFromPath(classpath.split(File.pathSeparator)); } public static ClassLoaderBuilder createClassPathFromPath(final String...classpath) { if (classpath == null || classpath.length == 0) { throw new IllegalArgumentException("Parameter 'classpath' must not be empty"); } return new ClassLoaderBuilder() { public ErrorHandlerBuilder usingDefaultClassLoader() { return this.usingClassLoader(Thread.currentThread().getContextClassLoader()); } public ErrorHandlerBuilder usingClassLoader(final ClassLoader classLoader) { if (classLoader == null) { throw new IllegalArgumentException("Parameter 'classLoader' must not be null"); } return new ErrorHandlerBuilder() { public ClassPath usingDefaultErrorHandler() { return this.usingErrorHandler(new DefaultErrorHandler()); } public ClassPath usingErrorHandler(final ErrorHandler errorHandler) { if (errorHandler == null) { throw new IllegalArgumentException("Parameter 'errorHandler' must not be null"); } return new CompositeClassPath(classpath, classLoader, errorHandler); } }; } }; } }
src/main/java/org/nnsoft/commons/meiyo/classpath/builder/ClassPathBuilder.java
/* * Copyright 2010 The Meiyo Team * * 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.commons.meiyo.classpath.builder; import java.io.File; import org.nnsoft.commons.meiyo.classpath.ClassPath; import org.nnsoft.commons.meiyo.classpath.ErrorHandler; /** * * @version $Id$ */ public final class ClassPathBuilder { private static final String JAVA_CLASS_PATH = "java.class.path"; /** * This class can't be instantiated. */ private ClassPathBuilder() { // do nothing } public static ClassPath createClassPathByDefaultSettings() { return createClassPathFromJVM() .usingDefaultClassLoader() .usingDefaultErrorHandler(); } public static ClassLoaderBuilder createClassPathFromJVM() { return createClassPathFromPath(System.getProperty(JAVA_CLASS_PATH)); } public static ClassLoaderBuilder createClassPathFromPath(final String classpath) { if (classpath == null || classpath.length() == 0) { throw new IllegalArgumentException("Parameter 'classpath' must not be empty"); } return createClassPathFromPath(classpath.split(File.pathSeparator)); } public static ClassLoaderBuilder createClassPathFromPath(final String...classpath) { if (classpath == null || classpath.length == 0) { throw new IllegalArgumentException("Parameter 'classpath' must not be empty"); } return new ClassLoaderBuilder() { public ErrorHandlerBuilder usingDefaultClassLoader() { return this.usingClassLoader(Thread.currentThread().getContextClassLoader()); } public ErrorHandlerBuilder usingClassLoader(final ClassLoader classLoader) { if (classLoader == null) { throw new IllegalArgumentException("Parameter 'classLoader' must not be null"); } return new ErrorHandlerBuilder() { public ClassPath usingDefaultErrorHandler() { return this.usingErrorHandler(new DefaultErrorHandler()); } public ClassPath usingErrorHandler(final ErrorHandler errorHandler) { if (errorHandler == null) { throw new IllegalArgumentException("Parameter 'errorHandler' must not be null"); } return new CompositeClassPath(classpath, classLoader, errorHandler); } }; } }; } }
minor format
src/main/java/org/nnsoft/commons/meiyo/classpath/builder/ClassPathBuilder.java
minor format
<ide><path>rc/main/java/org/nnsoft/commons/meiyo/classpath/builder/ClassPathBuilder.java <ide> import org.nnsoft.commons.meiyo.classpath.ClassPath; <ide> import org.nnsoft.commons.meiyo.classpath.ErrorHandler; <ide> <del> <ide> /** <del> * <del> * @version $Id$ <add> * TODO fill me <ide> */ <ide> public final class ClassPathBuilder { <ide>
Java
apache-2.0
1080d01f248299e4b1b8a1f9033f63fba8069a49
0
smartnews/presto,yuananf/presto,jiangyifangh/presto,miniway/presto,erichwang/presto,smartnews/presto,mandusm/presto,aramesh117/presto,yuananf/presto,treasure-data/presto,wagnermarkd/presto,jxiang/presto,sumitkgec/presto,nezihyigitbasi/presto,nezihyigitbasi/presto,wagnermarkd/presto,dain/presto,troels/nz-presto,jxiang/presto,elonazoulay/presto,arhimondr/presto,aramesh117/presto,miniway/presto,haozhun/presto,damiencarol/presto,mvp/presto,shixuan-fan/presto,jiangyifangh/presto,electrum/presto,hgschmie/presto,ebyhr/presto,Praveen2112/presto,mvp/presto,EvilMcJerkface/presto,11xor6/presto,stewartpark/presto,sopel39/presto,arhimondr/presto,gh351135612/presto,haozhun/presto,arhimondr/presto,ebyhr/presto,11xor6/presto,nezihyigitbasi/presto,treasure-data/presto,prateek1306/presto,mbeitchman/presto,dain/presto,yuananf/presto,treasure-data/presto,Yaliang/presto,wyukawa/presto,raghavsethi/presto,yuananf/presto,Praveen2112/presto,11xor6/presto,mbeitchman/presto,losipiuk/presto,twitter-forks/presto,troels/nz-presto,jiangyifangh/presto,stewartpark/presto,mandusm/presto,hgschmie/presto,EvilMcJerkface/presto,facebook/presto,mvp/presto,youngwookim/presto,electrum/presto,miniway/presto,youngwookim/presto,losipiuk/presto,sumitkgec/presto,gh351135612/presto,youngwookim/presto,sopel39/presto,raghavsethi/presto,martint/presto,facebook/presto,ebyhr/presto,stewartpark/presto,erichwang/presto,raghavsethi/presto,EvilMcJerkface/presto,jxiang/presto,losipiuk/presto,troels/nz-presto,sopel39/presto,prestodb/presto,elonazoulay/presto,martint/presto,twitter-forks/presto,hgschmie/presto,smartnews/presto,shixuan-fan/presto,prateek1306/presto,aramesh117/presto,jxiang/presto,dain/presto,mvp/presto,arhimondr/presto,11xor6/presto,troels/nz-presto,Teradata/presto,EvilMcJerkface/presto,sopel39/presto,mbeitchman/presto,nezihyigitbasi/presto,prestodb/presto,arhimondr/presto,mandusm/presto,twitter-forks/presto,gh351135612/presto,treasure-data/presto,prestodb/presto,sumitkgec/presto,ptkool/presto,nezihyigitbasi/presto,sumitkgec/presto,mandusm/presto,dain/presto,wyukawa/presto,zzhao0/presto,Praveen2112/presto,prateek1306/presto,yuananf/presto,Yaliang/presto,Yaliang/presto,facebook/presto,electrum/presto,miniway/presto,haozhun/presto,electrum/presto,damiencarol/presto,hgschmie/presto,twitter-forks/presto,erichwang/presto,prateek1306/presto,sumitkgec/presto,raghavsethi/presto,elonazoulay/presto,elonazoulay/presto,erichwang/presto,wyukawa/presto,EvilMcJerkface/presto,mandusm/presto,ptkool/presto,wagnermarkd/presto,ebyhr/presto,youngwookim/presto,mvp/presto,facebook/presto,mbeitchman/presto,martint/presto,haozhun/presto,shixuan-fan/presto,Praveen2112/presto,zzhao0/presto,losipiuk/presto,jiangyifangh/presto,facebook/presto,Teradata/presto,Teradata/presto,dain/presto,aramesh117/presto,martint/presto,mbeitchman/presto,youngwookim/presto,smartnews/presto,damiencarol/presto,smartnews/presto,gh351135612/presto,miniway/presto,prestodb/presto,twitter-forks/presto,prestodb/presto,prateek1306/presto,ebyhr/presto,ptkool/presto,troels/nz-presto,electrum/presto,treasure-data/presto,jxiang/presto,zzhao0/presto,treasure-data/presto,losipiuk/presto,ptkool/presto,erichwang/presto,jiangyifangh/presto,Teradata/presto,wagnermarkd/presto,Teradata/presto,damiencarol/presto,elonazoulay/presto,raghavsethi/presto,stewartpark/presto,prestodb/presto,zzhao0/presto,haozhun/presto,ptkool/presto,damiencarol/presto,shixuan-fan/presto,wyukawa/presto,wagnermarkd/presto,shixuan-fan/presto,Praveen2112/presto,wyukawa/presto,Yaliang/presto,hgschmie/presto,zzhao0/presto,martint/presto,stewartpark/presto,Yaliang/presto,sopel39/presto,gh351135612/presto,aramesh117/presto,11xor6/presto
/* * 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.facebook.presto.hive; import com.amazonaws.AbortedException; import com.amazonaws.AmazonClientException; import com.amazonaws.ClientConfiguration; import com.amazonaws.Protocol; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.auth.InstanceProfileCredentialsProvider; import com.amazonaws.event.ProgressEvent; import com.amazonaws.event.ProgressEventType; import com.amazonaws.event.ProgressListener; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.AmazonS3EncryptionClient; import com.amazonaws.services.s3.model.AmazonS3Exception; import com.amazonaws.services.s3.model.CryptoConfiguration; import com.amazonaws.services.s3.model.EncryptionMaterialsProvider; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.KMSEncryptionMaterialsProvider; import com.amazonaws.services.s3.model.ListObjectsRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.S3ObjectInputStream; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.amazonaws.services.s3.model.SSEAwsKeyManagementParams; import com.amazonaws.services.s3.transfer.Transfer; import com.amazonaws.services.s3.transfer.TransferManager; import com.amazonaws.services.s3.transfer.TransferManagerConfiguration; import com.amazonaws.services.s3.transfer.Upload; import com.facebook.presto.hadoop.HadoopFileStatus; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Throwables; import com.google.common.collect.AbstractSequentialIterator; import com.google.common.collect.Iterators; import io.airlift.log.Logger; import io.airlift.units.DataSize; import io.airlift.units.Duration; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.BlockLocation; import org.apache.hadoop.fs.BufferedFSInputStream; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FSInputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocatedFileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RemoteIterator; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.util.Progressable; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.net.URI; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import static com.amazonaws.services.s3.Headers.SERVER_SIDE_ENCRYPTION; import static com.amazonaws.services.s3.Headers.UNENCRYPTED_CONTENT_LENGTH; import static com.facebook.presto.hive.RetryDriver.retry; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.base.Strings.nullToEmpty; import static com.google.common.collect.Iterables.toArray; import static io.airlift.units.DataSize.Unit.MEGABYTE; import static java.lang.Math.max; import static java.lang.Math.toIntExact; import static java.lang.String.format; import static java.nio.file.Files.createDirectories; import static java.nio.file.Files.createTempFile; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.http.HttpStatus.SC_BAD_REQUEST; import static org.apache.http.HttpStatus.SC_FORBIDDEN; import static org.apache.http.HttpStatus.SC_NOT_FOUND; import static org.apache.http.HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE; public class PrestoS3FileSystem extends FileSystem { private static final Logger log = Logger.get(PrestoS3FileSystem.class); private static final PrestoS3FileSystemStats STATS = new PrestoS3FileSystemStats(); private static final PrestoS3FileSystemMetricCollector METRIC_COLLECTOR = new PrestoS3FileSystemMetricCollector(STATS); public static PrestoS3FileSystemStats getFileSystemStats() { return STATS; } private static final String DIRECTORY_SUFFIX = "_$folder$"; public static final String S3_ACCESS_KEY = "presto.s3.access-key"; public static final String S3_SECRET_KEY = "presto.s3.secret-key"; public static final String S3_ENDPOINT = "presto.s3.endpoint"; public static final String S3_SIGNER_TYPE = "presto.s3.signer-type"; public static final String S3_SSL_ENABLED = "presto.s3.ssl.enabled"; public static final String S3_MAX_ERROR_RETRIES = "presto.s3.max-error-retries"; public static final String S3_MAX_CLIENT_RETRIES = "presto.s3.max-client-retries"; public static final String S3_MAX_BACKOFF_TIME = "presto.s3.max-backoff-time"; public static final String S3_MAX_RETRY_TIME = "presto.s3.max-retry-time"; public static final String S3_CONNECT_TIMEOUT = "presto.s3.connect-timeout"; public static final String S3_SOCKET_TIMEOUT = "presto.s3.socket-timeout"; public static final String S3_MAX_CONNECTIONS = "presto.s3.max-connections"; public static final String S3_STAGING_DIRECTORY = "presto.s3.staging-directory"; public static final String S3_MULTIPART_MIN_FILE_SIZE = "presto.s3.multipart.min-file-size"; public static final String S3_MULTIPART_MIN_PART_SIZE = "presto.s3.multipart.min-part-size"; public static final String S3_USE_INSTANCE_CREDENTIALS = "presto.s3.use-instance-credentials"; public static final String S3_PIN_CLIENT_TO_CURRENT_REGION = "presto.s3.pin-client-to-current-region"; public static final String S3_ENCRYPTION_MATERIALS_PROVIDER = "presto.s3.encryption-materials-provider"; public static final String S3_KMS_KEY_ID = "presto.s3.kms-key-id"; public static final String S3_SSE_KMS_KEY_ID = "presto.s3.sse.kms-key-id"; public static final String S3_SSE_ENABLED = "presto.s3.sse.enabled"; public static final String S3_SSE_TYPE = "presto.s3.sse.type"; public static final String S3_CREDENTIALS_PROVIDER = "presto.s3.credentials-provider"; public static final String S3_USER_AGENT_PREFIX = "presto.s3.user-agent-prefix"; public static final String S3_USER_AGENT_SUFFIX = "presto"; private static final DataSize BLOCK_SIZE = new DataSize(32, MEGABYTE); private static final DataSize MAX_SKIP_SIZE = new DataSize(1, MEGABYTE); private static final String PATH_SEPARATOR = "/"; private static final Duration BACKOFF_MIN_SLEEP = new Duration(1, SECONDS); private final TransferManagerConfiguration transferConfig = new TransferManagerConfiguration(); private URI uri; private Path workingDirectory; private AmazonS3 s3; private File stagingDirectory; private int maxAttempts; private Duration maxBackoffTime; private Duration maxRetryTime; private boolean useInstanceCredentials; private boolean pinS3ClientToCurrentRegion; private boolean sseEnabled; private PrestoS3SseType sseType; private String sseKmsKeyId; @Override public void initialize(URI uri, Configuration conf) throws IOException { requireNonNull(uri, "uri is null"); requireNonNull(conf, "conf is null"); super.initialize(uri, conf); setConf(conf); this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority()); this.workingDirectory = new Path(PATH_SEPARATOR).makeQualified(this.uri, new Path(PATH_SEPARATOR)); HiveS3Config defaults = new HiveS3Config(); this.stagingDirectory = new File(conf.get(S3_STAGING_DIRECTORY, defaults.getS3StagingDirectory().toString())); this.maxAttempts = conf.getInt(S3_MAX_CLIENT_RETRIES, defaults.getS3MaxClientRetries()) + 1; this.maxBackoffTime = Duration.valueOf(conf.get(S3_MAX_BACKOFF_TIME, defaults.getS3MaxBackoffTime().toString())); this.maxRetryTime = Duration.valueOf(conf.get(S3_MAX_RETRY_TIME, defaults.getS3MaxRetryTime().toString())); int maxErrorRetries = conf.getInt(S3_MAX_ERROR_RETRIES, defaults.getS3MaxErrorRetries()); boolean sslEnabled = conf.getBoolean(S3_SSL_ENABLED, defaults.isS3SslEnabled()); Duration connectTimeout = Duration.valueOf(conf.get(S3_CONNECT_TIMEOUT, defaults.getS3ConnectTimeout().toString())); Duration socketTimeout = Duration.valueOf(conf.get(S3_SOCKET_TIMEOUT, defaults.getS3SocketTimeout().toString())); int maxConnections = conf.getInt(S3_MAX_CONNECTIONS, defaults.getS3MaxConnections()); long minFileSize = conf.getLong(S3_MULTIPART_MIN_FILE_SIZE, defaults.getS3MultipartMinFileSize().toBytes()); long minPartSize = conf.getLong(S3_MULTIPART_MIN_PART_SIZE, defaults.getS3MultipartMinPartSize().toBytes()); this.useInstanceCredentials = conf.getBoolean(S3_USE_INSTANCE_CREDENTIALS, defaults.isS3UseInstanceCredentials()); this.pinS3ClientToCurrentRegion = conf.getBoolean(S3_PIN_CLIENT_TO_CURRENT_REGION, defaults.isPinS3ClientToCurrentRegion()); this.sseEnabled = conf.getBoolean(S3_SSE_ENABLED, defaults.isS3SseEnabled()); this.sseType = PrestoS3SseType.valueOf(conf.get(S3_SSE_TYPE, defaults.getS3SseType().name())); this.sseKmsKeyId = conf.get(S3_SSE_KMS_KEY_ID, defaults.getS3SseKmsKeyId()); String userAgentPrefix = conf.get(S3_USER_AGENT_PREFIX, defaults.getS3UserAgentPrefix()); ClientConfiguration configuration = new ClientConfiguration() .withMaxErrorRetry(maxErrorRetries) .withProtocol(sslEnabled ? Protocol.HTTPS : Protocol.HTTP) .withConnectionTimeout(toIntExact(connectTimeout.toMillis())) .withSocketTimeout(toIntExact(socketTimeout.toMillis())) .withMaxConnections(maxConnections) .withUserAgentPrefix(userAgentPrefix) .withUserAgentSuffix(S3_USER_AGENT_SUFFIX); this.s3 = createAmazonS3Client(uri, conf, configuration); transferConfig.setMultipartUploadThreshold(minFileSize); transferConfig.setMinimumUploadPartSize(minPartSize); } @Override public void close() throws IOException { try { super.close(); } finally { if (s3 instanceof AmazonS3Client) { ((AmazonS3Client) s3).shutdown(); } } } @Override public URI getUri() { return uri; } @Override public Path getWorkingDirectory() { return workingDirectory; } @Override public void setWorkingDirectory(Path path) { workingDirectory = path; } @Override public FileStatus[] listStatus(Path path) throws IOException { STATS.newListStatusCall(); List<LocatedFileStatus> list = new ArrayList<>(); RemoteIterator<LocatedFileStatus> iterator = listLocatedStatus(path); while (iterator.hasNext()) { list.add(iterator.next()); } return toArray(list, LocatedFileStatus.class); } @Override public RemoteIterator<LocatedFileStatus> listLocatedStatus(Path path) { STATS.newListLocatedStatusCall(); return new RemoteIterator<LocatedFileStatus>() { private final Iterator<LocatedFileStatus> iterator = listPrefix(path); @Override public boolean hasNext() throws IOException { try { return iterator.hasNext(); } catch (AmazonClientException e) { throw new IOException(e); } } @Override public LocatedFileStatus next() throws IOException { try { return iterator.next(); } catch (AmazonClientException e) { throw new IOException(e); } } }; } @Override public FileStatus getFileStatus(Path path) throws IOException { if (path.getName().isEmpty()) { // the bucket root requires special handling if (getS3ObjectMetadata(path) != null) { return new FileStatus(0, true, 1, 0, 0, qualifiedPath(path)); } throw new FileNotFoundException("File does not exist: " + path); } ObjectMetadata metadata = getS3ObjectMetadata(path); if (metadata == null) { // check if this path is a directory Iterator<LocatedFileStatus> iterator = listPrefix(path); if (iterator.hasNext()) { return new FileStatus(0, true, 1, 0, 0, qualifiedPath(path)); } throw new FileNotFoundException("File does not exist: " + path); } return new FileStatus( getObjectSize(path, metadata), false, 1, BLOCK_SIZE.toBytes(), lastModifiedTime(metadata), qualifiedPath(path)); } private static long getObjectSize(Path path, ObjectMetadata metadata) throws IOException { Map<String, String> userMetadata = metadata.getUserMetadata(); String length = userMetadata.get(UNENCRYPTED_CONTENT_LENGTH); if (userMetadata.containsKey(SERVER_SIDE_ENCRYPTION) && length == null) { throw new IOException(format("%s header is not set on an encrypted object: %s", UNENCRYPTED_CONTENT_LENGTH, path)); } return (length != null) ? Long.parseLong(length) : metadata.getContentLength(); } @Override public FSDataInputStream open(Path path, int bufferSize) throws IOException { return new FSDataInputStream( new BufferedFSInputStream( new PrestoS3InputStream(s3, uri.getHost(), path, maxAttempts, maxBackoffTime, maxRetryTime), bufferSize)); } @Override public FSDataOutputStream create(Path path, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { if ((!overwrite) && exists(path)) { throw new IOException("File already exists:" + path); } if (!stagingDirectory.exists()) { createDirectories(stagingDirectory.toPath()); } if (!stagingDirectory.isDirectory()) { throw new IOException("Configured staging path is not a directory: " + stagingDirectory); } File tempFile = createTempFile(stagingDirectory.toPath(), "presto-s3-", ".tmp").toFile(); String key = keyFromPath(qualifiedPath(path)); return new FSDataOutputStream( new PrestoS3OutputStream(s3, transferConfig, uri.getHost(), key, tempFile, sseEnabled, sseType, sseKmsKeyId), statistics); } @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) { throw new UnsupportedOperationException("append"); } @Override public boolean rename(Path src, Path dst) throws IOException { boolean srcDirectory; try { srcDirectory = directory(src); } catch (FileNotFoundException e) { return false; } try { if (!directory(dst)) { // cannot copy a file to an existing file return keysEqual(src, dst); } // move source under destination directory dst = new Path(dst, src.getName()); } catch (FileNotFoundException e) { // destination does not exist } if (keysEqual(src, dst)) { return true; } if (srcDirectory) { for (FileStatus file : listStatus(src)) { rename(file.getPath(), new Path(dst, file.getPath().getName())); } deleteObject(keyFromPath(src) + DIRECTORY_SUFFIX); } else { s3.copyObject(uri.getHost(), keyFromPath(src), uri.getHost(), keyFromPath(dst)); delete(src, true); } return true; } @Override public boolean delete(Path path, boolean recursive) throws IOException { try { if (!directory(path)) { return deleteObject(keyFromPath(path)); } } catch (FileNotFoundException e) { return false; } if (!recursive) { throw new IOException("Directory " + path + " is not empty"); } for (FileStatus file : listStatus(path)) { delete(file.getPath(), true); } deleteObject(keyFromPath(path) + DIRECTORY_SUFFIX); return true; } private boolean directory(Path path) throws IOException { return HadoopFileStatus.isDirectory(getFileStatus(path)); } private boolean deleteObject(String key) { try { s3.deleteObject(uri.getHost(), key); return true; } catch (AmazonClientException e) { return false; } } @Override public boolean mkdirs(Path f, FsPermission permission) { // no need to do anything for S3 return true; } private Iterator<LocatedFileStatus> listPrefix(Path path) { String key = keyFromPath(path); if (!key.isEmpty()) { key += PATH_SEPARATOR; } ListObjectsRequest request = new ListObjectsRequest() .withBucketName(uri.getHost()) .withPrefix(key) .withDelimiter(PATH_SEPARATOR); STATS.newListObjectsCall(); Iterator<ObjectListing> listings = new AbstractSequentialIterator<ObjectListing>(s3.listObjects(request)) { @Override protected ObjectListing computeNext(ObjectListing previous) { if (!previous.isTruncated()) { return null; } return s3.listNextBatchOfObjects(previous); } }; return Iterators.concat(Iterators.transform(listings, this::statusFromListing)); } private Iterator<LocatedFileStatus> statusFromListing(ObjectListing listing) { return Iterators.concat( statusFromPrefixes(listing.getCommonPrefixes()), statusFromObjects(listing.getObjectSummaries())); } private Iterator<LocatedFileStatus> statusFromPrefixes(List<String> prefixes) { List<LocatedFileStatus> list = new ArrayList<>(); for (String prefix : prefixes) { Path path = qualifiedPath(new Path(PATH_SEPARATOR + prefix)); FileStatus status = new FileStatus(0, true, 1, 0, 0, path); list.add(createLocatedFileStatus(status)); } return list.iterator(); } private Iterator<LocatedFileStatus> statusFromObjects(List<S3ObjectSummary> objects) { // NOTE: for encrypted objects, S3ObjectSummary.size() used below is NOT correct, // however, to get the correct size we'd need to make an additional request to get // user metadata, and in this case it doesn't matter. return objects.stream() .filter(object -> !object.getKey().endsWith(PATH_SEPARATOR)) .map(object -> new FileStatus( object.getSize(), false, 1, BLOCK_SIZE.toBytes(), object.getLastModified().getTime(), qualifiedPath(new Path(PATH_SEPARATOR + object.getKey())))) .map(this::createLocatedFileStatus) .iterator(); } /** * This exception is for stopping retries for S3 calls that shouldn't be retried. * For example, "Caused by: com.amazonaws.services.s3.model.AmazonS3Exception: Forbidden (Service: Amazon S3; Status Code: 403 ..." */ @VisibleForTesting static class UnrecoverableS3OperationException extends RuntimeException { public UnrecoverableS3OperationException(Path path, Throwable cause) { // append the path info to the message super(format("%s (Path: %s)", cause, path), cause); } } @VisibleForTesting ObjectMetadata getS3ObjectMetadata(Path path) throws IOException { try { return retry() .maxAttempts(maxAttempts) .exponentialBackoff(BACKOFF_MIN_SLEEP, maxBackoffTime, maxRetryTime, 2.0) .stopOn(InterruptedException.class, UnrecoverableS3OperationException.class) .onRetry(STATS::newGetMetadataRetry) .run("getS3ObjectMetadata", () -> { try { STATS.newMetadataCall(); return s3.getObjectMetadata(uri.getHost(), keyFromPath(path)); } catch (RuntimeException e) { STATS.newGetMetadataError(); if (e instanceof AmazonS3Exception) { switch (((AmazonS3Exception) e).getStatusCode()) { case SC_NOT_FOUND: return null; case SC_FORBIDDEN: case SC_BAD_REQUEST: throw new UnrecoverableS3OperationException(path, e); } } throw Throwables.propagate(e); } }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } catch (Exception e) { Throwables.propagateIfInstanceOf(e, IOException.class); throw Throwables.propagate(e); } } private Path qualifiedPath(Path path) { return path.makeQualified(this.uri, getWorkingDirectory()); } private LocatedFileStatus createLocatedFileStatus(FileStatus status) { try { BlockLocation[] fakeLocation = getFileBlockLocations(status, 0, status.getLen()); return new LocatedFileStatus(status, fakeLocation); } catch (IOException e) { throw Throwables.propagate(e); } } private static long lastModifiedTime(ObjectMetadata metadata) { Date date = metadata.getLastModified(); return (date != null) ? date.getTime() : 0; } private static boolean keysEqual(Path p1, Path p2) { return keyFromPath(p1).equals(keyFromPath(p2)); } private static String keyFromPath(Path path) { checkArgument(path.isAbsolute(), "Path is not absolute: %s", path); String key = nullToEmpty(path.toUri().getPath()); if (key.startsWith(PATH_SEPARATOR)) { key = key.substring(PATH_SEPARATOR.length()); } if (key.endsWith(PATH_SEPARATOR)) { key = key.substring(0, key.length() - PATH_SEPARATOR.length()); } return key; } private AmazonS3Client createAmazonS3Client(URI uri, Configuration hadoopConfig, ClientConfiguration clientConfig) { AWSCredentialsProvider credentials = getAwsCredentialsProvider(uri, hadoopConfig); Optional<EncryptionMaterialsProvider> emp = createEncryptionMaterialsProvider(hadoopConfig); AmazonS3Client client; String signerType = hadoopConfig.get(S3_SIGNER_TYPE); if (signerType != null) { clientConfig.withSignerOverride(signerType); } if (emp.isPresent()) { client = new AmazonS3EncryptionClient(credentials, emp.get(), clientConfig, new CryptoConfiguration(), METRIC_COLLECTOR); } else { client = new AmazonS3Client(credentials, clientConfig, METRIC_COLLECTOR); } // use local region when running inside of EC2 if (pinS3ClientToCurrentRegion) { Region region = Regions.getCurrentRegion(); if (region != null) { client.setRegion(region); } } String endpoint = hadoopConfig.get(S3_ENDPOINT); if (endpoint != null) { client.setEndpoint(endpoint); } return client; } private static Optional<EncryptionMaterialsProvider> createEncryptionMaterialsProvider(Configuration hadoopConfig) { String kmsKeyId = hadoopConfig.get(S3_KMS_KEY_ID); if (kmsKeyId != null) { return Optional.of(new KMSEncryptionMaterialsProvider(kmsKeyId)); } String empClassName = hadoopConfig.get(S3_ENCRYPTION_MATERIALS_PROVIDER); if (empClassName == null) { return Optional.empty(); } try { Object instance = Class.forName(empClassName).getConstructor().newInstance(); if (!(instance instanceof EncryptionMaterialsProvider)) { throw new RuntimeException("Invalid encryption materials provider class: " + instance.getClass().getName()); } EncryptionMaterialsProvider emp = (EncryptionMaterialsProvider) instance; if (emp instanceof Configurable) { ((Configurable) emp).setConf(hadoopConfig); } return Optional.of(emp); } catch (ReflectiveOperationException e) { throw new RuntimeException("Unable to load or create S3 encryption materials provider: " + empClassName, e); } } private AWSCredentialsProvider getAwsCredentialsProvider(URI uri, Configuration conf) { Optional<AWSCredentials> credentials = getAwsCredentials(uri, conf); if (credentials.isPresent()) { return new AWSStaticCredentialsProvider(credentials.get()); } if (useInstanceCredentials) { return new InstanceProfileCredentialsProvider(); } String providerClass = conf.get(S3_CREDENTIALS_PROVIDER); if (!isNullOrEmpty(providerClass)) { return getCustomAWSCredentialsProvider(uri, conf, providerClass); } throw new RuntimeException("S3 credentials not configured"); } private static AWSCredentialsProvider getCustomAWSCredentialsProvider(URI uri, Configuration conf, String providerClass) { try { log.debug("Using AWS credential provider %s for URI %s", providerClass, uri); return conf.getClassByName(providerClass) .asSubclass(AWSCredentialsProvider.class) .getConstructor(URI.class, Configuration.class) .newInstance(uri, conf); } catch (ReflectiveOperationException e) { throw new RuntimeException(format("Error creating an instance of %s for URI %s", providerClass, uri), e); } } private static Optional<AWSCredentials> getAwsCredentials(URI uri, Configuration conf) { String accessKey = conf.get(S3_ACCESS_KEY); String secretKey = conf.get(S3_SECRET_KEY); String userInfo = uri.getUserInfo(); if (userInfo != null) { int index = userInfo.indexOf(':'); if (index < 0) { accessKey = userInfo; } else { accessKey = userInfo.substring(0, index); secretKey = userInfo.substring(index + 1); } } if (isNullOrEmpty(accessKey) || isNullOrEmpty(secretKey)) { return Optional.empty(); } return Optional.of(new BasicAWSCredentials(accessKey, secretKey)); } private static class PrestoS3InputStream extends FSInputStream { private final AmazonS3 s3; private final String host; private final Path path; private final int maxAttempts; private final Duration maxBackoffTime; private final Duration maxRetryTime; private boolean closed; private InputStream in; private long streamPosition; private long nextReadPosition; public PrestoS3InputStream(AmazonS3 s3, String host, Path path, int maxAttempts, Duration maxBackoffTime, Duration maxRetryTime) { this.s3 = requireNonNull(s3, "s3 is null"); this.host = requireNonNull(host, "host is null"); this.path = requireNonNull(path, "path is null"); checkArgument(maxAttempts >= 0, "maxAttempts cannot be negative"); this.maxAttempts = maxAttempts; this.maxBackoffTime = requireNonNull(maxBackoffTime, "maxBackoffTime is null"); this.maxRetryTime = requireNonNull(maxRetryTime, "maxRetryTime is null"); } @Override public void close() { closed = true; closeStream(); } @Override public void seek(long pos) { checkState(!closed, "already closed"); checkArgument(pos >= 0, "position is negative: %s", pos); // this allows a seek beyond the end of the stream but the next read will fail nextReadPosition = pos; } @Override public long getPos() { return nextReadPosition; } @Override public int read() { // This stream is wrapped with BufferedInputStream, so this method should never be called throw new UnsupportedOperationException(); } @Override public int read(byte[] buffer, int offset, int length) throws IOException { try { int bytesRead = retry() .maxAttempts(maxAttempts) .exponentialBackoff(BACKOFF_MIN_SLEEP, maxBackoffTime, maxRetryTime, 2.0) .stopOn(InterruptedException.class, UnrecoverableS3OperationException.class, AbortedException.class) .onRetry(STATS::newReadRetry) .run("readStream", () -> { seekStream(); try { return in.read(buffer, offset, length); } catch (Exception e) { STATS.newReadError(e); closeStream(); throw e; } }); if (bytesRead != -1) { streamPosition += bytesRead; nextReadPosition += bytesRead; } return bytesRead; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } catch (Exception e) { Throwables.propagateIfInstanceOf(e, IOException.class); throw Throwables.propagate(e); } } @Override public boolean seekToNewSource(long targetPos) { return false; } private void seekStream() throws IOException { if ((in != null) && (nextReadPosition == streamPosition)) { // already at specified position return; } if ((in != null) && (nextReadPosition > streamPosition)) { // seeking forwards long skip = nextReadPosition - streamPosition; if (skip <= max(in.available(), MAX_SKIP_SIZE.toBytes())) { // already buffered or seek is small enough try { if (in.skip(skip) == skip) { streamPosition = nextReadPosition; return; } } catch (IOException ignored) { // will retry by re-opening the stream } } } // close the stream and open at desired position streamPosition = nextReadPosition; closeStream(); openStream(); } private void openStream() throws IOException { if (in == null) { in = openStream(path, nextReadPosition); streamPosition = nextReadPosition; STATS.connectionOpened(); } } private InputStream openStream(Path path, long start) throws IOException { try { return retry() .maxAttempts(maxAttempts) .exponentialBackoff(BACKOFF_MIN_SLEEP, maxBackoffTime, maxRetryTime, 2.0) .stopOn(InterruptedException.class, UnrecoverableS3OperationException.class) .onRetry(STATS::newGetObjectRetry) .run("getS3Object", () -> { try { GetObjectRequest request = new GetObjectRequest(host, keyFromPath(path)).withRange(start, Long.MAX_VALUE); return s3.getObject(request).getObjectContent(); } catch (RuntimeException e) { STATS.newGetObjectError(); if (e instanceof AmazonS3Exception) { switch (((AmazonS3Exception) e).getStatusCode()) { case SC_REQUESTED_RANGE_NOT_SATISFIABLE: // ignore request for start past end of object return new ByteArrayInputStream(new byte[0]); case SC_FORBIDDEN: case SC_NOT_FOUND: case SC_BAD_REQUEST: throw new UnrecoverableS3OperationException(path, e); } } throw Throwables.propagate(e); } }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } catch (Exception e) { Throwables.propagateIfInstanceOf(e, IOException.class); throw Throwables.propagate(e); } } private void closeStream() { if (in != null) { try { if (in instanceof S3ObjectInputStream) { ((S3ObjectInputStream) in).abort(); } else { in.close(); } } catch (IOException | AbortedException ignored) { // thrown if the current thread is in the interrupted state } in = null; STATS.connectionReleased(); } } } private static class PrestoS3OutputStream extends FilterOutputStream { private final TransferManager transferManager; private final String host; private final String key; private final File tempFile; private final boolean sseEnabled; private final PrestoS3SseType sseType; private final String sseKmsKeyId; private boolean closed; public PrestoS3OutputStream(AmazonS3 s3, TransferManagerConfiguration config, String host, String key, File tempFile, boolean sseEnabled, PrestoS3SseType sseType, String sseKmsKeyId) throws IOException { super(new BufferedOutputStream(new FileOutputStream(requireNonNull(tempFile, "tempFile is null")))); transferManager = new TransferManager(requireNonNull(s3, "s3 is null")); transferManager.setConfiguration(requireNonNull(config, "config is null")); this.host = requireNonNull(host, "host is null"); this.key = requireNonNull(key, "key is null"); this.tempFile = tempFile; this.sseEnabled = sseEnabled; this.sseType = requireNonNull(sseType, "sseType is null"); this.sseKmsKeyId = sseKmsKeyId; log.debug("OutputStream for key '%s' using file: %s", key, tempFile); } @Override public void close() throws IOException { if (closed) { return; } closed = true; try { super.close(); uploadObject(); } finally { if (!tempFile.delete()) { log.warn("Could not delete temporary file: %s", tempFile); } // close transfer manager but keep underlying S3 client open transferManager.shutdownNow(false); } } private void uploadObject() throws IOException { try { log.debug("Starting upload for host: %s, key: %s, file: %s, size: %s", host, key, tempFile, tempFile.length()); STATS.uploadStarted(); PutObjectRequest request = new PutObjectRequest(host, key, tempFile); if (sseEnabled) { switch (sseType) { case KMS: if (sseKmsKeyId != null) { request.withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams(sseKmsKeyId)); } else { request.withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams()); } break; case S3: ObjectMetadata metadata = new ObjectMetadata(); metadata.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); request.setMetadata(metadata); break; } } Upload upload = transferManager.upload(request); if (log.isDebugEnabled()) { upload.addProgressListener(createProgressListener(upload)); } upload.waitForCompletion(); STATS.uploadSuccessful(); log.debug("Completed upload for host: %s, key: %s", host, key); } catch (AmazonClientException e) { STATS.uploadFailed(); throw new IOException(e); } catch (InterruptedException e) { STATS.uploadFailed(); Thread.currentThread().interrupt(); throw new InterruptedIOException(); } } private ProgressListener createProgressListener(Transfer transfer) { return new ProgressListener() { private ProgressEventType previousType; private double previousTransferred; @Override public synchronized void progressChanged(ProgressEvent progressEvent) { ProgressEventType eventType = progressEvent.getEventType(); if (previousType != eventType) { log.debug("Upload progress event (%s/%s): %s", host, key, eventType); previousType = eventType; } double transferred = transfer.getProgress().getPercentTransferred(); if (transferred >= (previousTransferred + 10.0)) { log.debug("Upload percentage (%s/%s): %.0f%%", host, key, transferred); previousTransferred = transferred; } } }; } } @VisibleForTesting AmazonS3 getS3Client() { return s3; } @VisibleForTesting void setS3Client(AmazonS3 client) { s3 = client; } }
presto-hive/src/main/java/com/facebook/presto/hive/PrestoS3FileSystem.java
/* * 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.facebook.presto.hive; import com.amazonaws.AbortedException; import com.amazonaws.AmazonClientException; import com.amazonaws.ClientConfiguration; import com.amazonaws.Protocol; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.auth.InstanceProfileCredentialsProvider; import com.amazonaws.event.ProgressEvent; import com.amazonaws.event.ProgressEventType; import com.amazonaws.event.ProgressListener; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.AmazonS3EncryptionClient; import com.amazonaws.services.s3.model.AmazonS3Exception; import com.amazonaws.services.s3.model.CryptoConfiguration; import com.amazonaws.services.s3.model.EncryptionMaterialsProvider; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.KMSEncryptionMaterialsProvider; import com.amazonaws.services.s3.model.ListObjectsRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.S3ObjectInputStream; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.amazonaws.services.s3.model.SSEAwsKeyManagementParams; import com.amazonaws.services.s3.transfer.Transfer; import com.amazonaws.services.s3.transfer.TransferManager; import com.amazonaws.services.s3.transfer.TransferManagerConfiguration; import com.amazonaws.services.s3.transfer.Upload; import com.facebook.presto.hadoop.HadoopFileStatus; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Throwables; import com.google.common.collect.AbstractSequentialIterator; import com.google.common.collect.Iterators; import io.airlift.log.Logger; import io.airlift.units.DataSize; import io.airlift.units.Duration; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.BlockLocation; import org.apache.hadoop.fs.BufferedFSInputStream; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FSInputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocatedFileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RemoteIterator; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.util.Progressable; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.net.URI; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Optional; import static com.amazonaws.services.s3.Headers.UNENCRYPTED_CONTENT_LENGTH; import static com.facebook.presto.hive.RetryDriver.retry; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.base.Strings.nullToEmpty; import static com.google.common.collect.Iterables.toArray; import static io.airlift.units.DataSize.Unit.MEGABYTE; import static java.lang.Math.max; import static java.lang.Math.toIntExact; import static java.lang.String.format; import static java.nio.file.Files.createDirectories; import static java.nio.file.Files.createTempFile; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.http.HttpStatus.SC_BAD_REQUEST; import static org.apache.http.HttpStatus.SC_FORBIDDEN; import static org.apache.http.HttpStatus.SC_NOT_FOUND; import static org.apache.http.HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE; public class PrestoS3FileSystem extends FileSystem { private static final Logger log = Logger.get(PrestoS3FileSystem.class); private static final PrestoS3FileSystemStats STATS = new PrestoS3FileSystemStats(); private static final PrestoS3FileSystemMetricCollector METRIC_COLLECTOR = new PrestoS3FileSystemMetricCollector(STATS); public static PrestoS3FileSystemStats getFileSystemStats() { return STATS; } private static final String DIRECTORY_SUFFIX = "_$folder$"; public static final String S3_ACCESS_KEY = "presto.s3.access-key"; public static final String S3_SECRET_KEY = "presto.s3.secret-key"; public static final String S3_ENDPOINT = "presto.s3.endpoint"; public static final String S3_SIGNER_TYPE = "presto.s3.signer-type"; public static final String S3_SSL_ENABLED = "presto.s3.ssl.enabled"; public static final String S3_MAX_ERROR_RETRIES = "presto.s3.max-error-retries"; public static final String S3_MAX_CLIENT_RETRIES = "presto.s3.max-client-retries"; public static final String S3_MAX_BACKOFF_TIME = "presto.s3.max-backoff-time"; public static final String S3_MAX_RETRY_TIME = "presto.s3.max-retry-time"; public static final String S3_CONNECT_TIMEOUT = "presto.s3.connect-timeout"; public static final String S3_SOCKET_TIMEOUT = "presto.s3.socket-timeout"; public static final String S3_MAX_CONNECTIONS = "presto.s3.max-connections"; public static final String S3_STAGING_DIRECTORY = "presto.s3.staging-directory"; public static final String S3_MULTIPART_MIN_FILE_SIZE = "presto.s3.multipart.min-file-size"; public static final String S3_MULTIPART_MIN_PART_SIZE = "presto.s3.multipart.min-part-size"; public static final String S3_USE_INSTANCE_CREDENTIALS = "presto.s3.use-instance-credentials"; public static final String S3_PIN_CLIENT_TO_CURRENT_REGION = "presto.s3.pin-client-to-current-region"; public static final String S3_ENCRYPTION_MATERIALS_PROVIDER = "presto.s3.encryption-materials-provider"; public static final String S3_KMS_KEY_ID = "presto.s3.kms-key-id"; public static final String S3_SSE_KMS_KEY_ID = "presto.s3.sse.kms-key-id"; public static final String S3_SSE_ENABLED = "presto.s3.sse.enabled"; public static final String S3_SSE_TYPE = "presto.s3.sse.type"; public static final String S3_CREDENTIALS_PROVIDER = "presto.s3.credentials-provider"; public static final String S3_USER_AGENT_PREFIX = "presto.s3.user-agent-prefix"; public static final String S3_USER_AGENT_SUFFIX = "presto"; private static final DataSize BLOCK_SIZE = new DataSize(32, MEGABYTE); private static final DataSize MAX_SKIP_SIZE = new DataSize(1, MEGABYTE); private static final String PATH_SEPARATOR = "/"; private static final Duration BACKOFF_MIN_SLEEP = new Duration(1, SECONDS); private final TransferManagerConfiguration transferConfig = new TransferManagerConfiguration(); private URI uri; private Path workingDirectory; private AmazonS3 s3; private File stagingDirectory; private int maxAttempts; private Duration maxBackoffTime; private Duration maxRetryTime; private boolean useInstanceCredentials; private boolean pinS3ClientToCurrentRegion; private boolean sseEnabled; private PrestoS3SseType sseType; private String sseKmsKeyId; @Override public void initialize(URI uri, Configuration conf) throws IOException { requireNonNull(uri, "uri is null"); requireNonNull(conf, "conf is null"); super.initialize(uri, conf); setConf(conf); this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority()); this.workingDirectory = new Path(PATH_SEPARATOR).makeQualified(this.uri, new Path(PATH_SEPARATOR)); HiveS3Config defaults = new HiveS3Config(); this.stagingDirectory = new File(conf.get(S3_STAGING_DIRECTORY, defaults.getS3StagingDirectory().toString())); this.maxAttempts = conf.getInt(S3_MAX_CLIENT_RETRIES, defaults.getS3MaxClientRetries()) + 1; this.maxBackoffTime = Duration.valueOf(conf.get(S3_MAX_BACKOFF_TIME, defaults.getS3MaxBackoffTime().toString())); this.maxRetryTime = Duration.valueOf(conf.get(S3_MAX_RETRY_TIME, defaults.getS3MaxRetryTime().toString())); int maxErrorRetries = conf.getInt(S3_MAX_ERROR_RETRIES, defaults.getS3MaxErrorRetries()); boolean sslEnabled = conf.getBoolean(S3_SSL_ENABLED, defaults.isS3SslEnabled()); Duration connectTimeout = Duration.valueOf(conf.get(S3_CONNECT_TIMEOUT, defaults.getS3ConnectTimeout().toString())); Duration socketTimeout = Duration.valueOf(conf.get(S3_SOCKET_TIMEOUT, defaults.getS3SocketTimeout().toString())); int maxConnections = conf.getInt(S3_MAX_CONNECTIONS, defaults.getS3MaxConnections()); long minFileSize = conf.getLong(S3_MULTIPART_MIN_FILE_SIZE, defaults.getS3MultipartMinFileSize().toBytes()); long minPartSize = conf.getLong(S3_MULTIPART_MIN_PART_SIZE, defaults.getS3MultipartMinPartSize().toBytes()); this.useInstanceCredentials = conf.getBoolean(S3_USE_INSTANCE_CREDENTIALS, defaults.isS3UseInstanceCredentials()); this.pinS3ClientToCurrentRegion = conf.getBoolean(S3_PIN_CLIENT_TO_CURRENT_REGION, defaults.isPinS3ClientToCurrentRegion()); this.sseEnabled = conf.getBoolean(S3_SSE_ENABLED, defaults.isS3SseEnabled()); this.sseType = PrestoS3SseType.valueOf(conf.get(S3_SSE_TYPE, defaults.getS3SseType().name())); this.sseKmsKeyId = conf.get(S3_SSE_KMS_KEY_ID, defaults.getS3SseKmsKeyId()); String userAgentPrefix = conf.get(S3_USER_AGENT_PREFIX, defaults.getS3UserAgentPrefix()); ClientConfiguration configuration = new ClientConfiguration() .withMaxErrorRetry(maxErrorRetries) .withProtocol(sslEnabled ? Protocol.HTTPS : Protocol.HTTP) .withConnectionTimeout(toIntExact(connectTimeout.toMillis())) .withSocketTimeout(toIntExact(socketTimeout.toMillis())) .withMaxConnections(maxConnections) .withUserAgentPrefix(userAgentPrefix) .withUserAgentSuffix(S3_USER_AGENT_SUFFIX); this.s3 = createAmazonS3Client(uri, conf, configuration); transferConfig.setMultipartUploadThreshold(minFileSize); transferConfig.setMinimumUploadPartSize(minPartSize); } @Override public void close() throws IOException { try { super.close(); } finally { if (s3 instanceof AmazonS3Client) { ((AmazonS3Client) s3).shutdown(); } } } @Override public URI getUri() { return uri; } @Override public Path getWorkingDirectory() { return workingDirectory; } @Override public void setWorkingDirectory(Path path) { workingDirectory = path; } @Override public FileStatus[] listStatus(Path path) throws IOException { STATS.newListStatusCall(); List<LocatedFileStatus> list = new ArrayList<>(); RemoteIterator<LocatedFileStatus> iterator = listLocatedStatus(path); while (iterator.hasNext()) { list.add(iterator.next()); } return toArray(list, LocatedFileStatus.class); } @Override public RemoteIterator<LocatedFileStatus> listLocatedStatus(Path path) { STATS.newListLocatedStatusCall(); return new RemoteIterator<LocatedFileStatus>() { private final Iterator<LocatedFileStatus> iterator = listPrefix(path); @Override public boolean hasNext() throws IOException { try { return iterator.hasNext(); } catch (AmazonClientException e) { throw new IOException(e); } } @Override public LocatedFileStatus next() throws IOException { try { return iterator.next(); } catch (AmazonClientException e) { throw new IOException(e); } } }; } @Override public FileStatus getFileStatus(Path path) throws IOException { if (path.getName().isEmpty()) { // the bucket root requires special handling if (getS3ObjectMetadata(path) != null) { return new FileStatus(0, true, 1, 0, 0, qualifiedPath(path)); } throw new FileNotFoundException("File does not exist: " + path); } ObjectMetadata metadata = getS3ObjectMetadata(path); if (metadata == null) { // check if this path is a directory Iterator<LocatedFileStatus> iterator = listPrefix(path); if (iterator.hasNext()) { return new FileStatus(0, true, 1, 0, 0, qualifiedPath(path)); } throw new FileNotFoundException("File does not exist: " + path); } return new FileStatus( getObjectSize(metadata), false, 1, BLOCK_SIZE.toBytes(), lastModifiedTime(metadata), qualifiedPath(path)); } private static long getObjectSize(ObjectMetadata metadata) { String length = metadata.getUserMetadata().get(UNENCRYPTED_CONTENT_LENGTH); return (length != null) ? Long.parseLong(length) : metadata.getContentLength(); } @Override public FSDataInputStream open(Path path, int bufferSize) throws IOException { return new FSDataInputStream( new BufferedFSInputStream( new PrestoS3InputStream(s3, uri.getHost(), path, maxAttempts, maxBackoffTime, maxRetryTime), bufferSize)); } @Override public FSDataOutputStream create(Path path, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { if ((!overwrite) && exists(path)) { throw new IOException("File already exists:" + path); } if (!stagingDirectory.exists()) { createDirectories(stagingDirectory.toPath()); } if (!stagingDirectory.isDirectory()) { throw new IOException("Configured staging path is not a directory: " + stagingDirectory); } File tempFile = createTempFile(stagingDirectory.toPath(), "presto-s3-", ".tmp").toFile(); String key = keyFromPath(qualifiedPath(path)); return new FSDataOutputStream( new PrestoS3OutputStream(s3, transferConfig, uri.getHost(), key, tempFile, sseEnabled, sseType, sseKmsKeyId), statistics); } @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) { throw new UnsupportedOperationException("append"); } @Override public boolean rename(Path src, Path dst) throws IOException { boolean srcDirectory; try { srcDirectory = directory(src); } catch (FileNotFoundException e) { return false; } try { if (!directory(dst)) { // cannot copy a file to an existing file return keysEqual(src, dst); } // move source under destination directory dst = new Path(dst, src.getName()); } catch (FileNotFoundException e) { // destination does not exist } if (keysEqual(src, dst)) { return true; } if (srcDirectory) { for (FileStatus file : listStatus(src)) { rename(file.getPath(), new Path(dst, file.getPath().getName())); } deleteObject(keyFromPath(src) + DIRECTORY_SUFFIX); } else { s3.copyObject(uri.getHost(), keyFromPath(src), uri.getHost(), keyFromPath(dst)); delete(src, true); } return true; } @Override public boolean delete(Path path, boolean recursive) throws IOException { try { if (!directory(path)) { return deleteObject(keyFromPath(path)); } } catch (FileNotFoundException e) { return false; } if (!recursive) { throw new IOException("Directory " + path + " is not empty"); } for (FileStatus file : listStatus(path)) { delete(file.getPath(), true); } deleteObject(keyFromPath(path) + DIRECTORY_SUFFIX); return true; } private boolean directory(Path path) throws IOException { return HadoopFileStatus.isDirectory(getFileStatus(path)); } private boolean deleteObject(String key) { try { s3.deleteObject(uri.getHost(), key); return true; } catch (AmazonClientException e) { return false; } } @Override public boolean mkdirs(Path f, FsPermission permission) { // no need to do anything for S3 return true; } private Iterator<LocatedFileStatus> listPrefix(Path path) { String key = keyFromPath(path); if (!key.isEmpty()) { key += PATH_SEPARATOR; } ListObjectsRequest request = new ListObjectsRequest() .withBucketName(uri.getHost()) .withPrefix(key) .withDelimiter(PATH_SEPARATOR); STATS.newListObjectsCall(); Iterator<ObjectListing> listings = new AbstractSequentialIterator<ObjectListing>(s3.listObjects(request)) { @Override protected ObjectListing computeNext(ObjectListing previous) { if (!previous.isTruncated()) { return null; } return s3.listNextBatchOfObjects(previous); } }; return Iterators.concat(Iterators.transform(listings, this::statusFromListing)); } private Iterator<LocatedFileStatus> statusFromListing(ObjectListing listing) { return Iterators.concat( statusFromPrefixes(listing.getCommonPrefixes()), statusFromObjects(listing.getObjectSummaries())); } private Iterator<LocatedFileStatus> statusFromPrefixes(List<String> prefixes) { List<LocatedFileStatus> list = new ArrayList<>(); for (String prefix : prefixes) { Path path = qualifiedPath(new Path(PATH_SEPARATOR + prefix)); FileStatus status = new FileStatus(0, true, 1, 0, 0, path); list.add(createLocatedFileStatus(status)); } return list.iterator(); } private Iterator<LocatedFileStatus> statusFromObjects(List<S3ObjectSummary> objects) { // NOTE: for encrypted objects, S3ObjectSummary.size() used below is NOT correct, // however, to get the correct size we'd need to make an additional request to get // user metadata, and in this case it doesn't matter. return objects.stream() .filter(object -> !object.getKey().endsWith(PATH_SEPARATOR)) .map(object -> new FileStatus( object.getSize(), false, 1, BLOCK_SIZE.toBytes(), object.getLastModified().getTime(), qualifiedPath(new Path(PATH_SEPARATOR + object.getKey())))) .map(this::createLocatedFileStatus) .iterator(); } /** * This exception is for stopping retries for S3 calls that shouldn't be retried. * For example, "Caused by: com.amazonaws.services.s3.model.AmazonS3Exception: Forbidden (Service: Amazon S3; Status Code: 403 ..." */ @VisibleForTesting static class UnrecoverableS3OperationException extends RuntimeException { public UnrecoverableS3OperationException(Path path, Throwable cause) { // append the path info to the message super(format("%s (Path: %s)", cause, path), cause); } } @VisibleForTesting ObjectMetadata getS3ObjectMetadata(Path path) throws IOException { try { return retry() .maxAttempts(maxAttempts) .exponentialBackoff(BACKOFF_MIN_SLEEP, maxBackoffTime, maxRetryTime, 2.0) .stopOn(InterruptedException.class, UnrecoverableS3OperationException.class) .onRetry(STATS::newGetMetadataRetry) .run("getS3ObjectMetadata", () -> { try { STATS.newMetadataCall(); return s3.getObjectMetadata(uri.getHost(), keyFromPath(path)); } catch (RuntimeException e) { STATS.newGetMetadataError(); if (e instanceof AmazonS3Exception) { switch (((AmazonS3Exception) e).getStatusCode()) { case SC_NOT_FOUND: return null; case SC_FORBIDDEN: case SC_BAD_REQUEST: throw new UnrecoverableS3OperationException(path, e); } } throw Throwables.propagate(e); } }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } catch (Exception e) { Throwables.propagateIfInstanceOf(e, IOException.class); throw Throwables.propagate(e); } } private Path qualifiedPath(Path path) { return path.makeQualified(this.uri, getWorkingDirectory()); } private LocatedFileStatus createLocatedFileStatus(FileStatus status) { try { BlockLocation[] fakeLocation = getFileBlockLocations(status, 0, status.getLen()); return new LocatedFileStatus(status, fakeLocation); } catch (IOException e) { throw Throwables.propagate(e); } } private static long lastModifiedTime(ObjectMetadata metadata) { Date date = metadata.getLastModified(); return (date != null) ? date.getTime() : 0; } private static boolean keysEqual(Path p1, Path p2) { return keyFromPath(p1).equals(keyFromPath(p2)); } private static String keyFromPath(Path path) { checkArgument(path.isAbsolute(), "Path is not absolute: %s", path); String key = nullToEmpty(path.toUri().getPath()); if (key.startsWith(PATH_SEPARATOR)) { key = key.substring(PATH_SEPARATOR.length()); } if (key.endsWith(PATH_SEPARATOR)) { key = key.substring(0, key.length() - PATH_SEPARATOR.length()); } return key; } private AmazonS3Client createAmazonS3Client(URI uri, Configuration hadoopConfig, ClientConfiguration clientConfig) { AWSCredentialsProvider credentials = getAwsCredentialsProvider(uri, hadoopConfig); Optional<EncryptionMaterialsProvider> emp = createEncryptionMaterialsProvider(hadoopConfig); AmazonS3Client client; String signerType = hadoopConfig.get(S3_SIGNER_TYPE); if (signerType != null) { clientConfig.withSignerOverride(signerType); } if (emp.isPresent()) { client = new AmazonS3EncryptionClient(credentials, emp.get(), clientConfig, new CryptoConfiguration(), METRIC_COLLECTOR); } else { client = new AmazonS3Client(credentials, clientConfig, METRIC_COLLECTOR); } // use local region when running inside of EC2 if (pinS3ClientToCurrentRegion) { Region region = Regions.getCurrentRegion(); if (region != null) { client.setRegion(region); } } String endpoint = hadoopConfig.get(S3_ENDPOINT); if (endpoint != null) { client.setEndpoint(endpoint); } return client; } private static Optional<EncryptionMaterialsProvider> createEncryptionMaterialsProvider(Configuration hadoopConfig) { String kmsKeyId = hadoopConfig.get(S3_KMS_KEY_ID); if (kmsKeyId != null) { return Optional.of(new KMSEncryptionMaterialsProvider(kmsKeyId)); } String empClassName = hadoopConfig.get(S3_ENCRYPTION_MATERIALS_PROVIDER); if (empClassName == null) { return Optional.empty(); } try { Object instance = Class.forName(empClassName).getConstructor().newInstance(); if (!(instance instanceof EncryptionMaterialsProvider)) { throw new RuntimeException("Invalid encryption materials provider class: " + instance.getClass().getName()); } EncryptionMaterialsProvider emp = (EncryptionMaterialsProvider) instance; if (emp instanceof Configurable) { ((Configurable) emp).setConf(hadoopConfig); } return Optional.of(emp); } catch (ReflectiveOperationException e) { throw new RuntimeException("Unable to load or create S3 encryption materials provider: " + empClassName, e); } } private AWSCredentialsProvider getAwsCredentialsProvider(URI uri, Configuration conf) { Optional<AWSCredentials> credentials = getAwsCredentials(uri, conf); if (credentials.isPresent()) { return new AWSStaticCredentialsProvider(credentials.get()); } if (useInstanceCredentials) { return new InstanceProfileCredentialsProvider(); } String providerClass = conf.get(S3_CREDENTIALS_PROVIDER); if (!isNullOrEmpty(providerClass)) { return getCustomAWSCredentialsProvider(uri, conf, providerClass); } throw new RuntimeException("S3 credentials not configured"); } private static AWSCredentialsProvider getCustomAWSCredentialsProvider(URI uri, Configuration conf, String providerClass) { try { log.debug("Using AWS credential provider %s for URI %s", providerClass, uri); return conf.getClassByName(providerClass) .asSubclass(AWSCredentialsProvider.class) .getConstructor(URI.class, Configuration.class) .newInstance(uri, conf); } catch (ReflectiveOperationException e) { throw new RuntimeException(format("Error creating an instance of %s for URI %s", providerClass, uri), e); } } private static Optional<AWSCredentials> getAwsCredentials(URI uri, Configuration conf) { String accessKey = conf.get(S3_ACCESS_KEY); String secretKey = conf.get(S3_SECRET_KEY); String userInfo = uri.getUserInfo(); if (userInfo != null) { int index = userInfo.indexOf(':'); if (index < 0) { accessKey = userInfo; } else { accessKey = userInfo.substring(0, index); secretKey = userInfo.substring(index + 1); } } if (isNullOrEmpty(accessKey) || isNullOrEmpty(secretKey)) { return Optional.empty(); } return Optional.of(new BasicAWSCredentials(accessKey, secretKey)); } private static class PrestoS3InputStream extends FSInputStream { private final AmazonS3 s3; private final String host; private final Path path; private final int maxAttempts; private final Duration maxBackoffTime; private final Duration maxRetryTime; private boolean closed; private InputStream in; private long streamPosition; private long nextReadPosition; public PrestoS3InputStream(AmazonS3 s3, String host, Path path, int maxAttempts, Duration maxBackoffTime, Duration maxRetryTime) { this.s3 = requireNonNull(s3, "s3 is null"); this.host = requireNonNull(host, "host is null"); this.path = requireNonNull(path, "path is null"); checkArgument(maxAttempts >= 0, "maxAttempts cannot be negative"); this.maxAttempts = maxAttempts; this.maxBackoffTime = requireNonNull(maxBackoffTime, "maxBackoffTime is null"); this.maxRetryTime = requireNonNull(maxRetryTime, "maxRetryTime is null"); } @Override public void close() { closed = true; closeStream(); } @Override public void seek(long pos) { checkState(!closed, "already closed"); checkArgument(pos >= 0, "position is negative: %s", pos); // this allows a seek beyond the end of the stream but the next read will fail nextReadPosition = pos; } @Override public long getPos() { return nextReadPosition; } @Override public int read() { // This stream is wrapped with BufferedInputStream, so this method should never be called throw new UnsupportedOperationException(); } @Override public int read(byte[] buffer, int offset, int length) throws IOException { try { int bytesRead = retry() .maxAttempts(maxAttempts) .exponentialBackoff(BACKOFF_MIN_SLEEP, maxBackoffTime, maxRetryTime, 2.0) .stopOn(InterruptedException.class, UnrecoverableS3OperationException.class, AbortedException.class) .onRetry(STATS::newReadRetry) .run("readStream", () -> { seekStream(); try { return in.read(buffer, offset, length); } catch (Exception e) { STATS.newReadError(e); closeStream(); throw e; } }); if (bytesRead != -1) { streamPosition += bytesRead; nextReadPosition += bytesRead; } return bytesRead; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } catch (Exception e) { Throwables.propagateIfInstanceOf(e, IOException.class); throw Throwables.propagate(e); } } @Override public boolean seekToNewSource(long targetPos) { return false; } private void seekStream() throws IOException { if ((in != null) && (nextReadPosition == streamPosition)) { // already at specified position return; } if ((in != null) && (nextReadPosition > streamPosition)) { // seeking forwards long skip = nextReadPosition - streamPosition; if (skip <= max(in.available(), MAX_SKIP_SIZE.toBytes())) { // already buffered or seek is small enough try { if (in.skip(skip) == skip) { streamPosition = nextReadPosition; return; } } catch (IOException ignored) { // will retry by re-opening the stream } } } // close the stream and open at desired position streamPosition = nextReadPosition; closeStream(); openStream(); } private void openStream() throws IOException { if (in == null) { in = openStream(path, nextReadPosition); streamPosition = nextReadPosition; STATS.connectionOpened(); } } private InputStream openStream(Path path, long start) throws IOException { try { return retry() .maxAttempts(maxAttempts) .exponentialBackoff(BACKOFF_MIN_SLEEP, maxBackoffTime, maxRetryTime, 2.0) .stopOn(InterruptedException.class, UnrecoverableS3OperationException.class) .onRetry(STATS::newGetObjectRetry) .run("getS3Object", () -> { try { GetObjectRequest request = new GetObjectRequest(host, keyFromPath(path)).withRange(start, Long.MAX_VALUE); return s3.getObject(request).getObjectContent(); } catch (RuntimeException e) { STATS.newGetObjectError(); if (e instanceof AmazonS3Exception) { switch (((AmazonS3Exception) e).getStatusCode()) { case SC_REQUESTED_RANGE_NOT_SATISFIABLE: // ignore request for start past end of object return new ByteArrayInputStream(new byte[0]); case SC_FORBIDDEN: case SC_NOT_FOUND: case SC_BAD_REQUEST: throw new UnrecoverableS3OperationException(path, e); } } throw Throwables.propagate(e); } }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } catch (Exception e) { Throwables.propagateIfInstanceOf(e, IOException.class); throw Throwables.propagate(e); } } private void closeStream() { if (in != null) { try { if (in instanceof S3ObjectInputStream) { ((S3ObjectInputStream) in).abort(); } else { in.close(); } } catch (IOException | AbortedException ignored) { // thrown if the current thread is in the interrupted state } in = null; STATS.connectionReleased(); } } } private static class PrestoS3OutputStream extends FilterOutputStream { private final TransferManager transferManager; private final String host; private final String key; private final File tempFile; private final boolean sseEnabled; private final PrestoS3SseType sseType; private final String sseKmsKeyId; private boolean closed; public PrestoS3OutputStream(AmazonS3 s3, TransferManagerConfiguration config, String host, String key, File tempFile, boolean sseEnabled, PrestoS3SseType sseType, String sseKmsKeyId) throws IOException { super(new BufferedOutputStream(new FileOutputStream(requireNonNull(tempFile, "tempFile is null")))); transferManager = new TransferManager(requireNonNull(s3, "s3 is null")); transferManager.setConfiguration(requireNonNull(config, "config is null")); this.host = requireNonNull(host, "host is null"); this.key = requireNonNull(key, "key is null"); this.tempFile = tempFile; this.sseEnabled = sseEnabled; this.sseType = requireNonNull(sseType, "sseType is null"); this.sseKmsKeyId = sseKmsKeyId; log.debug("OutputStream for key '%s' using file: %s", key, tempFile); } @Override public void close() throws IOException { if (closed) { return; } closed = true; try { super.close(); uploadObject(); } finally { if (!tempFile.delete()) { log.warn("Could not delete temporary file: %s", tempFile); } // close transfer manager but keep underlying S3 client open transferManager.shutdownNow(false); } } private void uploadObject() throws IOException { try { log.debug("Starting upload for host: %s, key: %s, file: %s, size: %s", host, key, tempFile, tempFile.length()); STATS.uploadStarted(); PutObjectRequest request = new PutObjectRequest(host, key, tempFile); if (sseEnabled) { switch (sseType) { case KMS: if (sseKmsKeyId != null) { request.withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams(sseKmsKeyId)); } else { request.withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams()); } break; case S3: ObjectMetadata metadata = new ObjectMetadata(); metadata.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); request.setMetadata(metadata); break; } } Upload upload = transferManager.upload(request); if (log.isDebugEnabled()) { upload.addProgressListener(createProgressListener(upload)); } upload.waitForCompletion(); STATS.uploadSuccessful(); log.debug("Completed upload for host: %s, key: %s", host, key); } catch (AmazonClientException e) { STATS.uploadFailed(); throw new IOException(e); } catch (InterruptedException e) { STATS.uploadFailed(); Thread.currentThread().interrupt(); throw new InterruptedIOException(); } } private ProgressListener createProgressListener(Transfer transfer) { return new ProgressListener() { private ProgressEventType previousType; private double previousTransferred; @Override public synchronized void progressChanged(ProgressEvent progressEvent) { ProgressEventType eventType = progressEvent.getEventType(); if (previousType != eventType) { log.debug("Upload progress event (%s/%s): %s", host, key, eventType); previousType = eventType; } double transferred = transfer.getProgress().getPercentTransferred(); if (transferred >= (previousTransferred + 10.0)) { log.debug("Upload percentage (%s/%s): %.0f%%", host, key, transferred); previousTransferred = transferred; } } }; } } @VisibleForTesting AmazonS3 getS3Client() { return s3; } @VisibleForTesting void setS3Client(AmazonS3 client) { s3 = client; } }
Fail when encrypted objects don't have unencrypted length header We now fail fast when an encrypted object doesn't have the x-amz-unencrypted-content-length header as that will cause problems when file formats try decoding them.
presto-hive/src/main/java/com/facebook/presto/hive/PrestoS3FileSystem.java
Fail when encrypted objects don't have unencrypted length header
<ide><path>resto-hive/src/main/java/com/facebook/presto/hive/PrestoS3FileSystem.java <ide> import java.util.Date; <ide> import java.util.Iterator; <ide> import java.util.List; <add>import java.util.Map; <ide> import java.util.Optional; <ide> <add>import static com.amazonaws.services.s3.Headers.SERVER_SIDE_ENCRYPTION; <ide> import static com.amazonaws.services.s3.Headers.UNENCRYPTED_CONTENT_LENGTH; <ide> import static com.facebook.presto.hive.RetryDriver.retry; <ide> import static com.google.common.base.Preconditions.checkArgument; <ide> } <ide> <ide> return new FileStatus( <del> getObjectSize(metadata), <add> getObjectSize(path, metadata), <ide> false, <ide> 1, <ide> BLOCK_SIZE.toBytes(), <ide> qualifiedPath(path)); <ide> } <ide> <del> private static long getObjectSize(ObjectMetadata metadata) <del> { <del> String length = metadata.getUserMetadata().get(UNENCRYPTED_CONTENT_LENGTH); <add> private static long getObjectSize(Path path, ObjectMetadata metadata) <add> throws IOException <add> { <add> Map<String, String> userMetadata = metadata.getUserMetadata(); <add> String length = userMetadata.get(UNENCRYPTED_CONTENT_LENGTH); <add> if (userMetadata.containsKey(SERVER_SIDE_ENCRYPTION) && length == null) { <add> throw new IOException(format("%s header is not set on an encrypted object: %s", UNENCRYPTED_CONTENT_LENGTH, path)); <add> } <ide> return (length != null) ? Long.parseLong(length) : metadata.getContentLength(); <ide> } <ide>
Java
mit
8624d1c3ae0b1008f3df276bc6a98696259a1566
0
RocketChat/Rocket.Chat.Java.SDK
package com.rocketchat.core; import com.rocketchat.common.RocketChatAuthException; import com.rocketchat.common.SocketListener; import com.rocketchat.common.data.CommonJsonAdapterFactory; import com.rocketchat.common.data.TimestampAdapter; import com.rocketchat.common.data.lightdb.DbManager; import com.rocketchat.common.data.model.BaseRoom; import com.rocketchat.common.data.model.BaseUser; import com.rocketchat.common.data.model.User; import com.rocketchat.common.listener.ConnectListener; import com.rocketchat.common.listener.PaginatedCallback; import com.rocketchat.common.listener.SimpleCallback; import com.rocketchat.common.listener.SimpleListCallback; import com.rocketchat.common.listener.SubscribeListener; import com.rocketchat.common.listener.TypingListener; import com.rocketchat.common.network.ReconnectionStrategy; import com.rocketchat.common.network.Socket; import com.rocketchat.common.network.SocketFactory; import com.rocketchat.common.utils.Logger; import com.rocketchat.common.utils.NoopLogger; import com.rocketchat.common.utils.Sort; import com.rocketchat.core.callback.HistoryCallback; import com.rocketchat.core.callback.LoginCallback; import com.rocketchat.core.callback.MessageCallback; import com.rocketchat.core.callback.RoomCallback; import com.rocketchat.core.callback.ServerInfoCallback; import com.rocketchat.core.factory.ChatRoomFactory; import com.rocketchat.core.internal.middleware.CoreStreamMiddleware; import com.rocketchat.core.model.Emoji; import com.rocketchat.core.model.JsonAdapterFactory; import com.rocketchat.core.model.Message; import com.rocketchat.core.model.Permission; import com.rocketchat.core.model.PublicSetting; import com.rocketchat.core.model.Room; import com.rocketchat.core.model.RoomRole; import com.rocketchat.core.model.Subscription; import com.rocketchat.core.model.Token; import com.rocketchat.core.model.attachment.Attachment; import com.rocketchat.core.provider.TokenProvider; import com.rocketchat.core.uploader.IFileUpload; import com.squareup.moshi.Moshi; import org.json.JSONObject; import java.util.Date; import java.util.List; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import static com.rocketchat.common.utils.Preconditions.checkNotNull; /** * Created by sachin on 8/6/17. */ // TODO: 30/7/17 Make it singletone like eventbus, add builder class to RocketChatAPI in order to use it anywhere, maybe a common builder class public class RocketChatClient { private final HttpUrl baseUrl; private final OkHttpClient client; private final Logger logger; private final SocketFactory factory; private DbManager dbManager; private TokenProvider tokenProvider; private RestImpl restImpl; private WebsocketImpl websocketImpl; private Moshi moshi; // chatRoomFactory class private ChatRoomFactory chatRoomFactory; private RocketChatClient(final Builder builder) { if (builder.baseUrl == null || builder.websocketUrl == null) { throw new IllegalStateException("You must provide both restBaseUrl and websocketUrl"); } this.baseUrl = builder.baseUrl; if (builder.client == null) { client = new OkHttpClient(); } else { client = builder.client; } if (builder.factory != null) { this.factory = builder.factory; } else { this.factory = new SocketFactory() { @Override public Socket create(OkHttpClient client, String url, Logger logger, SocketListener socketListener) { return new Socket(client, url, logger, socketListener); } }; } if (builder.logger != null) { this.logger = builder.logger; } else { this.logger = new NoopLogger(); } // TODO - Add to the Builder Moshi moshi = new Moshi.Builder() .add(new TimestampAdapter()) .add(JsonAdapterFactory.create()) .add(CommonJsonAdapterFactory.create()) .build(); dbManager = new DbManager(moshi); chatRoomFactory = new ChatRoomFactory(this); tokenProvider = builder.provider; restImpl = new RestImpl(client, moshi, baseUrl, tokenProvider, logger); websocketImpl = new WebsocketImpl(client, factory, moshi, builder.websocketUrl, logger); } public String getMyUserName() { // TODO - re-implement return null; //return dbManager.getUserCollection().get(userId).username(); } public String getMyUserId() { //return userId; // TODO - re-implement return null; } public ChatRoomFactory getChatRoomFactory() { return chatRoomFactory; } public DbManager getDbManager() { return dbManager; } public void signin(String username, String password, final LoginCallback loginCallback) { restImpl.signin(username, password, loginCallback); } public void serverInfo(ServerInfoCallback callback) { restImpl.serverInfo(callback); } public void pinMessage(String messageId, SimpleCallback callback) { restImpl.pinMessage(messageId, callback); } public void getRoomMembers(String roomId, BaseRoom.RoomType roomType, int offset, BaseUser.SortBy sortBy, Sort sort, final PaginatedCallback callback) { restImpl.getRoomMembers(roomId, roomType, offset, sortBy, sort, callback); } // TODO public void getRoomFavoriteMessages() { } // TODO public void getRoomPinnedMessages() { } public void getRoomFiles(String roomId, BaseRoom.RoomType roomType, int offset, Attachment.SortBy sortBy, Sort sort, final PaginatedCallback callback) { restImpl.getRoomFiles(roomId, roomType, offset, sortBy, sort, callback); } public void login(LoginCallback loginCallback) { Token token = tokenProvider != null ? tokenProvider.getToken() : null; if (token == null) { loginCallback.onError(new RocketChatAuthException("Missing token")); return; } loginUsingToken(token.getAuthToken(), loginCallback); } //Tested public void login(String username, String password, LoginCallback loginCallback) { websocketImpl.login(username, password, loginCallback); } //Tested public void loginUsingToken(String token, LoginCallback loginCallback) { websocketImpl.loginUsingToken(token, loginCallback); } //Tested public void getPermissions(SimpleListCallback<Permission> callback) { websocketImpl.getPermissions(callback); } //Tested public void getPublicSettings(SimpleListCallback<PublicSetting> callback) { websocketImpl.getPublicSettings(callback); } //Tested public void getUserRoles(SimpleListCallback<User> callback) { websocketImpl.getUserRoles(callback); } //Tested public void listCustomEmoji(SimpleListCallback<Emoji> callback) { websocketImpl.listCustomEmoji(callback); } //Tested public void logout(SimpleCallback callback) { websocketImpl.logout(callback); } //Tested public void getSubscriptions(SimpleListCallback<Subscription> callback) { websocketImpl.getSubscriptions(callback); } //Tested public void getRooms(SimpleListCallback<Room> callback) { websocketImpl.getRooms(callback); } //Tested void getRoomRoles(String roomId, SimpleListCallback<RoomRole> callback) { websocketImpl.getRoomRoles(roomId, callback); } //Tested void getChatHistory(String roomID, int limit, Date oldestMessageTimestamp, Date lasttimestamp, HistoryCallback callback) { websocketImpl.getChatHistory(roomID, limit, oldestMessageTimestamp, lasttimestamp, callback); } //Tested void sendIsTyping(String roomId, String username, Boolean istyping) { websocketImpl.sendIsTyping(roomId, username, istyping); } //Tested void sendMessage(String msgId, String roomID, String message, MessageCallback.MessageAckCallback callback) { websocketImpl.sendMessage(msgId, roomID, message, callback); } //Tested void deleteMessage(String msgId, SimpleCallback callback) { websocketImpl.deleteMessage(msgId, callback); } //Tested void updateMessage(String msgId, String roomId, String message, SimpleCallback callback) { websocketImpl.updateMessage(msgId, roomId, message, callback); } //Tested @Deprecated void pinMessage(JSONObject message, SimpleCallback callback) { websocketImpl.pinMessage(message, callback); } //Tested void unpinMessage(JSONObject message, SimpleCallback callback) { websocketImpl.unpinMessage(message, callback); } //Tested void starMessage(String msgId, String roomId, Boolean starred, SimpleCallback callback) { websocketImpl.starMessage(msgId, roomId, starred, callback); } //Tested void setReaction(String emojiId, String msgId, SimpleCallback callback) { websocketImpl.setReaction(emojiId, msgId, callback); } void searchMessage(String message, String roomId, int limit, SimpleListCallback<Message> callback) { websocketImpl.searchMessage(message, roomId, limit, callback); } //Tested public void createPublicGroup(String groupName, String[] users, Boolean readOnly, RoomCallback.GroupCreateCallback callback) { websocketImpl.createPublicGroup(groupName, users, readOnly, callback); } //Tested public void createPrivateGroup(String groupName, String[] users, RoomCallback.GroupCreateCallback callback) { websocketImpl.createPrivateGroup(groupName, users, callback); } //Tested void deleteGroup(String roomId, SimpleCallback callback) { websocketImpl.deleteGroup(roomId, callback); } //Tested void archiveRoom(String roomId, SimpleCallback callback) { websocketImpl.archiveRoom(roomId, callback); } //Tested void unarchiveRoom(String roomId, SimpleCallback callback) { websocketImpl.unarchiveRoom(roomId, callback); } //Tested public void joinPublicGroup(String roomId, String joinCode, SimpleCallback callback) { websocketImpl.joinPublicGroup(roomId, joinCode, callback); } //Tested void leaveGroup(String roomId, SimpleCallback callback) { websocketImpl.leaveGroup(roomId, callback); } //Tested void hideRoom(String roomId, SimpleCallback callback) { websocketImpl.hideRoom(roomId, callback); } //Tested void openRoom(String roomId, SimpleCallback callback) { websocketImpl.openRoom(roomId, callback); } //Tested void setFavouriteRoom(String roomId, Boolean isFavouriteRoom, SimpleCallback callback) { websocketImpl.setFavouriteRoom(roomId, isFavouriteRoom, callback); } void sendFileMessage(String roomId, String store, String fileId, String fileType, int size, String fileName, String desc, String url, MessageCallback.MessageAckCallback callback) { websocketImpl.sendFileMessage(roomId, store, fileId, fileType, size, fileName, desc, url, callback); } //Tested public void setStatus(User.Status s, SimpleCallback callback) { websocketImpl.setStatus(s, callback); } public void subscribeActiveUsers(SubscribeListener subscribeListener) { websocketImpl.subscribeActiveUsers(subscribeListener); } public void subscribeUserData(SubscribeListener subscribeListener) { websocketImpl.subscribeUserData(subscribeListener); } //Tested String subscribeRoomMessageEvent(String roomId, Boolean enable, SubscribeListener subscribeListener, MessageCallback.SubscriptionCallback listener) { return websocketImpl.subscribeRoomMessageEvent(roomId, enable, subscribeListener, listener); } String subscribeRoomTypingEvent(String roomId, Boolean enable, SubscribeListener subscribeListener, TypingListener listener) { return websocketImpl.subscribeRoomTypingEvent(roomId, enable, subscribeListener, listener); } void unsubscribeRoom(String subId, SubscribeListener subscribeListener) { websocketImpl.unsubscribeRoom(subId, subscribeListener); } public void createUFS(String fileName, int fileSize, String fileType, String roomId, String description, String store, IFileUpload.UfsCreateCallback listener) { websocketImpl.createUFS(fileName, fileSize, fileType, roomId, description, store, listener); } public void completeUFS(String fileId, String store, String token, IFileUpload.UfsCompleteListener listener) { websocketImpl.completeUFS(fileId, store, token, listener); } public void connect(ConnectListener connectListener) { websocketImpl.connect(connectListener); } public void disconnect() { websocketImpl.disconnect(); } public void setReconnectionStrategy(ReconnectionStrategy strategy) { websocketImpl.setReconnectionStrategy(strategy); } public void setPingInterval(long interval) { websocketImpl.setPingInterval(interval); } public void disablePing() { websocketImpl.disablePing(); } public void enablePing() { websocketImpl.enablePing(); } void removeSubscription(String roomId, CoreStreamMiddleware.SubscriptionType type) { websocketImpl.removeSubscription(roomId, CoreStreamMiddleware.SubscriptionType.SUBSCRIBE_ROOM_MESSAGE); } public void removeAllSubscriptions(String roomId) { websocketImpl.removeAllSubscriptions(roomId); } public static final class Builder { private String websocketUrl; private HttpUrl baseUrl; private OkHttpClient client; private SocketFactory factory; private TokenProvider provider; private Logger logger; public Builder websocketUrl(String url) { this.websocketUrl = checkNotNull(url, "url == null"); return this; } public Builder client(OkHttpClient client) { this.client = checkNotNull(client, "client must be non null"); return this; } public Builder socketFactory(SocketFactory factory) { this.factory = checkNotNull(factory, "factory == null"); return this; } public Builder restBaseUrl(String url) { checkNotNull(url, "url == null"); HttpUrl httpUrl = HttpUrl.parse(url); if (httpUrl == null) { throw new IllegalArgumentException("Illegal URL: " + url); } return restBaseUrl(httpUrl); } /** * Set the API base URL. * <p> * The specified endpoint values (such as with {@link GET @GET}) are resolved against this * value using {@link HttpUrl#resolve(String)}. The behavior of this matches that of an * {@code <a href="">} link on a website resolving on the current URL. * <p> * <b>Base URLs should always end in {@code /}.</b> * <p> * A trailing {@code /} ensures that endpoints values which are relative paths will correctly * append themselves to a base which has path components. * <p> * <b>Correct:</b><br> * Base URL: http://example.com/api/<br> * Endpoint: foo/bar/<br> * Result: http://example.com/api/foo/bar/ * <p> * <b>Incorrect:</b><br> * Base URL: http://example.com/api<br> * Endpoint: foo/bar/<br> * Result: http://example.com/foo/bar/ * <p> * This method enforces that {@code baseUrl} has a trailing {@code /}. * <p> * <b>Endpoint values which contain a leading {@code /} are absolute.</b> * <p> * Absolute values retain only the host from {@code baseUrl} and ignore any specified path * components. * <p> * Base URL: http://example.com/api/<br> * Endpoint: /foo/bar/<br> * Result: http://example.com/foo/bar/ * <p> * Base URL: http://example.com/<br> * Endpoint: /foo/bar/<br> * Result: http://example.com/foo/bar/ * <p> * <b>Endpoint values may be a full URL.</b> * <p> * Values which have a host replace the host of {@code baseUrl} and values also with a scheme * replace the scheme of {@code baseUrl}. * <p> * Base URL: http://example.com/<br> * Endpoint: https://github.com/square/retrofit/<br> * Result: https://github.com/square/retrofit/ * <p> * Base URL: http://example.com<br> * Endpoint: //github.com/square/retrofit/<br> * Result: http://github.com/square/retrofit/ (note the scheme stays 'http') */ private Builder restBaseUrl(HttpUrl baseUrl) { checkNotNull(baseUrl, "baseUrl == null"); List<String> pathSegments = baseUrl.pathSegments(); if (!"".equals(pathSegments.get(pathSegments.size() - 1))) { throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl); } this.baseUrl = baseUrl; return this; } public Builder tokenProvider(TokenProvider provider) { this.provider = checkNotNull(provider, "provider == null"); return this; } public Builder logger(Logger logger) { this.logger = checkNotNull(logger, "logger == null"); return this; } public RocketChatClient build() { return new RocketChatClient(this); } } }
rocketchat-core/src/main/java/com/rocketchat/core/RocketChatClient.java
package com.rocketchat.core; import com.rocketchat.common.RocketChatAuthException; import com.rocketchat.common.SocketListener; import com.rocketchat.common.data.CommonJsonAdapterFactory; import com.rocketchat.common.data.TimestampAdapter; import com.rocketchat.common.data.lightdb.DbManager; import com.rocketchat.common.data.model.BaseRoom; import com.rocketchat.common.data.model.BaseUser; import com.rocketchat.common.data.model.User; import com.rocketchat.common.listener.ConnectListener; import com.rocketchat.common.listener.PaginatedCallback; import com.rocketchat.common.listener.SimpleCallback; import com.rocketchat.common.listener.SimpleListCallback; import com.rocketchat.common.listener.SubscribeListener; import com.rocketchat.common.listener.TypingListener; import com.rocketchat.common.network.ReconnectionStrategy; import com.rocketchat.common.network.Socket; import com.rocketchat.common.network.SocketFactory; import com.rocketchat.common.utils.Logger; import com.rocketchat.common.utils.NoopLogger; import com.rocketchat.common.utils.Sort; import com.rocketchat.core.callback.HistoryCallback; import com.rocketchat.core.callback.LoginCallback; import com.rocketchat.core.callback.MessageCallback; import com.rocketchat.core.callback.RoomCallback; import com.rocketchat.core.callback.ServerInfoCallback; import com.rocketchat.core.factory.ChatRoomFactory; import com.rocketchat.core.internal.middleware.CoreStreamMiddleware; import com.rocketchat.core.model.Emoji; import com.rocketchat.core.model.JsonAdapterFactory; import com.rocketchat.core.model.Message; import com.rocketchat.core.model.Permission; import com.rocketchat.core.model.PublicSetting; import com.rocketchat.core.model.Room; import com.rocketchat.core.model.RoomRole; import com.rocketchat.core.model.Subscription; import com.rocketchat.core.model.Token; import com.rocketchat.core.model.attachment.Attachment; import com.rocketchat.core.provider.TokenProvider; import com.rocketchat.core.uploader.IFileUpload; import com.squareup.moshi.Moshi; import org.json.JSONObject; import java.util.Date; import java.util.List; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import static com.rocketchat.common.utils.Preconditions.checkNotNull; /** * Created by sachin on 8/6/17. */ // TODO: 30/7/17 Make it singletone like eventbus, add builder class to RocketChatAPI in order to use it anywhere, maybe a common builder class public class RocketChatClient { private final HttpUrl baseUrl; private final OkHttpClient client; private final Logger logger; private final SocketFactory factory; private DbManager dbManager; private TokenProvider tokenProvider; private RestImpl restImpl; private WebsocketImpl websocketImpl; private Moshi moshi; // chatRoomFactory class private ChatRoomFactory chatRoomFactory; private RocketChatClient(final Builder builder) { if (builder.baseUrl == null || builder.websocketUrl == null) { throw new IllegalStateException("You must provide both restBaseUrl and websocketUrl"); } this.baseUrl = builder.baseUrl; if (builder.client == null) { client = new OkHttpClient(); } else { client = builder.client; } if (builder.factory != null) { this.factory = builder.factory; } else { this.factory = new SocketFactory() { @Override public Socket create(OkHttpClient client, String url, Logger logger, SocketListener socketListener) { return new Socket(client, url, logger, socketListener); } }; } if (builder.logger != null) { this.logger = builder.logger; } else { this.logger = new NoopLogger(); } // TODO - Add to the Builder Moshi moshi = new Moshi.Builder() .add(new TimestampAdapter()) .add(JsonAdapterFactory.create()) .add(CommonJsonAdapterFactory.create()) .build(); dbManager = new DbManager(moshi); chatRoomFactory = new ChatRoomFactory(this); tokenProvider = builder.provider; restImpl = new RestImpl(client, moshi, baseUrl, tokenProvider, logger); websocketImpl = new WebsocketImpl(client, factory, moshi, builder.websocketUrl, logger); } public String getMyUserName() { // TODO - re-implement return null; //return dbManager.getUserCollection().get(userId).username(); } public String getMyUserId() { //return userId; // TODO - re-implement return null; } public ChatRoomFactory getChatRoomFactory() { return chatRoomFactory; } public DbManager getDbManager() { return dbManager; } public void signin(String username, String password, final LoginCallback loginCallback) { restImpl.signin(username, password, loginCallback); } public void serverInfo(ServerInfoCallback callback) { restImpl.serverInfo(callback); } public void pinMessage(String messageId, SimpleCallback callback) { restImpl.pinMessage(messageId, callback); } public void getRoomMembers(String roomId, BaseRoom.RoomType roomType, int offset, BaseUser.SortBy sortBy, Sort sort, final PaginatedCallback callback) { restImpl.getRoomMembers(roomId, roomType, offset, sortBy, sort, callback); } // TODO public void getRoomFavoriteMessages() { } // TODO public void getRoomPinnedMessages() { } public void getRoomFiles(String roomId, BaseRoom.RoomType roomType, int offset, Attachment.SortBy sortBy, Sort sort, final PaginatedCallback callback) { restImpl.getRoomFiles(roomId, roomType, offset, sortBy, sort, callback); } public void login(LoginCallback loginCallback) { Token token = tokenProvider != null ? tokenProvider.getToken() : null; if (token == null) { loginCallback.onError(new RocketChatAuthException("Missing token")); return; } loginUsingToken(token.getAuthToken(), loginCallback); } //Tested public void login(String username, String password, LoginCallback loginCallback) { websocketImpl.login(username, password, loginCallback); } //Tested public void loginUsingToken(String token, LoginCallback loginCallback) { websocketImpl.loginUsingToken(token, loginCallback); } //Tested public void getPermissions(SimpleListCallback<Permission> callback) { websocketImpl.getPermissions(callback); } //Tested public void getPublicSettings(SimpleListCallback<PublicSetting> callback) { websocketImpl.getPublicSettings(callback); } //Tested public void getUserRoles(SimpleListCallback<User> callback) { websocketImpl.getUserRoles(callback); } //Tested public void listCustomEmoji(SimpleListCallback<Emoji> callback) { websocketImpl.listCustomEmoji(callback); } //Tested public void logout(SimpleCallback callback) { websocketImpl.logout(callback); } //Tested public void getSubscriptions(SimpleListCallback<Subscription> callback) { websocketImpl.getSubscriptions(callback); } //Tested public void getRooms(SimpleListCallback<Room> callback) { websocketImpl.getRooms(callback); } //Tested void getRoomRoles(String roomId, SimpleListCallback<RoomRole> callback) { websocketImpl.getRoomRoles(roomId, callback); } //Tested void getChatHistory(String roomID, int limit, Date oldestMessageTimestamp, Date lasttimestamp, HistoryCallback callback) { websocketImpl.getChatHistory(roomID, limit, oldestMessageTimestamp, lasttimestamp, callback); } void getRoomMembers(String roomID, Boolean allUsers, RoomCallback.GetMembersCallback callback) { websocketImpl.getRoomMembers(roomID, allUsers, callback); } //Tested void sendIsTyping(String roomId, String username, Boolean istyping) { websocketImpl.sendIsTyping(roomId, username, istyping); } //Tested void sendMessage(String msgId, String roomID, String message, MessageCallback.MessageAckCallback callback) { websocketImpl.sendMessage(msgId, roomID, message, callback); } //Tested void deleteMessage(String msgId, SimpleCallback callback) { websocketImpl.deleteMessage(msgId, callback); } //Tested void updateMessage(String msgId, String roomId, String message, SimpleCallback callback) { websocketImpl.updateMessage(msgId, roomId, message, callback); } //Tested @Deprecated void pinMessage(JSONObject message, SimpleCallback callback) { websocketImpl.pinMessage(message, callback); } //Tested void unpinMessage(JSONObject message, SimpleCallback callback) { websocketImpl.unpinMessage(message, callback); } //Tested void starMessage(String msgId, String roomId, Boolean starred, SimpleCallback callback) { websocketImpl.starMessage(msgId, roomId, starred, callback); } //Tested void setReaction(String emojiId, String msgId, SimpleCallback callback) { websocketImpl.setReaction(emojiId, msgId, callback); } void searchMessage(String message, String roomId, int limit, SimpleListCallback<Message> callback) { websocketImpl.searchMessage(message, roomId, limit, callback); } //Tested public void createPublicGroup(String groupName, String[] users, Boolean readOnly, RoomCallback.GroupCreateCallback callback) { websocketImpl.createPublicGroup(groupName, users, readOnly, callback); } //Tested public void createPrivateGroup(String groupName, String[] users, RoomCallback.GroupCreateCallback callback) { websocketImpl.createPrivateGroup(groupName, users, callback); } //Tested void deleteGroup(String roomId, SimpleCallback callback) { websocketImpl.deleteGroup(roomId, callback); } //Tested void archiveRoom(String roomId, SimpleCallback callback) { websocketImpl.archiveRoom(roomId, callback); } //Tested void unarchiveRoom(String roomId, SimpleCallback callback) { websocketImpl.unarchiveRoom(roomId, callback); } //Tested public void joinPublicGroup(String roomId, String joinCode, SimpleCallback callback) { websocketImpl.joinPublicGroup(roomId, joinCode, callback); } //Tested void leaveGroup(String roomId, SimpleCallback callback) { websocketImpl.leaveGroup(roomId, callback); } //Tested void hideRoom(String roomId, SimpleCallback callback) { websocketImpl.hideRoom(roomId, callback); } //Tested void openRoom(String roomId, SimpleCallback callback) { websocketImpl.openRoom(roomId, callback); } //Tested void setFavouriteRoom(String roomId, Boolean isFavouriteRoom, SimpleCallback callback) { websocketImpl.setFavouriteRoom(roomId, isFavouriteRoom, callback); } void sendFileMessage(String roomId, String store, String fileId, String fileType, int size, String fileName, String desc, String url, MessageCallback.MessageAckCallback callback) { websocketImpl.sendFileMessage(roomId, store, fileId, fileType, size, fileName, desc, url, callback); } //Tested public void setStatus(User.Status s, SimpleCallback callback) { websocketImpl.setStatus(s, callback); } public void subscribeActiveUsers(SubscribeListener subscribeListener) { websocketImpl.subscribeActiveUsers(subscribeListener); } public void subscribeUserData(SubscribeListener subscribeListener) { websocketImpl.subscribeUserData(subscribeListener); } //Tested String subscribeRoomMessageEvent(String roomId, Boolean enable, SubscribeListener subscribeListener, MessageCallback.SubscriptionCallback listener) { return websocketImpl.subscribeRoomMessageEvent(roomId, enable, subscribeListener, listener); } String subscribeRoomTypingEvent(String roomId, Boolean enable, SubscribeListener subscribeListener, TypingListener listener) { return websocketImpl.subscribeRoomTypingEvent(roomId, enable, subscribeListener, listener); } void unsubscribeRoom(String subId, SubscribeListener subscribeListener) { websocketImpl.unsubscribeRoom(subId, subscribeListener); } public void createUFS(String fileName, int fileSize, String fileType, String roomId, String description, String store, IFileUpload.UfsCreateCallback listener) { websocketImpl.createUFS(fileName, fileSize, fileType, roomId, description, store, listener); } public void completeUFS(String fileId, String store, String token, IFileUpload.UfsCompleteListener listener) { websocketImpl.completeUFS(fileId, store, token, listener); } public void connect(ConnectListener connectListener) { websocketImpl.connect(connectListener); } public void disconnect() { websocketImpl.disconnect(); } public void setReconnectionStrategy(ReconnectionStrategy strategy) { websocketImpl.setReconnectionStrategy(strategy); } public void setPingInterval(long interval) { websocketImpl.setPingInterval(interval); } public void disablePing() { websocketImpl.disablePing(); } public void enablePing() { websocketImpl.enablePing(); } void removeSubscription(String roomId, CoreStreamMiddleware.SubscriptionType type) { websocketImpl.removeSubscription(roomId, CoreStreamMiddleware.SubscriptionType.SUBSCRIBE_ROOM_MESSAGE); } public void removeAllSubscriptions(String roomId) { websocketImpl.removeAllSubscriptions(roomId); } public static final class Builder { private String websocketUrl; private HttpUrl baseUrl; private OkHttpClient client; private SocketFactory factory; private TokenProvider provider; private Logger logger; public Builder websocketUrl(String url) { this.websocketUrl = checkNotNull(url, "url == null"); return this; } public Builder client(OkHttpClient client) { this.client = checkNotNull(client, "client must be non null"); return this; } public Builder socketFactory(SocketFactory factory) { this.factory = checkNotNull(factory, "factory == null"); return this; } public Builder restBaseUrl(String url) { checkNotNull(url, "url == null"); HttpUrl httpUrl = HttpUrl.parse(url); if (httpUrl == null) { throw new IllegalArgumentException("Illegal URL: " + url); } return restBaseUrl(httpUrl); } /** * Set the API base URL. * <p> * The specified endpoint values (such as with {@link GET @GET}) are resolved against this * value using {@link HttpUrl#resolve(String)}. The behavior of this matches that of an * {@code <a href="">} link on a website resolving on the current URL. * <p> * <b>Base URLs should always end in {@code /}.</b> * <p> * A trailing {@code /} ensures that endpoints values which are relative paths will correctly * append themselves to a base which has path components. * <p> * <b>Correct:</b><br> * Base URL: http://example.com/api/<br> * Endpoint: foo/bar/<br> * Result: http://example.com/api/foo/bar/ * <p> * <b>Incorrect:</b><br> * Base URL: http://example.com/api<br> * Endpoint: foo/bar/<br> * Result: http://example.com/foo/bar/ * <p> * This method enforces that {@code baseUrl} has a trailing {@code /}. * <p> * <b>Endpoint values which contain a leading {@code /} are absolute.</b> * <p> * Absolute values retain only the host from {@code baseUrl} and ignore any specified path * components. * <p> * Base URL: http://example.com/api/<br> * Endpoint: /foo/bar/<br> * Result: http://example.com/foo/bar/ * <p> * Base URL: http://example.com/<br> * Endpoint: /foo/bar/<br> * Result: http://example.com/foo/bar/ * <p> * <b>Endpoint values may be a full URL.</b> * <p> * Values which have a host replace the host of {@code baseUrl} and values also with a scheme * replace the scheme of {@code baseUrl}. * <p> * Base URL: http://example.com/<br> * Endpoint: https://github.com/square/retrofit/<br> * Result: https://github.com/square/retrofit/ * <p> * Base URL: http://example.com<br> * Endpoint: //github.com/square/retrofit/<br> * Result: http://github.com/square/retrofit/ (note the scheme stays 'http') */ private Builder restBaseUrl(HttpUrl baseUrl) { checkNotNull(baseUrl, "baseUrl == null"); List<String> pathSegments = baseUrl.pathSegments(); if (!"".equals(pathSegments.get(pathSegments.size() - 1))) { throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl); } this.baseUrl = baseUrl; return this; } public Builder tokenProvider(TokenProvider provider) { this.provider = checkNotNull(provider, "provider == null"); return this; } public Builder logger(Logger logger) { this.logger = checkNotNull(logger, "logger == null"); return this; } public RocketChatClient build() { return new RocketChatClient(this); } } }
Remove the getRoomMembers method (Realtime API). getRoomMembers will be done by the REST API.
rocketchat-core/src/main/java/com/rocketchat/core/RocketChatClient.java
Remove the getRoomMembers method (Realtime API).
<ide><path>ocketchat-core/src/main/java/com/rocketchat/core/RocketChatClient.java <ide> websocketImpl.getChatHistory(roomID, limit, oldestMessageTimestamp, lasttimestamp, callback); <ide> } <ide> <del> void getRoomMembers(String roomID, Boolean allUsers, RoomCallback.GetMembersCallback callback) { <del> websocketImpl.getRoomMembers(roomID, allUsers, callback); <del> } <del> <ide> //Tested <ide> void sendIsTyping(String roomId, String username, Boolean istyping) { <ide> websocketImpl.sendIsTyping(roomId, username, istyping);
Java
lgpl-2.1
ae6cfb4c4da4dd5849e0b6168537a404eb419b4b
0
zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform
/* * Copyright 2011, Red Hat, Inc. and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.zanata.webtrans.client.presenter; import java.util.ArrayList; import java.util.Set; import net.customware.gwt.presenter.client.EventBus; import net.customware.gwt.presenter.client.widget.WidgetPresenter; import org.zanata.webtrans.client.events.NotificationEvent; import org.zanata.webtrans.client.events.NotificationEvent.Severity; import org.zanata.webtrans.client.events.RunDocValidationEvent; import org.zanata.webtrans.client.events.RunDocValidationResultEvent; import org.zanata.webtrans.client.events.RunDocValidationResultHandler; import org.zanata.webtrans.client.events.WorkspaceContextUpdateEvent; import org.zanata.webtrans.client.events.WorkspaceContextUpdateEventHandler; import org.zanata.webtrans.client.resources.WebTransMessages; import org.zanata.webtrans.client.rpc.CachingDispatchAsync; import org.zanata.webtrans.client.service.ValidationService; import org.zanata.webtrans.client.view.ValidationOptionsDisplay; import org.zanata.webtrans.shared.model.DocumentId; import org.zanata.webtrans.shared.model.ValidationAction; import org.zanata.webtrans.shared.model.ValidationInfo; import org.zanata.webtrans.shared.rpc.DownloadAllFilesResult; import org.zanata.webtrans.shared.rpc.RunDocValidationReportAction; import org.zanata.webtrans.shared.rpc.RunDocValidationReportResult; import com.google.gwt.event.logical.shared.HasValueChangeHandlers; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.inject.Inject; /** * * * @author Alex Eng <a href="mailto:[email protected]">[email protected]</a> * **/ public class ValidationOptionsPresenter extends WidgetPresenter<ValidationOptionsDisplay> implements ValidationOptionsDisplay.Listener, WorkspaceContextUpdateEventHandler, RunDocValidationResultHandler { private final ValidationService validationService; private final WebTransMessages messages; private final CachingDispatchAsync dispatcher; private final UserConfigHolder configHolder; private MainView currentView; private Set<DocumentId> errorDocs; @Inject public ValidationOptionsPresenter(ValidationOptionsDisplay display, EventBus eventBus, CachingDispatchAsync dispatcher, final ValidationService validationService, final WebTransMessages messages, final UserConfigHolder configHolder) { super(display, eventBus); this.validationService = validationService; this.messages = messages; this.dispatcher = dispatcher; this.configHolder = configHolder; } @Override protected void onBind() { registerHandler(eventBus.addHandler(WorkspaceContextUpdateEvent.getType(), this)); registerHandler(eventBus.addHandler(RunDocValidationResultEvent.getType(), this)); initDisplay(); display.updateValidationResult(null, null); display.showReportLink(false); display.setListener(this); } public void initDisplay() { display.clearValidationSelector(); ArrayList<ValidationAction> validationActions = new ArrayList<ValidationAction>(validationService.getValidationMap().values()); for (final ValidationAction validationAction : validationActions) { ValidationInfo validationInfo = validationAction.getValidationInfo(); HasValueChangeHandlers<Boolean> changeHandler = display.addValidationSelector(validationAction.getId().getDisplayName(), validationAction.getDescription(), validationInfo.isEnabled(), validationInfo.isLocked()); changeHandler.addValueChangeHandler(new ValidationOptionValueChangeHandler(validationAction)); } } @Override protected void onUnbind() { } @Override protected void onRevealDisplay() { } class ValidationOptionValueChangeHandler implements ValueChangeHandler<Boolean> { private final ValidationAction validationAction; public ValidationOptionValueChangeHandler(ValidationAction validationAction) { this.validationAction = validationAction; } @Override public void onValueChange(ValueChangeEvent<Boolean> event) { validationService.updateStatus(validationAction.getId(), event.getValue()); if (event.getValue()) { for (ValidationAction excluded : validationAction.getExclusiveValidations()) { validationService.updateStatus(excluded.getId(), false); display.changeValidationSelectorValue(excluded.getId().getDisplayName(), false); } } } } @Override public void onWorkspaceContextUpdated(WorkspaceContextUpdateEvent event) { validationService.setValidationRules(event.getValidationInfoList()); initDisplay(); } public void setCurrentView(MainView view) { currentView = view; if (view == MainView.Documents) { display.setRunValidationVisible(true); display.setRunValidationTitle(messages.documentValidationTitle()); if (hasErrorReport()) { display.showReportLink(true); } } else { display.setRunValidationVisible(false); display.setRunValidationTitle(messages.editorValidationTitle()); display.showReportLink(false); } } @Override public void onRunValidation() { eventBus.fireEvent(new RunDocValidationEvent(currentView)); } @Override public void onCompleteRunDocValidation(RunDocValidationResultEvent event) { display.updateValidationResult(event.getStartTime(), event.getEndTime()); errorDocs = event.getErrorDocs(); if (currentView == MainView.Documents) { display.showReportLink(true); } } @Override public void onRequestValidationReport() { // display.showReportPopup(errorDocs); for (final DocumentId documentId : errorDocs) { dispatcher.execute(new RunDocValidationReportAction(configHolder.getState().getEnabledValidationIds(), documentId.getId()), new AsyncCallback<RunDocValidationReportResult>() { @Override public void onFailure(Throwable caught) { eventBus.fireEvent(new NotificationEvent(Severity.Error, "Error generating report for document " + documentId)); } @Override public void onSuccess(RunDocValidationReportResult result) { // display.updateReport(documentId, result.getResult()); } }); } } private boolean hasErrorReport() { return errorDocs != null && !errorDocs.isEmpty(); } }
zanata-war/src/main/java/org/zanata/webtrans/client/presenter/ValidationOptionsPresenter.java
/* * Copyright 2011, Red Hat, Inc. and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.zanata.webtrans.client.presenter; import java.util.ArrayList; import java.util.Set; import net.customware.gwt.presenter.client.EventBus; import net.customware.gwt.presenter.client.widget.WidgetPresenter; import org.zanata.webtrans.client.events.RunDocValidationEvent; import org.zanata.webtrans.client.events.RunDocValidationResultEvent; import org.zanata.webtrans.client.events.RunDocValidationResultHandler; import org.zanata.webtrans.client.events.WorkspaceContextUpdateEvent; import org.zanata.webtrans.client.events.WorkspaceContextUpdateEventHandler; import org.zanata.webtrans.client.resources.WebTransMessages; import org.zanata.webtrans.client.service.ValidationService; import org.zanata.webtrans.client.view.ValidationOptionsDisplay; import org.zanata.webtrans.shared.model.DocumentId; import org.zanata.webtrans.shared.model.ValidationAction; import org.zanata.webtrans.shared.model.ValidationInfo; import com.google.gwt.event.logical.shared.HasValueChangeHandlers; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.inject.Inject; /** * * * @author Alex Eng <a href="mailto:[email protected]">[email protected]</a> * **/ public class ValidationOptionsPresenter extends WidgetPresenter<ValidationOptionsDisplay> implements ValidationOptionsDisplay.Listener, WorkspaceContextUpdateEventHandler, RunDocValidationResultHandler { private final ValidationService validationService; private final WebTransMessages messages; private MainView currentView; private Set<DocumentId> errorDocs; @Inject public ValidationOptionsPresenter(ValidationOptionsDisplay display, EventBus eventBus, final ValidationService validationService, final WebTransMessages messages) { super(display, eventBus); this.validationService = validationService; this.messages = messages; } @Override protected void onBind() { registerHandler(eventBus.addHandler(WorkspaceContextUpdateEvent.getType(), this)); registerHandler(eventBus.addHandler(RunDocValidationResultEvent.getType(), this)); initDisplay(); display.updateValidationResult(null, null); display.showReportLink(false); display.setListener(this); } public void initDisplay() { display.clearValidationSelector(); ArrayList<ValidationAction> validationActions = new ArrayList<ValidationAction>(validationService.getValidationMap().values()); for (final ValidationAction validationAction : validationActions) { ValidationInfo validationInfo = validationAction.getValidationInfo(); HasValueChangeHandlers<Boolean> changeHandler = display.addValidationSelector(validationAction.getId().getDisplayName(), validationAction.getDescription(), validationInfo.isEnabled(), validationInfo.isLocked()); changeHandler.addValueChangeHandler(new ValidationOptionValueChangeHandler(validationAction)); } } @Override protected void onUnbind() { } @Override protected void onRevealDisplay() { } class ValidationOptionValueChangeHandler implements ValueChangeHandler<Boolean> { private final ValidationAction validationAction; public ValidationOptionValueChangeHandler(ValidationAction validationAction) { this.validationAction = validationAction; } @Override public void onValueChange(ValueChangeEvent<Boolean> event) { validationService.updateStatus(validationAction.getId(), event.getValue()); if (event.getValue()) { for (ValidationAction excluded : validationAction.getExclusiveValidations()) { validationService.updateStatus(excluded.getId(), false); display.changeValidationSelectorValue(excluded.getId().getDisplayName(), false); } } } } @Override public void onWorkspaceContextUpdated(WorkspaceContextUpdateEvent event) { validationService.setValidationRules(event.getValidationInfoList()); initDisplay(); } public void setCurrentView(MainView view) { currentView = view; if (view == MainView.Documents) { display.setRunValidationVisible(true); display.setRunValidationTitle(messages.documentValidationTitle()); if(hasErrorReport()) { display.showReportLink(true); } } else { display.setRunValidationVisible(false); display.setRunValidationTitle(messages.editorValidationTitle()); display.showReportLink(false); } } @Override public void onRunValidation() { eventBus.fireEvent(new RunDocValidationEvent(currentView)); } @Override public void onCompleteRunDocValidation(RunDocValidationResultEvent event) { display.updateValidationResult(event.getStartTime(), event.getEndTime()); errorDocs = event.getErrorDocs(); if (currentView == MainView.Documents) { display.showReportLink(true); } } @Override public void onRequestValidationReport() { // display.showReportPopup(errorDocs); // run RPC call, by each docs } private boolean hasErrorReport() { return errorDocs != null && !errorDocs.isEmpty(); } }
Work in progress: implementing validation report
zanata-war/src/main/java/org/zanata/webtrans/client/presenter/ValidationOptionsPresenter.java
Work in progress: implementing validation report
<ide><path>anata-war/src/main/java/org/zanata/webtrans/client/presenter/ValidationOptionsPresenter.java <ide> import net.customware.gwt.presenter.client.EventBus; <ide> import net.customware.gwt.presenter.client.widget.WidgetPresenter; <ide> <add>import org.zanata.webtrans.client.events.NotificationEvent; <add>import org.zanata.webtrans.client.events.NotificationEvent.Severity; <ide> import org.zanata.webtrans.client.events.RunDocValidationEvent; <ide> import org.zanata.webtrans.client.events.RunDocValidationResultEvent; <ide> import org.zanata.webtrans.client.events.RunDocValidationResultHandler; <ide> import org.zanata.webtrans.client.events.WorkspaceContextUpdateEvent; <ide> import org.zanata.webtrans.client.events.WorkspaceContextUpdateEventHandler; <ide> import org.zanata.webtrans.client.resources.WebTransMessages; <add>import org.zanata.webtrans.client.rpc.CachingDispatchAsync; <ide> import org.zanata.webtrans.client.service.ValidationService; <ide> import org.zanata.webtrans.client.view.ValidationOptionsDisplay; <ide> import org.zanata.webtrans.shared.model.DocumentId; <ide> import org.zanata.webtrans.shared.model.ValidationAction; <ide> import org.zanata.webtrans.shared.model.ValidationInfo; <add>import org.zanata.webtrans.shared.rpc.DownloadAllFilesResult; <add>import org.zanata.webtrans.shared.rpc.RunDocValidationReportAction; <add>import org.zanata.webtrans.shared.rpc.RunDocValidationReportResult; <ide> <ide> import com.google.gwt.event.logical.shared.HasValueChangeHandlers; <ide> import com.google.gwt.event.logical.shared.ValueChangeEvent; <ide> import com.google.gwt.event.logical.shared.ValueChangeHandler; <add>import com.google.gwt.user.client.rpc.AsyncCallback; <ide> import com.google.inject.Inject; <ide> <ide> /** <ide> { <ide> private final ValidationService validationService; <ide> private final WebTransMessages messages; <add> private final CachingDispatchAsync dispatcher; <add> private final UserConfigHolder configHolder; <ide> private MainView currentView; <ide> private Set<DocumentId> errorDocs; <ide> <ide> @Inject <del> public ValidationOptionsPresenter(ValidationOptionsDisplay display, EventBus eventBus, final ValidationService validationService, final WebTransMessages messages) <add> public ValidationOptionsPresenter(ValidationOptionsDisplay display, EventBus eventBus, CachingDispatchAsync dispatcher, final ValidationService validationService, final WebTransMessages messages, final UserConfigHolder configHolder) <ide> { <ide> super(display, eventBus); <ide> this.validationService = validationService; <ide> this.messages = messages; <add> this.dispatcher = dispatcher; <add> this.configHolder = configHolder; <ide> } <ide> <ide> @Override <ide> { <ide> display.setRunValidationVisible(true); <ide> display.setRunValidationTitle(messages.documentValidationTitle()); <del> if(hasErrorReport()) <add> if (hasErrorReport()) <ide> { <ide> display.showReportLink(true); <ide> } <ide> public void onRequestValidationReport() <ide> { <ide> // display.showReportPopup(errorDocs); <del> // run RPC call, by each docs <del> } <del> <add> for (final DocumentId documentId : errorDocs) <add> { <add> dispatcher.execute(new RunDocValidationReportAction(configHolder.getState().getEnabledValidationIds(), documentId.getId()), new AsyncCallback<RunDocValidationReportResult>() <add> { <add> @Override <add> public void onFailure(Throwable caught) <add> { <add> eventBus.fireEvent(new NotificationEvent(Severity.Error, "Error generating report for document " + documentId)); <add> } <add> <add> @Override <add> public void onSuccess(RunDocValidationReportResult result) <add> { <add> // display.updateReport(documentId, result.getResult()); <add> } <add> }); <add> } <add> } <add> <ide> private boolean hasErrorReport() <ide> { <ide> return errorDocs != null && !errorDocs.isEmpty(); <ide> } <ide> } <del> <del> <del>
Java
apache-2.0
4ab7681a508357f46706af54b3194900b85fdba3
0
apache/openwebbeans,apache/openwebbeans,apache/openwebbeans
/* * 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.webbeans.config; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.net.URL; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.ArrayList; import java.util.Stack; import javax.enterprise.context.Dependent; import javax.enterprise.inject.Model; import javax.enterprise.inject.Specializes; import javax.enterprise.inject.spi.AnnotatedType; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.Decorator; import javax.enterprise.inject.spi.InjectionPoint; import javax.enterprise.inject.spi.ProcessAnnotatedType; import javax.interceptor.Interceptor; import org.apache.webbeans.component.AbstractInjectionTargetBean; import org.apache.webbeans.component.AbstractProducerBean; import org.apache.webbeans.component.EnterpriseBeanMarker; import org.apache.webbeans.component.InjectionTargetBean; import org.apache.webbeans.component.InjectionTargetWrapper; import org.apache.webbeans.component.InterceptedMarker; import org.apache.webbeans.component.ManagedBean; import org.apache.webbeans.component.NewBean; import org.apache.webbeans.component.OwbBean; import org.apache.webbeans.component.WebBeansType; import org.apache.webbeans.component.creation.ManagedBeanCreatorImpl; import org.apache.webbeans.component.creation.BeanCreator.MetaDataProvider; import org.apache.webbeans.config.OWBLogConst; import org.apache.webbeans.container.BeanManagerImpl; import org.apache.webbeans.container.InjectionResolver; import org.apache.webbeans.corespi.ServiceLoader; import org.apache.webbeans.decorator.DecoratorsManager; import org.apache.webbeans.decorator.WebBeansDecorator; import org.apache.webbeans.deployment.StereoTypeManager; import org.apache.webbeans.deployment.StereoTypeModel; import org.apache.webbeans.exception.WebBeansConfigurationException; import org.apache.webbeans.exception.WebBeansDeploymentException; import org.apache.webbeans.exception.inject.InconsistentSpecializationException; import org.apache.webbeans.inject.OWBInjector; import org.apache.webbeans.intercept.InterceptorsManager; import org.apache.webbeans.intercept.webbeans.WebBeansInterceptor; import org.apache.webbeans.logger.WebBeansLogger; import org.apache.webbeans.plugins.PluginLoader; import org.apache.webbeans.portable.AnnotatedElementFactory; import org.apache.webbeans.portable.events.ExtensionLoader; import org.apache.webbeans.portable.events.ProcessAnnotatedTypeImpl; import org.apache.webbeans.portable.events.ProcessInjectionTargetImpl; import org.apache.webbeans.portable.events.discovery.AfterBeanDiscoveryImpl; import org.apache.webbeans.portable.events.discovery.AfterDeploymentValidationImpl; import org.apache.webbeans.portable.events.discovery.BeforeBeanDiscoveryImpl; import org.apache.webbeans.spi.JNDIService; import org.apache.webbeans.spi.ScannerService; import org.apache.webbeans.spi.plugins.OpenWebBeansJavaEEPlugin; import org.apache.webbeans.spi.plugins.OpenWebBeansWebPlugin; import org.apache.webbeans.util.AnnotationUtil; import org.apache.webbeans.util.ClassUtil; import org.apache.webbeans.util.WebBeansAnnotatedTypeUtil; import org.apache.webbeans.util.WebBeansConstants; import org.apache.webbeans.util.WebBeansUtil; import org.apache.webbeans.xml.WebBeansXMLConfigurator; import org.apache.webbeans.xml.XMLAnnotationTypeManager; import org.apache.webbeans.xml.XMLSpecializesManager; /** * Deploys the all beans that are defined in the {@link WebBeansScanner} at * the scanner phase. */ @SuppressWarnings("unchecked") //This class written as single threaded. public class BeansDeployer { //Logger instance private static final WebBeansLogger logger = WebBeansLogger.getLogger(BeansDeployer.class); /**Deployment is started or not*/ protected boolean deployed = false; /**XML Configurator*/ protected WebBeansXMLConfigurator xmlConfigurator = null; /**Discover ejb or not*/ protected boolean discoverEjb = false; /** * Creates a new deployer with given xml configurator. * * @param xmlConfigurator xml configurator */ public BeansDeployer(WebBeansXMLConfigurator xmlConfigurator) { this.xmlConfigurator = xmlConfigurator; String usage = OpenWebBeansConfiguration.getInstance().getProperty(OpenWebBeansConfiguration.USE_EJB_DISCOVERY); this.discoverEjb = Boolean.parseBoolean(usage); } /** * Deploys all the defined web beans components in the container startup. * <p> * It deploys from the web-beans.xml files and from the class files. It uses * the {@link org.apache.webbeans.corespi.ScannerService} to get classes. * </p> * * @throws WebBeansDeploymentException if any deployment exception occurs */ public void deploy(ScannerService scanner) { try { if (!deployed) { //Load Extensions ExtensionLoader.getInstance().loadExtensionServices(); // Bind manager JNDIService service = ServiceLoader.getService(JNDIService.class); service.bind(WebBeansConstants.WEB_BEANS_MANAGER_JNDI_NAME, BeanManagerImpl.getManager()); // Register Manager built-in component BeanManagerImpl.getManager().addBean(WebBeansUtil.getManagerBean()); //Fire Event fireBeforeBeanDiscoveryEvent(); //Deploy bean from XML. Also configures deployments, interceptors, decorators. deployFromXML(scanner); //Checking stereotype conditions checkStereoTypes(scanner); //Configure Default Beans configureDefaultBeans(); //Discover classpath classes deployFromClassPath(scanner); //Check Specialization checkSpecializations(scanner); //Fire Event fireAfterBeanDiscoveryEvent(); //Validate injection Points validateInjectionPoints(); //Fire Event fireAfterDeploymentValidationEvent(); deployed = true; } } catch(Exception e) { logger.error(e); WebBeansUtil.throwRuntimeExceptions(e); } } /** * Configure Default Beans. */ private void configureDefaultBeans() { BeanManagerImpl beanManager = BeanManagerImpl.getManager(); // Register Conversation built-in component beanManager.addBean(WebBeansUtil.getConversationBean()); // Register InjectionPoint bean beanManager.addBean(WebBeansUtil.getInjectionPointBean()); //Register Instance Bean beanManager.addBean(WebBeansUtil.getInstanceBean()); //Register Event Bean beanManager.addBean(WebBeansUtil.getEventBean()); //REgister Provider Beans OpenWebBeansJavaEEPlugin beanEeProvider = PluginLoader.getInstance().getJavaEEPlugin(); OpenWebBeansWebPlugin beanWebProvider = PluginLoader.getInstance().getWebPlugin(); if(beanEeProvider != null) { addDefaultBean(beanManager, "org.apache.webbeans.ee.common.beans.PrinicipalBean"); addDefaultBean(beanManager, "org.apache.webbeans.ee.beans.ValidatorBean"); addDefaultBean(beanManager, "org.apache.webbeans.ee.beans.ValidatorFactoryBean"); addDefaultBean(beanManager, "org.apache.webbeans.ee.beans.UserTransactionBean"); } else if(beanWebProvider != null) { addDefaultBean(beanManager, "org.apache.webbeans.ee.common.beans.PrinicipalBean"); } } private void addDefaultBean(BeanManagerImpl manager,String className) { Bean<?> bean = null; Class<?> beanClass = ClassUtil.getClassFromName(className); if(beanClass != null) { bean = (Bean)ClassUtil.newInstance(beanClass); } if(bean != null) { manager.addBean(bean); } } /** * Fires event before bean discovery. */ private void fireBeforeBeanDiscoveryEvent() { BeanManager manager = BeanManagerImpl.getManager(); manager.fireEvent(new BeforeBeanDiscoveryImpl(),new Annotation[0]); } /** * Fires event after bean discovery. */ private void fireAfterBeanDiscoveryEvent() { BeanManagerImpl manager = BeanManagerImpl.getManager(); manager.fireEvent(new AfterBeanDiscoveryImpl(),new Annotation[0]); WebBeansUtil.inspectErrorStack("There are errors that are added by AfterBeanDiscovery event observers. Look at logs for further details"); } /** * Fires event after deployment valdiation. */ private void fireAfterDeploymentValidationEvent() { BeanManagerImpl manager = BeanManagerImpl.getManager(); manager.fireEvent(new AfterDeploymentValidationImpl(),new Annotation[0]); WebBeansUtil.inspectErrorStack("There are errors that are added by AfterDeploymentValidation event observers. Look at logs for further details"); } /** * Validate all injection points. */ private void validateInjectionPoints() { logger.debug("Validation of injection points has started."); DecoratorsManager.getInstance().validateDecoratorClasses(); InterceptorsManager.getInstance().validateInterceptorClasses(); BeanManagerImpl manager = BeanManagerImpl.getManager(); Set<Bean<?>> beans = new HashSet<Bean<?>>(); //Adding decorators to validate Set<Decorator<?>> decorators = manager.getDecorators(); for(Decorator decorator : decorators) { WebBeansDecorator wbDec = (WebBeansDecorator)decorator; beans.add(wbDec); } logger.debug("Validation of the decorator's injection points has started."); //Validate Decorators validate(beans); beans.clear(); //Adding interceptors to validate Set<javax.enterprise.inject.spi.Interceptor<?>> interceptors = manager.getInterceptors(); for(javax.enterprise.inject.spi.Interceptor interceptor : interceptors) { WebBeansInterceptor wbInt = (WebBeansInterceptor)interceptor; beans.add(wbInt); } logger.debug("Validation of the interceptor's injection points has started."); //Validate Interceptors validate(beans); beans.clear(); beans = manager.getBeans(); //Validate Others validate(beans); logger.info(OWBLogConst.INFO_0008); } /** * Validates beans. * * @param beans deployed beans */ private void validate(Set<Bean<?>> beans) { BeanManagerImpl manager = BeanManagerImpl.getManager(); if (beans != null && beans.size() > 0) { Stack<String> beanNames = new Stack<String>(); for (Bean<?> bean : beans) { String beanName = null; if((beanName = bean.getName()) != null) { beanNames.push(beanName); } if((bean instanceof Decorator) || (bean instanceof javax.enterprise.inject.spi.Interceptor)) { if(!bean.getScope().equals(Dependent.class)) { logger.warn("Bean " + bean.toString() + "has not DependentScope. If an interceptor or decorator has any scope other than @Dependent, non-portable behaviour results."); } } if(bean instanceof InjectionTargetBean) { //Decorators not applied to interceptors/decorators/@NewBean if(!(bean instanceof Decorator) && !(bean instanceof javax.enterprise.inject.spi.Interceptor) && !(bean instanceof NewBean)) { DefinitionUtil.defineDecoratorStack((AbstractInjectionTargetBean<Object>)bean); } //If intercepted marker if(bean instanceof InterceptedMarker) { DefinitionUtil.defineBeanInterceptorStack((AbstractInjectionTargetBean<Object>)bean); } } //Check passivation scope checkPassivationScope(bean); //Bean injection points Set<InjectionPoint> injectionPoints = bean.getInjectionPoints(); //Check injection points if(injectionPoints != null) { for (InjectionPoint injectionPoint : injectionPoints) { if(!injectionPoint.isDelegate()) { manager.validate(injectionPoint); } else { if(!bean.getBeanClass().isAnnotationPresent(javax.decorator.Decorator.class) && !BeanManagerImpl.getManager().containsCustomDecoratorClass(bean.getBeanClass())) { throw new WebBeansConfigurationException("Delegate injection points can not defined by beans that are not decorator. Injection point : " + injectionPoint); } } } } } //Validate Bean names validateBeanNames(beanNames); //Clear Names beanNames.clear(); } } private void validateBeanNames(Stack<String> beanNames) { if(beanNames.size() > 0) { for(String beanName : beanNames) { for(String other : beanNames) { String part = null; int i = beanName.lastIndexOf('.'); if(i != -1) { part = beanName.substring(0,i); } if(beanName.equals(other)) { InjectionResolver resolver = InjectionResolver.getInstance(); Set<Bean<?>> beans = resolver.implResolveByName(beanName); if(beans.size() > 1) { beans = resolver.findByAlternatives(beans); if(beans.size() > 1) { throw new WebBeansConfigurationException("There are two different beans with name : " + beanName + " in the deployment archieve"); } } } else { if(part != null) { if(part.equals(other)) { throw new WebBeansConfigurationException("EL name of one bean is of the form x.y, where y is a valid bean EL name, and " + "x is the EL name of the other bean for the bean name : " + beanName); } } } } } } } /** * Discovers and deploys classes from class path. * * @param scanner discovery scanner * @throws ClassNotFoundException if class not found */ protected void deployFromClassPath(ScannerService scanner) throws ClassNotFoundException { logger.debug("Deploying configurations from class files has started."); // Start from the class Set<Class<?>> classIndex = scanner.getBeanClasses(); //Iterating over each class if (classIndex != null) { for(Class<?> implClass : classIndex) { //Define annotation type AnnotatedType<?> annotatedType = AnnotatedElementFactory.newAnnotatedType(implClass); //Fires ProcessAnnotatedType ProcessAnnotatedTypeImpl<?> processAnnotatedEvent = WebBeansUtil.fireProcessAnnotatedTypeEvent(annotatedType); //if veto() is called if(processAnnotatedEvent.isVeto()) { continue; } //Try class is Managed Bean boolean isDefined = defineManagedBean((Class<Object>)implClass, (ProcessAnnotatedTypeImpl<Object>)processAnnotatedEvent); //Try class is EJB bean if(!isDefined && this.discoverEjb) { if(EJBWebBeansConfigurator.isSessionBean(implClass)) { logger.debug(OWBLogConst.INFO_0010, new Object[]{implClass.getName()}); defineEnterpriseWebBean((Class<Object>)implClass, (ProcessAnnotatedTypeImpl<Object>)processAnnotatedEvent); } } } } logger.debug("Deploying configurations from class files has ended."); } /** * Discovers and deploys classes from XML. * * NOTE : Currently XML file is just used for configuring. * * @param scanner discovery scanner * @throws WebBeansDeploymentException if exception */ protected void deployFromXML(ScannerService scanner) throws WebBeansDeploymentException { logger.debug("Deploying configurations from XML files has started."); Set<URL> xmlLocations = scanner.getBeanXmls(); Iterator<URL> it = xmlLocations.iterator(); while (it.hasNext()) { URL fileURL = it.next(); String fileName = fileURL.getFile(); InputStream fis = null; try { fis = fileURL.openStream(); this.xmlConfigurator.configure(fis, fileName); } catch (IOException e) { throw new WebBeansDeploymentException(e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // all ok, ignore this! } } } } logger.debug("Deploying configurations from XML has ended successfully."); } /** * Checks specialization. * @param scanner scanner instance */ protected void checkSpecializations(ScannerService scanner) { logger.debug("Checking Specialization constraints has started."); try { Set<Class<?>> beanClasses = scanner.getBeanClasses(); if (beanClasses != null && beanClasses.size() > 0) { //superClassList is used to handle the case: Car, CarToyota, Bus, SchoolBus, CarFord //for which case, the owb should throw exception that both CarToyota and CarFord are //specialize Car. Class<?> superClass = null; ArrayList<Class<?>> superClassList = new ArrayList<Class<?>>(); ArrayList<Class<?>> specialClassList = new ArrayList<Class<?>>(); for(Class<?> specialClass : beanClasses) { if(AnnotationUtil.hasClassAnnotation(specialClass, Specializes.class)) { superClass = specialClass.getSuperclass(); if(superClass.equals(Object.class)) { throw new WebBeansConfigurationException(logger.getTokenString(OWBLogConst.EXCEPT_0003) + specialClass.getName() + logger.getTokenString(OWBLogConst.EXCEPT_0004)); } if (superClassList.contains(superClass)) { throw new InconsistentSpecializationException(logger.getTokenString(OWBLogConst.EXCEPT_0005) + superClass.getName()); } superClassList.add(superClass); specialClassList.add(specialClass); } } WebBeansUtil.configureSpecializations(specialClassList); } // XML Defined Specializations checkXMLSpecializations(); //configure specialized producer beans. WebBeansUtil.configureProducerMethodSpecializations(); } catch(Exception e) { throw new WebBeansDeploymentException(e); } logger.debug("Checking Specialization constraints has ended."); } /** * Check xml specializations. * NOTE : Currently XML is not used in configuration. */ protected void checkXMLSpecializations() { // Check XML specializations Set<Class<?>> clazzes = XMLSpecializesManager.getInstance().getXMLSpecializationClasses(); Iterator<Class<?>> it = clazzes.iterator(); Class<?> superClass = null; Class<?> specialClass = null; ArrayList<Class<?>> specialClassList = new ArrayList<Class<?>>(); while (it.hasNext()) { specialClass = it.next(); if (superClass == null) { superClass = specialClass.getSuperclass(); } else { if (superClass.equals(specialClass.getSuperclass())) { throw new InconsistentSpecializationException(logger.getTokenString(OWBLogConst.EXCEPT_XML) + logger.getTokenString(OWBLogConst.EXCEPT_0005) + superClass.getName()); } } specialClassList.add(specialClass); } WebBeansUtil.configureSpecializations(specialClassList); } /** * Check passivations. */ protected void checkPassivationScope(Bean<?> beanObj) { boolean validate = false; if(EnterpriseBeanMarker.class.isAssignableFrom(beanObj.getClass())) { EnterpriseBeanMarker marker = (EnterpriseBeanMarker)beanObj; if(marker.isPassivationCapable()) { validate = true; } } else if(BeanManagerImpl.getManager().isPassivatingScope(beanObj.getScope())) { if(WebBeansUtil.isPassivationCapable(beanObj) == null) { if(!(beanObj instanceof AbstractProducerBean)) { throw new WebBeansConfigurationException("Passivation scoped defined bean must be passivation capable, " + "but bean : " + beanObj.toString() + " is not passivation capable"); } else { validate = true; } } validate = true; } if(validate) { ((OwbBean<?>)beanObj).validatePassivationDependencies(); } } /** * Check steretypes. * @param scanner scanner instance */ protected void checkStereoTypes(ScannerService scanner) { logger.debug("Checking StereoType constraints has started."); addDefaultStereoTypes(); Set<Class<?>> beanClasses = scanner.getBeanClasses(); if (beanClasses != null && beanClasses.size() > 0) { for(Class<?> beanClass : beanClasses) { if(beanClass.isAnnotation()) { Class<? extends Annotation> stereoClass = (Class<? extends Annotation>) beanClass; if (AnnotationUtil.isStereoTypeAnnotation(stereoClass)) { if (!XMLAnnotationTypeManager.getInstance().hasStereoType(stereoClass)) { WebBeansUtil.checkStereoTypeClass(stereoClass); StereoTypeModel model = new StereoTypeModel(stereoClass); StereoTypeManager.getInstance().addStereoTypeModel(model); } } } } } logger.debug("Checking StereoType constraints has ended."); } /** * Adds default stereotypes. */ protected void addDefaultStereoTypes() { StereoTypeModel model = new StereoTypeModel(Model.class); StereoTypeManager.getInstance().addStereoTypeModel(model); model = new StereoTypeModel(javax.decorator.Decorator.class); StereoTypeManager.getInstance().addStereoTypeModel(model); model = new StereoTypeModel(Interceptor.class); StereoTypeManager.getInstance().addStereoTypeModel(model); } /** * Defines and configures managed bean. * @param <T> type info * @param clazz bean class * @return true if given class is configured as a managed bean */ protected <T> boolean defineManagedBean(Class<T> clazz, ProcessAnnotatedTypeImpl<T> processAnnotatedEvent) { //Bean manager BeanManagerImpl manager = BeanManagerImpl.getManager(); //Create an annotated type AnnotatedType<T> annotatedType = processAnnotatedEvent.getAnnotatedType(); //Fires ProcessInjectionTarget event for Java EE components instances //That supports injections but not managed beans ProcessInjectionTargetImpl<T> processInjectionTargetEvent = null; if(WebBeansUtil.supportsJavaEeComponentInjections(clazz)) { //Fires ProcessInjectionTarget processInjectionTargetEvent = WebBeansUtil.fireProcessInjectionTargetEventForJavaEeComponents(clazz); WebBeansUtil.inspectErrorStack("There are errors that are added by ProcessInjectionTarget event observers. Look at logs for further details"); //Sets custom InjectionTarget instance if(processInjectionTargetEvent.isSet()) { //Adding injection target manager.putInjectionTargetWrapperForJavaEeComponents(clazz, new InjectionTargetWrapper<T>(processInjectionTargetEvent.getInjectionTarget())); } //Checks that not contains @Inject InjectionPoint OWBInjector.checkInjectionPointForInjectInjectionPoint(clazz); } //Check for whether this class is candidate for Managed Bean if (ManagedBeanConfigurator.isManagedBean(clazz)) { //Check conditions ManagedBeanConfigurator.checkManagedBeanCondition(clazz); //Temporary managed bean instance creationa ManagedBean<T> managedBean = new ManagedBean<T>(clazz,WebBeansType.MANAGED); ManagedBeanCreatorImpl<T> managedBeanCreator = new ManagedBeanCreatorImpl<T>(managedBean); boolean annotationTypeSet = false; if(processAnnotatedEvent.isSet()) { annotationTypeSet = true; managedBean.setAnnotatedType(annotatedType); annotatedType = processAnnotatedEvent.getAnnotatedType(); managedBeanCreator.setAnnotatedType(annotatedType); managedBeanCreator.setMetaDataProvider(MetaDataProvider.THIRDPARTY); } //If ProcessInjectionTargetEvent is not set, set it if(processInjectionTargetEvent == null) { processInjectionTargetEvent = WebBeansUtil.fireProcessInjectionTargetEvent(managedBean); } //Decorator if(WebBeansAnnotatedTypeUtil.isAnnotatedTypeDecorator(annotatedType)) { logger.debug(OWBLogConst.INFO_0012, new Object[]{annotatedType.getJavaClass().getName()}); if(annotationTypeSet) { WebBeansAnnotatedTypeUtil.defineDecorator(annotatedType); } else { WebBeansUtil.defineDecorator(managedBeanCreator, processInjectionTargetEvent); } } //Interceptor else if(WebBeansAnnotatedTypeUtil.isAnnotatedTypeInterceptor(annotatedType)) { logger.debug(OWBLogConst.INFO_0011, new Object[]{annotatedType.getJavaClass().getName()}); if(annotationTypeSet) { WebBeansAnnotatedTypeUtil.defineInterceptor(annotatedType); } else { WebBeansUtil.defineInterceptor(managedBeanCreator, processInjectionTargetEvent); } } else { if(BeanManagerImpl.getManager().containsCustomDecoratorClass(annotatedType.getJavaClass()) || BeanManagerImpl.getManager().containsCustomInterceptorClass(annotatedType.getJavaClass())) { return false; } logger.debug(OWBLogConst.INFO_0009, new Object[]{annotatedType.getJavaClass().getName()}); WebBeansUtil.defineManagedBean(managedBeanCreator, processInjectionTargetEvent); } return true; } //Not a managed bean else { return false; } } /** * Defines enterprise bean via plugin. * @param <T> bean class type * @param clazz bean class */ protected <T> void defineEnterpriseWebBean(Class<T> clazz, ProcessAnnotatedType<T> processAnnotatedTypeEvent) { InjectionTargetBean<T> bean = (InjectionTargetBean<T>) EJBWebBeansConfigurator.defineEjbBean(clazz, processAnnotatedTypeEvent); WebBeansUtil.setInjectionTargetBeanEnableFlag(bean); } }
webbeans-impl/src/main/java/org/apache/webbeans/config/BeansDeployer.java
/* * 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.webbeans.config; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.net.URL; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.ArrayList; import java.util.Stack; import javax.enterprise.context.Dependent; import javax.enterprise.inject.Model; import javax.enterprise.inject.Specializes; import javax.enterprise.inject.spi.AnnotatedType; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.Decorator; import javax.enterprise.inject.spi.InjectionPoint; import javax.enterprise.inject.spi.ProcessAnnotatedType; import javax.interceptor.Interceptor; import org.apache.webbeans.component.AbstractInjectionTargetBean; import org.apache.webbeans.component.AbstractProducerBean; import org.apache.webbeans.component.EnterpriseBeanMarker; import org.apache.webbeans.component.InjectionTargetBean; import org.apache.webbeans.component.InjectionTargetWrapper; import org.apache.webbeans.component.InterceptedMarker; import org.apache.webbeans.component.ManagedBean; import org.apache.webbeans.component.NewBean; import org.apache.webbeans.component.OwbBean; import org.apache.webbeans.component.WebBeansType; import org.apache.webbeans.component.creation.ManagedBeanCreatorImpl; import org.apache.webbeans.component.creation.BeanCreator.MetaDataProvider; import org.apache.webbeans.config.OWBLogConst; import org.apache.webbeans.container.BeanManagerImpl; import org.apache.webbeans.container.InjectionResolver; import org.apache.webbeans.corespi.ServiceLoader; import org.apache.webbeans.decorator.DecoratorsManager; import org.apache.webbeans.decorator.WebBeansDecorator; import org.apache.webbeans.deployment.StereoTypeManager; import org.apache.webbeans.deployment.StereoTypeModel; import org.apache.webbeans.exception.WebBeansConfigurationException; import org.apache.webbeans.exception.WebBeansDeploymentException; import org.apache.webbeans.exception.inject.InconsistentSpecializationException; import org.apache.webbeans.inject.OWBInjector; import org.apache.webbeans.intercept.InterceptorsManager; import org.apache.webbeans.intercept.webbeans.WebBeansInterceptor; import org.apache.webbeans.logger.WebBeansLogger; import org.apache.webbeans.plugins.PluginLoader; import org.apache.webbeans.portable.AnnotatedElementFactory; import org.apache.webbeans.portable.events.ExtensionLoader; import org.apache.webbeans.portable.events.ProcessAnnotatedTypeImpl; import org.apache.webbeans.portable.events.ProcessInjectionTargetImpl; import org.apache.webbeans.portable.events.discovery.AfterBeanDiscoveryImpl; import org.apache.webbeans.portable.events.discovery.AfterDeploymentValidationImpl; import org.apache.webbeans.portable.events.discovery.BeforeBeanDiscoveryImpl; import org.apache.webbeans.spi.JNDIService; import org.apache.webbeans.spi.ScannerService; import org.apache.webbeans.spi.plugins.OpenWebBeansJavaEEPlugin; import org.apache.webbeans.spi.plugins.OpenWebBeansWebPlugin; import org.apache.webbeans.util.AnnotationUtil; import org.apache.webbeans.util.ClassUtil; import org.apache.webbeans.util.WebBeansAnnotatedTypeUtil; import org.apache.webbeans.util.WebBeansConstants; import org.apache.webbeans.util.WebBeansUtil; import org.apache.webbeans.xml.WebBeansXMLConfigurator; import org.apache.webbeans.xml.XMLAnnotationTypeManager; import org.apache.webbeans.xml.XMLSpecializesManager; /** * Deploys the all beans that are defined in the {@link WebBeansScanner} at * the scanner phase. */ @SuppressWarnings("unchecked") //This class written as single threaded. public class BeansDeployer { //Logger instance private static final WebBeansLogger logger = WebBeansLogger.getLogger(BeansDeployer.class); /**Deployment is started or not*/ protected boolean deployed = false; /**XML Configurator*/ protected WebBeansXMLConfigurator xmlConfigurator = null; /**Discover ejb or not*/ protected boolean discoverEjb = false; /** * Creates a new deployer with given xml configurator. * * @param xmlConfigurator xml configurator */ public BeansDeployer(WebBeansXMLConfigurator xmlConfigurator) { this.xmlConfigurator = xmlConfigurator; String usage = OpenWebBeansConfiguration.getInstance().getProperty(OpenWebBeansConfiguration.USE_EJB_DISCOVERY); this.discoverEjb = Boolean.parseBoolean(usage); } /** * Deploys all the defined web beans components in the container startup. * <p> * It deploys from the web-beans.xml files and from the class files. It uses * the {@link org.apache.webbeans.corespi.ScannerService} to get classes. * </p> * * @throws WebBeansDeploymentException if any deployment exception occurs */ public void deploy(ScannerService scanner) { try { if (!deployed) { //Load Extensions ExtensionLoader.getInstance().loadExtensionServices(); // Bind manager JNDIService service = ServiceLoader.getService(JNDIService.class); service.bind(WebBeansConstants.WEB_BEANS_MANAGER_JNDI_NAME, BeanManagerImpl.getManager()); // Register Manager built-in component BeanManagerImpl.getManager().addBean(WebBeansUtil.getManagerBean()); //Fire Event fireBeforeBeanDiscoveryEvent(); //Deploy bean from XML. Also configures deployments, interceptors, decorators. deployFromXML(scanner); //Checking stereotype conditions checkStereoTypes(scanner); //Configure Default Beans configureDefaultBeans(); //Discover classpath classes deployFromClassPath(scanner); //Check Specialization checkSpecializations(scanner); //Fire Event fireAfterBeanDiscoveryEvent(); //Validate injection Points validateInjectionPoints(); //Fire Event fireAfterDeploymentValidationEvent(); deployed = true; } } catch(Exception e) { logger.error(e); WebBeansUtil.throwRuntimeExceptions(e); } } /** * Configure Default Beans. */ private void configureDefaultBeans() { BeanManagerImpl beanManager = BeanManagerImpl.getManager(); // Register Conversation built-in component beanManager.addBean(WebBeansUtil.getConversationBean()); // Register InjectionPoint bean beanManager.addBean(WebBeansUtil.getInjectionPointBean()); //Register Instance Bean beanManager.addBean(WebBeansUtil.getInstanceBean()); //Register Event Bean beanManager.addBean(WebBeansUtil.getEventBean()); //REgister Provider Beans OpenWebBeansJavaEEPlugin beanEeProvider = PluginLoader.getInstance().getJavaEEPlugin(); OpenWebBeansWebPlugin beanWebProvider = PluginLoader.getInstance().getWebPlugin(); if(beanEeProvider != null) { addDefaultBean(beanManager, "org.apache.webbeans.ee.common.beans.PrinicipalBean"); addDefaultBean(beanManager, "org.apache.webbeans.ee.beans.ValidatorBean"); addDefaultBean(beanManager, "org.apache.webbeans.ee.beans.ValidatorFactoryBean"); addDefaultBean(beanManager, "org.apache.webbeans.ee.beans.UserTransactionBean"); } else if(beanWebProvider != null) { addDefaultBean(beanManager, "org.apache.webbeans.ee.common.beans.PrinicipalBean"); } } private void addDefaultBean(BeanManagerImpl manager,String className) { Bean<?> bean = null; Class<?> beanClass = ClassUtil.getClassFromName(className); if(beanClass != null) { bean = (Bean)ClassUtil.newInstance(beanClass); } if(bean != null) { manager.addBean(bean); } } /** * Fires event before bean discovery. */ private void fireBeforeBeanDiscoveryEvent() { BeanManager manager = BeanManagerImpl.getManager(); manager.fireEvent(new BeforeBeanDiscoveryImpl(),new Annotation[0]); } /** * Fires event after bean discovery. */ private void fireAfterBeanDiscoveryEvent() { BeanManagerImpl manager = BeanManagerImpl.getManager(); manager.fireEvent(new AfterBeanDiscoveryImpl(),new Annotation[0]); WebBeansUtil.inspectErrorStack("There are errors that are added by AfterBeanDiscovery event observers. Look at logs for further details"); } /** * Fires event after deployment valdiation. */ private void fireAfterDeploymentValidationEvent() { BeanManagerImpl manager = BeanManagerImpl.getManager(); manager.fireEvent(new AfterDeploymentValidationImpl(),new Annotation[0]); WebBeansUtil.inspectErrorStack("There are errors that are added by AfterDeploymentValidation event observers. Look at logs for further details"); } /** * Validate all injection points. */ private void validateInjectionPoints() { logger.debug("Validation of injection points has started."); DecoratorsManager.getInstance().validateDecoratorClasses(); InterceptorsManager.getInstance().validateInterceptorClasses(); BeanManagerImpl manager = BeanManagerImpl.getManager(); Set<Bean<?>> beans = new HashSet<Bean<?>>(); //Adding decorators to validate Set<Decorator<?>> decorators = manager.getDecorators(); for(Decorator decorator : decorators) { WebBeansDecorator wbDec = (WebBeansDecorator)decorator; beans.add(wbDec); } logger.debug("Validation of the decorator's injection points has started."); //Validate Decorators validate(beans); beans.clear(); //Adding interceptors to validate Set<javax.enterprise.inject.spi.Interceptor<?>> interceptors = manager.getInterceptors(); for(javax.enterprise.inject.spi.Interceptor interceptor : interceptors) { WebBeansInterceptor wbInt = (WebBeansInterceptor)interceptor; beans.add(wbInt); } logger.debug("Validation of the interceptor's injection points has started."); //Validate Interceptors validate(beans); beans.clear(); beans = manager.getBeans(); //Validate Others validate(beans); logger.info(OWBLogConst.INFO_0008); } /** * Validates beans. * * @param beans deployed beans */ private void validate(Set<Bean<?>> beans) { BeanManagerImpl manager = BeanManagerImpl.getManager(); if (beans != null && beans.size() > 0) { Stack<String> beanNames = new Stack<String>(); for (Bean<?> bean : beans) { String beanName = null; if((beanName = bean.getName()) != null) { beanNames.push(beanName); } if((bean instanceof Decorator) || (bean instanceof javax.enterprise.inject.spi.Interceptor)) { if(!bean.getScope().equals(Dependent.class)) { logger.warn("Bean " + bean.toString() + "has not DependentScope. If an interceptor or decorator has any scope other than @Dependent, non-portable behaviour results."); } } if(bean instanceof InjectionTargetBean) { //Decorators not applied to interceptors/decorators/@NewBean if(!(bean instanceof Decorator) && !(bean instanceof javax.enterprise.inject.spi.Interceptor) && !(bean instanceof NewBean)) { DefinitionUtil.defineDecoratorStack((AbstractInjectionTargetBean<Object>)bean); } //If intercepted marker if(bean instanceof InterceptedMarker) { DefinitionUtil.defineBeanInterceptorStack((AbstractInjectionTargetBean<Object>)bean); } } //Check passivation scope checkPassivationScope(bean); //Bean injection points Set<InjectionPoint> injectionPoints = bean.getInjectionPoints(); //Check injection points if(injectionPoints != null) { for (InjectionPoint injectionPoint : injectionPoints) { if(!injectionPoint.isDelegate()) { manager.validate(injectionPoint); } else { if(!bean.getBeanClass().isAnnotationPresent(javax.decorator.Decorator.class) && !BeanManagerImpl.getManager().containsCustomDecoratorClass(bean.getBeanClass())) { throw new WebBeansConfigurationException("Delegate injection points can not defined by beans that are not decorator. Injection point : " + injectionPoint); } } } } } //Validate Bean names validateBeanNames(beanNames); //Clear Names beanNames.clear(); } } private void validateBeanNames(Stack<String> beanNames) { if(beanNames.size() > 0) { for(String beanName : beanNames) { for(String other : beanNames) { String part = null; int i = beanName.lastIndexOf('.'); if(i != -1) { part = beanName.substring(0,i); } if(beanName.equals(other)) { InjectionResolver resolver = InjectionResolver.getInstance(); Set<Bean<?>> beans = resolver.implResolveByName(beanName); if(beans.size() > 1) { beans = resolver.findByAlternatives(beans); if(beans.size() > 1) { throw new WebBeansConfigurationException("There are two different beans with name : " + beanName + " in the deployment archieve"); } } } else { if(part != null) { if(part.equals(other)) { throw new WebBeansConfigurationException("EL name of one bean is of the form x.y, where y is a valid bean EL name, and " + "x is the EL name of the other bean for the bean name : " + beanName); } } } } } } } /** * Discovers and deploys classes from class path. * * @param scanner discovery scanner * @throws ClassNotFoundException if class not found */ protected void deployFromClassPath(ScannerService scanner) throws ClassNotFoundException { logger.debug("Deploying configurations from class files has started."); // Start from the class Set<Class<?>> classIndex = scanner.getBeanClasses(); //Iterating over each class if (classIndex != null) { for(Class<?> implClass : classIndex) { //Define annotation type AnnotatedType<?> annotatedType = AnnotatedElementFactory.newAnnotatedType(implClass); //Fires ProcessAnnotatedType ProcessAnnotatedTypeImpl<?> processAnnotatedEvent = WebBeansUtil.fireProcessAnnotatedTypeEvent(annotatedType); //if veto() is called if(processAnnotatedEvent.isVeto()) { continue; } //Try class is Managed Bean boolean isDefined = defineManagedBean((Class<Object>)implClass, (ProcessAnnotatedTypeImpl<Object>)processAnnotatedEvent); //Try class is EJB bean if(!isDefined && this.discoverEjb) { if(EJBWebBeansConfigurator.isSessionBean(implClass)) { logger.info(OWBLogConst.INFO_0010, new Object[]{implClass.getName()}); defineEnterpriseWebBean((Class<Object>)implClass, (ProcessAnnotatedTypeImpl<Object>)processAnnotatedEvent); } } } } logger.debug("Deploying configurations from class files has ended."); } /** * Discovers and deploys classes from XML. * * NOTE : Currently XML file is just used for configuring. * * @param scanner discovery scanner * @throws WebBeansDeploymentException if exception */ protected void deployFromXML(ScannerService scanner) throws WebBeansDeploymentException { logger.debug("Deploying configurations from XML files has started."); Set<URL> xmlLocations = scanner.getBeanXmls(); Iterator<URL> it = xmlLocations.iterator(); while (it.hasNext()) { URL fileURL = it.next(); String fileName = fileURL.getFile(); InputStream fis = null; try { fis = fileURL.openStream(); this.xmlConfigurator.configure(fis, fileName); } catch (IOException e) { throw new WebBeansDeploymentException(e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // all ok, ignore this! } } } } logger.debug("Deploying configurations from XML has ended successfully."); } /** * Checks specialization. * @param scanner scanner instance */ protected void checkSpecializations(ScannerService scanner) { logger.debug("Checking Specialization constraints has started."); try { Set<Class<?>> beanClasses = scanner.getBeanClasses(); if (beanClasses != null && beanClasses.size() > 0) { //superClassList is used to handle the case: Car, CarToyota, Bus, SchoolBus, CarFord //for which case, the owb should throw exception that both CarToyota and CarFord are //specialize Car. Class<?> superClass = null; ArrayList<Class<?>> superClassList = new ArrayList<Class<?>>(); ArrayList<Class<?>> specialClassList = new ArrayList<Class<?>>(); for(Class<?> specialClass : beanClasses) { if(AnnotationUtil.hasClassAnnotation(specialClass, Specializes.class)) { superClass = specialClass.getSuperclass(); if(superClass.equals(Object.class)) { throw new WebBeansConfigurationException(logger.getTokenString(OWBLogConst.EXCEPT_0003) + specialClass.getName() + logger.getTokenString(OWBLogConst.EXCEPT_0004)); } if (superClassList.contains(superClass)) { throw new InconsistentSpecializationException(logger.getTokenString(OWBLogConst.EXCEPT_0005) + superClass.getName()); } superClassList.add(superClass); specialClassList.add(specialClass); } } WebBeansUtil.configureSpecializations(specialClassList); } // XML Defined Specializations checkXMLSpecializations(); //configure specialized producer beans. WebBeansUtil.configureProducerMethodSpecializations(); } catch(Exception e) { throw new WebBeansDeploymentException(e); } logger.debug("Checking Specialization constraints has ended."); } /** * Check xml specializations. * NOTE : Currently XML is not used in configuration. */ protected void checkXMLSpecializations() { // Check XML specializations Set<Class<?>> clazzes = XMLSpecializesManager.getInstance().getXMLSpecializationClasses(); Iterator<Class<?>> it = clazzes.iterator(); Class<?> superClass = null; Class<?> specialClass = null; ArrayList<Class<?>> specialClassList = new ArrayList<Class<?>>(); while (it.hasNext()) { specialClass = it.next(); if (superClass == null) { superClass = specialClass.getSuperclass(); } else { if (superClass.equals(specialClass.getSuperclass())) { throw new InconsistentSpecializationException(logger.getTokenString(OWBLogConst.EXCEPT_XML) + logger.getTokenString(OWBLogConst.EXCEPT_0005) + superClass.getName()); } } specialClassList.add(specialClass); } WebBeansUtil.configureSpecializations(specialClassList); } /** * Check passivations. */ protected void checkPassivationScope(Bean<?> beanObj) { boolean validate = false; if(EnterpriseBeanMarker.class.isAssignableFrom(beanObj.getClass())) { EnterpriseBeanMarker marker = (EnterpriseBeanMarker)beanObj; if(marker.isPassivationCapable()) { validate = true; } } else if(BeanManagerImpl.getManager().isPassivatingScope(beanObj.getScope())) { if(WebBeansUtil.isPassivationCapable(beanObj) == null) { if(!(beanObj instanceof AbstractProducerBean)) { throw new WebBeansConfigurationException("Passivation scoped defined bean must be passivation capable, " + "but bean : " + beanObj.toString() + " is not passivation capable"); } else { validate = true; } } validate = true; } if(validate) { ((OwbBean<?>)beanObj).validatePassivationDependencies(); } } /** * Check steretypes. * @param scanner scanner instance */ protected void checkStereoTypes(ScannerService scanner) { logger.debug("Checking StereoType constraints has started."); addDefaultStereoTypes(); Set<Class<?>> beanClasses = scanner.getBeanClasses(); if (beanClasses != null && beanClasses.size() > 0) { for(Class<?> beanClass : beanClasses) { if(beanClass.isAnnotation()) { Class<? extends Annotation> stereoClass = (Class<? extends Annotation>) beanClass; if (AnnotationUtil.isStereoTypeAnnotation(stereoClass)) { if (!XMLAnnotationTypeManager.getInstance().hasStereoType(stereoClass)) { WebBeansUtil.checkStereoTypeClass(stereoClass); StereoTypeModel model = new StereoTypeModel(stereoClass); StereoTypeManager.getInstance().addStereoTypeModel(model); } } } } } logger.debug("Checking StereoType constraints has ended."); } /** * Adds default stereotypes. */ protected void addDefaultStereoTypes() { StereoTypeModel model = new StereoTypeModel(Model.class); StereoTypeManager.getInstance().addStereoTypeModel(model); model = new StereoTypeModel(javax.decorator.Decorator.class); StereoTypeManager.getInstance().addStereoTypeModel(model); model = new StereoTypeModel(Interceptor.class); StereoTypeManager.getInstance().addStereoTypeModel(model); } /** * Defines and configures managed bean. * @param <T> type info * @param clazz bean class * @return true if given class is configured as a managed bean */ protected <T> boolean defineManagedBean(Class<T> clazz, ProcessAnnotatedTypeImpl<T> processAnnotatedEvent) { //Bean manager BeanManagerImpl manager = BeanManagerImpl.getManager(); //Create an annotated type AnnotatedType<T> annotatedType = processAnnotatedEvent.getAnnotatedType(); //Fires ProcessInjectionTarget event for Java EE components instances //That supports injections but not managed beans ProcessInjectionTargetImpl<T> processInjectionTargetEvent = null; if(WebBeansUtil.supportsJavaEeComponentInjections(clazz)) { //Fires ProcessInjectionTarget processInjectionTargetEvent = WebBeansUtil.fireProcessInjectionTargetEventForJavaEeComponents(clazz); WebBeansUtil.inspectErrorStack("There are errors that are added by ProcessInjectionTarget event observers. Look at logs for further details"); //Sets custom InjectionTarget instance if(processInjectionTargetEvent.isSet()) { //Adding injection target manager.putInjectionTargetWrapperForJavaEeComponents(clazz, new InjectionTargetWrapper<T>(processInjectionTargetEvent.getInjectionTarget())); } //Checks that not contains @Inject InjectionPoint OWBInjector.checkInjectionPointForInjectInjectionPoint(clazz); } //Check for whether this class is candidate for Managed Bean if (ManagedBeanConfigurator.isManagedBean(clazz)) { //Check conditions ManagedBeanConfigurator.checkManagedBeanCondition(clazz); //Temporary managed bean instance creationa ManagedBean<T> managedBean = new ManagedBean<T>(clazz,WebBeansType.MANAGED); ManagedBeanCreatorImpl<T> managedBeanCreator = new ManagedBeanCreatorImpl<T>(managedBean); boolean annotationTypeSet = false; if(processAnnotatedEvent.isSet()) { annotationTypeSet = true; managedBean.setAnnotatedType(annotatedType); annotatedType = processAnnotatedEvent.getAnnotatedType(); managedBeanCreator.setAnnotatedType(annotatedType); managedBeanCreator.setMetaDataProvider(MetaDataProvider.THIRDPARTY); } //If ProcessInjectionTargetEvent is not set, set it if(processInjectionTargetEvent == null) { processInjectionTargetEvent = WebBeansUtil.fireProcessInjectionTargetEvent(managedBean); } //Decorator if(WebBeansAnnotatedTypeUtil.isAnnotatedTypeDecorator(annotatedType)) { logger.debug(OWBLogConst.INFO_0012, new Object[]{annotatedType.getJavaClass().getName()}); if(annotationTypeSet) { WebBeansAnnotatedTypeUtil.defineDecorator(annotatedType); } else { WebBeansUtil.defineDecorator(managedBeanCreator, processInjectionTargetEvent); } } //Interceptor else if(WebBeansAnnotatedTypeUtil.isAnnotatedTypeInterceptor(annotatedType)) { logger.debug(OWBLogConst.INFO_0011, new Object[]{annotatedType.getJavaClass().getName()}); if(annotationTypeSet) { WebBeansAnnotatedTypeUtil.defineInterceptor(annotatedType); } else { WebBeansUtil.defineInterceptor(managedBeanCreator, processInjectionTargetEvent); } } else { if(BeanManagerImpl.getManager().containsCustomDecoratorClass(annotatedType.getJavaClass()) || BeanManagerImpl.getManager().containsCustomInterceptorClass(annotatedType.getJavaClass())) { return false; } logger.debug(OWBLogConst.INFO_0009, new Object[]{annotatedType.getJavaClass().getName()}); WebBeansUtil.defineManagedBean(managedBeanCreator, processInjectionTargetEvent); } return true; } //Not a managed bean else { return false; } } /** * Defines enterprise bean via plugin. * @param <T> bean class type * @param clazz bean class */ protected <T> void defineEnterpriseWebBean(Class<T> clazz, ProcessAnnotatedType<T> processAnnotatedTypeEvent) { InjectionTargetBean<T> bean = (InjectionTargetBean<T>) EJBWebBeansConfigurator.defineEjbBean(clazz, processAnnotatedTypeEvent); WebBeansUtil.setInjectionTargetBeanEnableFlag(bean); } }
Change info message to debug git-svn-id: 6e2e506005f11016269006bf59d22f905406eeba@944809 13f79535-47bb-0310-9956-ffa450edef68
webbeans-impl/src/main/java/org/apache/webbeans/config/BeansDeployer.java
Change info message to debug
<ide><path>ebbeans-impl/src/main/java/org/apache/webbeans/config/BeansDeployer.java <ide> { <ide> if(EJBWebBeansConfigurator.isSessionBean(implClass)) <ide> { <del> logger.info(OWBLogConst.INFO_0010, new Object[]{implClass.getName()}); <add> logger.debug(OWBLogConst.INFO_0010, new Object[]{implClass.getName()}); <ide> defineEnterpriseWebBean((Class<Object>)implClass, (ProcessAnnotatedTypeImpl<Object>)processAnnotatedEvent); <ide> } <ide> }
JavaScript
apache-2.0
7ccadb57fad73ffe84dbc73a43c7edaa64367f54
0
membase/ns_server,membase/ns_server,ceejatec/ns_server,t3rm1n4l/ns_server,vzasade/ns_server,mschoch/ns_server,mschoch/ns_server,t3rm1n4l/ns_server,mschoch/ns_server,daverigby/ns_server,nimishzynga/ns_server,t3rm1n4l/ns_server,membase/ns_server,pavel-blagodov/ns_server,daverigby/ns_server,vzasade/ns_server,membase/ns_server,nimishzynga/ns_server,nimishzynga/ns_server,t3rm1n4l/ns_server,pavel-blagodov/ns_server,pavel-blagodov/ns_server,ceejatec/ns_server,ceejatec/ns_server,nimishzynga/ns_server,ceejatec/ns_server,ceejatec/ns_server,vzasade/ns_server,daverigby/ns_server,vzasade/ns_server,ceejatec/ns_server,nimishzynga/ns_server,daverigby/ns_server,membase/ns_server,membase/ns_server,daverigby/ns_server,mschoch/ns_server,mschoch/ns_server,nimishzynga/ns_server,t3rm1n4l/ns_server,pavel-blagodov/ns_server,mschoch/ns_server
/** Copyright 2011 Couchbase, 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. **/ var ServersSection = { hostnameComparator: mkComparatorByProp('hostname', naturalSort), pendingEject: [], // nodes to eject on next rebalance pending: [], // nodes for pending tab active: [], // nodes for active tab allNodes: [], // all known nodes visitTab: function (tabName) { if (ThePage.currentSection != 'servers') { $('html, body').animate({scrollTop: 0}, 250); } ThePage.ensureSection('servers'); this.tabs.setValue(tabName); }, updateData: function () { var self = this; var serversValue = self.serversCell.value || {}; _.each("pendingEject pending active allNodes".split(' '), function (attr) { self[attr] = serversValue[attr] || []; }); }, renderEverything: function () { this.detailsWidget.prepareDrawing(); var details = this.poolDetails.value; var rebalancing = details && details.rebalanceStatus != 'none'; var pending = this.pending; var active = this.active; this.serversQ.find('.add_button').toggle(!!(details && !rebalancing)); this.serversQ.find('.stop_rebalance_button').toggle(!!rebalancing); var mayRebalance = !rebalancing && pending.length !=0; if (details && !rebalancing && !details.balanced) mayRebalance = true; var unhealthyActive = _.detect(active, function (n) { return n.clusterMembership == 'active' && !n.pendingEject && n.status === 'unhealthy' }) if (unhealthyActive) mayRebalance = false; var rebalanceButton = this.serversQ.find('.rebalance_button').toggle(!!details); rebalanceButton.toggleClass('disabled', !mayRebalance); if (details && !rebalancing) { $('#rebalance_tab .badge span').text(pending.length); $('#rebalance_tab').toggleClass('badge_display', !!pending.length); } else { $('#rebalance_tab').toggleClass('badge_display', false); } this.serversQ.toggleClass('rebalancing', !!rebalancing); if (!details) return; if (active.length) { renderTemplate('manage_server_list', { rows: active, expandingAllowed: !IOCenter.staleness.value }, $i('active_server_list_container')); renderTemplate('manage_server_list', { rows: pending, expandingAllowed: false }, $i('pending_server_list_container')); } if (rebalancing) { $('#servers .add_button').hide(); this.renderRebalance(details); } if (IOCenter.staleness.value) { $('#servers .staleness-notice').show(); $('#servers').find('.add_button, .rebalance_button').hide(); $('#active_server_list_container, #pending_server_list_container').find('.re_add_button, .eject_server, .failover_server, .remove_from_list').addClass('disabled'); } else { $('#servers .staleness-notice').hide(); $('#servers').find('.rebalance_button').show(); $('#servers .add_button')[rebalancing ? 'hide' : 'show'](); } $('#active_server_list_container .last-active').find('.eject_server').addClass('disabled').end() .find('.failover_server').addClass('disabled'); $('#active_server_list_container .server_down .eject_server').addClass('disabled'); $('.failed_over .eject_server, .failed_over .failover_server').hide(); }, renderServerDetails: function (item) { return this.detailsWidget.renderItemDetails(item); }, renderRebalance: function (details) { var progress = this.rebalanceProgress.value; if (!progress) { progress = {}; } nodes = _.clone(details.nodes); nodes.sort(this.hostnameComparator); var emptyProgress = {progress: 0}; _.each(nodes, function (n) { var p = progress[n.otpNode]; if (!p) p = emptyProgress; n.progress = p.progress; n.percent = truncateTo3Digits(n.progress * 100); $($i(n.otpNode.replace('@', '-'))).find('.actions').html('<span class="usage_info">' + escapeHTML(n.percent) + '% Complete</span><span class="server_usage"><span style="width: ' + escapeHTML(n.percent) + '%;"></span></span>'); }); }, refreshEverything: function () { this.updateData(); this.renderEverything(); // It displays the status of auto-failover, hence we need to refresh // it to get the current values AutoFailoverSection.refreshStatus(); }, onRebalanceProgress: function () { var value = this.rebalanceProgress.value; console.log("got progress: ", value); if (value.status == 'none') { this.poolDetails.invalidate(); this.rebalanceProgressIsInteresting.setValue(false); if (value.errorMessage) { displayNotice(value.errorMessage, true); } return } this.renderRebalance(this.poolDetails.value); this.rebalanceProgress.recalculateAfterDelay(250); }, init: function () { var self = this; self.poolDetails = DAL.cells.currentPoolDetailsCell; self.tabs = new TabsCell("serversTab", "#servers .tabs", "#servers .panes > div", ["active", "pending"]); var detailsWidget = self.detailsWidget = new MultiDrawersWidget({ hashFragmentParam: 'openedServers', template: 'server_details', elementKey: 'otpNode', placeholderCSS: '#servers .settings-placeholder', actionLink: 'openServer', actionLinkCallback: function () { ThePage.ensureSection('servers'); }, uriExtractor: function (nodeInfo) { return "/nodes/" + encodeURIComponent(nodeInfo.otpNode); }, valueTransformer: function (nodeInfo, nodeSettings) { return _.extend({}, nodeInfo, nodeSettings); }, listCell: Cell.compute(function (v) {return v.need(DAL.cells.serversCell).active}) }); self.serversCell = DAL.cells.serversCell; self.poolDetails.subscribeValue(function (poolDetails) { $($.makeArray($('#servers .failover_warning')).slice(1)).remove(); var warning = $('#servers .failover_warning'); if (!poolDetails || poolDetails.rebalanceStatus != 'none') { return; } function showWarning(text) { warning.after(warning.clone().find('.warning-text').text(text).end().css('display', 'block')); } _.each(poolDetails.failoverWarnings, function (failoverWarning) { switch (failoverWarning) { case 'failoverNeeded': break; case 'rebalanceNeeded': showWarning('Rebalance required, some data is not currently replicated!'); break; case 'hardNodesNeeded': showWarning('At least two servers are required to provide replication!'); break; case 'softNodesNeeded': showWarning('Additional active servers required to provide the desired number of replicas!'); break; case 'softRebalanceNeeded': showWarning('Rebalance recommended, some data does not have the desired number of replicas!'); break; default: console.log('Got unknown failover warning: ' + failoverSafety); } }); }); self.serversCell.subscribeAny($m(self, "refreshEverything")); prepareTemplateForCell('active_server_list', self.serversCell); prepareTemplateForCell('pending_server_list', self.serversCell); var serversQ = self.serversQ = $('#servers'); serversQ.find('.rebalance_button').live('click', self.accountForDisabled($m(self, 'onRebalance'))); serversQ.find('.add_button').live('click', $m(self, 'onAdd')); serversQ.find('.stop_rebalance_button').live('click', $m(self, 'onStopRebalance')); function mkServerRowHandler(handler) { return function (e) { var serverRow = $(this).closest('.server_row').find('td:first-child').data('server') || $(this).closest('.add_back_row').next().find('td:first-child').data('server'); return handler.call(this, e, serverRow); } } function mkServerAction(handler) { return ServersSection.accountForDisabled(mkServerRowHandler(function (e, serverRow) { e.preventDefault(); return handler(serverRow.hostname); })); } serversQ.find('.re_add_button').live('click', mkServerAction($m(self, 'reAddNode'))); serversQ.find('.eject_server').live('click', mkServerAction($m(self, 'ejectNode'))); serversQ.find('.failover_server').live('click', mkServerAction($m(self, 'failoverNode'))); serversQ.find('.remove_from_list').live('click', mkServerAction($m(self, 'removeFromList'))); self.rebalanceProgressIsInteresting = new Cell(); self.rebalanceProgressIsInteresting.setValue(false); self.poolDetails.subscribeValue(function (poolDetails) { if (poolDetails && poolDetails.rebalanceStatus != 'none') self.rebalanceProgressIsInteresting.setValue(true); }); // TODO: should we ignore errors here ? this.rebalanceProgress = new Cell(function (interesting, poolDetails) { if (!interesting) return; return future.get({url: poolDetails.rebalanceProgressUri}); }, {interesting: self.rebalanceProgressIsInteresting, poolDetails: self.poolDetails}); self.rebalanceProgress.keepValueDuringAsync = true; self.rebalanceProgress.subscribe($m(self, 'onRebalanceProgress')); }, accountForDisabled: function (handler) { return function (e) { if ($(e.currentTarget).hasClass('disabled')) { e.preventDefault(); return; } return handler.call(this, e); } }, renderUsage: function (e, totals, withQuotaTotal) { var options = { topAttrs: {'class': "usage-block"}, topRight: ['Total', ViewHelpers.formatMemSize(totals.total)], items: [ {name: 'In Use', value: totals.usedByData, attrs: {style: 'background-color:#00BCE9'}, tdAttrs: {style: "color:#1878A2;"} }, {name: 'Other Data', value: totals.used - totals.usedByData, attrs: {style:"background-color:#FDC90D"}, tdAttrs: {style: "color:#C19710;"}}, {name: 'Free', value: totals.total - totals.used} ], markers: [] }; if (withQuotaTotal) { options.topLeft = ['Membase Quota', ViewHelpers.formatMemSize(totals.quotaTotal)]; options.markers.push({value: totals.quotaTotal, attrs: {style: "background-color:#E43A1B;"}}); } $(e).replaceWith(memorySizesGaugeHTML(options)); }, onEnter: function () { // we need this 'cause switchSection clears rebalancing class this.refreshEverything(); }, onLeave: function () { this.detailsWidget.reset(); }, onRebalance: function () { var self = this; if (!self.poolDetails.value) { return; } self.postAndReload(self.poolDetails.value.controllers.rebalance.uri, {knownNodes: _.pluck(self.allNodes, 'otpNode').join(','), ejectedNodes: _.pluck(self.pendingEject, 'otpNode').join(',')}); self.poolDetails.getValue(function () { // switch to active server tab when poolDetails reload is complete self.tabs.setValue("active"); }); }, onStopRebalance: function () { if (!self.poolDetails.value) { return; } this.postAndReload(this.poolDetails.value.stopRebalanceUri, ""); }, validateJoinClusterParams: function (form) { var data = {} _.each("hostname user password".split(' '), function (name) { data[name] = form.find('[name=' + name + ']').val(); }); var errors = []; if (data['hostname'] == "") errors.push("Server IP Address cannot be blank."); if (!data['user'] || !data['password']) errors.push("Username and Password are both required to join a cluster."); if (!errors.length) return data; return errors; }, onAdd: function () { var self = this; if (!self.poolDetails.value) { return; } var uri = self.poolDetails.value.controllers.addNode.uri; var dialog = $('#join_cluster_dialog'); var form = dialog.find('form'); $('#join_cluster_dialog_errors_container').empty(); $('#join_cluster_dialog form').get(0).reset(); dialog.find("input:not([type]), input[type=text], input[type=password]").val(''); dialog.find('[name=user]').val('Administrator'); showDialog('join_cluster_dialog', { onHide: function () { form.unbind('submit'); }}); form.bind('submit', function (e) { e.preventDefault(); var errors = self.validateJoinClusterParams(form); if (errors.length) { renderTemplate('join_cluster_dialog_errors', errors); return; } var confirmed; $('#join_cluster_dialog').addClass('overlayed') .dialog('option', 'closeOnEscape', false); showDialog('add_confirmation_dialog', { closeOnEscape: false, eventBindings: [['.save_button', 'click', function (e) { e.preventDefault(); confirmed = true; hideDialog('add_confirmation_dialog'); $('#join_cluster_dialog_errors_container').empty(); var overlay = overlayWithSpinner($($i('join_cluster_dialog'))); self.poolDetails.setValue(undefined); postWithValidationErrors(uri, form, function (data, status) { self.poolDetails.invalidate(); overlay.remove(); if (status != 'success') { renderTemplate('join_cluster_dialog_errors', data) } else { hideDialog('join_cluster_dialog'); } }) }]], onHide: function () { $('#join_cluster_dialog').removeClass('overlayed') .dialog('option', 'closeOnEscape', true); } }); }); }, findNode: function (hostname) { return _.detect(this.allNodes, function (n) { return n.hostname == hostname; }); }, mustFindNode: function (hostname) { var rv = this.findNode(hostname); if (!rv) { throw new Error("failed to find node info for: " + hostname); } return rv; }, reDraw: function () { this.serversCell.invalidate(); }, ejectNode: function (hostname) { var self = this; var node = self.mustFindNode(hostname); if (node.pendingEject) return; showDialogHijackingSave("eject_confirmation_dialog", ".save_button", function () { if (!self.poolDetails.value) { return; } if (node.clusterMembership == 'inactiveAdded') { self.postAndReload(self.poolDetails.value.controllers.ejectNode.uri, {otpNode: node.otpNode}); } else { self.pendingEject.push(node); self.reDraw(); } }); }, failoverNode: function (hostname) { var self = this; var node; showDialogHijackingSave("failover_confirmation_dialog", ".save_button", function () { if (!node) throw new Error("must not happen!"); if (!self.poolDetails.value) { return; } self.postAndReload(self.poolDetails.value.controllers.failOver.uri, {otpNode: node.otpNode}, undefined, {timeout: 120000}); }); var dialog = $('#failover_confirmation_dialog'); var overlay = overlayWithSpinner(dialog.find('.content').need(1)); var statusesCell = DAL.cells.nodeStatusesCell; statusesCell.setValue(undefined); statusesCell.invalidate(); statusesCell.changedSlot.subscribeOnce(function () { overlay.remove(); dialog.find('.warning').hide(); var statuses = statusesCell.value; node = statuses[hostname]; if (!node) { hideDialog("failover_confirmation_dialog"); return; } var backfill = node.replication < 1; var down = node.status != 'healthy'; var visibleWarning = dialog.find(['.warning', down ? 'down' : 'up', backfill ? 'backfill' : 'no_backfill'].join('_')).show(); dialog.find('.backfill_percent').text(truncateTo3Digits(node.replication * 100)); var confirmation = visibleWarning.find('[name=confirmation]') if (confirmation.length) { confirmation.boolAttr('checked', false); function onChange() { var checked = !!confirmation.attr('checked'); dialog.find('.save_button').boolAttr('disabled', !checked); } function onHide() { confirmation.unbind('change', onChange); dialog.unbind('dialog:hide', onHide); } confirmation.bind('change', onChange); dialog.bind('dialog:hide', onHide); onChange(); } else { dialog.find(".save_button").removeAttr("disabled"); } }); }, reAddNode: function (hostname) { if (!self.poolDetails.value) { return; } var node = this.mustFindNode(hostname); this.postAndReload(this.poolDetails.value.controllers.reAddNode.uri, {otpNode: node.otpNode}); }, removeFromList: function (hostname) { var node = this.mustFindNode(hostname); if (node.pendingEject) { this.serversCell.cancelPendingEject(node); return; } var ejectNodeURI = this.poolDetails.value.controllers.ejectNode.uri; this.postAndReload(ejectNodeURI, {otpNode: node.otpNode}); }, postAndReload: function (uri, data, errorMessage, ajaxOptions) { var self = this; // keep poolDetails undefined for now self.poolDetails.setValue(undefined); errorMessage = errorMessage || "Request failed. Check logs." postWithValidationErrors(uri, $.param(data), function (data, status) { // re-calc poolDetails according to it's formula self.poolDetails.invalidate(); if (status == 'error') { if (data[0].mismatch) { self.poolDetails.changedSlot.subscribeOnce(function () { var msg = "Could not Rebalance because the cluster configuration was modified by someone else.\nYou may want to verify the latest cluster configuration and, if necessary, please retry a Rebalance." alert(msg); }); } else { displayNotice(errorMessage, true); } } }, ajaxOptions); } }; configureActionHashParam('visitServersTab', $m(ServersSection, 'visitTab'));
priv/public/js/servers.js
/** Copyright 2011 Couchbase, 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. **/ var ServersSection = { hostnameComparator: mkComparatorByProp('hostname', naturalSort), pendingEject: [], // nodes to eject on next rebalance pending: [], // nodes for pending tab active: [], // nodes for active tab allNodes: [], // all known nodes visitTab: function (tabName) { if (ThePage.currentSection != 'servers') { $('html, body').animate({scrollTop: 0}, 250); } ThePage.ensureSection('servers'); this.tabs.setValue(tabName); }, updateData: function () { var self = this; var serversValue = self.serversCell.value || {}; _.each("pendingEject pending active allNodes".split(' '), function (attr) { self[attr] = serversValue[attr] || []; }); }, renderEverything: function () { this.detailsWidget.prepareDrawing(); var details = this.poolDetails.value; var rebalancing = details && details.rebalanceStatus != 'none'; var pending = this.pending; var active = this.active; this.serversQ.find('.add_button').toggle(!!(details && !rebalancing)); this.serversQ.find('.stop_rebalance_button').toggle(!!rebalancing); var mayRebalance = !rebalancing && pending.length !=0; if (details && !rebalancing && !details.balanced) mayRebalance = true; var unhealthyActive = _.detect(active, function (n) { return n.clusterMembership == 'active' && !n.pendingEject && n.status === 'unhealthy' }) if (unhealthyActive) mayRebalance = false; var rebalanceButton = this.serversQ.find('.rebalance_button').toggle(!!details); rebalanceButton.toggleClass('disabled', !mayRebalance); if (details && !rebalancing) { $('#rebalance_tab .badge span').text(pending.length); $('#rebalance_tab').toggleClass('badge_display', !!pending.length); } else { $('#rebalance_tab').toggleClass('badge_display', false); } this.serversQ.toggleClass('rebalancing', !!rebalancing); if (!details) return; if (active.length) { renderTemplate('manage_server_list', { rows: active, expandingAllowed: !IOCenter.staleness.value }, $i('active_server_list_container')); renderTemplate('manage_server_list', { rows: pending, expandingAllowed: false }, $i('pending_server_list_container')); } if (rebalancing) { $('#servers .add_button').hide(); this.renderRebalance(details); } if (IOCenter.staleness.value) { $('#servers .staleness-notice').show(); $('#servers').find('.add_button, .rebalance_button').hide(); $('#active_server_list_container, #pending_server_list_container').find('.re_add_button, .eject_server, .failover_server, .remove_from_list').addClass('disabled'); } else { $('#servers .staleness-notice').hide(); $('#servers').find('.rebalance_button').show(); $('#servers .add_button')[rebalancing ? 'hide' : 'show'](); } $('#active_server_list_container .last-active').find('.eject_server').addClass('disabled').end() .find('.failover_server').addClass('disabled'); $('#active_server_list_container .server_down .eject_server').addClass('disabled'); $('.failed_over .eject_server, .failed_over .failover_server').hide(); }, renderServerDetails: function (item) { return this.detailsWidget.renderItemDetails(item); }, renderRebalance: function (details) { var progress = this.rebalanceProgress.value; if (!progress) { progress = {}; } nodes = _.clone(details.nodes); nodes.sort(this.hostnameComparator); var emptyProgress = {progress: 0}; _.each(nodes, function (n) { var p = progress[n.otpNode]; if (!p) p = emptyProgress; n.progress = p.progress; n.percent = truncateTo3Digits(n.progress * 100); $($i(n.otpNode.replace('@', '-'))).find('.actions').html('<span class="usage_info">' + escapeHTML(n.percent) + '% Complete</span><span class="server_usage"><span style="width: ' + escapeHTML(n.percent) + '%;"></span></span>'); }); }, refreshEverything: function () { this.updateData(); this.renderEverything(); // It displays the status of auto-failover, hence we need to refresh // it to get the current values AutoFailoverSection.refreshStatus(); }, onRebalanceProgress: function () { var value = this.rebalanceProgress.value; console.log("got progress: ", value); if (value.status == 'none') { this.poolDetails.invalidate(); this.rebalanceProgressIsInteresting.setValue(false); if (value.errorMessage) { displayNotice(value.errorMessage, true); } return } this.renderRebalance(this.poolDetails.value); this.rebalanceProgress.recalculateAfterDelay(250); }, init: function () { var self = this; self.poolDetails = DAL.cells.currentPoolDetailsCell; self.tabs = new TabsCell("serversTab", "#servers .tabs", "#servers .panes > div", ["active", "pending"]); var detailsWidget = self.detailsWidget = new MultiDrawersWidget({ hashFragmentParam: 'openedServers', template: 'server_details', elementKey: 'otpNode', placeholderCSS: '#servers .settings-placeholder', actionLink: 'openServer', actionLinkCallback: function () { ThePage.ensureSection('servers'); }, uriExtractor: function (nodeInfo) { return "/nodes/" + encodeURIComponent(nodeInfo.otpNode); }, valueTransformer: function (nodeInfo, nodeSettings) { return _.extend({}, nodeInfo, nodeSettings); }, listCell: Cell.compute(function (v) {return v.need(DAL.cells.serversCell).active}) }); self.serversCell = DAL.cells.serversCell; self.poolDetails.subscribeValue(function (poolDetails) { $($.makeArray($('#servers .failover_warning')).slice(1)).remove(); var warning = $('#servers .failover_warning'); if (!poolDetails || poolDetails.rebalanceStatus != 'none') { return; } function showWarning(text) { warning.after(warning.clone().find('.warning-text').text(text).end().css('display', 'block')); } _.each(poolDetails.failoverWarnings, function (failoverWarning) { switch (failoverWarning) { case 'failoverNeeded': break; case 'rebalanceNeeded': showWarning('Rebalance required, some data is not currently replicated!'); break; case 'hardNodesNeeded': showWarning('At least two servers are required to provide replication!'); break; case 'softNodesNeeded': showWarning('Additional active servers required to provide the desired number of replicas!'); break; case 'softRebalanceNeeded': showWarning('Rebalance recommended, some data does not have the desired number of replicas!'); break; default: console.log('Got unknown failover warning: ' + failoverSafety); } }); }); self.serversCell.subscribeAny($m(self, "refreshEverything")); prepareTemplateForCell('active_server_list', self.serversCell); prepareTemplateForCell('pending_server_list', self.serversCell); var serversQ = self.serversQ = $('#servers'); serversQ.find('.rebalance_button').live('click', self.accountForDisabled($m(self, 'onRebalance'))); serversQ.find('.add_button').live('click', $m(self, 'onAdd')); serversQ.find('.stop_rebalance_button').live('click', $m(self, 'onStopRebalance')); function mkServerRowHandler(handler) { return function (e) { var serverRow = $(this).closest('.server_row').find('td:first-child').data('server') || $(this).closest('.add_back_row').next().find('td:first-child').data('server'); return handler.call(this, e, serverRow); } } function mkServerAction(handler) { return ServersSection.accountForDisabled(mkServerRowHandler(function (e, serverRow) { e.preventDefault(); return handler(serverRow.hostname); })); } serversQ.find('.re_add_button').live('click', mkServerAction($m(self, 'reAddNode'))); serversQ.find('.eject_server').live('click', mkServerAction($m(self, 'ejectNode'))); serversQ.find('.failover_server').live('click', mkServerAction($m(self, 'failoverNode'))); serversQ.find('.remove_from_list').live('click', mkServerAction($m(self, 'removeFromList'))); self.rebalanceProgressIsInteresting = new Cell(); self.rebalanceProgressIsInteresting.setValue(false); self.poolDetails.subscribeValue(function (poolDetails) { if (poolDetails && poolDetails.rebalanceStatus != 'none') self.rebalanceProgressIsInteresting.setValue(true); }); // TODO: should we ignore errors here ? this.rebalanceProgress = new Cell(function (interesting, poolDetails) { if (!interesting) return; return future.get({url: poolDetails.rebalanceProgressUri}); }, {interesting: self.rebalanceProgressIsInteresting, poolDetails: self.poolDetails}); self.rebalanceProgress.keepValueDuringAsync = true; self.rebalanceProgress.subscribe($m(self, 'onRebalanceProgress')); }, accountForDisabled: function (handler) { return function (e) { if ($(e.currentTarget).hasClass('disabled')) { e.preventDefault(); return; } return handler.call(this, e); } }, renderUsage: function (e, totals, withQuotaTotal) { var options = { topAttrs: {'class': "usage-block"}, topRight: ['Total', ViewHelpers.formatMemSize(totals.total)], items: [ {name: 'In Use', value: totals.usedByData, attrs: {style: 'background-color:#00BCE9'}, tdAttrs: {style: "color:#1878A2;"} }, {name: 'Other Data', value: totals.used - totals.usedByData, attrs: {style:"background-color:#FDC90D"}, tdAttrs: {style: "color:#C19710;"}}, {name: 'Free', value: totals.total - totals.used} ], markers: [] }; if (withQuotaTotal) { options.topLeft = ['Membase Quota', ViewHelpers.formatMemSize(totals.quotaTotal)]; options.markers.push({value: totals.quotaTotal, attrs: {style: "background-color:#E43A1B;"}}); } $(e).replaceWith(memorySizesGaugeHTML(options)); }, onEnter: function () { // we need this 'cause switchSection clears rebalancing class this.refreshEverything(); }, onLeave: function () { this.detailsWidget.reset(); }, onRebalance: function () { var self = this; self.postAndReload(self.poolDetails.value.controllers.rebalance.uri, {knownNodes: _.pluck(self.allNodes, 'otpNode').join(','), ejectedNodes: _.pluck(self.pendingEject, 'otpNode').join(',')}); self.poolDetails.getValue(function () { // switch to active server tab when poolDetails reload is complete self.tabs.setValue("active"); }); }, onStopRebalance: function () { this.postAndReload(this.poolDetails.value.stopRebalanceUri, ""); }, validateJoinClusterParams: function (form) { var data = {} _.each("hostname user password".split(' '), function (name) { data[name] = form.find('[name=' + name + ']').val(); }); var errors = []; if (data['hostname'] == "") errors.push("Server IP Address cannot be blank."); if (!data['user'] || !data['password']) errors.push("Username and Password are both required to join a cluster."); if (!errors.length) return data; return errors; }, onAdd: function () { var self = this; var uri = self.poolDetails.value.controllers.addNode.uri; var dialog = $('#join_cluster_dialog'); var form = dialog.find('form'); $('#join_cluster_dialog_errors_container').empty(); $('#join_cluster_dialog form').get(0).reset(); dialog.find("input:not([type]), input[type=text], input[type=password]").val(''); dialog.find('[name=user]').val('Administrator'); showDialog('join_cluster_dialog', { onHide: function () { form.unbind('submit'); }}); form.bind('submit', function (e) { e.preventDefault(); var errors = self.validateJoinClusterParams(form); if (errors.length) { renderTemplate('join_cluster_dialog_errors', errors); return; } var confirmed; $('#join_cluster_dialog').addClass('overlayed') .dialog('option', 'closeOnEscape', false); showDialog('add_confirmation_dialog', { closeOnEscape: false, eventBindings: [['.save_button', 'click', function (e) { e.preventDefault(); confirmed = true; hideDialog('add_confirmation_dialog'); $('#join_cluster_dialog_errors_container').empty(); var overlay = overlayWithSpinner($($i('join_cluster_dialog'))); self.poolDetails.setValue(undefined); postWithValidationErrors(uri, form, function (data, status) { self.poolDetails.invalidate(); overlay.remove(); if (status != 'success') { renderTemplate('join_cluster_dialog_errors', data) } else { hideDialog('join_cluster_dialog'); } }) }]], onHide: function () { $('#join_cluster_dialog').removeClass('overlayed') .dialog('option', 'closeOnEscape', true); } }); }); }, findNode: function (hostname) { return _.detect(this.allNodes, function (n) { return n.hostname == hostname; }); }, mustFindNode: function (hostname) { var rv = this.findNode(hostname); if (!rv) { throw new Error("failed to find node info for: " + hostname); } return rv; }, reDraw: function () { this.serversCell.invalidate(); }, ejectNode: function (hostname) { var self = this; var node = self.mustFindNode(hostname); if (node.pendingEject) return; showDialogHijackingSave("eject_confirmation_dialog", ".save_button", function () { if (node.clusterMembership == 'inactiveAdded') { self.postAndReload(self.poolDetails.value.controllers.ejectNode.uri, {otpNode: node.otpNode}); } else { self.pendingEject.push(node); self.reDraw(); } }); }, failoverNode: function (hostname) { var self = this; var node; showDialogHijackingSave("failover_confirmation_dialog", ".save_button", function () { if (!node) throw new Error("must not happen!"); self.postAndReload(self.poolDetails.value.controllers.failOver.uri, {otpNode: node.otpNode}, undefined, {timeout: 120000}); }); var dialog = $('#failover_confirmation_dialog'); var overlay = overlayWithSpinner(dialog.find('.content').need(1)); var statusesCell = DAL.cells.nodeStatusesCell; statusesCell.setValue(undefined); statusesCell.invalidate(); statusesCell.changedSlot.subscribeOnce(function () { overlay.remove(); dialog.find('.warning').hide(); var statuses = statusesCell.value; node = statuses[hostname]; if (!node) { hideDialog("failover_confirmation_dialog"); return; } var backfill = node.replication < 1; var down = node.status != 'healthy'; var visibleWarning = dialog.find(['.warning', down ? 'down' : 'up', backfill ? 'backfill' : 'no_backfill'].join('_')).show(); dialog.find('.backfill_percent').text(truncateTo3Digits(node.replication * 100)); var confirmation = visibleWarning.find('[name=confirmation]') if (confirmation.length) { confirmation.boolAttr('checked', false); function onChange() { var checked = !!confirmation.attr('checked'); dialog.find('.save_button').boolAttr('disabled', !checked); } function onHide() { confirmation.unbind('change', onChange); dialog.unbind('dialog:hide', onHide); } confirmation.bind('change', onChange); dialog.bind('dialog:hide', onHide); onChange(); } else { dialog.find(".save_button").removeAttr("disabled"); } }); }, reAddNode: function (hostname) { var node = this.mustFindNode(hostname); this.postAndReload(this.poolDetails.value.controllers.reAddNode.uri, {otpNode: node.otpNode}); }, removeFromList: function (hostname) { var node = this.mustFindNode(hostname); if (node.pendingEject) { this.serversCell.cancelPendingEject(node); return; } var ejectNodeURI = this.poolDetails.value.controllers.ejectNode.uri; this.postAndReload(ejectNodeURI, {otpNode: node.otpNode}); }, postAndReload: function (uri, data, errorMessage, ajaxOptions) { var self = this; // keep poolDetails undefined for now self.poolDetails.setValue(undefined); errorMessage = errorMessage || "Request failed. Check logs." postWithValidationErrors(uri, $.param(data), function (data, status) { // re-calc poolDetails according to it's formula self.poolDetails.invalidate(); if (status == 'error') { if (data[0].mismatch) { self.poolDetails.changedSlot.subscribeOnce(function () { var msg = "Could not Rebalance because the cluster configuration was modified by someone else.\nYou may want to verify the latest cluster configuration and, if necessary, please retry a Rebalance." alert(msg); }); } else { displayNotice(errorMessage, true); } } }, ajaxOptions); } }; configureActionHashParam('visitServersTab', $m(ServersSection, 'visitTab'));
MB-4215 Ignore empty pool details. When pool details are undefined then UI changes correspondingly: spinners appear and some of the buttons disappear. So it's very unlikely to encounter a situation when poolDetails.value is undefined. Thus we just ignore this. Change-Id: I46ac38d5603c15440119ec0454a8a7a78da140e3 Reviewed-on: http://review.couchbase.org/9153 Tested-by: Aliaksey Artamonau <[email protected]> Reviewed-by: Aliaksey Kandratsenka <[email protected]>
priv/public/js/servers.js
MB-4215 Ignore empty pool details.
<ide><path>riv/public/js/servers.js <ide> }, <ide> onRebalance: function () { <ide> var self = this; <add> <add> if (!self.poolDetails.value) { <add> return; <add> } <add> <ide> self.postAndReload(self.poolDetails.value.controllers.rebalance.uri, <ide> {knownNodes: _.pluck(self.allNodes, 'otpNode').join(','), <ide> ejectedNodes: _.pluck(self.pendingEject, 'otpNode').join(',')}); <ide> }); <ide> }, <ide> onStopRebalance: function () { <add> if (!self.poolDetails.value) { <add> return; <add> } <add> <ide> this.postAndReload(this.poolDetails.value.stopRebalanceUri, ""); <ide> }, <ide> validateJoinClusterParams: function (form) { <ide> }, <ide> onAdd: function () { <ide> var self = this; <add> <add> if (!self.poolDetails.value) { <add> return; <add> } <add> <ide> var uri = self.poolDetails.value.controllers.addNode.uri; <ide> <ide> var dialog = $('#join_cluster_dialog'); <ide> return; <ide> <ide> showDialogHijackingSave("eject_confirmation_dialog", ".save_button", function () { <add> if (!self.poolDetails.value) { <add> return; <add> } <add> <ide> if (node.clusterMembership == 'inactiveAdded') { <ide> self.postAndReload(self.poolDetails.value.controllers.ejectNode.uri, <ide> {otpNode: node.otpNode}); <ide> showDialogHijackingSave("failover_confirmation_dialog", ".save_button", function () { <ide> if (!node) <ide> throw new Error("must not happen!"); <add> if (!self.poolDetails.value) { <add> return; <add> } <ide> self.postAndReload(self.poolDetails.value.controllers.failOver.uri, <ide> {otpNode: node.otpNode}, undefined, {timeout: 120000}); <ide> }); <ide> }); <ide> }, <ide> reAddNode: function (hostname) { <add> if (!self.poolDetails.value) { <add> return; <add> } <add> <ide> var node = this.mustFindNode(hostname); <ide> this.postAndReload(this.poolDetails.value.controllers.reAddNode.uri, <ide> {otpNode: node.otpNode});
Java
apache-2.0
594abcfd0a92efaf2712958b75a29d00f130fce0
0
frekele/elasticsearch-mapping-builder,frekele/elasticsearch-mapping-builder
package org.frekele.elasticsearch; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.frekele.elasticsearch.annotations.ElasticDocument; import org.frekele.elasticsearch.annotations.ElasticField; import org.frekele.elasticsearch.exceptions.InvalidDocumentClassException; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MappingBuilder implements Serializable { private List<Class> docsClass; XContentBuilder mapping; public MappingBuilder(Class... documentClass) { if (documentClass != null && documentClass.length > 0) { this.docsClass = Arrays.asList(documentClass); } else { this.docsClass = new ArrayList<>(0); } this.validateElasticDocument(); } static boolean isElasticDocument(Class documentClass) { return (documentClass.isAnnotationPresent(ElasticDocument.class)); } void validateElasticDocument() { for (Class clazz : this.docsClass) { if (!isElasticDocument(clazz)) { throw new InvalidDocumentClassException("Document Class[" + clazz.getCanonicalName() + "] Invalid. @ElasticDocument must be present."); } } } public XContentBuilder source() throws IOException { if (this.mapping == null) { return build(); } else { return this.mapping; } } public String sourceAsString() throws IOException { return this.source().string(); } XContentBuilder build() throws IOException { if (this.mapping == null) { this.mapping = XContentFactory.jsonBuilder(); //this.mapping.prettyPrint(); //BEGIN this.mapping.startObject(); this.mapping.startObject("mappings"); for (Class clazz : this.docsClass) { ElasticDocument elasticDocument = (ElasticDocument) clazz.getAnnotation(ElasticDocument.class); this.mapping.startObject(elasticDocument.value()); Field[] fields = clazz.getDeclaredFields(); if (fields != null && fields.length > 0) { this.mapping.startObject("properties"); for (Field field : fields) { if (field.isAnnotationPresent(ElasticField.class)) { ElasticField elasticField = field.getAnnotation(ElasticField.class); this.mapping.startObject(field.getName()); this.mapping.field("type", elasticField.type().toString().toLowerCase()); this.mapping.endObject(); } } //properties this.mapping.endObject(); } //ElasticDocument this.mapping.endObject(); } //mappings this.mapping.endObject(); //END this.mapping.endObject(); } return this.mapping; } public XContentBuilder old() throws IOException { XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type1") .startObject("properties") .startObject("text").field("type", "text").field("analyzer", "keyword").endObject() .endObject() .endObject().endObject(); return mapping; } }
src/main/java/org/frekele/elasticsearch/MappingBuilder.java
package org.frekele.elasticsearch; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.frekele.elasticsearch.annotations.ElasticDocument; import org.frekele.elasticsearch.exceptions.InvalidDocumentClassException; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; import java.util.List; public class MappingBuilder implements Serializable { private List<Class> docsClass; public MappingBuilder(Class... documentClass) { if (documentClass != null && documentClass.length > 0) { this.docsClass = Arrays.asList(documentClass); } this.validateElasticDocument(); } static boolean isElasticDocument(Class documentClass) { return (documentClass.isAnnotationPresent(ElasticDocument.class)); } void validateElasticDocument() { for (Class clazz : docsClass) { if (!isElasticDocument(clazz)) { throw new InvalidDocumentClassException("Document Class[" + clazz.getCanonicalName() + "] Invalid. @ElasticDocument must be present."); } } } public XContentBuilder build() throws IOException { XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type1") .startObject("properties") .startObject("text").field("type", "text").field("analyzer", "keyword").endObject() .endObject() .endObject().endObject(); return mapping; } //public String buildToJson(); public void teste() throws IOException { // System.out.println(mapping.string()); } }
implementing the build process.
src/main/java/org/frekele/elasticsearch/MappingBuilder.java
implementing the build process.
<ide><path>rc/main/java/org/frekele/elasticsearch/MappingBuilder.java <ide> import org.elasticsearch.common.xcontent.XContentBuilder; <ide> import org.elasticsearch.common.xcontent.XContentFactory; <ide> import org.frekele.elasticsearch.annotations.ElasticDocument; <add>import org.frekele.elasticsearch.annotations.ElasticField; <ide> import org.frekele.elasticsearch.exceptions.InvalidDocumentClassException; <ide> <ide> import java.io.IOException; <ide> import java.io.Serializable; <add>import java.lang.reflect.Field; <add>import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.List; <ide> <ide> <ide> private List<Class> docsClass; <ide> <add> XContentBuilder mapping; <add> <ide> public MappingBuilder(Class... documentClass) { <ide> if (documentClass != null && documentClass.length > 0) { <ide> this.docsClass = Arrays.asList(documentClass); <add> } else { <add> this.docsClass = new ArrayList<>(0); <ide> } <ide> this.validateElasticDocument(); <ide> } <ide> } <ide> <ide> void validateElasticDocument() { <del> for (Class clazz : docsClass) { <add> for (Class clazz : this.docsClass) { <ide> if (!isElasticDocument(clazz)) { <ide> throw new InvalidDocumentClassException("Document Class[" + clazz.getCanonicalName() + "] Invalid. @ElasticDocument must be present."); <ide> } <ide> } <del> <ide> } <ide> <del> public XContentBuilder build() throws IOException { <add> public XContentBuilder source() throws IOException { <add> if (this.mapping == null) { <add> return build(); <add> } else { <add> return this.mapping; <add> } <add> } <add> <add> public String sourceAsString() throws IOException { <add> return this.source().string(); <add> } <add> <add> XContentBuilder build() throws IOException { <add> if (this.mapping == null) { <add> this.mapping = XContentFactory.jsonBuilder(); <add> //this.mapping.prettyPrint(); <add> //BEGIN <add> this.mapping.startObject(); <add> this.mapping.startObject("mappings"); <add> <add> for (Class clazz : this.docsClass) { <add> ElasticDocument elasticDocument = (ElasticDocument) clazz.getAnnotation(ElasticDocument.class); <add> this.mapping.startObject(elasticDocument.value()); <add> Field[] fields = clazz.getDeclaredFields(); <add> <add> if (fields != null && fields.length > 0) { <add> this.mapping.startObject("properties"); <add> <add> for (Field field : fields) { <add> if (field.isAnnotationPresent(ElasticField.class)) { <add> ElasticField elasticField = field.getAnnotation(ElasticField.class); <add> this.mapping.startObject(field.getName()); <add> this.mapping.field("type", elasticField.type().toString().toLowerCase()); <add> this.mapping.endObject(); <add> } <add> } <add> <add> //properties <add> this.mapping.endObject(); <add> } <add> <add> //ElasticDocument <add> this.mapping.endObject(); <add> } <add> <add> //mappings <add> this.mapping.endObject(); <add> //END <add> this.mapping.endObject(); <add> } <add> return this.mapping; <add> } <add> <add> public XContentBuilder old() throws IOException { <ide> XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type1") <ide> .startObject("properties") <ide> .startObject("text").field("type", "text").field("analyzer", "keyword").endObject() <ide> .endObject().endObject(); <ide> return mapping; <ide> } <del> <del> //public String buildToJson(); <del> <del> public void teste() throws IOException { <del> <del> // System.out.println(mapping.string()); <del> } <del> <ide> }
JavaScript
mit
9db9ffb094f888f69d2d2e01c3d5f738f20a7aa6
0
finagin/Gulpfile.js,finagin/Gulpfile.js
"use strict"; var fs = require("fs"), gulp = require("gulp"), csso = require("gulp-csso"), file = require('gulp-file'), rimraf = require("gulp-rimraf"), uglify = require("gulp-uglify"), stylus = require("gulp-stylus"), concat = require("gulp-concat"), browserSync = require("browser-sync"), sourcemaps = require("gulp-sourcemaps"), autoprefixer = require("gulp-autoprefixer"), defaults = function defaults(obj, def) { function req(obj, def) { for (var key in def) { if (obj[key] !== undefined) { if (typeof obj[key] == "object") { req(obj[key], def[key]); } } else { obj[key] = def[key]; } } } req(obj, def); return obj; }, settings = defaults( JSON.parse(fs.readFileSync("Gulpfile.json", "utf8")), { "path": { "src": "./src", "root": "./", "dest": "./assets/" }, "proxy": { "path": "localhost", "port": 8888 }, "gitignore": true } ), path = { src: settings.path.src, root: settings.path.root, dest: settings.path.dest, include: function include() { var a = Array.from(arguments); return a.join("/").replace(/\/+/g, "/"); }, exclude: function exclude() { return "!" + path.include.apply(this, arguments); } }, buildTasks; gulp.task("stylus:clear", function () { return gulp .src([ path.include(path.dest, "css") ], {read: false}) .pipe(rimraf({force: true})); }); gulp.task("stylus:main", ["stylus:clear"], function () { return gulp .src([ path.include(path.src, "stylus/**/**.{styl,css}"), path.exclude(path.src, "stylus/separate/**/**.{styl,css}"), path.exclude(path.src, "stylus/imports/**/**.{styl,css}") ]) .pipe(sourcemaps.init()) .pipe(stylus({ compress: true })) .pipe(csso({ sourceMap: true })) .pipe(concat("style.css")) .pipe(sourcemaps.write("./")) .pipe(gulp.dest(path.include(path.dest, "css"))) .pipe(browserSync.stream()); }); gulp.task("stylus:separate", ["stylus:clear"], function () { return gulp .src([ path.include(path.src, "stylus/separate/**/**.{styl,css}") ]) .pipe(sourcemaps.init()) .pipe(stylus({ compress: true })) .pipe(sourcemaps.write("./")) .pipe(gulp.dest(path.include(path.dest, "css"))) .pipe(browserSync.stream()); }); gulp.task("js:clear", function () { return gulp .src([ path.include(path.dest, "js") ], {read: false}) .pipe(rimraf({force: true})); }); gulp.task("js:main", ["js:clear"], function () { return gulp .src([ path.include(path.src, "js/**/**.js"), path.exclude(path.src, "js/separate/**/**.js") ]) .pipe(sourcemaps.init()) .pipe(uglify({ compress: true })) .pipe(concat("main.js")) .pipe(sourcemaps.write("./")) .pipe(gulp.dest(path.include(path.dest, "js"))); }); gulp.task("js:separate", ["js:clear"], function () { return gulp .src([ path.include(path.src, "js/separate/**/**.js") ]) .pipe(sourcemaps.init()) .pipe(uglify({ compress: true })) .pipe(sourcemaps.write("./")) .pipe(gulp.dest(path.include(path.dest, "js"))); }); gulp.task("js:reload", ["js:main", "js:separate"], function () { return gulp .src([ path.include(path.src + "js/**/**.js") ]) .pipe(browserSync.stream()); }); gulp.task("images:clear", function () { return gulp .src([ path.include(path.dist, "images") ], {read: false}) .pipe(rimraf({force: true})); }); gulp.task("images:copy", function () { return gulp .src([ path.include(path.src, "images/**/**.*") ]) .pipe(gulp.dest(path.include(path.dest, "images"))); }); gulp.task("git-ignore", function () { return file(".gitignore", "*", {src: true}) .pipe(gulp.dest(path.dest)); }); gulp.task("php-html", function () { return gulp .src([ path.include(path.root, "**/**.{php,html}") ]) .pipe(browserSync.stream()); }); gulp.task("stylus", [ "stylus:clear", "stylus:main", "stylus:separate" ]); gulp.task("js", [ "js:clear", "js:main", "js:separate", "js:reload" ]); gulp.task("images", [ "images:clear", "images:copy" ]); gulp.task("watch", function (cb) { browserSync.init({ notify: true, https: false, open: true, proxy: { target: "http://" + settings.proxy.path + (settings.proxy.port != "80" ? (":" + settings.proxy.port) : ""), ws: true }, serveStatic: [ settings.path.dest ], localOnly: true }, cb); process.on("exit", function () { browserSync.exit(); }); gulp.watch([ path.include(path.src, "stylus/**/**.{styl,css}") ], ["stylus"]); gulp.watch([ path.include(path.src, "js/**/**.js") ], ["js"]); gulp.watch([ path.include(path.src, "images/**/**.*") ], ["images"]); gulp.watch([ path.include(path.root, "**/**.{php,html}") ], ["php-html"]); }); buildTasks = ["stylus", "js", "images"]; buildTasks.unshift.apply(buildTasks, settings.gitignore ? ["git-ignore"] : []); gulp.task("build", buildTasks); gulp.task("default", ["build", "watch"]);
Gulpfile.js
"use strict"; var fs = require("fs"), gulp = require("gulp"), csso = require("gulp-csso"), file = require('gulp-file'), rimraf = require("gulp-rimraf"), uglify = require("gulp-uglify"), stylus = require("gulp-stylus"), concat = require("gulp-concat"), browserSync = require("browser-sync"), sourcemaps = require("gulp-sourcemaps"), autoprefixer = require("gulp-autoprefixer"), defaults = function defaults(obj, def) { function req(obj, def) { for (var key in def) { if (obj[key] !== undefined) { if (typeof obj[key] == "object") { req(obj[key], def[key]); } } else { obj[key] = def[key]; } } } req(obj, def); return obj; }, settings = defaults( JSON.parse(fs.readFileSync("Gulpfile.json", "utf8")), { "path": { "src": "./src", "root": "./", "dest": "./assets/" }, "proxy": { "path": "localhost", "port": 8888 } } ), path = { src: settings.path.src, root: settings.path.root, dest: settings.path.dest, include: function include() { var a = Array.from(arguments); return a.join("/").replace(/\/+/g, "/"); }, exclude: function exclude() { return "!" + path.include.apply(this, arguments); } }; gulp.task("stylus:clear", function () { return gulp .src([ path.include(path.dest, "css") ], {read: false}) .pipe(rimraf({force: true})); }); gulp.task("stylus:main", ["stylus:clear"], function () { return gulp .src([ path.include(path.src, "stylus/**/**.{styl,css}"), path.exclude(path.src, "stylus/separate/**/**.{styl,css}"), path.exclude(path.src, "stylus/imports/**/**.{styl,css}") ]) .pipe(sourcemaps.init()) .pipe(stylus({ compress: true })) .pipe(csso({ sourceMap: true })) .pipe(concat("style.css")) .pipe(sourcemaps.write("./")) .pipe(gulp.dest(path.include(path.dest, "css"))) .pipe(browserSync.stream()); }); gulp.task("stylus:separate", ["stylus:clear"], function () { return gulp .src([ path.include(path.src, "stylus/separate/**/**.{styl,css}") ]) .pipe(sourcemaps.init()) .pipe(stylus({ compress: true })) .pipe(sourcemaps.write("./")) .pipe(gulp.dest(path.include(path.dest, "css"))) .pipe(browserSync.stream()); }); gulp.task("js:clear", function () { return gulp .src([ path.include(path.dest, "js") ], {read: false}) .pipe(rimraf({force: true})); }); gulp.task("js:main", ["js:clear"], function () { return gulp .src([ path.include(path.src, "js/**/**.js"), path.exclude(path.src, "js/separate/**/**.js") ]) .pipe(sourcemaps.init()) .pipe(uglify({ compress: true })) .pipe(concat("main.js")) .pipe(sourcemaps.write("./")) .pipe(gulp.dest(path.include(path.dest, "js"))); }); gulp.task("js:separate", ["js:clear"], function () { return gulp .src([ path.include(path.src, "js/separate/**/**.js") ]) .pipe(sourcemaps.init()) .pipe(uglify({ compress: true })) .pipe(sourcemaps.write("./")) .pipe(gulp.dest(path.include(path.dest, "js"))); }); gulp.task("js:reload", ["js:main", "js:separate"], function () { return gulp .src([ path.include(path.src + "js/**/**.js") ]) .pipe(browserSync.stream()); }); gulp.task("images:clear", function () { return gulp .src([ path.include(path.dist, "images") ], {read: false}) .pipe(rimraf({force: true})); }); gulp.task("images:copy", function () { return gulp .src([ path.include(path.src, "images/**/**.*") ]) .pipe(gulp.dest(path.include(path.dest, "images"))); }); gulp.task("git-ignore", function () { return file(".gitignore", "*", {src: true}) .pipe(gulp.dest(path.dest)); }); gulp.task("php-html", function () { return gulp .src([ path.include(path.root, "**/**.{php,html}") ]) .pipe(browserSync.stream()); }); gulp.task("stylus", [ "stylus:clear", "stylus:main", "stylus:separate" ]); gulp.task("js", [ "js:clear", "js:main", "js:separate", "js:reload" ]); gulp.task("images", [ "images:clear", "images:copy" ]); gulp.task("watch", function (cb) { browserSync.init({ notify: true, https: false, open: true, proxy: { target: "http://" + settings.proxy.path + (settings.proxy.port != "80" ? (":" + settings.proxy.port) : ""), ws: true }, serveStatic: [ settings.path.dest ], localOnly: true }, cb); process.on("exit", function () { browserSync.exit(); }); gulp.watch([ path.include(path.src, "stylus/**/**.{styl,css}") ], ["stylus"]); gulp.watch([ path.include(path.src, "js/**/**.js") ], ["js"]); gulp.watch([ path.include(path.src, "images/**/**.*") ], ["images"]); gulp.watch([ path.include(path.root, "**/**.{php,html}") ], ["php-html"]); }); gulp.task("build", ["git-ignore", "stylus", "js", "images"]); gulp.task("default", ["build", "watch"]);
Gitignore settings
Gulpfile.js
Gitignore settings
<ide><path>ulpfile.js <ide> "proxy": { <ide> "path": "localhost", <ide> "port": 8888 <del> } <add> }, <add> "gitignore": true <ide> } <ide> ), <ide> path = { <ide> exclude: function exclude() { <ide> return "!" + path.include.apply(this, arguments); <ide> } <del> }; <add> }, <add> buildTasks; <ide> <ide> <ide> gulp.task("stylus:clear", function () { <ide> <ide> }); <ide> <del> <del>gulp.task("build", ["git-ignore", "stylus", "js", "images"]); <add>buildTasks = ["stylus", "js", "images"]; <add>buildTasks.unshift.apply(buildTasks, settings.gitignore ? ["git-ignore"] : []); <add>gulp.task("build", buildTasks); <ide> <ide> <ide> gulp.task("default", ["build", "watch"]);
JavaScript
mit
d980db60bc1675c3000cf2ced5c8fe127d45797a
0
andreash92/andreasBot,andreash92/andreasBot,andreash92/andreasBot
// Commands: // `github login` // `github repos` // `github open|closed|all issues of repo <repo_name>` // `github commits of repo <repo_name>` // `github issues of repo <repo_name>` // `github issue <issue_num>` - get the the commit of the last repo lookup // `github repo <repo_name> issue <issue_num> comments` // `github issue reply <comment_text>` // convert this to the above 2nd // `github comments of issue <issue num> of repo <repo_name>` // `github (open|closed|all) pull requests of repo <repo_name>` - Default: open // `github create issue` // `github open|closed|all pull requests of all repos` // `github show sumup open|closed|all` // `github sumup( all| closed| open|)` 'use strict'; // init const querystring = require('querystring') var GitHubApi = require("github") var slackMsgs = require('./slackMsgs.js') var c = require('./config.json') var encryption = require('./encryption.js') var cache = require('./cache.js').getCache() const Conversation = require('./hubot-conversation/index.js') var dialog = require('./dynamic-dialog.js') var convModel = require('./conversation-models.js') var color = require('./colors.js') var path = require('path') var async = require('async') var dateFormat = require('dateformat') var request = require('request-promise') var Promise = require('bluebird') var mongoskin = require('mongoskin') Promise.promisifyAll(mongoskin) // config var mongodb_uri = process.env.MONGODB_URI var bot_host_url = process.env.HUBOT_HOST_URL; var GITHUB_API = 'https://api.github.com' var githubURL = 'https://www.github.com/' module.exports = function (robot) { /*************************************************************************/ /* Listeners */ /*************************************************************************/ var switchBoard = new Conversation(robot); robot.respond(/github login/, function (res) { oauthLogin(res.message.user.id) }) robot.on('githubOAuthLogin', function (res) { oauthLogin(res.message.user.id) }) robot.respond(/github repos/, (res) => { listRepos(res.message.user.id) }) robot.on('listGithubRepos', (data, res) => { listRepos(res.message.user.id) }) robot.respond(/github( last (\d+)|) (open |closed |all |mentioned |)issues( of)? repo (.*)/i, function (res) { var userid = res.message.user.id var repo = res.match.pop() var issuesCnt = res.match[2] console.log(issuesCnt) var parameter = res.match[3].trim() console.log(res.match) if (parameter == 'mentioned') { var paramsObj = { mentioned: getCredentials(userid).username } } else if (parameter != '') { paramsObj = { state: parameter } } updateConversationContent(userid, { github_repo: repo }) listRepoIssues(userid, repo, paramsObj, issuesCnt) }) robot.respond(/github comments of issue (\d+) of repo (.*)/i, function (res) { var userid = res.message.user.id var repo = res.match[2].trim() var issueNum = res.match[1].trim() updateConversationContent(userid, { github_repo: repo, github_issue: issueNum }) // updateConversationContent(userid, { github_issue: issueNum }) listIssueComments(userid, issueNum, repo) }) robot.respond(/github (open |closed |all |)pull requests of repo (.*)/i, function (res) { var userid = res.message.user.id var state = res.match[1].trim() var repo = res.match[2].trim() listPullRequests(userid, repo, state) }) robot.respond(/github (open |closed |all |)pull requests of all repos/i, function (res) { var userid = res.message.user.id var state = res.match[1].trim() listPullRequestsForAllRepos(userid, state) }) robot.respond(/github commits( of)?( repo)? (.*)/i, function (res) { var repo = res.match.pop().trim() var userid = res.message.user.id updateConversationContent(userid, { repo: repo }) listRepoCommits(userid, repo) }) robot.on('listRepoCommits', function (result, res) { var userid = res.message.user.id var since = result.parameters['date-time'] var repoName = result.parameters['repo'] listRepoCommits(userid, repoName, since) }) // TODO: maybe replace it with api.ai robot.respond(/\bgithub\s(create|open)\sissue\b/i, function (res) { var userid = res.message.user.id dialog.startDialog(switchBoard, res, convModel.createIssue) .then(data => { createIssue(userid, 'anbot', data.title, data.body) }) .catch(err => console.log(err)) }) robot.respond(/github issue (\d+) comment (.*)/i, function (res) { var userid = res.message.user.id var issueNum = res.match[1] var commentText = res.match.pop() var repo = getConversationContent(userid, 'github_repo') if (repo) { createIssueComment(userid, repo, issueNum, commentText) } else { // TODO: send the bellow msg or use api.ai event to ask for the repo robot.messageRoom(userid, 'Sorry but i dont have your last repo lookup.' + '\nYou need to search for a repo first for this command. i.e. `github commits repo <repo_name>`' + '\nor use another command to specify repo as well.') } }) // TODO robot.respond(/^github issue (\d+) comment$/, function (res) { var issueNum = res.match[1] // ask for the comment text }) function createIssueComment(userid, repo, issueNum, comment) { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account var cred = getCredentials(userid) if (!cred) { return 0 } var dataString = { body: comment } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/issues/${issueNum}/comments`, method: 'POST', body: dataString, headers: getUserHeaders(cred.token), json: true } request(options) .then(r => { robot.messageRoom(userid, `Comment added on issue #${issueNum} of repo ${repo}!`) }) .catch(error => { robot.logger.error(error) robot.messageRoom(userid, error.message) }) } robot.on('githubSumUp', function (userid, query, saveLastSumupDate) { listGithubSumUp(userid, query, saveLastSumupDate) }) // reply instantly to the last github issue mentioned robot.respond(/github reply (.*)/i, function (res) { var userid = res.message.user.id var commentText = res.match[1] try { var repo = cache.get(userid).github_last_repo var issue = cache.get(userid).github_last_issue if (repo && issue) { createIssueComment(userid, repo, issue, commentText) } else { throw null } } catch (error) { robot.messageRoom(userid, 'Sorry but i couldn\'t process your query.') } }) robot.respond(/\bgithub close$/i, function (res) { var userid = res.message.user.id var commentText = res.match[1] try { var repo = cache.get(userid).github_last_repo var issue = cache.get(userid).github_last_issue if (repo && issue) { updateIssue(userid, repo, issue, { state: 'close' }) } else { throw null } } catch (error) { robot.messageRoom(userid, 'Sorry but i couldn\'t process your query.') } }) robot.respond(/\wgithub sum-?ups?( all| closed| open|)\b/i, function (res) { var queryObj, state state = res.match[1].trim() if (state != null) { queryObj = { state: state } } else { queryObj = { state: 'open' } } listGithubSumUp(res.message.user.id, queryObj, false) }) robot.respond(/github (close |re-?open )issue (\d+) repo (.*)/i, function (res) { var userid = res.message.user.id var repoName = res.match[3].trim() var issueNum = parseInt(res.match[2]) var state = res.match[1].trim() if (state.includes('open')) { state = 'open' } else { state = 'closed' } updateIssue(userid, repoName, issueNum, { state: state }) }) /*************************************************************************/ /* API Calls */ /*************************************************************************/ function updateIssue(userid, repo, issueNum, updateObj) { var ghApp = cache.get('GithubApp') var owner = ghApp[0].account var cred = getCredentials(userid) if (!cred) { return 0 } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/issues/${issueNum}`, method: 'PATCH', headers: getUserHeaders(cred.token), body: updateObj, json: true } request(options).then(res => { var updateInfo = `${Object.keys(updateObj)}: ${updateObj[Object.keys(updateObj)]}` var msg = { unfurl_links: true } msg.text = `Issue <${res.html_url}|#${res.number}: ${res.title}> updated. ${updateInfo}.` robot.messageRoom(userid, msg) }).catch(error => { robot.messageRoom(userid, error.message) robot.logger.error(error) }) } function listPullRequestsForAllRepos(userid, state) { getAccesibleReposName(userid) .then(repos => { for (var i = 0; i < repos.length; i++) { listPullRequests(userid, repos[i], state) } }) .catch(error => { robot.messageRoom(user, c.errorMessage) robot.logger.error(error) }) } function listGithubSumUp(userid, query, saveLastSumupDate = false) { var ghApp = cache.get('GithubApp') var orgName = ghApp[0].account var credentials = getCredentials(userid) if (!credentials) { return 0 } if (saveLastSumupDate) { var date = new Date().toISOString() cache.set(userid, { github_last_sumup_date: date }) var db = mongoskin.MongoClient.connect(mongodb_uri); db.bind('users').findAndModifyAsync( { _id: userid }, [["_id", 1]], { $set: { github_last_sumup_date: date } }, { upsert: true }) .catch(error => { robot.logger.error(error) if (c.errorsChannel) { robot.messageRoom(c.errorsChannel, c.errorMessage + `Script: ${path.basename(__filename)}`) } }) } getAccesibleReposName(userid) .then(repos => { var sinceText = '' if (query.since) { sinceText = ` since *${dateFormat(new Date(query.since), 'mmm dS yyyy, HH:MM')}*` } robot.messageRoom(userid, `Here is your github summary${sinceText}:`) for (var i = 0; i < repos.length; i++) { var repoName = repos[i] Promise.mapSeries([ `<${githubURL}${orgName}/${repoName}|[${orgName}/${repoName}]>`, getCommitsSumup(userid, repoName, query.since), getIssuesSumup(userid, repoName, query.state, query.since), getPullRequestsSumup(userid, repoName, query.state) ], function (sumupMsg) { return sumupMsg }).then(function (data) { var msg = { unfurl_links: false, text: `${data[0]}`, attachments: [] } for (var i = 1; i < data.length; i++) { msg.attachments.push(data[i]) } return msg }).then((msg) => { robot.messageRoom(userid, msg) }) } }) .catch(error => { robot.logger.error(error) robot.messageRoom(userid, c.errorMessage + `Script: ${path.basename(__filename)}`) }) } function displayRepoSumup(userid, repo, state = '') { } // TODO: // check the state when is not provided. // better msg + title // same for the functions bellow function getPullRequestsSumup(userid, repo, state = '') { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account var cred = getCredentials(userid) if (!cred) { return 0 } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/pulls?state=${state}`, method: 'GET', headers: getUserHeaders(cred.token), json: true } return new Promise((resolve, reject) => { request(options) .then(pullRequests => { var attachment = slackMsgs.attachment() var quantityText, s = 's' if (pullRequests.length > 1) { quantityText = 'There are ' + pullRequests.length } else if (pullRequests.length == 1) { quantityText = 'There is 1' s = '' } else { quantityText = 'There are no' } if (state == '' || state == 'all') { state = 'open/closed' } attachment.text = `${quantityText} (${state}) ${bold('pull request' + s)}.` attachment.color = color.rgbToHex(parseInt(pullRequests.length) * 25, 0, 0) resolve(attachment) }) .catch(error => { reject(error) }) }) } // TODOs: as mentioned in displayPullRequestsSumup function getIssuesSumup(userid, repo, state = '', since = '') { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account if (since) { since = `&since=${since}` } else { since = '' } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/issues?state=${state}${since}`, method: 'GET', headers: getAppHeaders(appToken), json: true } return new Promise((resolve, reject) => { request(options) .then(issues => { var attachment = slackMsgs.attachment() var s = '' if (issues.length > 1) { s = 's' } attachment.text = `${issues.length} ${bold('issue' + s)} (including PRs) created or updated.` attachment.color = color.rgbToHex(parseInt(issues.length) * 25, 0, 0) resolve(attachment) }) .catch(error => { reject(error) // robot.logger.error(error) // robot.messageRoom(userid, c.errorMessage) }) }) } // TODOs: as mentioned in displayPullRequestsSumup function getCommitsSumup(userid, repo, since = '') { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account if (since) { since = `?since=${since}` } else { since = '' } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/commits${since}`, method: 'GET', headers: getAppHeaders(appToken), json: true } return new Promise((resolve, reject) => { request(options) .then(commits => { var attachment = slackMsgs.attachment() var s = 's' var commitsNum = commits.length if (commitsNum == 1) { s = '' } if (commitsNum == 30) { // 30 = the max commits github returns commitsNum = '30 or more' } attachment.text = `${commitsNum} ${bold('commit' + s)} were made.` attachment.color = color.rgbToHex(parseInt(commitsNum) * 25, 0, 0) resolve(attachment) }) .catch(error => { reject(error) // robot.logger.error(error) // robot.messageRoom(userid, c.errorMessage) }) }) } function listPullRequests(userid, repo, state) { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account var cred = getCredentials(userid) if (!cred) { return 0 } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/pulls?state=${state}`, method: 'GET', headers: getUserHeaders(cred.token), json: true } request(options) .then(pullRequests => { var msg = {} msg.unfurl_links = false if (pullRequests.length > 0) { msg.attachments = [] msg.text = `Pull Requests of <https://www.github.com/${owner}/${repo}|${owner}/${repo}>:` } else { msg.text = `There aren't any Pull Requests on <https://www.github.com/${owner}/${repo}|${owner}/${repo}>` } Promise.each(pullRequests, function (pr) { var attachment = slackMsgs.attachment() var title = pr.title var url = pr.html_url var num = pr.number attachment.text = `<${url}|#${num} ${title}>` attachment.author_name = pr.user.login attachment.author_link = pr.user.html_url attachment.author_icon = pr.user.avatar_url if (pr.state.includes('open')) { attachment.color = 'good' } else { attachment.color = 'danger' } msg.attachments.push(attachment) }).done(() => { robot.messageRoom(userid, msg) }) }) .catch(error => { robot.messageRoom(userid, c.errorMessage) }) } function listRepos(userid) { var cred = getCredentials(userid) if (!cred) { return 0 } /* (Possible feature) having more than one Github App installations */ var installations = cache.get('GithubApp').length for (var i = 0; i < installations; i++) { var ghApp = cache.get('GithubApp') var installation_id = ghApp[i].id var options = { url: `${GITHUB_API}/user/installations/${installation_id}/repositories`, headers: getUserHeaders(cred.token), json: true, }; request(options) .then(res => { var msg = slackMsgs.basicMessage(); res.repositories.forEach(function (repo) { // TODO: add link to repo msg.attachments[0].text += (`${repo.full_name}\n`) }) return { msg: msg } }) .then((data) => { data.msg.text = `Your accessible Repositories: ` robot.messageRoom(userid, data.msg) }) .catch(err => { //TODO handle error codes: i.e. 404 not found -> dont post console.log(err) }) } } function getAccesibleReposName(userid) { var cred = getCredentials(userid) if (!cred) { return 0 } var ghApp = cache.get('GithubApp') var installation_id = ghApp[0].id var options = { url: `${GITHUB_API}/user/installations/${installation_id}/repositories`, headers: getUserHeaders(cred.token), json: true, }; return new Promise(function (resolve, reject) { request(options) .then(res => { var reposArray = [] Promise.each(res.repositories, function (repo) { reposArray.push(repo.name) }).then(() => { resolve(reposArray) }) }) .catch(error => { reject(error) }) }) } function listRepoCommits(userid, repo, since) { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account var parameters = '' if (since) { parameters = `?since=${since}` } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/commits${parameters}`, method: 'GET', headers: getAppHeaders(appToken), json: true } request(options) .then(repoCommits => { var msg = { attachments: [] } var attachment = slackMsgs.attachment() msg.unfurl_links = false if (repoCommits.length > 0) { msg.attachments = [] msg.text = `Commits of <${githubURL}${owner}/${repo}|${owner}/${repo}>:` } else { msg.text = `<${githubURL}${owner}/${repo}|{${owner}/${repo}]>: No Commits found` } Promise.each(repoCommits, function (commit) { var authorUsername = commit.author.login; var authorURL = githubURL + authorUsername; var commitID = commit.sha.substr(0, 7); // get the first 7 chars of the commit id var commitMsg = commit.commit.message.split('\n', 1); // get only the commit msg, not the description var commitURL = commit.html_url; commitID = "`" + commitID + "`" attachment.text += `\n<${commitURL}|${commitID}> ${commitMsg} - ${authorUsername}`; }).then(() => { msg.attachments.push(attachment) }).done(() => { robot.messageRoom(userid, msg) }) }) .catch(err => { console.log(err) }) } function listRepoIssues(userid, repo, paramsObj = { state: 'open' }, issuesCnt) { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account var params = querystring.stringify(paramsObj) var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/issues?${params}`, method: 'GET', headers: getAppHeaders(appToken), json: true } request(options) .then(repoIssues => { var msg = {} msg.unfurl_links = false if (repoIssues.length > 0) { msg.attachments = [] msg.text = `${paramsObj.state.capitalize()} issues of <https://www.github.com/${owner}/${repo}|${owner}/${repo}>:` } else { msg.text = `There aren't any issues on <https://www.github.com/${owner}/${repo}|${owner}/${repo}>` } if (issuesCnt) { repoIssues = repoIssues.slice(0, issuesCnt) } Promise.each(repoIssues, function (issue) { var attachment = slackMsgs.attachment() var title = issue.title var url = issue.html_url var num = `#${issue.number}` var userLogin = issue.user.login var userAvatar = issue.user.avatar_url var userUrl = issue.user.html_url attachment.author_name = userLogin attachment.author_icon = userAvatar attachment.author_link = userUrl attachment.text = ` <${url}|${num}: ${title}>` if (issue.body) { attachment.fields.push({ title: '', value: issue.body, short: false }) } /* Do i have to provide the state of issue when i use green and red color instead? */ // attachment.fields.push({ // title: 'State', // value: issue.state, // short: true // }) if (issue.state.includes('open')) { attachment.color = 'good' } else { attachment.color = 'danger' } msg.attachments.push(attachment) }).done(() => { robot.messageRoom(userid, msg) }) }) .catch(err => { console.log(err) }) } function listIssueComments(userid, issueNum, repo = null) { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account var cred = getCredentials(userid) if (!cred) { return 0 } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/issues/${issueNum}/comments`, method: 'GET', headers: getUserHeaders(cred.token), json: true } request(options) .then(issueComments => { var msg = {} msg.unfurl_links = false var repo_url = `${githubURL}${owner}/${repo}` if (issueComments.length > 0) { msg.attachments = [] msg.text = `<${repo_url}|[${owner}/${repo}]> <${repo_url}/issues/${issueNum}|Issue #${issueNum}>:` } else { msg.text = `<${repo_url}/issues/${issueNum}|Issue #${issueNum}> of repository ${repo} hasn't any comments yet.` } Promise.each(issueComments, function (comment) { var attachment = slackMsgs.attachment() var body = comment.body // tODO: should i use created_at instead of updated_at ? var ts = Date.parse(comment.updated_at) / 1000//dateFormat(new Date(comment.created_at), 'mmm dS yyyy, HH:MM' var url = comment.html_url var userLogin = comment.user.login var userUrl = comment.user.html_url var userAvatar = comment.user.avatar_url attachment.author_name = userLogin attachment.author_icon = userAvatar attachment.author_link = userUrl attachment.ts = ts attachment.color = 'warning' // attachment.pretext = `*${user}* commented on <${url}|${created_at}>` attachment.text = body msg.attachments.push(attachment) }).done(() => { robot.messageRoom(userid, msg) }) }) .catch(err => { //TODO handle error codes: i.e. 404 not found -> dont post console.log(err) }) } function createIssue(userid, repo, title, body, label = [], assignees = []) { var cred = getCredentials(userid) if (!cred) { return 0 } var ghApp = cache.get('GithubApp') var owner = ghApp[0].account var dataObj = { title: title, body: body, labels: label, assignees: assignees } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/issues`, method: 'POST', body: dataObj, headers: getUserHeaders(cred.token), json: true } request(options) .then(res => { // TODO: maybe format the massage and give a url for the issue robot.messageRoom(userid, `issue created. `) // console.log(res) }) .catch(err => { //TODO handle error codes: i.e. 404 not found -> dont post console.log(err) }) } /*************************************************************************/ /* helpful functions */ /*************************************************************************/ function getCredentials(userid) { try { var token = cache.get(userid).github_token var username = cache.get(userid).github_username if (!token || !username) { // catch the case where username or token are null/undefined throw `User credentials not found. userid: ${userid}` } } catch (error) { oauthLogin(userid) return false } return { username: username, token: token } } function getUserHeaders(token) { return { 'Authorization': `token ${token}`, 'Accept': 'application/vnd.github.machine-man-preview+json', 'User-Agent': 'Hubot For Github' } } function getAppHeaders(token) { return { 'Authorization': `Bearer ${token}`, 'Accept': 'application/vnd.github.machine-man-preview+json', 'User-Agent': 'Hubot For Github' } } function oauthLogin(userid) { // TODO change message text robot.messageRoom(userid, `<${bot_host_url}/auth/github?userid=${userid}|login>`); } function getAppToken(appID) { var db = mongoskin.MongoClient.connect(mongodb_uri) db.bind('GithubApp') return db.GithubApp.findOneAsync({ _id: appID }) .then(dbData => encryption.decrypt(dbData.token)) .catch(error => { robot.logger.error(error) if (c.errorsChannel) { robot.messageRoom(c.errorsChannel, c.errorMessage + `Script: ${path.basename(__filename)}`) } }) } function errorHandler(userid, error) { // TODO change the messages if (error.statusCode == 401) { robot.messageRoom(userid, c.jenkins.badCredentialsMsg) } else if (error.statusCode == 404) { robot.messageRoom(userid, c.jenkins.jobNotFoundMsg) } else { robot.messageRoom(userid, c.errorMessage + 'Status Code: ' + error.statusCode) robot.logger.error(error) } } function updateConversationContent(userid, content) { cache.set(userid, { content: content }) } function getConversationContent(userid, key) { try { var content = cache.get(userid, content)[key] if (!content) { throw 'content ' + key + ' for userid ' + userid + ' not found.' } else { return content } } catch (error) { return false } } function getSlackUser(username) { var userids = cache.get('userIDs') for (var i = 0; i < userids.length; i++) { var id = userids[i] var user = cache.get(id) var githubUsername try { var githubUsername = user.github_username if (githubUsername == username) { return robot.brain.userForId(id) } } catch (e) { } return false } } function bold(text) { if (robot.adapterName == 'slack') { return `*${text}*` } // Add any other adapters here else { return text } } }
scripts/github-integration.js
// Commands: // `github login` // `github repos` // `github open|closed|all issues of repo <repo_name>` // `github commits of repo <repo_name>` // `github issues of repo <repo_name>` // `github issue <issue_num>` - get the the commit of the last repo lookup // `github repo <repo_name> issue <issue_num> comments` // `github issue reply <comment_text>` // convert this to the above 2nd // `github comments of issue <issue num> of repo <repo_name>` // `github (open|closed|all) pull requests of repo <repo_name>` - Default: open // `github create issue` // `github open|closed|all pull requests of all repos` // `github show sumup open|closed|all` // `github sumup( all| closed| open|)` 'use strict'; // init const querystring = require('querystring') var GitHubApi = require("github") var slackMsgs = require('./slackMsgs.js') var c = require('./config.json') var encryption = require('./encryption.js') var cache = require('./cache.js').getCache() const Conversation = require('./hubot-conversation/index.js') var dialog = require('./dynamic-dialog.js') var convModel = require('./conversation-models.js') var color = require('./colors.js') var path = require('path') var async = require('async') var dateFormat = require('dateformat') var request = require('request-promise') var Promise = require('bluebird') var mongoskin = require('mongoskin') Promise.promisifyAll(mongoskin) // config var mongodb_uri = process.env.MONGODB_URI var bot_host_url = process.env.HUBOT_HOST_URL; var GITHUB_API = 'https://api.github.com' var githubURL = 'https://www.github.com/' module.exports = function (robot) { /*************************************************************************/ /* Listeners */ /*************************************************************************/ var switchBoard = new Conversation(robot); robot.respond(/github login/, function (res) { oauthLogin(res.message.user.id) }) robot.on('githubOAuthLogin', function (res) { oauthLogin(res.message.user.id) }) robot.respond(/github repos/, (res) => { listRepos(res.message.user.id) }) robot.on('listGithubRepos', (data, res) => { listRepos(res.message.user.id) }) robot.respond(/github( last (\d+)|) (open |closed |all |mentioned |)issues( of)? repo (.*)/i, function (res) { var userid = res.message.user.id var repo = res.match.pop() var issuesCnt = res.match[2] console.log(issuesCnt) var parameter = res.match[3].trim() console.log(res.match) if (parameter == 'mentioned') { var paramsObj = { mentioned: getCredentials(userid).username } } else if (parameter != '') { paramsObj = { state: parameter } } updateConversationContent(userid, { github_repo: repo }) listRepoIssues(userid, repo, paramsObj, issuesCnt) }) robot.respond(/github comments of issue (\d+) of repo (.*)/i, function (res) { var userid = res.message.user.id var repo = res.match[2].trim() var issueNum = res.match[1].trim() updateConversationContent(userid, { github_repo: repo, github_issue: issueNum }) // updateConversationContent(userid, { github_issue: issueNum }) listIssueComments(userid, issueNum, repo) }) robot.respond(/github (open |closed |all |)pull requests of repo (.*)/i, function (res) { var userid = res.message.user.id var state = res.match[1].trim() var repo = res.match[2].trim() listPullRequests(userid, repo, state) }) robot.respond(/github (open |closed |all |)pull requests of all repos/i, function (res) { var userid = res.message.user.id var state = res.match[1].trim() listPullRequestsForAllRepos(userid, state) }) robot.respond(/github commits( of)?( repo)? (.*)/i, function (res) { var repo = res.match.pop().trim() var userid = res.message.user.id updateConversationContent(userid, { repo: repo }) listRepoCommits(userid, repo) }) robot.on('listRepoCommits', function (result, res) { var userid = res.message.user.id var since = result.parameters['date-time'] var repoName = result.parameters['repo'] listRepoCommits(userid, repoName, since) }) // TODO: maybe replace it with api.ai robot.respond(/\bgithub\s(create|open)\sissue\b/i, function (res) { var userid = res.message.user.id dialog.startDialog(switchBoard, res, convModel.createIssue) .then(data => { createIssue(userid, 'anbot', data.title, data.body) }) .catch(err => console.log(err)) }) robot.respond(/github issue (\d+) comment (.*)/i, function (res) { var userid = res.message.user.id var issueNum = res.match[1] var commentText = res.match.pop() var repo = getConversationContent(userid, 'github_repo') if (repo) { createIssueComment(userid, repo, issueNum, commentText) } else { // TODO: send the bellow msg or use api.ai event to ask for the repo robot.messageRoom(userid, 'Sorry but i dont have your last repo lookup.' + '\nYou need to search for a repo first for this command. i.e. `github commits repo <repo_name>`' + '\nor use another command to specify repo as well.') } }) // TODO robot.respond(/^github issue (\d+) comment$/, function (res) { var issueNum = res.match[1] // ask for the comment text }) function createIssueComment(userid, repo, issueNum, comment) { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account var cred = getCredentials(userid) if (!cred) { return 0 } var dataString = { body: comment } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/issues/${issueNum}/comments`, method: 'POST', body: dataString, headers: getUserHeaders(cred.token), json: true } request(options) .then(r => { robot.messageRoom(userid, `Comment added on issue #${issueNum} of repo ${repo}!`) }) .catch(error => { robot.logger.error(error) robot.messageRoom(userid, error.message) }) } robot.on('githubSumUp', function (userid, query, saveLastSumupDate) { listGithubSumUp(userid, query, saveLastSumupDate) }) // reply instantly to the last github issue mentioned robot.respond(/github reply (.*)/i, function (res) { var userid = res.message.user.id var commentText = res.match[1] try { var repo = cache.get(userid).github_last_repo var issue = cache.get(userid).github_last_issue if (repo && issue) { createIssueComment(userid, repo, issue, commentText) } else { throw null } } catch (error) { robot.messageRoom(userid, 'Sorry but i couldn\'t process your query.') } }) robot.respond(/\bgithub close$/i, function (res) { var userid = res.message.user.id var commentText = res.match[1] try { var repo = cache.get(userid).github_last_repo var issue = cache.get(userid).github_last_issue if (repo && issue) { updateIssue(userid, repo, issue, { state: 'close' }) } else { throw null } } catch (error) { robot.messageRoom(userid, 'Sorry but i couldn\'t process your query.') } }) robot.respond(/\wgithub sum-?ups?( all| closed| open|)\b/i, function (res) { var queryObj, state state = res.match[1].trim() if (state != null) { queryObj = { state: state } } else { queryObj = { state: 'open' } } listGithubSumUp(res.message.user.id, queryObj, false) }) robot.respond(/github (close |re-?open )issue (\d+) repo (.*)/i, function (res) { var userid = res.message.user.id var repoName = res.match[3].trim() var issueNum = parseInt(res.match[2]) var state = res.match[1].trim() if (state.includes('open')) { state = 'open' } else { state = 'closed' } updateIssue(userid, repoName, issueNum, { state: state }) }) /*************************************************************************/ /* API Calls */ /*************************************************************************/ function updateIssue(userid, repo, issueNum, updateObj) { var ghApp = cache.get('GithubApp') var owner = ghApp[0].account var cred = getCredentials(userid) if (!cred) { return 0 } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/issues/${issueNum}`, method: 'PATCH', headers: getUserHeaders(cred.token), body: updateObj, json: true } request(options).then(res => { var updateInfo = `${Object.keys(updateObj)}: ${updateObj[Object.keys(updateObj)]}` var msg = { unfurl_links: true } msg.text = `Issue <${res.html_url}|#${res.number}: ${res.title}> updated. ${updateInfo}.` robot.messageRoom(userid, msg) }).catch(error => { robot.messageRoom(userid, error.message) robot.logger.error(error) }) } function listPullRequestsForAllRepos(userid, state) { getAccesibleReposName(userid) .then(repos => { for (var i = 0; i < repos.length; i++) { listPullRequests(userid, repos[i], state) } }) .catch(error => { robot.messageRoom(user, c.errorMessage) robot.logger.error(error) }) } function listGithubSumUp(userid, query, saveLastSumupDate = false) { var ghApp = cache.get('GithubApp') var orgName = ghApp[0].account var credentials = getCredentials(userid) if (!credentials) { return 0 } if (saveLastSumupDate) { var date = new Date().toISOString() cache.set(userid, { github_last_sumup_date: date }) var db = mongoskin.MongoClient.connect(mongodb_uri); db.bind('users').findAndModifyAsync( { _id: userid }, [["_id", 1]], { $set: { github_last_sumup_date: date } }, { upsert: true }) .catch(error => { robot.logger.error(error) if (c.errorsChannel) { robot.messageRoom(c.errorsChannel, c.errorMessage + `Script: ${path.basename(__filename)}`) } }) } getAccesibleReposName(userid) .then(repos => { var sinceText = '' if (query.since) { sinceText = ` since *${dateFormat(new Date(query.since), 'mmm dS yyyy, HH:MM')}*` } robot.messageRoom(userid, `Here is your github summary${sinceText}:`) for (var i = 0; i < repos.length; i++) { var repoName = repos[i] Promise.mapSeries([ `<${githubURL}${orgName}/${repoName}|[${orgName}/${repoName}]>`, getCommitsSumup(userid, repoName, query.since), getIssuesSumup(userid, repoName, query.state, query.since), getPullRequestsSumup(userid, repoName, query.state) ], function (sumupMsg) { return sumupMsg }).then(function (data) { var msg = { unfurl_links: false, text: `${data[0]}`, attachments: [] } for (var i = 1; i < data.length; i++) { msg.attachments.push(data[i]) } return msg }).then((msg) => { robot.messageRoom(userid, msg) }) } }) .catch(error => { robot.logger.error(error) robot.messageRoom(userid, c.errorMessage + `Script: ${path.basename(__filename)}`) }) } function displayRepoSumup(userid, repo, state = '') { } // TODO: // check the state when is not provided. // better msg + title // same for the functions bellow function getPullRequestsSumup(userid, repo, state = '') { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account var cred = getCredentials(userid) if (!cred) { return 0 } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/pulls?state=${state}`, method: 'GET', headers: getUserHeaders(cred.token), json: true } return new Promise((resolve, reject) => { request(options) .then(pullRequests => { var attachment = slackMsgs.attachment() var quantityText, s = 's' if (pullRequests.length > 1) { quantityText = 'There are ' + pullRequests.length } else if (pullRequests.length == 1) { quantityText = 'There is 1' s = '' } else { quantityText = 'There are no' } if (state == '' || state == 'all') { state = 'open/closed' } attachment.text = `${quantityText} (${state}) ${bold('pull request' + s)}.` attachment.color = color.rgbToHex(parseInt(pullRequests.length) * 25, 0, 0) resolve(attachment) }) .catch(error => { reject(error) }) }) } // TODOs: as mentioned in displayPullRequestsSumup function getIssuesSumup(userid, repo, state = '', since = '') { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account if (since) { since = `&since=${since}` } else { since = '' } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/issues?state=${state}${since}`, method: 'GET', headers: getAppHeaders(appToken), json: true } return new Promise((resolve, reject) => { request(options) .then(issues => { var attachment = slackMsgs.attachment() var s = '' if (issues.length > 1) { s = 's' } attachment.text = `${issues.length} ${bold('issue' + s)} (including PRs) created or updated.` attachment.color = color.rgbToHex(parseInt(issues.length) * 25, 0, 0) resolve(attachment) }) .catch(error => { reject(error) // robot.logger.error(error) // robot.messageRoom(userid, c.errorMessage) }) }) } // TODOs: as mentioned in displayPullRequestsSumup function getCommitsSumup(userid, repo, since = '') { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account if (since) { since = `?since=${since}` } else { since = '' } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/commits${since}`, method: 'GET', headers: getAppHeaders(appToken), json: true } return new Promise((resolve, reject) => { request(options) .then(commits => { var attachment = slackMsgs.attachment() var s = 's' var commitsNum = commits.length if (commitsNum == 1) { s = '' } if (commitsNum == 30) { // 30 = the max commits github returns commitsNum = '30 or more' } attachment.text = `${commitsNum} ${bold('commit' + s)} were made.` attachment.color = color.rgbToHex(parseInt(commitsNum) * 25, 0, 0) resolve(attachment) }) .catch(error => { reject(error) // robot.logger.error(error) // robot.messageRoom(userid, c.errorMessage) }) }) } function listPullRequests(userid, repo, state) { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account var cred = getCredentials(userid) if (!cred) { return 0 } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/pulls?state=${state}`, method: 'GET', headers: getUserHeaders(cred.token), json: true } request(options) .then(pullRequests => { var msg = {} msg.unfurl_links = false if (pullRequests.length > 0) { msg.attachments = [] msg.text = `Pull Requests of <https://www.github.com/${owner}/${repo}|${owner}/${repo}>:` } else { msg.text = `There aren't any Pull Requests on <https://www.github.com/${owner}/${repo}|${owner}/${repo}>` } Promise.each(pullRequests, function (pr) { var attachment = slackMsgs.attachment() var title = pr.title var url = pr.html_url var num = pr.number attachment.text = `<${url}|#${num} ${title}>` attachment.author_name = pr.user.login attachment.author_link = pr.user.html_url attachment.author_icon = pr.user.avatar_url if (pr.state.includes('open')) { attachment.color = 'good' } else { attachment.color = 'danger' } msg.attachments.push(attachment) }).done(() => { robot.messageRoom(userid, msg) }) }) .catch(error => { robot.messageRoom(userid, c.errorMessage) }) } function listRepos(userid) { var cred = getCredentials(userid) if (!cred) { return 0 } /* (Possible feature) having more than one Github App installations */ var installations = cache.get('GithubApp').length for (var i = 0; i < installations; i++) { var ghApp = cache.get('GithubApp') var installation_id = ghApp[i].id var options = { url: `${GITHUB_API}/user/installations/${installation_id}/repositories`, headers: getUserHeaders(cred.token), json: true, }; request(options) .then(res => { var msg = slackMsgs.basicMessage(); res.repositories.forEach(function (repo) { // TODO: add link to repo msg.attachments[0].text += (`${repo.full_name}\n`) }) return { msg: msg } }) .then((data) => { data.msg.text = `Your accessible Repositories: ` robot.messageRoom(userid, data.msg) }) .catch(err => { //TODO handle error codes: i.e. 404 not found -> dont post console.log(err) }) } } function getAccesibleReposName(userid) { var cred = getCredentials(userid) if (!cred) { return 0 } var ghApp = cache.get('GithubApp') var installation_id = ghApp[0].id var options = { url: `${GITHUB_API}/user/installations/${installation_id}/repositories`, headers: getUserHeaders(cred.token), json: true, }; return new Promise(function (resolve, reject) { request(options) .then(res => { var reposArray = [] Promise.each(res.repositories, function (repo) { reposArray.push(repo.name) }).then(() => { resolve(reposArray) }) }) .catch(error => { reject(error) }) }) } function listRepoCommits(userid, repo, since) { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account var parameters = '' if (since) { parameters = `?since=${since}` } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/commits${parameters}`, method: 'GET', headers: getAppHeaders(appToken), json: true } request(options) .then(repoCommits => { var msg = { attachments: [] } var attachment = slackMsgs.attachment() msg.unfurl_links = false if (repoCommits.length > 0) { msg.attachments = [] msg.text = `Commits of <${githubURL}${owner}/${repo}|${owner}/${repo}>:` } else { msg.text = `<${githubURL}${owner}/${repo}|{${owner}/${repo}]>: No Commits found` } Promise.each(repoCommits, function (commit) { var authorUsername = commit.author.login; var authorURL = githubURL + authorUsername; var commitID = commit.sha.substr(0, 7); // get the first 7 chars of the commit id var commitMsg = commit.commit.message.split('\n', 1); // get only the commit msg, not the description var commitURL = commit.html_url; commitID = "`" + commitID + "`" attachment.text += `\n<${commitURL}|${commitID}> ${commitMsg} - ${authorUsername}`; }).then(() => { msg.attachments.push(attachment) }).done(() => { robot.messageRoom(userid, msg) }) }) .catch(err => { console.log(err) }) } function listRepoIssues(userid, repo, paramsObj = { state: 'open' }, issuesCnt) { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account var params = querystring.stringify(paramsObj) var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/issues?${params}`, method: 'GET', headers: getAppHeaders(appToken), json: true } request(options) .then(repoIssues => { var msg = {} msg.unfurl_links = false if (repoIssues.length > 0) { msg.attachments = [] msg.text = `${paramsObj.state.capitalize()} issues of <https://www.github.com/${owner}/${repo}|${owner}/${repo}>:` } else { msg.text = `There aren't any issues on <https://www.github.com/${owner}/${repo}|${owner}/${repo}>` } if (issuesCnt) { repoIssues = repoIssues.slice(0, issuesCnt) } Promise.each(repoIssues, function (issue) { var attachment = slackMsgs.attachment() var title = issue.title var url = issue.html_url var num = `#${issue.number}` var userLogin = issue.user.login var userAvatar = issue.user.avatar_url var userUrl = issue.user.html_url attachment.author_name = userLogin attachment.author_icon = userAvatar attachment.author_link = userUrl attachment.text = ` <${url}|${num}: ${title}>` if (issue.body) { attachment.fields.push({ title: '', value: '```'+issue.body+'```', short: false }) } /* Do i have to provide the state of issue when i use green and red color instead? */ // attachment.fields.push({ // title: 'State', // value: issue.state, // short: true // }) if (issue.state.includes('open')) { attachment.color = 'good' } else { attachment.color = 'danger' } msg.attachments.push(attachment) }).done(() => { robot.messageRoom(userid, msg) }) }) .catch(err => { console.log(err) }) } function listIssueComments(userid, issueNum, repo = null) { var ghApp = cache.get('GithubApp') var appToken = ghApp[0].token var owner = ghApp[0].account var cred = getCredentials(userid) if (!cred) { return 0 } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/issues/${issueNum}/comments`, method: 'GET', headers: getUserHeaders(cred.token), json: true } request(options) .then(issueComments => { var msg = {} msg.unfurl_links = false var repo_url = `${githubURL}${owner}/${repo}` if (issueComments.length > 0) { msg.attachments = [] msg.text = `<${repo_url}|[${owner}/${repo}]> <${repo_url}/issues/${issueNum}|Issue #${issueNum}>:` } else { msg.text = `<${repo_url}/issues/${issueNum}|Issue #${issueNum}> of repository ${repo} hasn't any comments yet.` } Promise.each(issueComments, function (comment) { var attachment = slackMsgs.attachment() var body = comment.body // tODO: should i use created_at instead of updated_at ? var ts = Date.parse(comment.updated_at) / 1000//dateFormat(new Date(comment.created_at), 'mmm dS yyyy, HH:MM' var url = comment.html_url var userLogin = comment.user.login var userUrl = comment.user.html_url var userAvatar = comment.user.avatar_url attachment.author_name = userLogin attachment.author_icon = userAvatar attachment.author_link = userUrl attachment.ts = ts attachment.color = 'warning' // attachment.pretext = `*${user}* commented on <${url}|${created_at}>` attachment.text = body msg.attachments.push(attachment) }).done(() => { robot.messageRoom(userid, msg) }) }) .catch(err => { //TODO handle error codes: i.e. 404 not found -> dont post console.log(err) }) } function createIssue(userid, repo, title, body, label = [], assignees = []) { var cred = getCredentials(userid) if (!cred) { return 0 } var ghApp = cache.get('GithubApp') var owner = ghApp[0].account var dataObj = { title: title, body: body, labels: label, assignees: assignees } var options = { url: `${GITHUB_API}/repos/${owner}/${repo}/issues`, method: 'POST', body: dataObj, headers: getUserHeaders(cred.token), json: true } request(options) .then(res => { // TODO: maybe format the massage and give a url for the issue robot.messageRoom(userid, `issue created. `) // console.log(res) }) .catch(err => { //TODO handle error codes: i.e. 404 not found -> dont post console.log(err) }) } /*************************************************************************/ /* helpful functions */ /*************************************************************************/ function getCredentials(userid) { try { var token = cache.get(userid).github_token var username = cache.get(userid).github_username if (!token || !username) { // catch the case where username or token are null/undefined throw `User credentials not found. userid: ${userid}` } } catch (error) { oauthLogin(userid) return false } return { username: username, token: token } } function getUserHeaders(token) { return { 'Authorization': `token ${token}`, 'Accept': 'application/vnd.github.machine-man-preview+json', 'User-Agent': 'Hubot For Github' } } function getAppHeaders(token) { return { 'Authorization': `Bearer ${token}`, 'Accept': 'application/vnd.github.machine-man-preview+json', 'User-Agent': 'Hubot For Github' } } function oauthLogin(userid) { // TODO change message text robot.messageRoom(userid, `<${bot_host_url}/auth/github?userid=${userid}|login>`); } function getAppToken(appID) { var db = mongoskin.MongoClient.connect(mongodb_uri) db.bind('GithubApp') return db.GithubApp.findOneAsync({ _id: appID }) .then(dbData => encryption.decrypt(dbData.token)) .catch(error => { robot.logger.error(error) if (c.errorsChannel) { robot.messageRoom(c.errorsChannel, c.errorMessage + `Script: ${path.basename(__filename)}`) } }) } function errorHandler(userid, error) { // TODO change the messages if (error.statusCode == 401) { robot.messageRoom(userid, c.jenkins.badCredentialsMsg) } else if (error.statusCode == 404) { robot.messageRoom(userid, c.jenkins.jobNotFoundMsg) } else { robot.messageRoom(userid, c.errorMessage + 'Status Code: ' + error.statusCode) robot.logger.error(error) } } function updateConversationContent(userid, content) { cache.set(userid, { content: content }) } function getConversationContent(userid, key) { try { var content = cache.get(userid, content)[key] if (!content) { throw 'content ' + key + ' for userid ' + userid + ' not found.' } else { return content } } catch (error) { return false } } function getSlackUser(username) { var userids = cache.get('userIDs') for (var i = 0; i < userids.length; i++) { var id = userids[i] var user = cache.get(id) var githubUsername try { var githubUsername = user.github_username if (githubUsername == username) { return robot.brain.userForId(id) } } catch (e) { } return false } } function bold(text) { if (robot.adapterName == 'slack') { return `*${text}*` } // Add any other adapters here else { return text } } }
sunday work
scripts/github-integration.js
sunday work
<ide><path>cripts/github-integration.js <ide> if (issue.body) { <ide> attachment.fields.push({ <ide> title: '', <del> value: '```'+issue.body+'```', <add> value: issue.body, <ide> short: false <ide> }) <ide> }
JavaScript
mit
5890c4c2f50b3da6d2189f42e77563eea05658c0
0
RyanGosden/react-poll,leo60228/HouseRuler,jamesrf/weddingwebsite,willchertoff/planner,kriasoft/react-static-boilerplate,srossross-tableau/hackathon,kriasoft/react-static-boilerplate,willchertoff/planner,jamesrf/weddingwebsite,lifeiscontent/OpenPoGoUI,kyoyadmoon/fuzzy-hw1,raffidil/garnanain,kyoyadmoon/fuzzy-hw1,koistya/react-static-boilerplate,koistya/react-static-boilerplate,gmorel/me,leo60228/HouseRuler,gadflying/profileSite,zedd45/react-static-todos,srossross-tableau/hackathon,lifeiscontent/OpenPoGoUI,gadflying/profileSite,zedd45/react-static-todos,gmorel/me,RyanGosden/react-poll,raffidil/garnanain
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { PropTypes } from 'react'; import cx from 'classnames'; import Link from '../Link'; class Button extends React.Component { static propTypes = { component: PropTypes.oneOf([ PropTypes.string, PropTypes.element, PropTypes.func, ]), type: PropTypes.oneOf(['raised', 'fab', 'mini-fab', 'icon']), to: PropTypes.oneOf([PropTypes.string, PropTypes.object]), href: PropTypes.string, className: PropTypes.string, colored: PropTypes.bool, primary: PropTypes.bool, accent: PropTypes.bool, ripple: PropTypes.bool, children: PropTypes.node, }; componentDidMount() { window.componentHandler.upgradeElement(this.root); } componentWillUnmount() { window.componentHandler.downgradeElements(this.root); } render() { const { component, type, className, colored, to, href, primary, accent, ripple, children, ...other } = this.props; return React.createElement( component || (to ? Link : (href ? 'a' : 'button')), // eslint-disable-line no-nested-ternary { ref: node => (this.root = node), className: cx( 'mdl-button mdl-js-button', type && `mdl-button--${type}`, { 'mdl-button--colored': colored, 'mdl-button--primary': primary, 'mdl-button--accent': accent, 'mdl-button--ripple': ripple, }, className ), to, href, ...other, }, children ); } } export default Button;
components/Button/Button.js
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { PropTypes } from 'react'; import cx from 'classnames'; import Link from '../Link'; class Button extends React.Component { static propTypes = { component: PropTypes.oneOf([ PropTypes.string, PropTypes.element, PropTypes.func, ]), type: PropTypes.oneOf(['raised', 'fab', 'mini-fab', 'icon']), className: PropTypes.string, colored: PropTypes.bool, primary: PropTypes.bool, accent: PropTypes.bool, ripple: PropTypes.bool, }; componentDidMount() { window.componentHandler.upgradeElement(this.root); } componentWillUnmount() { window.componentHandler.downgradeElements(this.root); } render() { const { component, type, className, colored, to, href, primary, accent, ripple, children, ...other } = this.props; return React.createElement( component || (to ? Link : (href ? 'a' : 'button')), { ref: node => (this.root = node), className: cx( 'mdl-button mdl-js-button', type && `mdl-button--${type}`, { 'mdl-button--colored': colored, 'mdl-button--primary': primary, 'mdl-button--accent': accent, 'mdl-button--ripple': ripple, }, this.props.className ), ...other, }, children ); } } export default Button;
Fix ESLint warnings in the Button component
components/Button/Button.js
Fix ESLint warnings in the Button component
<ide><path>omponents/Button/Button.js <ide> PropTypes.func, <ide> ]), <ide> type: PropTypes.oneOf(['raised', 'fab', 'mini-fab', 'icon']), <add> to: PropTypes.oneOf([PropTypes.string, PropTypes.object]), <add> href: PropTypes.string, <ide> className: PropTypes.string, <ide> colored: PropTypes.bool, <ide> primary: PropTypes.bool, <ide> accent: PropTypes.bool, <ide> ripple: PropTypes.bool, <add> children: PropTypes.node, <ide> }; <ide> <ide> componentDidMount() { <ide> const { component, type, className, colored, to, href, <ide> primary, accent, ripple, children, ...other } = this.props; <ide> return React.createElement( <del> component || (to ? Link : (href ? 'a' : 'button')), <add> component || (to ? Link : (href ? 'a' : 'button')), // eslint-disable-line no-nested-ternary <ide> { <ide> ref: node => (this.root = node), <ide> className: cx( <ide> 'mdl-button--accent': accent, <ide> 'mdl-button--ripple': ripple, <ide> }, <del> this.props.className <add> className <ide> ), <add> to, <add> href, <ide> ...other, <ide> }, <ide> children
Java
mit
79f0a1ba3f0351d1b546ef065cdf56f8f6308029
0
JGerdes/Schauburgr
package com.jonasgerdes.schauburgr.model.schauburg.parsing; import android.text.Html; import com.jonasgerdes.schauburgr.model.schauburg.entity.Movie; import com.jonasgerdes.schauburgr.util.StringUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Parser for movies retrieved via schauburg-cineworld.de "API". * Create instances of {@link Movie} based on single lines which define a movie as * JavaScript object (via a constructor though, not as JSON) * Sample movie definition: * movies[2] = new movie('fw1','A Cure for Wellness','1703051945','146','16', * 'Ein junger, ehrgeiziger Manager...','','2','','','',''); * Attributes like ressource-id, title, release date etc are extracted from this string via regex. * Sometimes the title of a movie contains additional information (e.g. whether it's in Dolby Atmos). * These attributes are extract and remove from title. * * @author Jonas Gerdes <[email protected]> * @since 05.03.2017 */ public class MovieParser { private static final String REGEX_PREFIX = "new movie\\("; private static final String REGEX_ID = "'(\\w\\w\\d\\d?)'"; private static final String REGEX_TITLE = "'(.*?)'"; private static final String REGEX_RELEASE_DATE = "'(\\d{10})'"; private static final String REGEX_DURATION = "'(\\d{0,3})'"; //0 if there is nothing provided private static final String REGEX_CONTENT_RATING = "'(\\d\\d?)'"; private static final String REGEX_DESCRIPTION = "'((?>\\s|\\S)*?)'"; private static final String REGEX_IS_3D = "'(1?)'"; private static final String REGEX_STUB = "'.*?'"; //description content patterns //find all "Genre: ... <br>", "Genres ... <br>", "(*) ... *" //[\s\w,\-\/öüäÖÜÄß] is used instead of . to prevent "(*) Darsteller:" to be detected as genre private static final String REGEX_DESCRIPTION_GENRE = "(?>Genres?:?|\\(\\*\\)) (.[\\s\\w,\\-\\/öüäÖÜÄß]*?)(<br>|\\*)"; //safety threshold of max. 30 (and min 5) chars as name for director to prevent //capturing sentences starting with "Von" as director private static final String REGEX_DESCRIPTION_DIRECTOR = "(?>Regie|Von):? (.{5,30}?)(<br>|;)"; //cast is often start with "Cast:", but sometimes just with "Mit ". //also sometimes it ends with "und mehr" or "mehr" //alternative pattern sometimes start with "(*) Darsteller:" and ends with ";" (but names //sometimes contain "&apos;", some make sure not word char is follorws by ; private static final String REGEX_DESCRIPTION_CAST //= "(?>^|<br>|\\(\\*\\) ?)(?>Cast|Mit|Darsteller):? (.*?)(?>(?>und)? mehr ?)?(?><br>|;\\W)"; = "(?>^|<br>|\\(\\*\\) ?)(?>Cast|Mit|Darsteller):? (.*?)(?>(?>und)? mehr ?)?;?<br>"; private static final String REGEX_DESCRIPTION_DURATION = "(?>Laufzeit|Länge):(.*?)(>?<br>|$)"; private static final String REGEX_DESCRIPTION_CONTENT_RATING = "FSK:(.*?)(>?<br>|$)"; private static final String REGEX_DESCRIPTION_LOCATION = "Produktionsland:? (.*?)(>?<br>|$)"; private static final String REGEX_MOVIE = "" + REGEX_PREFIX + REGEX_ID + ',' + REGEX_TITLE + ',' + REGEX_RELEASE_DATE + ',' + REGEX_DURATION + ',' + REGEX_CONTENT_RATING + ',' + REGEX_DESCRIPTION + ',' + REGEX_STUB + ',' + REGEX_STUB + ',' + REGEX_IS_3D; /** * Possible appearances of extra attributes in title of movie. They are quite inconsistent so it * should be testes for a variety of spellings and symbol usage (like hyphens and brackets) */ private static final ExtraMapping[] EXTRA_MAPPINGS = new ExtraMapping[]{ new ExtraMapping(Movie.EXTRA_3D, "(3D)", "in 3D", "- 3D", "3D"), new ExtraMapping(Movie.EXTRA_ATMOS, ": in Dolby Atmos", "in Dolby Atmos", "- Dolby Atmos", "Dolby Atmos"), new ExtraMapping(Movie.EXTRA_OT, "Original Ton", "O-Ton", "OTon", " OT", "(OV englisch)", "OV englisch", " OV"), new ExtraMapping(Movie.EXTRA_TIP, "- Filmtipp", "Filmtipp", "Tipp"), new ExtraMapping(Movie.EXTRA_REEL, "Filmrolle:", "- der besondere Film"), new ExtraMapping(Movie.EXTRA_LADIES_NIGHT, "Ladies Night:", "Ladies Night -"), new ExtraMapping(Movie.EXTRA_PREVIEW, ": Vorpremiere", "- Vorpremiere", "Vorpremiere:", "Vorp:", "Vorp.:", "- Vorp", ":Vorp", "Vorp."), new ExtraMapping(Movie.EXTRA_LAST_SCREENINGS, ": Letzte Chance!", ": Letzte Chance", "- Letzte Chance!", "- Letzte Chance", ": Letzte Gelegenheit!", ": Letzte Gelegenheit", "- Letzte Gelegenheit!", "- Letzte Gelegenheit"), //various stuff which might is added to title and should be removed new ExtraMapping(Movie.EXTRA_IGNORE, "- Jetzt in 2D", "- in 2D", " in 2D", "- Das Kino Event!", "CDU Vechta presents:" ), }; /** * Max char length of a single genre title. Is used as kind of security to prevent using * hole descriptions as genre in case there isn't a new line after genre definitions or * some other weird stuff. */ private static final int GENRE_MAX_LENGTH = 16; private final Pattern mMoviePattern; private final Pattern mGenrePattern; private final Pattern mDirectorPattern; private final Pattern mCastPattern; private final Pattern mDurationPattern; private final Pattern mContentRatingPattern; private final Pattern mLocationPattern; public MovieParser() { mMoviePattern = Pattern.compile(REGEX_MOVIE); mGenrePattern = Pattern.compile(REGEX_DESCRIPTION_GENRE); mDirectorPattern = Pattern.compile(REGEX_DESCRIPTION_DIRECTOR); mCastPattern = Pattern.compile(REGEX_DESCRIPTION_CAST); mDurationPattern = Pattern.compile(REGEX_DESCRIPTION_DURATION); mContentRatingPattern = Pattern.compile(REGEX_DESCRIPTION_CONTENT_RATING); mLocationPattern = Pattern.compile(REGEX_DESCRIPTION_LOCATION); } /** * Creates a {@link Movie} instance by parsing give line from "API" * * @param line single JavaScript line calling movie constructor (as used in schauburgs "API") * @return new instance of {@link Movie} with data parse from string or null if parsing fails */ public Movie parse(String line) { //in the javascript to parse, all movies are put in an array, so this is the simples way to //test whether we have a line containing a movie construction and can parse it if (!line.startsWith("movies[")) { return null; } Movie movie; Matcher matcher = mMoviePattern.matcher(line); if (matcher.find()) { movie = new Movie(); movie.setResourceId(matcher.group(1)); movie.setDuration(Long.parseLong(matcher.group(4))); movie.setContentRating(Integer.parseInt(matcher.group(5))); String rawTitle = matcher.group(2); rawTitle = parseExtras(movie, rawTitle); rawTitle = rawTitle.trim(); //remove possible whitespace around title rawTitle = removeHtmlEntities(rawTitle); movie.setTitle(rawTitle); //advanced parsing of description String description = matcher.group(6); description = remove(description, mDurationPattern); description = remove(description, mContentRatingPattern); description = remove(description, mLocationPattern); movie.setDescription(description); movie.setGenres(parseFromDescription(movie, mGenrePattern)); movie.setDirectors(parseFromDescription(movie, mDirectorPattern)); movie.setCast(parseFromDescription(movie, mCastPattern)); //clean up whitespace description = movie.getDescription(); description = cleanDescription(description); description = description.trim(); description = removeLineBreaks(description); movie.setDescription(description); parseAndAddGenresFromTitle(movie); } else { movie = null; // TODO: 02-Nov-17 somehow (remotly) log this to debug movies which couldn't be parsed } return movie; } /** * Cleans description from junk (like "* *") * @param description description to clean * @return cleaned description */ private String cleanDescription(String description) { //replace "* *" sometimes appear in description description = description.replaceAll("\\* \\*", "<br>"); return description; } /** * Remove/Replace Html entities like &amp; etc with respective char * * @param string * @return */ private String removeHtmlEntities(String string) { return Html.fromHtml(string).toString(); //fix &amp; etc } /** * Removes leading HTML line break tags * * @param description to remove line breaks from * @return Cleaned description */ private String removeLineBreaks(String description) { while (description.startsWith("<br>")) { description = description.substring(4, description.length()); } return description; } /** * Extract data from given {@link Movie} by parsing its description text with help of provided * regex pattern. Automatically splits multiple values (concatenated by either , or /). * Removes everything matching the regex pattern from description. * * @param movie Movie to parse genres from and save them into * @param pattern Compiled regex pattern to find data with * @return List of found data items */ private List<String> parseFromDescription(Movie movie, Pattern pattern) { List<String> parsed = new ArrayList<>(); //search description for pattern String description = movie.getDescription(); Matcher matcher = pattern.matcher(description); //sometimes description contains some introduction texts, already including information //like cast and director - so loop to find all occurrences while (matcher.find()) { String found = matcher.group(1); //split found parts string and remove whitespace String[] splitted = found.split("(,|/)"); for (String item : splitted) { item = item.trim(); //only add item not empty if (!item.isEmpty()) { item = removeHtmlEntities(item); parsed.add(item.trim()); } } description = description.replace(matcher.group(0), ""); } //remove found item(s) from description movie.setDescription(description); return parsed; } private String remove(String string, Pattern toRemove) { Matcher matcher = toRemove.matcher(string); if (matcher.find()) { return string.replace(matcher.group(0), ""); } return string; } /** * Parses some specials genres (like operas) from title of movie. Already adds parsed genres * to movie. * * @param movie Movie to parse and add genres from title */ private void parseAndAddGenresFromTitle(Movie movie) { //special "genre" for live operas List<String> operaIndicators = Arrays.asList("Met Opera Live:", "MET Opera:"); List<String> genres = new ArrayList<>(); genres.addAll(movie.getGenres()); for (String operaIndicator : operaIndicators) { if (movie.getTitle().toLowerCase().startsWith(operaIndicator.toLowerCase())) { //only add genre once, but remove all indicators from title if (!genres.contains(Movie.GENRE_MET_OPERA)) { genres.add(Movie.GENRE_MET_OPERA); } //tidy up title String title = movie.getTitle(); title = title.substring(operaIndicator.length(), title.length()); title = title.trim(); movie.setTitle(title); } } movie.setGenres(genres); } /** * Parses extras like Dolby Atmos, "Filmrolle" etc from raw title. Adds parsed extras to given * {@link Movie} instance and removes them from title. * * @param movie Movie to add found extras to * @param rawTitle Raw title containing extras * @return new title with parsed extras removed */ private String parseExtras(Movie movie, String rawTitle) { List<String> extras = new ArrayList<>(); for (ExtraMapping extraMapping : EXTRA_MAPPINGS) { ExtraParseResult result = parseExtra(rawTitle, extraMapping.hints); if (result.found) { //only save extra when not already found and not to be ignored if (!extras.contains(extraMapping.extra) && !extraMapping.extra.equals(Movie.EXTRA_IGNORE)) { extras.add(extraMapping.extra); } rawTitle = result.newTitle; } } movie.setExtras(extras); return rawTitle; } /** * Checks whether given titl contains extra defined by given hints array. * * @param rawTitle raw title of a movie containing extras * @param hints hints to look for in title to determine if movie has an extra * @return result object containing a new title without found extras and whether the extra * was found at all */ private ExtraParseResult parseExtra(String rawTitle, String[] hints) { ExtraParseResult result = new ExtraParseResult(); for (String hint : hints) { int start = rawTitle.toLowerCase().indexOf(hint.toLowerCase()); if (start != -1) { //cut found string out of title rawTitle = StringUtil.remove(rawTitle, start, hint.length()); result.found = true; } } result.newTitle = rawTitle; return result; } /** * Result of a check whether a title contains a hint to an extra */ private class ExtraParseResult { String newTitle; boolean found; } /** * Mapping between an extra title and hints which determine that a movie has an extra */ private static class ExtraMapping { public ExtraMapping(String extra, String... hints) { this.extra = extra; this.hints = hints; } String extra; String[] hints; } }
app/src/main/java/com/jonasgerdes/schauburgr/model/schauburg/parsing/MovieParser.java
package com.jonasgerdes.schauburgr.model.schauburg.parsing; import android.text.Html; import com.jonasgerdes.schauburgr.model.schauburg.entity.Movie; import com.jonasgerdes.schauburgr.util.StringUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Parser for movies retrieved via schauburg-cineworld.de "API". * Create instances of {@link Movie} based on single lines which define a movie as * JavaScript object (via a constructor though, not as JSON) * Sample movie definition: * movies[2] = new movie('fw1','A Cure for Wellness','1703051945','146','16', * 'Ein junger, ehrgeiziger Manager...','','2','','','',''); * Attributes like ressource-id, title, release date etc are extracted from this string via regex. * Sometimes the title of a movie contains additional information (e.g. whether it's in Dolby Atmos). * These attributes are extract and remove from title. * * @author Jonas Gerdes <[email protected]> * @since 05.03.2017 */ public class MovieParser { private static final String REGEX_PREFIX = "new movie\\("; private static final String REGEX_ID = "'(\\w\\w\\d\\d?)'"; private static final String REGEX_TITLE = "'(.*?)'"; private static final String REGEX_RELEASE_DATE = "'(\\d{10})'"; private static final String REGEX_DURATION = "'(\\d{0,3})'"; //0 if there is nothing provided private static final String REGEX_CONTENT_RATING = "'(\\d\\d?)'"; private static final String REGEX_DESCRIPTION = "'((?>\\s|\\S)*?)'"; private static final String REGEX_IS_3D = "'(1?)'"; private static final String REGEX_STUB = "'.*?'"; //description content patterns private static final String REGEX_DESCRIPTION_GENRE = "Genre:? (.*?)<br>"; //safety threshold of max. 30 (and min 5) chars as name for director to prevent //capturing sentences starting with "Von" as director private static final String REGEX_DESCRIPTION_DIRECTOR = "(?>Regie|Von):? (.{5,30}?)<br>"; //cast is often start with "Cast:", but sometimes just with "Mit ". //also sometimes it ends with "und mehr" or "mehr" private static final String REGEX_DESCRIPTION_CAST = "(?>^|<br>)(?>Cast|Mit):? (.*?)(?>(?>und)? mehr ?)?<br>"; private static final String REGEX_DESCRIPTION_DURATION = "(?>Laufzeit|Länge):(.*?)(>?<br>|$)"; private static final String REGEX_DESCRIPTION_CONTENT_RATING = "FSK:(.*?)(>?<br>|$)"; private static final String REGEX_DESCRIPTION_LOCATION = "Produktionsland:? (.*?)(>?<br>|$)"; private static final String REGEX_MOVIE = "" + REGEX_PREFIX + REGEX_ID + ',' + REGEX_TITLE + ',' + REGEX_RELEASE_DATE + ',' + REGEX_DURATION + ',' + REGEX_CONTENT_RATING + ',' + REGEX_DESCRIPTION + ',' + REGEX_STUB + ',' + REGEX_STUB + ',' + REGEX_IS_3D; /** * Possible appearances of extra attributes in title of movie. They are quite inconsistent so it * should be testes for a variety of spellings and symbol usage (like hyphens and brackets) */ private static final ExtraMapping[] EXTRA_MAPPINGS = new ExtraMapping[]{ new ExtraMapping(Movie.EXTRA_3D, "(3D)", "in 3D", "- 3D", "3D"), new ExtraMapping(Movie.EXTRA_ATMOS, ": in Dolby Atmos", "in Dolby Atmos", "- Dolby Atmos", "Dolby Atmos"), new ExtraMapping(Movie.EXTRA_OT, "Original Ton", "O-Ton", "OTon", " OT", "(OV englisch)", "OV englisch", " OV"), new ExtraMapping(Movie.EXTRA_TIP, "- Filmtipp", "Filmtipp", "Tipp"), new ExtraMapping(Movie.EXTRA_REEL, "Filmrolle:", "- der besondere Film"), new ExtraMapping(Movie.EXTRA_LADIES_NIGHT, "Ladies Night:", "Ladies Night -"), new ExtraMapping(Movie.EXTRA_PREVIEW, ": Vorpremiere", "- Vorpremiere", "Vorpremiere:", "Vorp:", "Vorp.:", "- Vorp", ":Vorp", "Vorp."), new ExtraMapping(Movie.EXTRA_LAST_SCREENINGS, ": Letzte Chance!", ": Letzte Chance", "- Letzte Chance!", "- Letzte Chance", ": Letzte Gelegenheit!", ": Letzte Gelegenheit", "- Letzte Gelegenheit!", "- Letzte Gelegenheit"), //various stuff which might is added to title and should be removed new ExtraMapping(Movie.EXTRA_IGNORE, "- Jetzt in 2D", "- in 2D", " in 2D", "- Das Kino Event!", "CDU Vechta presents:" ), }; /** * Max char length of a single genre title. Is used as kind of security to prevent using * hole descriptions as genre in case there isn't a new line after genre definitions or * some other weird stuff. */ private static final int GENRE_MAX_LENGTH = 16; private final Pattern mMoviePattern; private final Pattern mGenrePattern; private final Pattern mDirectorPattern; private final Pattern mCastPattern; private final Pattern mDurationPattern; private final Pattern mContentRatingPattern; private final Pattern mLocationPattern; public MovieParser() { mMoviePattern = Pattern.compile(REGEX_MOVIE); mGenrePattern = Pattern.compile(REGEX_DESCRIPTION_GENRE); mDirectorPattern = Pattern.compile(REGEX_DESCRIPTION_DIRECTOR); mCastPattern = Pattern.compile(REGEX_DESCRIPTION_CAST); mDurationPattern = Pattern.compile(REGEX_DESCRIPTION_DURATION); mContentRatingPattern = Pattern.compile(REGEX_DESCRIPTION_CONTENT_RATING); mLocationPattern = Pattern.compile(REGEX_DESCRIPTION_LOCATION); } /** * Creates a {@link Movie} instance by parsing give line from "API" * * @param line single JavaScript line calling movie constructor (as used in schauburgs "API") * @return new instance of {@link Movie} with data parse from string or null if parsing fails */ public Movie parse(String line) { //in the javascript to parse, all movies are put in an array, so this is the simples way to //test whether we have a line containing a movie construction and can parse it if (!line.startsWith("movies[")) { return null; } Movie movie; Matcher matcher = mMoviePattern.matcher(line); if (matcher.find()) { movie = new Movie(); movie.setResourceId(matcher.group(1)); movie.setDuration(Long.parseLong(matcher.group(4))); movie.setContentRating(Integer.parseInt(matcher.group(5))); String rawTitle = matcher.group(2); rawTitle = parseExtras(movie, rawTitle); rawTitle = rawTitle.trim(); //remove possible whitespace around title rawTitle = removeHtmlEntities(rawTitle); movie.setTitle(rawTitle); //advanced parsing of description String description = matcher.group(6); description = remove(description, mDurationPattern); description = remove(description, mContentRatingPattern); description = remove(description, mLocationPattern); movie.setDescription(description); movie.setGenres(parseFromDescription(movie, mGenrePattern)); movie.setDirectors(parseFromDescription(movie, mDirectorPattern)); movie.setCast(parseFromDescription(movie, mCastPattern)); //clean up whitespace description = movie.getDescription(); description = description.trim(); description = removeLineBreaks(description); movie.setDescription(description); parseAndAddGenresFromTitle(movie); } else { movie = null; // TODO: 02-Nov-17 somehow (remotly) log this to debug movies which couldn't be parsed } return movie; } /** * Remove/Replace Html entities like &amp; etc with respective char * * @param string * @return */ private String removeHtmlEntities(String string) { return Html.fromHtml(string).toString(); //fix &amp; etc } /** * Removes leading HTML line break tags * * @param description to remove line breaks from * @return Cleaned description */ private String removeLineBreaks(String description) { while (description.startsWith("<br>")) { description = description.substring(4, description.length()); } return description; } /** * Extract data from given {@link Movie} by parsing its description text with help of provided * regex pattern. Automatically splits multiple values (concatenated by either , or /). * Removes everything matching the regex pattern from description. * * @param movie Movie to parse genres from and save them into * @param pattern Compiled regex pattern to find data with * @return List of found data items */ private List<String> parseFromDescription(Movie movie, Pattern pattern) { List<String> parsed = new ArrayList<>(); //search description for pattern String description = movie.getDescription(); Matcher matcher = pattern.matcher(description); //sometimes description contains some introduction texts, already including information //like cast and director - so loop to find all occurrences while (matcher.find()) { String found = matcher.group(1); //split found parts string and remove whitespace String[] splitted = found.split("(,|/)"); for (String item : splitted) { item = item.trim(); //only add item not empty if (!item.isEmpty()) { item = removeHtmlEntities(item); parsed.add(item.trim()); } } description = description.replace(matcher.group(0), ""); } //remove found item(s) from description movie.setDescription(description); return parsed; } private String remove(String string, Pattern toRemove) { Matcher matcher = toRemove.matcher(string); if (matcher.find()) { return string.replace(matcher.group(0), ""); } return string; } /** * Parses some specials genres (like operas) from title of movie. Already adds parsed genres * to movie. * * @param movie Movie to parse and add genres from title */ private void parseAndAddGenresFromTitle(Movie movie) { //special "genre" for live operas List<String> operaIndicators = Arrays.asList("Met Opera Live:", "MET Opera:"); List<String> genres = new ArrayList<>(); genres.addAll(movie.getGenres()); for (String operaIndicator : operaIndicators) { if (movie.getTitle().toLowerCase().startsWith(operaIndicator.toLowerCase())) { //only add genre once, but remove all indicators from title if (!genres.contains(Movie.GENRE_MET_OPERA)) { genres.add(Movie.GENRE_MET_OPERA); } //tidy up title String title = movie.getTitle(); title = title.substring(operaIndicator.length(), title.length()); title = title.trim(); movie.setTitle(title); } } movie.setGenres(genres); } /** * Parses extras like Dolby Atmos, "Filmrolle" etc from raw title. Adds parsed extras to given * {@link Movie} instance and removes them from title. * * @param movie Movie to add found extras to * @param rawTitle Raw title containing extras * @return new title with parsed extras removed */ private String parseExtras(Movie movie, String rawTitle) { List<String> extras = new ArrayList<>(); for (ExtraMapping extraMapping : EXTRA_MAPPINGS) { ExtraParseResult result = parseExtra(rawTitle, extraMapping.hints); if (result.found) { //only save extra when not already found and not to be ignored if (!extras.contains(extraMapping.extra) && !extraMapping.extra.equals(Movie.EXTRA_IGNORE)) { extras.add(extraMapping.extra); } rawTitle = result.newTitle; } } movie.setExtras(extras); return rawTitle; } /** * Checks whether given titl contains extra defined by given hints array. * * @param rawTitle raw title of a movie containing extras * @param hints hints to look for in title to determine if movie has an extra * @return result object containing a new title without found extras and whether the extra * was found at all */ private ExtraParseResult parseExtra(String rawTitle, String[] hints) { ExtraParseResult result = new ExtraParseResult(); for (String hint : hints) { int start = rawTitle.toLowerCase().indexOf(hint.toLowerCase()); if (start != -1) { //cut found string out of title rawTitle = StringUtil.remove(rawTitle, start, hint.length()); result.found = true; } } result.newTitle = rawTitle; return result; } /** * Result of a check whether a title contains a hint to an extra */ private class ExtraParseResult { String newTitle; boolean found; } /** * Mapping between an extra title and hints which determine that a movie has an extra */ private static class ExtraMapping { public ExtraMapping(String extra, String... hints) { this.extra = extra; this.hints = hints; } String extra; String[] hints; } }
Improve parsing cast from description
app/src/main/java/com/jonasgerdes/schauburgr/model/schauburg/parsing/MovieParser.java
Improve parsing cast from description
<ide><path>pp/src/main/java/com/jonasgerdes/schauburgr/model/schauburg/parsing/MovieParser.java <ide> private static final String REGEX_STUB = "'.*?'"; <ide> <ide> //description content patterns <del> private static final String REGEX_DESCRIPTION_GENRE = "Genre:? (.*?)<br>"; <add> //find all "Genre: ... <br>", "Genres ... <br>", "(*) ... *" <add> //[\s\w,\-\/öüäÖÜÄß] is used instead of . to prevent "(*) Darsteller:" to be detected as genre <add> private static final String REGEX_DESCRIPTION_GENRE = <add> "(?>Genres?:?|\\(\\*\\)) (.[\\s\\w,\\-\\/öüäÖÜÄß]*?)(<br>|\\*)"; <ide> //safety threshold of max. 30 (and min 5) chars as name for director to prevent <ide> //capturing sentences starting with "Von" as director <del> private static final String REGEX_DESCRIPTION_DIRECTOR = "(?>Regie|Von):? (.{5,30}?)<br>"; <add> private static final String REGEX_DESCRIPTION_DIRECTOR = "(?>Regie|Von):? (.{5,30}?)(<br>|;)"; <ide> //cast is often start with "Cast:", but sometimes just with "Mit ". <ide> //also sometimes it ends with "und mehr" or "mehr" <add> //alternative pattern sometimes start with "(*) Darsteller:" and ends with ";" (but names <add> //sometimes contain "&apos;", some make sure not word char is follorws by ; <ide> private static final String REGEX_DESCRIPTION_CAST <del> = "(?>^|<br>)(?>Cast|Mit):? (.*?)(?>(?>und)? mehr ?)?<br>"; <add> //= "(?>^|<br>|\\(\\*\\) ?)(?>Cast|Mit|Darsteller):? (.*?)(?>(?>und)? mehr ?)?(?><br>|;\\W)"; <add> = "(?>^|<br>|\\(\\*\\) ?)(?>Cast|Mit|Darsteller):? (.*?)(?>(?>und)? mehr ?)?;?<br>"; <ide> private static final String REGEX_DESCRIPTION_DURATION = "(?>Laufzeit|Länge):(.*?)(>?<br>|$)"; <ide> private static final String REGEX_DESCRIPTION_CONTENT_RATING = "FSK:(.*?)(>?<br>|$)"; <ide> private static final String REGEX_DESCRIPTION_LOCATION = "Produktionsland:? (.*?)(>?<br>|$)"; <ide> <ide> //clean up whitespace <ide> description = movie.getDescription(); <add> description = cleanDescription(description); <ide> description = description.trim(); <ide> description = removeLineBreaks(description); <ide> movie.setDescription(description); <ide> } <ide> <ide> return movie; <add> } <add> <add> /** <add> * Cleans description from junk (like "* *") <add> * @param description description to clean <add> * @return cleaned description <add> */ <add> private String cleanDescription(String description) { <add> //replace "* *" sometimes appear in description <add> description = description.replaceAll("\\* \\*", "<br>"); <add> return description; <ide> } <ide> <ide> /**
JavaScript
mit
e8f821b16afbee5043c75212f6b5507cf66d09b6
0
mathieumg/eslint-plugin-babel,zaygraveyard/eslint-plugin-babel
helpers.js
var _parse = require('babel-core').parse; module.exports = { parse: function(code){ var ast = null try { ast = _parse(code, { locations: true, ranges: true }).body[0] //unwrap body } catch (err){ console.warn(err) } return ast } }
remove helpers.js, which is unused
helpers.js
remove helpers.js, which is unused
<ide><path>elpers.js <del>var _parse = require('babel-core').parse; <del> <del>module.exports = { <del> parse: function(code){ <del> var ast = null <del> try { <del> ast = _parse(code, { locations: true, ranges: true }).body[0] //unwrap body <del> } <del> catch (err){ <del> console.warn(err) <del> } <del> <del> return ast <del> } <del>}
Java
apache-2.0
89478966db1d9be013cd7a8bf0700bb0894f3ea6
0
rcordovano/autopsy,wschaeferB/autopsy,esaunders/autopsy,rcordovano/autopsy,rcordovano/autopsy,wschaeferB/autopsy,rcordovano/autopsy,wschaeferB/autopsy,esaunders/autopsy,rcordovano/autopsy,esaunders/autopsy,wschaeferB/autopsy,esaunders/autopsy,esaunders/autopsy,rcordovano/autopsy,wschaeferB/autopsy
/* * Autopsy Forensic Browser * * Copyright 2017-2018 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.modules.encryptiondetection; import com.healthmarketscience.jackcess.CryptCodecProvider; import com.healthmarketscience.jackcess.Database; import com.healthmarketscience.jackcess.DatabaseBuilder; import com.healthmarketscience.jackcess.InvalidCredentialsException; import com.healthmarketscience.jackcess.impl.CodecProvider; import com.healthmarketscience.jackcess.impl.UnsupportedCodecException; import com.healthmarketscience.jackcess.util.MemFileChannel; import java.io.IOException; import java.util.Collections; import java.util.logging.Level; import org.sleuthkit.datamodel.ReadContentInputStream; import java.io.BufferedInputStream; import java.io.InputStream; import java.nio.BufferUnderflowException; import org.apache.tika.exception.EncryptedDocumentException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.sax.BodyContentHandler; import org.openide.util.NbBundle.Messages; import org.sleuthkit.autopsy.casemodule.Case; import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException; import org.sleuthkit.autopsy.casemodule.services.Blackboard; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.ingest.FileIngestModuleAdapter; import org.sleuthkit.autopsy.ingest.IngestJobContext; import org.sleuthkit.autopsy.ingest.IngestMessage; import org.sleuthkit.autopsy.ingest.IngestModule; import org.sleuthkit.autopsy.ingest.IngestServices; import org.sleuthkit.autopsy.ingest.ModuleDataEvent; import org.sleuthkit.autopsy.modules.filetypeid.FileTypeDetector; import org.sleuthkit.datamodel.AbstractFile; import org.sleuthkit.datamodel.BlackboardArtifact; import org.sleuthkit.datamodel.BlackboardAttribute; import org.sleuthkit.datamodel.ReadContentInputStream.ReadContentInputStreamException; import org.sleuthkit.datamodel.TskCoreException; import org.sleuthkit.datamodel.TskData; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; /** * File ingest module to detect encryption and password protection. */ final class EncryptionDetectionFileIngestModule extends FileIngestModuleAdapter { private static final int FILE_SIZE_MODULUS = 512; private static final String DATABASE_FILE_EXTENSION = "db"; private static final int MINIMUM_DATABASE_FILE_SIZE = 65536; //64 KB private static final String MIME_TYPE_OOXML_PROTECTED = "application/x-ooxml-protected"; private static final String MIME_TYPE_MSWORD = "application/msword"; private static final String MIME_TYPE_MSEXCEL = "application/vnd.ms-excel"; private static final String MIME_TYPE_MSPOWERPOINT = "application/vnd.ms-powerpoint"; private static final String MIME_TYPE_MSACCESS = "application/x-msaccess"; private static final String MIME_TYPE_PDF = "application/pdf"; private static final String[] FILE_IGNORE_LIST = {"hiberfile.sys", "pagefile.sys"}; private final IngestServices services = IngestServices.getInstance(); private final Logger logger = services.getLogger(EncryptionDetectionModuleFactory.getModuleName()); private FileTypeDetector fileTypeDetector; private Blackboard blackboard; private double calculatedEntropy; private final double minimumEntropy; private final int minimumFileSize; private final boolean fileSizeMultipleEnforced; private final boolean slackFilesAllowed; /** * Create a EncryptionDetectionFileIngestModule object that will detect * files that are either encrypted or password protected and create * blackboard artifacts as appropriate. The supplied * EncryptionDetectionIngestJobSettings object is used to configure the * module. */ EncryptionDetectionFileIngestModule(EncryptionDetectionIngestJobSettings settings) { minimumEntropy = settings.getMinimumEntropy(); minimumFileSize = settings.getMinimumFileSize(); fileSizeMultipleEnforced = settings.isFileSizeMultipleEnforced(); slackFilesAllowed = settings.isSlackFilesAllowed(); } @Override public void startUp(IngestJobContext context) throws IngestModule.IngestModuleException { try { validateSettings(); blackboard = Case.getCurrentCaseThrows().getServices().getBlackboard(); fileTypeDetector = new FileTypeDetector(); } catch (FileTypeDetector.FileTypeDetectorInitException ex) { throw new IngestModule.IngestModuleException("Failed to create file type detector", ex); } catch (NoCurrentCaseException ex) { throw new IngestModule.IngestModuleException("Exception while getting open case.", ex); } } @Messages({ "EncryptionDetectionFileIngestModule.artifactComment.password=Password protection detected.", "EncryptionDetectionFileIngestModule.artifactComment.suspected=Suspected encryption due to high entropy (%f)." }) @Override public IngestModule.ProcessResult process(AbstractFile file) { try { /* * Qualify the file type, qualify it against hash databases, and * verify the file hasn't been deleted. */ if (!file.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.UNALLOC_BLOCKS) && !file.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.UNUSED_BLOCKS) && !file.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.VIRTUAL_DIR) && !file.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.LOCAL_DIR) && (!file.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.SLACK) || slackFilesAllowed) && !file.getKnown().equals(TskData.FileKnown.KNOWN) && !file.isMetaFlagSet(TskData.TSK_FS_META_FLAG_ENUM.UNALLOC)) { /* * Is the file in FILE_IGNORE_LIST? */ String filePath = file.getParentPath(); if (filePath.equals("/")) { String fileName = file.getName(); for (String listEntry : FILE_IGNORE_LIST) { if (fileName.equalsIgnoreCase(listEntry)) { // Skip this file. return IngestModule.ProcessResult.OK; } } } /* * Qualify the MIME type. */ String mimeType = fileTypeDetector.getMIMEType(file); if (mimeType.equals("application/octet-stream") && isFileEncryptionSuspected(file)) { return flagFile(file, BlackboardArtifact.ARTIFACT_TYPE.TSK_ENCRYPTION_SUSPECTED, String.format(Bundle.EncryptionDetectionFileIngestModule_artifactComment_suspected(), calculatedEntropy)); } else if (isFilePasswordProtected(file)) { return flagFile(file, BlackboardArtifact.ARTIFACT_TYPE.TSK_ENCRYPTION_DETECTED, Bundle.EncryptionDetectionFileIngestModule_artifactComment_password()); } } } catch (ReadContentInputStreamException | SAXException | TikaException | UnsupportedCodecException ex) { logger.log(Level.WARNING, String.format("Unable to read file '%s'", file.getParentPath() + file.getName()), ex); return IngestModule.ProcessResult.ERROR; } catch (IOException ex) { logger.log(Level.SEVERE, String.format("Unable to process file '%s'", file.getParentPath() + file.getName()), ex); return IngestModule.ProcessResult.ERROR; } return IngestModule.ProcessResult.OK; } /** * Validate ingest module settings. * * @throws IngestModule.IngestModuleException If the input is empty, * invalid, or out of range. */ private void validateSettings() throws IngestModule.IngestModuleException { EncryptionDetectionTools.validateMinEntropyValue(minimumEntropy); EncryptionDetectionTools.validateMinFileSizeValue(minimumFileSize); } /** * Create a blackboard artifact. * * @param file The file to be processed. * @param artifactType The type of artifact to create. * @param comment A comment to be attached to the artifact. * * @return 'OK' if the file was processed successfully, or 'ERROR' if there * was a problem. */ private IngestModule.ProcessResult flagFile(AbstractFile file, BlackboardArtifact.ARTIFACT_TYPE artifactType, String comment) { try { BlackboardArtifact artifact = file.newArtifact(artifactType); artifact.addAttribute(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_COMMENT, EncryptionDetectionModuleFactory.getModuleName(), comment)); try { /* * Index the artifact for keyword search. */ blackboard.indexArtifact(artifact); } catch (Blackboard.BlackboardException ex) { logger.log(Level.SEVERE, "Unable to index blackboard artifact " + artifact.getArtifactID(), ex); //NON-NLS } /* * Send an event to update the view with the new result. */ services.fireModuleDataEvent(new ModuleDataEvent(EncryptionDetectionModuleFactory.getModuleName(), artifactType, Collections.singletonList(artifact))); /* * Make an ingest inbox message. */ StringBuilder detailsSb = new StringBuilder(); detailsSb.append("File: ").append(file.getParentPath()).append(file.getName()); if (artifactType.equals(BlackboardArtifact.ARTIFACT_TYPE.TSK_ENCRYPTION_SUSPECTED)) { detailsSb.append("<br/>\nEntropy: ").append(calculatedEntropy); } services.postMessage(IngestMessage.createDataMessage(EncryptionDetectionModuleFactory.getModuleName(), artifactType.getDisplayName() + " Match: " + file.getName(), detailsSb.toString(), file.getName(), artifact)); return IngestModule.ProcessResult.OK; } catch (TskCoreException ex) { logger.log(Level.SEVERE, String.format("Failed to create blackboard artifact for '%s'.", file.getParentPath() + file.getName()), ex); //NON-NLS return IngestModule.ProcessResult.ERROR; } } /** * This method checks if the AbstractFile input is password protected. * * @param file AbstractFile to be checked. * * @return True if the file is password protected. * * @throws ReadContentInputStreamException If there is a failure reading * from the InputStream. * @throws IOException If there is a failure closing or * reading from the InputStream. * @throws SAXException If there was an issue parsing the * file with Tika. * @throws TikaException If there was an issue parsing the * file with Tika. * @throws UnsupportedCodecException If an Access database could not * be opened by Jackcess due to * unsupported encoding. */ private boolean isFilePasswordProtected(AbstractFile file) throws ReadContentInputStreamException, IOException, SAXException, TikaException, UnsupportedCodecException { boolean passwordProtected = false; switch (file.getMIMEType()) { case MIME_TYPE_OOXML_PROTECTED: /* * Office Open XML files that are password protected can be * determined so simply by checking the MIME type. */ passwordProtected = true; break; case MIME_TYPE_MSWORD: case MIME_TYPE_MSEXCEL: case MIME_TYPE_MSPOWERPOINT: case MIME_TYPE_PDF: { /* * A file of one of these types will be determined to be * password protected or not by attempting to parse it via Tika. */ InputStream in = null; BufferedInputStream bin = null; try { in = new ReadContentInputStream(file); bin = new BufferedInputStream(in); ContentHandler handler = new BodyContentHandler(-1); Metadata metadata = new Metadata(); metadata.add(Metadata.RESOURCE_NAME_KEY, file.getName()); AutoDetectParser parser = new AutoDetectParser(); parser.parse(bin, handler, metadata, new ParseContext()); } catch (EncryptedDocumentException ex) { /* * File is determined to be password protected. */ passwordProtected = true; } finally { if (in != null) { in.close(); } if (bin != null) { bin.close(); } } break; } case MIME_TYPE_MSACCESS: { /* * Access databases are determined to be password protected * using Jackcess. If the database can be opened, the password * is read from it to see if it's null. If the database can not * be opened due to an InvalidCredentialException being thrown, * it is automatically determined to be password protected. */ InputStream in = null; BufferedInputStream bin = null; try { in = new ReadContentInputStream(file); bin = new BufferedInputStream(in); MemFileChannel memFileChannel = MemFileChannel.newChannel(bin); CodecProvider codecProvider = new CryptCodecProvider(); DatabaseBuilder databaseBuilder = new DatabaseBuilder(); databaseBuilder.setChannel(memFileChannel); databaseBuilder.setCodecProvider(codecProvider); Database accessDatabase; try { accessDatabase = databaseBuilder.open(); } catch (IOException | BufferUnderflowException | IndexOutOfBoundsException ignored) { //Usually caused by an Unsupported newer version IOException error while attempting to open the jackcess databaseBuilder, we do not know if it is password //they are not being logged because we do not know that anything can be done to resolve them and they are numerous. return passwordProtected; } /* * No exception has been thrown at this point, so the file * is either a JET database, or an unprotected ACE database. * Read the password from the database to see if it exists. */ if (accessDatabase.getDatabasePassword() != null) { passwordProtected = true; } } catch (InvalidCredentialsException ex) { /* * The ACE database is determined to be password protected. */ passwordProtected = true; } finally { if (in != null) { in.close(); } if (bin != null) { bin.close(); } } } } return passwordProtected; } /** * This method checks if the AbstractFile input is encrypted. It must meet * file size requirements before its entropy is calculated. If the entropy * result meets the minimum entropy value set, the file will be considered * to be possibly encrypted. * * @param file AbstractFile to be checked. * * @return True if encryption is suspected. * * @throws ReadContentInputStreamException If there is a failure reading * from the InputStream. * @throws IOException If there is a failure closing or * reading from the InputStream. */ private boolean isFileEncryptionSuspected(AbstractFile file) throws ReadContentInputStreamException, IOException { /* * Criteria for the checks in this method are partially based on * http://www.forensicswiki.org/wiki/TrueCrypt#Detection */ boolean possiblyEncrypted = false; /* * Qualify the size. */ boolean fileSizeQualified = false; String fileExtension = file.getNameExtension(); long contentSize = file.getSize(); // Database files qualify at 64 KB minimum for SQLCipher detection. if (fileExtension.equalsIgnoreCase(DATABASE_FILE_EXTENSION)) { if (contentSize >= MINIMUM_DATABASE_FILE_SIZE) { fileSizeQualified = true; } } else if (contentSize >= minimumFileSize) { if (!fileSizeMultipleEnforced || (contentSize % FILE_SIZE_MODULUS) == 0) { fileSizeQualified = true; } } if (fileSizeQualified) { /* * Qualify the entropy. */ calculatedEntropy = EncryptionDetectionTools.calculateEntropy(file); if (calculatedEntropy >= minimumEntropy) { possiblyEncrypted = true; } } return possiblyEncrypted; } }
Core/src/org/sleuthkit/autopsy/modules/encryptiondetection/EncryptionDetectionFileIngestModule.java
/* * Autopsy Forensic Browser * * Copyright 2017-2018 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.modules.encryptiondetection; import com.healthmarketscience.jackcess.CryptCodecProvider; import com.healthmarketscience.jackcess.Database; import com.healthmarketscience.jackcess.DatabaseBuilder; import com.healthmarketscience.jackcess.InvalidCredentialsException; import com.healthmarketscience.jackcess.impl.CodecProvider; import com.healthmarketscience.jackcess.impl.UnsupportedCodecException; import com.healthmarketscience.jackcess.util.MemFileChannel; import java.io.IOException; import java.util.Collections; import java.util.logging.Level; import org.sleuthkit.datamodel.ReadContentInputStream; import java.io.BufferedInputStream; import java.io.InputStream; import org.apache.tika.exception.EncryptedDocumentException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.sax.BodyContentHandler; import org.openide.util.NbBundle.Messages; import org.sleuthkit.autopsy.casemodule.Case; import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException; import org.sleuthkit.autopsy.casemodule.services.Blackboard; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.ingest.FileIngestModuleAdapter; import org.sleuthkit.autopsy.ingest.IngestJobContext; import org.sleuthkit.autopsy.ingest.IngestMessage; import org.sleuthkit.autopsy.ingest.IngestModule; import org.sleuthkit.autopsy.ingest.IngestServices; import org.sleuthkit.autopsy.ingest.ModuleDataEvent; import org.sleuthkit.autopsy.modules.filetypeid.FileTypeDetector; import org.sleuthkit.datamodel.AbstractFile; import org.sleuthkit.datamodel.BlackboardArtifact; import org.sleuthkit.datamodel.BlackboardAttribute; import org.sleuthkit.datamodel.ReadContentInputStream.ReadContentInputStreamException; import org.sleuthkit.datamodel.TskCoreException; import org.sleuthkit.datamodel.TskData; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; /** * File ingest module to detect encryption and password protection. */ final class EncryptionDetectionFileIngestModule extends FileIngestModuleAdapter { private static final int FILE_SIZE_MODULUS = 512; private static final String DATABASE_FILE_EXTENSION = "db"; private static final int MINIMUM_DATABASE_FILE_SIZE = 65536; //64 KB private static final String MIME_TYPE_OOXML_PROTECTED = "application/x-ooxml-protected"; private static final String MIME_TYPE_MSWORD = "application/msword"; private static final String MIME_TYPE_MSEXCEL = "application/vnd.ms-excel"; private static final String MIME_TYPE_MSPOWERPOINT = "application/vnd.ms-powerpoint"; private static final String MIME_TYPE_MSACCESS = "application/x-msaccess"; private static final String MIME_TYPE_PDF = "application/pdf"; private static final String[] FILE_IGNORE_LIST = {"hiberfile.sys", "pagefile.sys"}; private final IngestServices services = IngestServices.getInstance(); private final Logger logger = services.getLogger(EncryptionDetectionModuleFactory.getModuleName()); private FileTypeDetector fileTypeDetector; private Blackboard blackboard; private double calculatedEntropy; private final double minimumEntropy; private final int minimumFileSize; private final boolean fileSizeMultipleEnforced; private final boolean slackFilesAllowed; /** * Create a EncryptionDetectionFileIngestModule object that will detect * files that are either encrypted or password protected and create * blackboard artifacts as appropriate. The supplied * EncryptionDetectionIngestJobSettings object is used to configure the * module. */ EncryptionDetectionFileIngestModule(EncryptionDetectionIngestJobSettings settings) { minimumEntropy = settings.getMinimumEntropy(); minimumFileSize = settings.getMinimumFileSize(); fileSizeMultipleEnforced = settings.isFileSizeMultipleEnforced(); slackFilesAllowed = settings.isSlackFilesAllowed(); } @Override public void startUp(IngestJobContext context) throws IngestModule.IngestModuleException { try { validateSettings(); blackboard = Case.getCurrentCaseThrows().getServices().getBlackboard(); fileTypeDetector = new FileTypeDetector(); } catch (FileTypeDetector.FileTypeDetectorInitException ex) { throw new IngestModule.IngestModuleException("Failed to create file type detector", ex); } catch (NoCurrentCaseException ex) { throw new IngestModule.IngestModuleException("Exception while getting open case.", ex); } } @Messages({ "EncryptionDetectionFileIngestModule.artifactComment.password=Password protection detected.", "EncryptionDetectionFileIngestModule.artifactComment.suspected=Suspected encryption due to high entropy (%f)." }) @Override public IngestModule.ProcessResult process(AbstractFile file) { try { /* * Qualify the file type, qualify it against hash databases, and * verify the file hasn't been deleted. */ if (!file.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.UNALLOC_BLOCKS) && !file.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.UNUSED_BLOCKS) && !file.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.VIRTUAL_DIR) && !file.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.LOCAL_DIR) && (!file.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.SLACK) || slackFilesAllowed) && !file.getKnown().equals(TskData.FileKnown.KNOWN) && !file.isMetaFlagSet(TskData.TSK_FS_META_FLAG_ENUM.UNALLOC)) { /* * Is the file in FILE_IGNORE_LIST? */ String filePath = file.getParentPath(); if (filePath.equals("/")) { String fileName = file.getName(); for (String listEntry : FILE_IGNORE_LIST) { if (fileName.equalsIgnoreCase(listEntry)) { // Skip this file. return IngestModule.ProcessResult.OK; } } } /* * Qualify the MIME type. */ String mimeType = fileTypeDetector.getMIMEType(file); if (mimeType.equals("application/octet-stream") && isFileEncryptionSuspected(file)) { return flagFile(file, BlackboardArtifact.ARTIFACT_TYPE.TSK_ENCRYPTION_SUSPECTED, String.format(Bundle.EncryptionDetectionFileIngestModule_artifactComment_suspected(), calculatedEntropy)); } else if (isFilePasswordProtected(file)) { return flagFile(file, BlackboardArtifact.ARTIFACT_TYPE.TSK_ENCRYPTION_DETECTED, Bundle.EncryptionDetectionFileIngestModule_artifactComment_password()); } } } catch (ReadContentInputStreamException | SAXException | TikaException | UnsupportedCodecException ex) { logger.log(Level.WARNING, String.format("Unable to read file '%s'", file.getParentPath() + file.getName()), ex); return IngestModule.ProcessResult.ERROR; } catch (IOException ex) { logger.log(Level.SEVERE, String.format("Unable to process file '%s'", file.getParentPath() + file.getName()), ex); return IngestModule.ProcessResult.ERROR; } return IngestModule.ProcessResult.OK; } /** * Validate ingest module settings. * * @throws IngestModule.IngestModuleException If the input is empty, * invalid, or out of range. */ private void validateSettings() throws IngestModule.IngestModuleException { EncryptionDetectionTools.validateMinEntropyValue(minimumEntropy); EncryptionDetectionTools.validateMinFileSizeValue(minimumFileSize); } /** * Create a blackboard artifact. * * @param file The file to be processed. * @param artifactType The type of artifact to create. * @param comment A comment to be attached to the artifact. * * @return 'OK' if the file was processed successfully, or 'ERROR' if there * was a problem. */ private IngestModule.ProcessResult flagFile(AbstractFile file, BlackboardArtifact.ARTIFACT_TYPE artifactType, String comment) { try { BlackboardArtifact artifact = file.newArtifact(artifactType); artifact.addAttribute(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_COMMENT, EncryptionDetectionModuleFactory.getModuleName(), comment)); try { /* * Index the artifact for keyword search. */ blackboard.indexArtifact(artifact); } catch (Blackboard.BlackboardException ex) { logger.log(Level.SEVERE, "Unable to index blackboard artifact " + artifact.getArtifactID(), ex); //NON-NLS } /* * Send an event to update the view with the new result. */ services.fireModuleDataEvent(new ModuleDataEvent(EncryptionDetectionModuleFactory.getModuleName(), artifactType, Collections.singletonList(artifact))); /* * Make an ingest inbox message. */ StringBuilder detailsSb = new StringBuilder(); detailsSb.append("File: ").append(file.getParentPath()).append(file.getName()); if (artifactType.equals(BlackboardArtifact.ARTIFACT_TYPE.TSK_ENCRYPTION_SUSPECTED)) { detailsSb.append("<br/>\nEntropy: ").append(calculatedEntropy); } services.postMessage(IngestMessage.createDataMessage(EncryptionDetectionModuleFactory.getModuleName(), artifactType.getDisplayName() + " Match: " + file.getName(), detailsSb.toString(), file.getName(), artifact)); return IngestModule.ProcessResult.OK; } catch (TskCoreException ex) { logger.log(Level.SEVERE, String.format("Failed to create blackboard artifact for '%s'.", file.getParentPath() + file.getName()), ex); //NON-NLS return IngestModule.ProcessResult.ERROR; } } /** * This method checks if the AbstractFile input is password protected. * * @param file AbstractFile to be checked. * * @return True if the file is password protected. * * @throws ReadContentInputStreamException If there is a failure reading * from the InputStream. * @throws IOException If there is a failure closing or * reading from the InputStream. * @throws SAXException If there was an issue parsing the * file with Tika. * @throws TikaException If there was an issue parsing the * file with Tika. * @throws UnsupportedCodecException If an Access database could not * be opened by Jackcess due to * unsupported encoding. */ private boolean isFilePasswordProtected(AbstractFile file) throws ReadContentInputStreamException, IOException, SAXException, TikaException, UnsupportedCodecException { boolean passwordProtected = false; switch (file.getMIMEType()) { case MIME_TYPE_OOXML_PROTECTED: /* * Office Open XML files that are password protected can be * determined so simply by checking the MIME type. */ passwordProtected = true; break; case MIME_TYPE_MSWORD: case MIME_TYPE_MSEXCEL: case MIME_TYPE_MSPOWERPOINT: case MIME_TYPE_PDF: { /* * A file of one of these types will be determined to be * password protected or not by attempting to parse it via Tika. */ InputStream in = null; BufferedInputStream bin = null; try { in = new ReadContentInputStream(file); bin = new BufferedInputStream(in); ContentHandler handler = new BodyContentHandler(-1); Metadata metadata = new Metadata(); metadata.add(Metadata.RESOURCE_NAME_KEY, file.getName()); AutoDetectParser parser = new AutoDetectParser(); parser.parse(bin, handler, metadata, new ParseContext()); } catch (EncryptedDocumentException ex) { /* * File is determined to be password protected. */ passwordProtected = true; } finally { if (in != null) { in.close(); } if (bin != null) { bin.close(); } } break; } case MIME_TYPE_MSACCESS: { /* * Access databases are determined to be password protected * using Jackcess. If the database can be opened, the password * is read from it to see if it's null. If the database can not * be opened due to an InvalidCredentialException being thrown, * it is automatically determined to be password protected. */ InputStream in = null; BufferedInputStream bin = null; try { in = new ReadContentInputStream(file); bin = new BufferedInputStream(in); MemFileChannel memFileChannel = MemFileChannel.newChannel(bin); CodecProvider codecProvider = new CryptCodecProvider(); DatabaseBuilder databaseBuilder = new DatabaseBuilder(); databaseBuilder.setChannel(memFileChannel); databaseBuilder.setCodecProvider(codecProvider); Database accessDatabase = databaseBuilder.open(); /* * No exception has been thrown at this point, so the file * is either a JET database, or an unprotected ACE database. * Read the password from the database to see if it exists. */ if (accessDatabase.getDatabasePassword() != null) { passwordProtected = true; } } catch (InvalidCredentialsException ex) { /* * The ACE database is determined to be password protected. */ passwordProtected = true; } finally { if (in != null) { in.close(); } if (bin != null) { bin.close(); } } } } return passwordProtected; } /** * This method checks if the AbstractFile input is encrypted. It must meet * file size requirements before its entropy is calculated. If the entropy * result meets the minimum entropy value set, the file will be considered * to be possibly encrypted. * * @param file AbstractFile to be checked. * * @return True if encryption is suspected. * * @throws ReadContentInputStreamException If there is a failure reading * from the InputStream. * @throws IOException If there is a failure closing or * reading from the InputStream. */ private boolean isFileEncryptionSuspected(AbstractFile file) throws ReadContentInputStreamException, IOException { /* * Criteria for the checks in this method are partially based on * http://www.forensicswiki.org/wiki/TrueCrypt#Detection */ boolean possiblyEncrypted = false; /* * Qualify the size. */ boolean fileSizeQualified = false; String fileExtension = file.getNameExtension(); long contentSize = file.getSize(); // Database files qualify at 64 KB minimum for SQLCipher detection. if (fileExtension.equalsIgnoreCase(DATABASE_FILE_EXTENSION)) { if (contentSize >= MINIMUM_DATABASE_FILE_SIZE) { fileSizeQualified = true; } } else if (contentSize >= minimumFileSize) { if (!fileSizeMultipleEnforced || (contentSize % FILE_SIZE_MODULUS) == 0) { fileSizeQualified = true; } } if (fileSizeQualified) { /* * Qualify the entropy. */ calculatedEntropy = EncryptionDetectionTools.calculateEntropy(file); if (calculatedEntropy >= minimumEntropy) { possiblyEncrypted = true; } } return possiblyEncrypted; } }
4297 silence io, bufferunderflow, and indexoutofbounds exceptions from jackcess DatabaseBuilder.open
Core/src/org/sleuthkit/autopsy/modules/encryptiondetection/EncryptionDetectionFileIngestModule.java
4297 silence io, bufferunderflow, and indexoutofbounds exceptions from jackcess DatabaseBuilder.open
<ide><path>ore/src/org/sleuthkit/autopsy/modules/encryptiondetection/EncryptionDetectionFileIngestModule.java <ide> import org.sleuthkit.datamodel.ReadContentInputStream; <ide> import java.io.BufferedInputStream; <ide> import java.io.InputStream; <add>import java.nio.BufferUnderflowException; <ide> import org.apache.tika.exception.EncryptedDocumentException; <ide> import org.apache.tika.exception.TikaException; <ide> import org.apache.tika.metadata.Metadata; <ide> DatabaseBuilder databaseBuilder = new DatabaseBuilder(); <ide> databaseBuilder.setChannel(memFileChannel); <ide> databaseBuilder.setCodecProvider(codecProvider); <del> Database accessDatabase = databaseBuilder.open(); <add> Database accessDatabase; <add> try { <add> accessDatabase = databaseBuilder.open(); <add> } catch (IOException | BufferUnderflowException | IndexOutOfBoundsException ignored) { <add> //Usually caused by an Unsupported newer version IOException error while attempting to open the jackcess databaseBuilder, we do not know if it is password <add> //they are not being logged because we do not know that anything can be done to resolve them and they are numerous. <add> return passwordProtected; <add> } <ide> /* <ide> * No exception has been thrown at this point, so the file <ide> * is either a JET database, or an unprotected ACE database.
Java
apache-2.0
efaf68409bf98efcd4c880d6cd55be7632b65362
0
apache/isis,apache/isis,apache/isis,apache/isis,apache/isis,apache/isis
/* * 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.isis.viewer.restfulobjects.rendering.domainobjects; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import java.util.function.Function; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import org.apache.isis.commons.internal.collections._Lists; import org.apache.isis.core.metamodel.spec.ManagedObject; import org.apache.isis.viewer.restfulobjects.applib.JsonRepresentation; import org.apache.isis.viewer.restfulobjects.rendering.domainobjects.JsonValueEncoder.JsonValueConverter; import lombok.val; /** * Similar to Isis' value encoding, but with additional support for JSON * primitives. */ public final class JsonValueEncoder_Converters { public List<JsonValueConverter> asList(final Function<Object, ManagedObject> pojoToAdapter) { val converters = _Lists.<JsonValueConverter>newArrayList(); converters.add(new JsonValueConverter(null, "string", String.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { return pojoToAdapter.apply(repr.asString()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { val obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof String) { repr.mapPutString("value", (String) obj); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter(null, "boolean", boolean.class, Boolean.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isBoolean()) { return pojoToAdapter.apply(repr.asBoolean()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { val obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Boolean) { repr.mapPutBooleanNullable("value", (Boolean) obj); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("int", "byte", byte.class, Byte.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isNumber()) { return pojoToAdapter.apply(repr.asNumber().byteValue()); } if (repr.isInt()) { return pojoToAdapter.apply((byte)(int)repr.asInt()); } if (repr.isLong()) { return pojoToAdapter.apply((byte)(long)repr.asLong()); } if (repr.isBigInteger()) { return pojoToAdapter.apply(repr.asBigInteger().byteValue()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { val obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Byte) { repr.mapPutByteNullable("value", (Byte) obj); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("int", "short", short.class, Short.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isNumber()) { return pojoToAdapter.apply(repr.asNumber().shortValue()); } if (repr.isInt()) { return pojoToAdapter.apply((short)(int)repr.asInt()); } if (repr.isLong()) { return pojoToAdapter.apply((short)(long)repr.asLong()); } if (repr.isBigInteger()) { return pojoToAdapter.apply(repr.asBigInteger().shortValue()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Short) { repr.mapPutShortNullable("value", (Short) obj); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("int", "int", int.class, Integer.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isInt()) { return pojoToAdapter.apply(repr.asInt()); } if (repr.isLong()) { return pojoToAdapter.apply(repr.asLong().intValue()); } if (repr.isBigInteger()) { return pojoToAdapter.apply(repr.asBigInteger().intValue()); } if (repr.isNumber()) { return pojoToAdapter.apply(repr.asNumber().intValue()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Integer) { repr.mapPutIntNullable("value", (Integer) obj); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("int", "long", long.class, Long.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isLong()) { return pojoToAdapter.apply(repr.asLong()); } if (repr.isInt()) { return pojoToAdapter.apply(repr.asLong()); } if (repr.isBigInteger()) { return pojoToAdapter.apply(repr.asBigInteger().longValue()); } if (repr.isNumber()) { return pojoToAdapter.apply(repr.asNumber().longValue()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Long) { final Long l = (Long) obj; repr.mapPutLongNullable("value", l); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("decimal", "float", float.class, Float.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isDecimal()) { return pojoToAdapter.apply(repr.asDouble().floatValue()); } if (repr.isNumber()) { return pojoToAdapter.apply(repr.asNumber().floatValue()); } if (repr.isLong()) { return pojoToAdapter.apply(repr.asLong().floatValue()); } if (repr.isInt()) { return pojoToAdapter.apply(repr.asInt().floatValue()); } if (repr.isBigInteger()) { return pojoToAdapter.apply(repr.asBigInteger().floatValue()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Float) { final Float f = (Float) obj; repr.mapPutFloatNullable("value", f); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("decimal", "double", double.class, Double.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isDecimal()) { return pojoToAdapter.apply(repr.asDouble()); } if (repr.isLong()) { return pojoToAdapter.apply(repr.asLong().doubleValue()); } if (repr.isInt()) { return pojoToAdapter.apply(repr.asInt().doubleValue()); } if (repr.isBigInteger()) { return pojoToAdapter.apply(repr.asBigInteger().doubleValue()); } if (repr.isBigDecimal()) { return pojoToAdapter.apply(repr.asBigDecimal().doubleValue()); } if (repr.isNumber()) { return pojoToAdapter.apply(repr.asNumber().doubleValue()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Double) { final Double d = (Double) obj; repr.mapPutDoubleNullable("value", d); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter(null, "char", char.class, Character.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { final String str = repr.asString(); if(str != null && str.length()>0) { return pojoToAdapter.apply(str.charAt(0)); } } // in case a char literal was provided if(repr.isInt()) { final Integer x = repr.asInt(); if(Character.MIN_VALUE <= x && x <= Character.MAX_VALUE) { char c = (char) x.intValue(); return pojoToAdapter.apply(c); } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Character) { final Character c = (Character) obj; repr.mapPutCharNullable("value", c); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("big-integer(18)", "javamathbiginteger", BigInteger.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { return pojoToAdapter.apply(new BigInteger(repr.asString())); } if (repr.isBigInteger()) { return pojoToAdapter.apply(repr.asBigInteger(format)); } if (repr.isLong()) { return pojoToAdapter.apply(BigInteger.valueOf(repr.asLong())); } if (repr.isInt()) { return pojoToAdapter.apply(BigInteger.valueOf(repr.asInt())); } if (repr.isNumber()) { return pojoToAdapter.apply(BigInteger.valueOf(repr.asNumber().longValue())); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof BigInteger) { final BigInteger bi = (BigInteger) obj; repr.mapPutBigInteger("value", bi); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("big-decimal", "javamathbigdecimal", BigDecimal.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { return pojoToAdapter.apply(new BigDecimal(repr.asString())); } if (repr.isBigDecimal()) { return pojoToAdapter.apply(repr.asBigDecimal(format)); } if (repr.isBigInteger()) { return pojoToAdapter.apply(new BigDecimal(repr.asBigInteger())); } if (repr.isDecimal()) { return pojoToAdapter.apply(BigDecimal.valueOf(repr.asDouble())); } if (repr.isLong()) { return pojoToAdapter.apply(BigDecimal.valueOf(repr.asLong())); } if (repr.isInt()) { return pojoToAdapter.apply(BigDecimal.valueOf(repr.asInt())); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof BigDecimal) { final BigDecimal bd = (BigDecimal) obj; repr.mapPutBigDecimal("value", bd); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("date", "jodalocaldate", LocalDate.class){ // these formatters do NOT use withZoneUTC() final List<DateTimeFormatter> formatters = Arrays.asList( ISODateTimeFormat.date(), ISODateTimeFormat.basicDate(), DateTimeFormat.forPattern("yyyyMMdd"), JsonRepresentation.yyyyMMdd ); @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { final String dateStr = repr.asString(); for (DateTimeFormatter formatter : formatters) { try { final LocalDate parsedDate = formatter.parseLocalDate(dateStr); return pojoToAdapter.apply(parsedDate); } catch (IllegalArgumentException ex) { // fall through } } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof LocalDate) { final LocalDate date = (LocalDate) obj; final String dateStr = formatters.get(0).print(date.toDateTimeAtStartOfDay()); repr.mapPutString("value", dateStr); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("date-time", "jodalocaldatetime", LocalDateTime.class){ final List<DateTimeFormatter> formatters = Arrays.asList( ISODateTimeFormat.dateTimeNoMillis().withZoneUTC(), ISODateTimeFormat.dateTime().withZoneUTC(), ISODateTimeFormat.basicDateTimeNoMillis().withZoneUTC(), ISODateTimeFormat.basicDateTime().withZoneUTC(), JsonRepresentation.yyyyMMddTHHmmssZ.withZoneUTC() ); @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { final String dateStr = repr.asString(); for (DateTimeFormatter formatter : formatters) { try { final LocalDateTime parsedDate = formatter.parseLocalDateTime(dateStr); return pojoToAdapter.apply(parsedDate); } catch (IllegalArgumentException ex) { // fall through } } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof LocalDateTime) { final LocalDateTime date = (LocalDateTime) obj; final String dateStr = formatters.get(0).print(date.toDateTime()); repr.mapPutString("value", dateStr); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("date-time", "jodadatetime", DateTime.class){ final List<DateTimeFormatter> formatters = Arrays.asList( ISODateTimeFormat.dateTimeNoMillis().withZoneUTC(), ISODateTimeFormat.dateTime().withZoneUTC(), ISODateTimeFormat.basicDateTimeNoMillis().withZoneUTC(), ISODateTimeFormat.basicDateTime().withZoneUTC(), JsonRepresentation.yyyyMMddTHHmmssZ.withZoneUTC() ); @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { final String dateStr = repr.asString(); for (DateTimeFormatter formatter : formatters) { try { final DateTime parsedDate = formatter.parseDateTime(dateStr); return pojoToAdapter.apply(parsedDate); } catch (IllegalArgumentException ex) { // fall through } } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof DateTime) { final DateTime date = (DateTime) obj; final String dateStr = formatters.get(0).print(date.toDateTime()); repr.mapPutString("value", dateStr); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("date-time", "javautildate", java.util.Date.class){ final List<DateTimeFormatter> formatters = Arrays.asList( ISODateTimeFormat.dateTimeNoMillis().withZoneUTC(), ISODateTimeFormat.dateTime().withZoneUTC(), ISODateTimeFormat.basicDateTimeNoMillis().withZoneUTC(), ISODateTimeFormat.basicDateTime().withZoneUTC(), JsonRepresentation.yyyyMMddTHHmmssZ.withZoneUTC() ); @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { final String dateStr = repr.asString(); for (DateTimeFormatter formatter : formatters) { try { final DateTime parseDateTime = formatter.parseDateTime(dateStr); final java.util.Date parsedDate = parseDateTime.toDate(); return pojoToAdapter.apply(parsedDate); } catch (IllegalArgumentException ex) { // fall through } } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof java.util.Date) { final java.util.Date date = (java.util.Date) obj; final DateTimeFormatter dateTimeFormatter = formatters.get(0); final String dateStr = dateTimeFormatter.print(new DateTime(date)); repr.mapPutString("value", dateStr); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("date", "javasqldate", java.sql.Date.class){ final List<DateTimeFormatter> formatters = Arrays.asList( ISODateTimeFormat.date().withZoneUTC(), ISODateTimeFormat.basicDate().withZoneUTC(), JsonRepresentation.yyyyMMdd.withZoneUTC() ); @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { final String dateStr = repr.asString(); for (DateTimeFormatter formatter : formatters) { try { final DateTime parseDateTime = formatter.parseDateTime(dateStr); final java.sql.Date parsedDate = new java.sql.Date(parseDateTime.getMillis()); return pojoToAdapter.apply(parsedDate); } catch (IllegalArgumentException ex) { // fall through } } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof java.sql.Date) { final java.sql.Date date = (java.sql.Date) obj; final String dateStr = formatters.get(0).print(new DateTime(date)); repr.mapPutString("value", dateStr); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("time", "javasqltime", java.sql.Time.class){ final List<DateTimeFormatter> formatters = Arrays.asList( ISODateTimeFormat.hourMinuteSecond().withZoneUTC(), ISODateTimeFormat.basicTimeNoMillis().withZoneUTC(), ISODateTimeFormat.basicTime().withZoneUTC(), JsonRepresentation._HHmmss.withZoneUTC() ); @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { final String dateStr = repr.asString(); for (DateTimeFormatter formatter : formatters) { try { final DateTime parseDateTime = formatter.parseDateTime(dateStr); final java.sql.Time parsedTime = new java.sql.Time(parseDateTime.getMillis()); return pojoToAdapter.apply(parsedTime); } catch (IllegalArgumentException ex) { // fall through } } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof java.sql.Time) { final java.sql.Time date = (java.sql.Time) obj; final String dateStr = formatters.get(0).print(new DateTime(date)); repr.mapPutString("value", dateStr); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("utc-millisec", "javasqltimestamp", java.sql.Timestamp.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isLong()) { final Long millis = repr.asLong(); final java.sql.Timestamp parsedTimestamp = new java.sql.Timestamp(millis); return pojoToAdapter.apply(parsedTimestamp); } if (repr.isString()) { final String dateStr = repr.asString(); try { final Long parseMillis = Long.parseLong(dateStr); final java.sql.Timestamp parsedTimestamp = new java.sql.Timestamp(parseMillis); return pojoToAdapter.apply(parsedTimestamp); } catch (IllegalArgumentException ex) { // fall through } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof java.sql.Timestamp) { final java.sql.Timestamp date = (java.sql.Timestamp) obj; final long millisStr = date.getTime(); repr.mapPutLong("value", millisStr); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); return converters; } static void appendFormats(final JsonRepresentation repr, final String format, final String xIsisFormat, final boolean suppressExtensions) { JsonValueEncoder.appendFormats(repr, format, xIsisFormat, suppressExtensions); } static Object unwrapAsObjectElseNullNode(final ManagedObject adapter) { return JsonValueEncoder.unwrapAsObjectElseNullNode(adapter); } }
viewers/restfulobjects/rendering/src/main/java/org/apache/isis/viewer/restfulobjects/rendering/domainobjects/JsonValueEncoder_Converters.java
/* * 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.isis.viewer.restfulobjects.rendering.domainobjects; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import java.util.function.Function; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import org.apache.isis.commons.internal.collections._Lists; import org.apache.isis.core.metamodel.spec.ManagedObject; import org.apache.isis.viewer.restfulobjects.applib.JsonRepresentation; import org.apache.isis.viewer.restfulobjects.rendering.domainobjects.JsonValueEncoder.JsonValueConverter; import lombok.val; /** * Similar to Isis' value encoding, but with additional support for JSON * primitives. */ public final class JsonValueEncoder_Converters { public List<JsonValueConverter> asList(final Function<Object, ManagedObject> pojoToAdapter) { val converters = _Lists.<JsonValueConverter>newArrayList(); converters.add(new JsonValueConverter(null, "string", String.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { return pojoToAdapter.apply(repr.asString()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { val obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof String) { repr.mapPutString("value", (String) obj); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter(null, "boolean", boolean.class, Boolean.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isBoolean()) { return pojoToAdapter.apply(repr.asBoolean()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { val obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Boolean) { repr.mapPutBooleanNullable("value", (Boolean) obj); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("int", "byte", byte.class, Byte.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isNumber()) { return pojoToAdapter.apply(repr.asNumber().byteValue()); } if (repr.isInt()) { return pojoToAdapter.apply((byte)(int)repr.asInt()); } if (repr.isLong()) { return pojoToAdapter.apply((byte)(long)repr.asLong()); } if (repr.isBigInteger()) { return pojoToAdapter.apply(repr.asBigInteger().byteValue()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { val obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Byte) { repr.mapPutByteNullable("value", (Byte) obj); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("int", "short", short.class, Short.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isNumber()) { return pojoToAdapter.apply(repr.asNumber().shortValue()); } if (repr.isInt()) { return pojoToAdapter.apply((short)(int)repr.asInt()); } if (repr.isLong()) { return pojoToAdapter.apply((short)(long)repr.asLong()); } if (repr.isBigInteger()) { return pojoToAdapter.apply(repr.asBigInteger().shortValue()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Short) { repr.mapPutShortNullable("value", (Short) obj); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("int", "int", int.class, Integer.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isInt()) { return pojoToAdapter.apply(repr.asInt()); } if (repr.isLong()) { return pojoToAdapter.apply(repr.asLong().intValue()); } if (repr.isBigInteger()) { return pojoToAdapter.apply(repr.asBigInteger().intValue()); } if (repr.isNumber()) { return pojoToAdapter.apply(repr.asNumber().intValue()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Integer) { repr.mapPutIntNullable("value", (Integer) obj); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("int", "long", long.class, Long.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isLong()) { return pojoToAdapter.apply(repr.asLong()); } if (repr.isInt()) { return pojoToAdapter.apply(repr.asLong()); } if (repr.isBigInteger()) { return pojoToAdapter.apply(repr.asBigInteger().longValue()); } if (repr.isNumber()) { return pojoToAdapter.apply(repr.asNumber().longValue()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Long) { final Long l = (Long) obj; repr.mapPutLongNullable("value", l); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("decimal", "float", float.class, Float.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isDecimal()) { return pojoToAdapter.apply(repr.asDouble().floatValue()); } if (repr.isNumber()) { return pojoToAdapter.apply(repr.asNumber().floatValue()); } if (repr.isLong()) { return pojoToAdapter.apply(repr.asLong().floatValue()); } if (repr.isInt()) { return pojoToAdapter.apply(repr.asInt().floatValue()); } if (repr.isBigInteger()) { return pojoToAdapter.apply(repr.asBigInteger().floatValue()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Float) { final Float f = (Float) obj; repr.mapPutFloatNullable("value", f); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("decimal", "double", double.class, Double.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isDecimal()) { return pojoToAdapter.apply(repr.asDouble()); } if (repr.isLong()) { return pojoToAdapter.apply(repr.asLong().doubleValue()); } if (repr.isInt()) { return pojoToAdapter.apply(repr.asInt().doubleValue()); } if (repr.isBigInteger()) { return pojoToAdapter.apply(repr.asBigInteger().doubleValue()); } if (repr.isBigDecimal()) { return pojoToAdapter.apply(repr.asBigDecimal().doubleValue()); } if (repr.isNumber()) { return pojoToAdapter.apply(repr.asNumber().doubleValue()); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Double) { final Double d = (Double) obj; repr.mapPutDoubleNullable("value", d); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter(null, "char", char.class, Character.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { final String str = repr.asString(); if(str != null && str.length()>0) { return pojoToAdapter.apply(str.charAt(0)); } } // in case a char literal was provided if(repr.isInt()) { final Integer x = repr.asInt(); if(Character.MIN_VALUE <= x && x <= Character.MAX_VALUE) { char c = (char) x.intValue(); return pojoToAdapter.apply(c); } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof Character) { final Character c = (Character) obj; repr.mapPutCharNullable("value", c); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("big-integer(18)", "javamathbiginteger", BigInteger.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { return pojoToAdapter.apply(new BigInteger(repr.asString())); } if (repr.isBigInteger()) { return pojoToAdapter.apply(repr.asBigInteger(format)); } if (repr.isLong()) { return pojoToAdapter.apply(BigInteger.valueOf(repr.asLong())); } if (repr.isInt()) { return pojoToAdapter.apply(BigInteger.valueOf(repr.asInt())); } if (repr.isNumber()) { return pojoToAdapter.apply(BigInteger.valueOf(repr.asNumber().longValue())); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof BigInteger) { final BigInteger bi = (BigInteger) obj; repr.mapPutBigInteger("value", bi); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("big-decimal", "javamathbigdecimal", BigDecimal.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { return pojoToAdapter.apply(new BigDecimal(repr.asString())); } if (repr.isBigDecimal()) { return pojoToAdapter.apply(repr.asBigDecimal(format)); } if (repr.isBigInteger()) { return pojoToAdapter.apply(new BigDecimal(repr.asBigInteger())); } if (repr.isDecimal()) { return pojoToAdapter.apply(BigDecimal.valueOf(repr.asDouble())); } if (repr.isLong()) { return pojoToAdapter.apply(BigDecimal.valueOf(repr.asLong())); } if (repr.isInt()) { return pojoToAdapter.apply(BigDecimal.valueOf(repr.asInt())); } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof BigDecimal) { repr.mapPut("value", (BigDecimal) obj); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("date", "jodalocaldate", LocalDate.class){ // these formatters do NOT use withZoneUTC() final List<DateTimeFormatter> formatters = Arrays.asList( ISODateTimeFormat.date(), ISODateTimeFormat.basicDate(), DateTimeFormat.forPattern("yyyyMMdd"), JsonRepresentation.yyyyMMdd ); @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { final String dateStr = repr.asString(); for (DateTimeFormatter formatter : formatters) { try { final LocalDate parsedDate = formatter.parseLocalDate(dateStr); return pojoToAdapter.apply(parsedDate); } catch (IllegalArgumentException ex) { // fall through } } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof LocalDate) { final LocalDate date = (LocalDate) obj; final String dateStr = formatters.get(0).print(date.toDateTimeAtStartOfDay()); repr.mapPutString("value", dateStr); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("date-time", "jodalocaldatetime", LocalDateTime.class){ final List<DateTimeFormatter> formatters = Arrays.asList( ISODateTimeFormat.dateTimeNoMillis().withZoneUTC(), ISODateTimeFormat.dateTime().withZoneUTC(), ISODateTimeFormat.basicDateTimeNoMillis().withZoneUTC(), ISODateTimeFormat.basicDateTime().withZoneUTC(), JsonRepresentation.yyyyMMddTHHmmssZ.withZoneUTC() ); @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { final String dateStr = repr.asString(); for (DateTimeFormatter formatter : formatters) { try { final LocalDateTime parsedDate = formatter.parseLocalDateTime(dateStr); return pojoToAdapter.apply(parsedDate); } catch (IllegalArgumentException ex) { // fall through } } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof LocalDateTime) { final LocalDateTime date = (LocalDateTime) obj; final String dateStr = formatters.get(0).print(date.toDateTime()); repr.mapPutString("value", dateStr); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("date-time", "jodadatetime", DateTime.class){ final List<DateTimeFormatter> formatters = Arrays.asList( ISODateTimeFormat.dateTimeNoMillis().withZoneUTC(), ISODateTimeFormat.dateTime().withZoneUTC(), ISODateTimeFormat.basicDateTimeNoMillis().withZoneUTC(), ISODateTimeFormat.basicDateTime().withZoneUTC(), JsonRepresentation.yyyyMMddTHHmmssZ.withZoneUTC() ); @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { final String dateStr = repr.asString(); for (DateTimeFormatter formatter : formatters) { try { final DateTime parsedDate = formatter.parseDateTime(dateStr); return pojoToAdapter.apply(parsedDate); } catch (IllegalArgumentException ex) { // fall through } } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof DateTime) { final DateTime date = (DateTime) obj; final String dateStr = formatters.get(0).print(date.toDateTime()); repr.mapPutString("value", dateStr); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("date-time", "javautildate", java.util.Date.class){ final List<DateTimeFormatter> formatters = Arrays.asList( ISODateTimeFormat.dateTimeNoMillis().withZoneUTC(), ISODateTimeFormat.dateTime().withZoneUTC(), ISODateTimeFormat.basicDateTimeNoMillis().withZoneUTC(), ISODateTimeFormat.basicDateTime().withZoneUTC(), JsonRepresentation.yyyyMMddTHHmmssZ.withZoneUTC() ); @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { final String dateStr = repr.asString(); for (DateTimeFormatter formatter : formatters) { try { final DateTime parseDateTime = formatter.parseDateTime(dateStr); final java.util.Date parsedDate = parseDateTime.toDate(); return pojoToAdapter.apply(parsedDate); } catch (IllegalArgumentException ex) { // fall through } } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof java.util.Date) { final java.util.Date date = (java.util.Date) obj; final DateTimeFormatter dateTimeFormatter = formatters.get(0); final String dateStr = dateTimeFormatter.print(new DateTime(date)); repr.mapPutString("value", dateStr); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("date", "javasqldate", java.sql.Date.class){ final List<DateTimeFormatter> formatters = Arrays.asList( ISODateTimeFormat.date().withZoneUTC(), ISODateTimeFormat.basicDate().withZoneUTC(), JsonRepresentation.yyyyMMdd.withZoneUTC() ); @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { final String dateStr = repr.asString(); for (DateTimeFormatter formatter : formatters) { try { final DateTime parseDateTime = formatter.parseDateTime(dateStr); final java.sql.Date parsedDate = new java.sql.Date(parseDateTime.getMillis()); return pojoToAdapter.apply(parsedDate); } catch (IllegalArgumentException ex) { // fall through } } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof java.sql.Date) { final java.sql.Date date = (java.sql.Date) obj; final String dateStr = formatters.get(0).print(new DateTime(date)); repr.mapPutString("value", dateStr); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("time", "javasqltime", java.sql.Time.class){ final List<DateTimeFormatter> formatters = Arrays.asList( ISODateTimeFormat.hourMinuteSecond().withZoneUTC(), ISODateTimeFormat.basicTimeNoMillis().withZoneUTC(), ISODateTimeFormat.basicTime().withZoneUTC(), JsonRepresentation._HHmmss.withZoneUTC() ); @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isString()) { final String dateStr = repr.asString(); for (DateTimeFormatter formatter : formatters) { try { final DateTime parseDateTime = formatter.parseDateTime(dateStr); final java.sql.Time parsedTime = new java.sql.Time(parseDateTime.getMillis()); return pojoToAdapter.apply(parsedTime); } catch (IllegalArgumentException ex) { // fall through } } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof java.sql.Time) { final java.sql.Time date = (java.sql.Time) obj; final String dateStr = formatters.get(0).print(new DateTime(date)); repr.mapPutString("value", dateStr); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); converters.add(new JsonValueConverter("utc-millisec", "javasqltimestamp", java.sql.Timestamp.class){ @Override public ManagedObject asAdapter(final JsonRepresentation repr, final String format) { if (repr.isLong()) { final Long millis = repr.asLong(); final java.sql.Timestamp parsedTimestamp = new java.sql.Timestamp(millis); return pojoToAdapter.apply(parsedTimestamp); } if (repr.isString()) { final String dateStr = repr.asString(); try { final Long parseMillis = Long.parseLong(dateStr); final java.sql.Timestamp parsedTimestamp = new java.sql.Timestamp(parseMillis); return pojoToAdapter.apply(parsedTimestamp); } catch (IllegalArgumentException ex) { // fall through } } return null; } @Override public Object appendValueAndFormat(final ManagedObject objectAdapter, final String formatOverride, final JsonRepresentation repr, final boolean suppressExtensions) { final Object obj = unwrapAsObjectElseNullNode(objectAdapter); if(obj instanceof java.sql.Timestamp) { final java.sql.Timestamp date = (java.sql.Timestamp) obj; final long millisStr = date.getTime(); repr.mapPutLong("value", millisStr); } else { repr.mapPut("value", obj); } appendFormats(repr, effectiveFormat(formatOverride), xIsisFormat, suppressExtensions); return obj; } }); return converters; } static void appendFormats(final JsonRepresentation repr, final String format, final String xIsisFormat, final boolean suppressExtensions) { JsonValueEncoder.appendFormats(repr, format, xIsisFormat, suppressExtensions); } static Object unwrapAsObjectElseNullNode(final ManagedObject adapter) { return JsonValueEncoder.unwrapAsObjectElseNullNode(adapter); } }
ISIS-3127: fixes prev. commit
viewers/restfulobjects/rendering/src/main/java/org/apache/isis/viewer/restfulobjects/rendering/domainobjects/JsonValueEncoder_Converters.java
ISIS-3127: fixes prev. commit
<ide><path>iewers/restfulobjects/rendering/src/main/java/org/apache/isis/viewer/restfulobjects/rendering/domainobjects/JsonValueEncoder_Converters.java <ide> final JsonRepresentation repr, final boolean suppressExtensions) { <ide> final Object obj = unwrapAsObjectElseNullNode(objectAdapter); <ide> if(obj instanceof BigDecimal) { <del> repr.mapPut("value", (BigDecimal) obj); <add> final BigDecimal bd = (BigDecimal) obj; <add> repr.mapPutBigDecimal("value", bd); <ide> } else { <ide> repr.mapPut("value", obj); <ide> }
Java
apache-2.0
error: pathspec 'src/main/java/net/hamnaberg/json/extension/Errors.java' did not match any file(s) known to git
26c4e9684f17ba90ad2d7fda10c82c22632c21e2
1
rayrc/json-collection,collection-json/collection-json.java,hamnis/json-collection
package net.hamnaberg.json.extension; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import net.hamnaberg.funclite.Function; import net.hamnaberg.funclite.FunctionalMap; import net.hamnaberg.funclite.Optional; import net.hamnaberg.json.InternalObjectFactory; import net.hamnaberg.json.Error; public class Errors { private final Map<String, List<Error>> errors = new LinkedHashMap<String, List<Error>>(); public Errors(Map<String, List<Error>> errors) { this.errors.putAll(errors); } public List<Error> getErrors(String name) { List<Error> v = errors.get(name); if (v != null) { return Collections.unmodifiableList(v); } return Collections.emptyList(); } private JsonNode asJson() { ObjectNode n = JsonNodeFactory.instance.objectNode(); n.putAll(FunctionalMap.create(errors).mapValues(new Function<List<Error>, JsonNode>() { @Override public JsonNode apply(List<Error> errors) { ArrayNode n = JsonNodeFactory.instance.arrayNode(); for (Error error : errors) { n.add(error.asJson()); } return n; } })); return n; } public static class Builder { private Map<String, List<Error>> m = new LinkedHashMap<String, List<Error>>(); public Builder put(String name, List<Error> errors) { m.put(name, errors); return this; } public Builder add(String name, List<Error> errors) { List<Error> list = m.get(name); if (list == null) { return put(name, errors); } list.addAll(errors); return this; } public Errors build() { return new Errors(m); } } public static class Ext extends Extension<Optional<Errors>> { private InternalObjectFactory factory = new InternalObjectFactory() {}; @Override public Optional<Errors> extract(ObjectNode node) { if (node.has("errors")) { //extract stuff Map<String, List<Error>> errors = new LinkedHashMap<String, List<Error>>(); JsonNode n = node.get("errors"); Iterator<Map.Entry<String,JsonNode>> fields = n.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> next = fields.next(); List<Error> list = new ArrayList<Error>(); for (JsonNode e : next.getValue()) { Error error = factory.createError((ObjectNode) e); list.add(error); } errors.put(next.getKey(), list); } return Optional.some(new Errors(errors)); } return Optional.none(); } @Override public Map<String, JsonNode> apply(Optional<Errors> value) { Map<String, JsonNode> m = new HashMap<String, JsonNode>(); for (Errors e : value) { m.put("errors", e.asJson()); } return m; } } }
src/main/java/net/hamnaberg/json/extension/Errors.java
Errors extension.
src/main/java/net/hamnaberg/json/extension/Errors.java
Errors extension.
<ide><path>rc/main/java/net/hamnaberg/json/extension/Errors.java <add>package net.hamnaberg.json.extension; <add> <add>import java.util.ArrayList; <add>import java.util.Collections; <add>import java.util.HashMap; <add>import java.util.Iterator; <add>import java.util.LinkedHashMap; <add>import java.util.List; <add>import java.util.Map; <add> <add>import com.fasterxml.jackson.databind.JsonNode; <add>import com.fasterxml.jackson.databind.node.ArrayNode; <add>import com.fasterxml.jackson.databind.node.JsonNodeFactory; <add>import com.fasterxml.jackson.databind.node.ObjectNode; <add>import net.hamnaberg.funclite.Function; <add>import net.hamnaberg.funclite.FunctionalMap; <add>import net.hamnaberg.funclite.Optional; <add>import net.hamnaberg.json.InternalObjectFactory; <add>import net.hamnaberg.json.Error; <add> <add>public class Errors { <add> private final Map<String, List<Error>> errors = new LinkedHashMap<String, List<Error>>(); <add> <add> public Errors(Map<String, List<Error>> errors) { <add> this.errors.putAll(errors); <add> } <add> <add> public List<Error> getErrors(String name) { <add> List<Error> v = errors.get(name); <add> if (v != null) { <add> return Collections.unmodifiableList(v); <add> } <add> return Collections.emptyList(); <add> } <add> <add> private JsonNode asJson() { <add> ObjectNode n = JsonNodeFactory.instance.objectNode(); <add> n.putAll(FunctionalMap.create(errors).mapValues(new Function<List<Error>, JsonNode>() { <add> @Override <add> public JsonNode apply(List<Error> errors) { <add> ArrayNode n = JsonNodeFactory.instance.arrayNode(); <add> for (Error error : errors) { <add> n.add(error.asJson()); <add> } <add> return n; <add> } <add> })); <add> return n; <add> } <add> <add> public static class Builder { <add> private Map<String, List<Error>> m = new LinkedHashMap<String, List<Error>>(); <add> <add> public Builder put(String name, List<Error> errors) { <add> m.put(name, errors); <add> return this; <add> } <add> <add> public Builder add(String name, List<Error> errors) { <add> List<Error> list = m.get(name); <add> if (list == null) { <add> return put(name, errors); <add> } <add> list.addAll(errors); <add> return this; <add> } <add> <add> public Errors build() { <add> return new Errors(m); <add> } <add> } <add> <add> <add> public static class Ext extends Extension<Optional<Errors>> { <add> private InternalObjectFactory factory = new InternalObjectFactory() {}; <add> <add> @Override <add> public Optional<Errors> extract(ObjectNode node) { <add> if (node.has("errors")) { <add> //extract stuff <add> Map<String, List<Error>> errors = new LinkedHashMap<String, List<Error>>(); <add> JsonNode n = node.get("errors"); <add> Iterator<Map.Entry<String,JsonNode>> fields = n.fields(); <add> while (fields.hasNext()) { <add> Map.Entry<String, JsonNode> next = fields.next(); <add> List<Error> list = new ArrayList<Error>(); <add> for (JsonNode e : next.getValue()) { <add> Error error = factory.createError((ObjectNode) e); <add> list.add(error); <add> } <add> errors.put(next.getKey(), list); <add> } <add> return Optional.some(new Errors(errors)); <add> } <add> return Optional.none(); <add> } <add> <add> @Override <add> public Map<String, JsonNode> apply(Optional<Errors> value) { <add> Map<String, JsonNode> m = new HashMap<String, JsonNode>(); <add> for (Errors e : value) { <add> m.put("errors", e.asJson()); <add> } <add> return m; <add> } <add> } <add>} <add> <add>
Java
apache-2.0
ae06d36a7382c58f8b5b775efd9e58559cbfe7bb
0
ivan-fedorov/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,semonte/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,kdwink/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,kdwink/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,robovm/robovm-studio,hurricup/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,clumsy/intellij-community,amith01994/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,holmes/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,caot/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,FHannes/intellij-community,slisson/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,ibinti/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,vvv1559/intellij-community,da1z/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,da1z/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,ibinti/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,signed/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,signed/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,holmes/intellij-community,izonder/intellij-community,slisson/intellij-community,petteyg/intellij-community,izonder/intellij-community,asedunov/intellij-community,retomerz/intellij-community,asedunov/intellij-community,retomerz/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,holmes/intellij-community,samthor/intellij-community,fitermay/intellij-community,jagguli/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,semonte/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,hurricup/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,apixandru/intellij-community,xfournet/intellij-community,robovm/robovm-studio,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,petteyg/intellij-community,caot/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,clumsy/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,kool79/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,slisson/intellij-community,vladmm/intellij-community,signed/intellij-community,signed/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,dslomov/intellij-community,clumsy/intellij-community,caot/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,hurricup/intellij-community,FHannes/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,hurricup/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,caot/intellij-community,ahb0327/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,da1z/intellij-community,apixandru/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,slisson/intellij-community,FHannes/intellij-community,blademainer/intellij-community,clumsy/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,caot/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,da1z/intellij-community,semonte/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,caot/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,fitermay/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,FHannes/intellij-community,kool79/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,jagguli/intellij-community,supersven/intellij-community,kdwink/intellij-community,robovm/robovm-studio,caot/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,signed/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,holmes/intellij-community,asedunov/intellij-community,caot/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,petteyg/intellij-community,jagguli/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,asedunov/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,semonte/intellij-community,allotria/intellij-community,asedunov/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,FHannes/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,allotria/intellij-community,caot/intellij-community,supersven/intellij-community,slisson/intellij-community,izonder/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,hurricup/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,semonte/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,orekyuu/intellij-community,samthor/intellij-community,vladmm/intellij-community,da1z/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,semonte/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,samthor/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,apixandru/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,holmes/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,allotria/intellij-community,fnouama/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,izonder/intellij-community,supersven/intellij-community,da1z/intellij-community,dslomov/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,xfournet/intellij-community,amith01994/intellij-community,ryano144/intellij-community,holmes/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,asedunov/intellij-community,supersven/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,allotria/intellij-community,samthor/intellij-community,dslomov/intellij-community,slisson/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,adedayo/intellij-community,FHannes/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,suncycheng/intellij-community,kool79/intellij-community,signed/intellij-community,samthor/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,semonte/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,slisson/intellij-community,fitermay/intellij-community,vladmm/intellij-community,kdwink/intellij-community,FHannes/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,signed/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,izonder/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,clumsy/intellij-community,semonte/intellij-community,allotria/intellij-community,petteyg/intellij-community,apixandru/intellij-community,adedayo/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,supersven/intellij-community,gnuhub/intellij-community,signed/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,diorcety/intellij-community,vladmm/intellij-community,blademainer/intellij-community,supersven/intellij-community,ryano144/intellij-community,jagguli/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,kool79/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,xfournet/intellij-community,supersven/intellij-community,semonte/intellij-community,gnuhub/intellij-community,izonder/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,petteyg/intellij-community,diorcety/intellij-community,dslomov/intellij-community,signed/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,FHannes/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,kdwink/intellij-community,caot/intellij-community,izonder/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,da1z/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,supersven/intellij-community,adedayo/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,diorcety/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,signed/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,ryano144/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,xfournet/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,blademainer/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,retomerz/intellij-community,wreckJ/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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.intellij.ide.plugins; import com.intellij.ide.ClassUtilCore; import com.intellij.ide.IdeBundle; import com.intellij.ide.StartupProgress; import com.intellij.ide.plugins.cl.PluginClassLoader; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.ExtensionAreas; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.*; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.StreamUtil; import com.intellij.openapi.util.io.ZipFileCache; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.*; import com.intellij.util.containers.MultiMap; import com.intellij.util.execution.ParametersListUtil; import com.intellij.util.graph.CachingSemiGraph; import com.intellij.util.graph.DFSTBuilder; import com.intellij.util.graph.Graph; import com.intellij.util.graph.GraphGenerator; import com.intellij.util.xmlb.XmlSerializationException; import gnu.trove.THashMap; import gnu.trove.THashSet; import gnu.trove.TIntProcedure; import org.jdom.Document; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.net.URLDecoder; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class PluginManagerCore { @NonNls public static final String DISABLED_PLUGINS_FILENAME = "disabled_plugins.txt"; @NonNls public static final String CORE_PLUGIN_ID = "com.intellij"; @NonNls public static final String META_INF = "META-INF"; @NonNls public static final String PLUGIN_XML = "plugin.xml"; public static final float PLUGINS_PROGRESS_MAX_VALUE = 0.3f; private static final Map<PluginId,Integer> ourId2Index = new THashMap<PluginId, Integer>(); @NonNls static final String MODULE_DEPENDENCY_PREFIX = "com.intellij.module"; private static final Map<String, IdeaPluginDescriptorImpl> ourModulesToContainingPlugins = new THashMap<String, IdeaPluginDescriptorImpl>(); private static final PluginClassCache ourPluginClasses = new PluginClassCache(); @NonNls static final String SPECIAL_IDEA_PLUGIN = "IDEA CORE"; static final String DISABLE = "disable"; static final String ENABLE = "enable"; static final String EDIT = "edit"; @NonNls private static final String PROPERTY_PLUGIN_PATH = "plugin.path"; static List<String> ourDisabledPlugins; private static MultiMap<String, String> ourBrokenPluginVersions; private static IdeaPluginDescriptor[] ourPlugins; static String myPluginError; static List<String> myPlugins2Disable = null; static LinkedHashSet<String> myPlugins2Enable = null; public static String BUILD_NUMBER; private static BuildNumber ourBuildNumber; /** * do not call this method during bootstrap, should be called in a copy of PluginManager, loaded by IdeaClassLoader */ public static synchronized IdeaPluginDescriptor[] getPlugins() { if (ourPlugins == null) { initPlugins(null); } return ourPlugins; } public static void loadDisabledPlugins(final String configPath, final Collection<String> disabledPlugins) { final File file = new File(configPath, DISABLED_PLUGINS_FILENAME); if (file.isFile()) { try { BufferedReader reader = new BufferedReader(new FileReader(file)); try { String id; while ((id = reader.readLine()) != null) { disabledPlugins.add(id.trim()); } } finally { reader.close(); } } catch (IOException ignored) { } } } @NotNull public static List<String> getDisabledPlugins() { if (ourDisabledPlugins == null) { ourDisabledPlugins = new ArrayList<String>(); if (System.getProperty("idea.ignore.disabled.plugins") == null && !isUnitTestMode()) { loadDisabledPlugins(PathManager.getConfigPath(), ourDisabledPlugins); } } return ourDisabledPlugins; } public static boolean isBrokenPlugin(IdeaPluginDescriptor descriptor) { return getBrokenPluginVersions().get(descriptor.getPluginId().getIdString()).contains(descriptor.getVersion()); } public static MultiMap<String, String> getBrokenPluginVersions() { if (ourBrokenPluginVersions == null) { ourBrokenPluginVersions = MultiMap.createSet(); if (System.getProperty("idea.ignore.disabled.plugins") == null && !isUnitTestMode()) { BufferedReader br = new BufferedReader(new InputStreamReader(PluginManagerCore.class.getResourceAsStream("/brokenPlugins.txt"))); try { String s; while ((s = br.readLine()) != null) { s = s.trim(); if (s.startsWith("//")) continue; List<String> tokens = ParametersListUtil.parse(s); if (tokens.isEmpty()) continue; if (tokens.size() == 1) { throw new RuntimeException("brokenPlugins.txt is broken. The line contains plugin name, but does not contains version: " + s); } String pluginId = tokens.get(0); List<String> versions = tokens.subList(1, tokens.size()); ourBrokenPluginVersions.putValues(pluginId, versions); } } catch (IOException e) { throw new RuntimeException("Failed to read /brokenPlugins.txt", e); } finally { StreamUtil.closeStream(br); } } } return ourBrokenPluginVersions; } static boolean isUnitTestMode() { final Application app = ApplicationManager.getApplication(); return app != null && app.isUnitTestMode(); } public static void savePluginsList(@NotNull Collection<String> ids, boolean append, @NotNull File plugins) throws IOException { if (!plugins.isFile()) { FileUtil.ensureCanCreateFile(plugins); } PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(plugins, append))); try { for (String id : ids) { printWriter.println(id); } printWriter.flush(); } finally { printWriter.close(); } } public static boolean disablePlugin(String id) { List<String> disabledPlugins = getDisabledPlugins(); if (disabledPlugins.contains(id)) { return false; } disabledPlugins.add(id); try { saveDisabledPlugins(disabledPlugins, false); } catch (IOException e) { return false; } return true; } public static boolean enablePlugin(String id) { if (!getDisabledPlugins().contains(id)) return false; getDisabledPlugins().remove(id); try { saveDisabledPlugins(getDisabledPlugins(), false); } catch (IOException e) { return false; } return true; } public static void saveDisabledPlugins(Collection<String> ids, boolean append) throws IOException { File plugins = new File(PathManager.getConfigPath(), DISABLED_PLUGINS_FILENAME); savePluginsList(ids, append, plugins); ourDisabledPlugins = null; } public static Logger getLogger() { return LoggerHolder.ourLogger; } public static int getPluginLoadingOrder(PluginId id) { return ourId2Index.get(id); } public static boolean isModuleDependency(final PluginId dependentPluginId) { return dependentPluginId.getIdString().startsWith(MODULE_DEPENDENCY_PREFIX); } public static void checkDependants(final IdeaPluginDescriptor pluginDescriptor, final Function<PluginId, IdeaPluginDescriptor> pluginId2Descriptor, final Condition<PluginId> check) { checkDependants(pluginDescriptor, pluginId2Descriptor, check, new THashSet<PluginId>()); } private static boolean checkDependants(final IdeaPluginDescriptor pluginDescriptor, final Function<PluginId, IdeaPluginDescriptor> pluginId2Descriptor, final Condition<PluginId> check, final Set<PluginId> processed) { processed.add(pluginDescriptor.getPluginId()); final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds(); final Set<PluginId> optionalDependencies = new THashSet<PluginId>(Arrays.asList(pluginDescriptor.getOptionalDependentPluginIds())); for (final PluginId dependentPluginId : dependentPluginIds) { if (processed.contains(dependentPluginId)) { continue; } if (isModuleDependency(dependentPluginId) && (ourModulesToContainingPlugins.isEmpty() || ourModulesToContainingPlugins.containsKey( dependentPluginId.getIdString()))) { continue; } if (!optionalDependencies.contains(dependentPluginId)) { if (!check.value(dependentPluginId)) { return false; } final IdeaPluginDescriptor dependantPluginDescriptor = pluginId2Descriptor.fun(dependentPluginId); if (dependantPluginDescriptor != null && !checkDependants(dependantPluginDescriptor, pluginId2Descriptor, check, processed)) { return false; } } } return true; } public static void addPluginClass(@NotNull String className, PluginId pluginId, boolean loaded) { ourPluginClasses.addPluginClass(className, pluginId, loaded); } @Nullable public static PluginId getPluginByClassName(@NotNull String className) { return ourPluginClasses.getPluginByClassName(className); } public static void dumpPluginClassStatistics() { ourPluginClasses.dumpPluginClassStatistics(); } static boolean isDependent(final IdeaPluginDescriptor descriptor, final PluginId on, Map<PluginId, IdeaPluginDescriptor> map, final boolean checkModuleDependencies) { for (PluginId id: descriptor.getDependentPluginIds()) { if (ArrayUtil.contains(id, (Object[])descriptor.getOptionalDependentPluginIds())) { continue; } if (!checkModuleDependencies && isModuleDependency(id)) { continue; } if (id.equals(on)) { return true; } final IdeaPluginDescriptor depDescriptor = map.get(id); if (depDescriptor != null && isDependent(depDescriptor, on, map, checkModuleDependencies)) { return true; } } return false; } static boolean hasModuleDependencies(final IdeaPluginDescriptor descriptor) { final PluginId[] dependentPluginIds = descriptor.getDependentPluginIds(); for (PluginId dependentPluginId : dependentPluginIds) { if (isModuleDependency(dependentPluginId)) { return true; } } return false; } static boolean shouldLoadPlugins() { try { // no plugins during bootstrap Class.forName("com.intellij.openapi.extensions.Extensions"); } catch (ClassNotFoundException e) { return false; } //noinspection HardCodedStringLiteral final String loadPlugins = System.getProperty("idea.load.plugins"); return loadPlugins == null || Boolean.TRUE.toString().equals(loadPlugins); } static void configureExtensions() { Extensions.setLogProvider(new IdeaLogProvider()); Extensions.registerAreaClass(ExtensionAreas.IDEA_PROJECT, null); Extensions.registerAreaClass(ExtensionAreas.IDEA_MODULE, ExtensionAreas.IDEA_PROJECT); } private static Method getAddUrlMethod(final ClassLoader loader) { return ReflectionUtil.getDeclaredMethod(loader instanceof URLClassLoader ? URLClassLoader.class : loader.getClass(), "addURL", URL.class); } @Nullable static ClassLoader createPluginClassLoader(@NotNull File[] classPath, @NotNull ClassLoader[] parentLoaders, @NotNull IdeaPluginDescriptor pluginDescriptor) { if (pluginDescriptor.getUseIdeaClassLoader()) { try { final ClassLoader loader = PluginManagerCore.class.getClassLoader(); final Method addUrlMethod = getAddUrlMethod(loader); for (File aClassPath : classPath) { final File file = aClassPath.getCanonicalFile(); addUrlMethod.invoke(loader, file.toURI().toURL()); } return loader; } catch (IOException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } PluginId pluginId = pluginDescriptor.getPluginId(); File pluginRoot = pluginDescriptor.getPath(); //if (classPath.length == 0) return null; if (isUnitTestMode()) return null; try { final List<URL> urls = new ArrayList<URL>(classPath.length); for (File aClassPath : classPath) { final File file = aClassPath.getCanonicalFile(); // it is critical not to have "." and ".." in classpath elements urls.add(file.toURI().toURL()); } return new PluginClassLoader(urls, parentLoaders, pluginId, pluginDescriptor.getVersion(), pluginRoot); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static void invalidatePlugins() { ourPlugins = null; ourDisabledPlugins = null; } public static boolean isPluginClass(String className) { return ourPlugins != null && getPluginByClassName(className) != null; } static void logPlugins() { List<String> loadedBundled = new ArrayList<String>(); List<String> disabled = new ArrayList<String>(); List<String> loadedCustom = new ArrayList<String>(); for (IdeaPluginDescriptor descriptor : ourPlugins) { final String version = descriptor.getVersion(); String s = descriptor.getName() + (version != null ? " (" + version + ")" : ""); if (descriptor.isEnabled()) { if (descriptor.isBundled() || SPECIAL_IDEA_PLUGIN.equals(descriptor.getName())) loadedBundled.add(s); else loadedCustom.add(s); } else { disabled.add(s); } } Collections.sort(loadedBundled); Collections.sort(loadedCustom); Collections.sort(disabled); getLogger().info("Loaded bundled plugins: " + StringUtil.join(loadedBundled, ", ")); if (!loadedCustom.isEmpty()) { getLogger().info("Loaded custom plugins: " + StringUtil.join(loadedCustom, ", ")); } if (!disabled.isEmpty()) { getLogger().info("Disabled plugins: " + StringUtil.join(disabled, ", ")); } } static ClassLoader[] getParentLoaders(Map<PluginId, ? extends IdeaPluginDescriptor> idToDescriptorMap, PluginId[] pluginIds) { if (isUnitTestMode()) return new ClassLoader[0]; final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(); for (final PluginId id : pluginIds) { IdeaPluginDescriptor pluginDescriptor = idToDescriptorMap.get(id); if (pluginDescriptor == null) { continue; // Might be an optional dependency } final ClassLoader loader = pluginDescriptor.getPluginClassLoader(); if (loader == null) { getLogger().error("Plugin class loader should be initialized for plugin " + id); } classLoaders.add(loader); } return classLoaders.toArray(new ClassLoader[classLoaders.size()]); } static int countPlugins(String pluginsPath) { File configuredPluginsDir = new File(pluginsPath); if (configuredPluginsDir.exists()) { String[] list = configuredPluginsDir.list(); if (list != null) { return list.length; } } return 0; } static Collection<URL> getClassLoaderUrls() { final ClassLoader classLoader = PluginManagerCore.class.getClassLoader(); final Class<? extends ClassLoader> aClass = classLoader.getClass(); try { @SuppressWarnings("unchecked") List<URL> urls = (List<URL>)aClass.getMethod("getUrls").invoke(classLoader); return urls; } catch (IllegalAccessException ignored) { } catch (InvocationTargetException ignored) { } catch (NoSuchMethodException ignored) { } if (classLoader instanceof URLClassLoader) { return Arrays.asList(((URLClassLoader)classLoader).getURLs()); } return Collections.emptyList(); } static void prepareLoadingPluginsErrorMessage(final String errorMessage) { if (!StringUtil.isEmptyOrSpaces(errorMessage)) { if (ApplicationManager.getApplication() != null && !ApplicationManager.getApplication().isHeadlessEnvironment() && !ApplicationManager.getApplication().isUnitTestMode()) { if (myPluginError == null) { myPluginError = errorMessage; } else { myPluginError += "\n" + errorMessage; } } else { getLogger().error(errorMessage); } } } private static void addModulesAsDependents(Map<PluginId, ? super IdeaPluginDescriptorImpl> map) { for (Map.Entry<String, IdeaPluginDescriptorImpl> entry : ourModulesToContainingPlugins.entrySet()) { map.put(PluginId.getId(entry.getKey()), entry.getValue()); } } static Comparator<IdeaPluginDescriptor> getPluginDescriptorComparator(final Map<PluginId, ? extends IdeaPluginDescriptor> idToDescriptorMap) { final Graph<PluginId> graph = createPluginIdGraph(idToDescriptorMap); final DFSTBuilder<PluginId> builder = new DFSTBuilder<PluginId>(graph); if (!builder.isAcyclic()) { builder.getSCCs().forEach(new TIntProcedure() { int myTNumber = 0; @Override public boolean execute(int size) { if (size > 1) { for (int j = 0; j < size; j++) { idToDescriptorMap.get(builder.getNodeByTNumber(myTNumber + j)).setEnabled(false); } } myTNumber += size; return true; } }); } final Comparator<PluginId> idComparator = builder.comparator(); return new Comparator<IdeaPluginDescriptor>() { @Override public int compare(@NotNull IdeaPluginDescriptor o1, @NotNull IdeaPluginDescriptor o2) { final PluginId pluginId1 = o1.getPluginId(); final PluginId pluginId2 = o2.getPluginId(); if (pluginId1.getIdString().equals(CORE_PLUGIN_ID)) return -1; if (pluginId2.getIdString().equals(CORE_PLUGIN_ID)) return 1; return idComparator.compare(pluginId1, pluginId2); } }; } private static Graph<PluginId> createPluginIdGraph(final Map<PluginId, ? extends IdeaPluginDescriptor> idToDescriptorMap) { final List<PluginId> ids = new ArrayList<PluginId>(idToDescriptorMap.keySet()); // this magic ensures that the dependent plugins always follow their dependencies in lexicographic order // needed to make sure that extensions are always in the same order Collections.sort(ids, new Comparator<PluginId>() { @Override public int compare(@NotNull PluginId o1, @NotNull PluginId o2) { return o2.getIdString().compareTo(o1.getIdString()); } }); return GraphGenerator.create(CachingSemiGraph.create(new GraphGenerator.SemiGraph<PluginId>() { @Override public Collection<PluginId> getNodes() { return ids; } @Override public Iterator<PluginId> getIn(PluginId pluginId) { final IdeaPluginDescriptor descriptor = idToDescriptorMap.get(pluginId); ArrayList<PluginId> plugins = new ArrayList<PluginId>(); for (PluginId dependentPluginId : descriptor.getDependentPluginIds()) { // check for missing optional dependency IdeaPluginDescriptor dep = idToDescriptorMap.get(dependentPluginId); if (dep != null) { plugins.add(dep.getPluginId()); } } return plugins.iterator(); } })); } @Nullable static IdeaPluginDescriptorImpl loadDescriptorFromDir(@NotNull File file, @NotNull String fileName) { File descriptorFile = new File(file, META_INF + File.separator + fileName); if (descriptorFile.exists()) { try { IdeaPluginDescriptorImpl descriptor = new IdeaPluginDescriptorImpl(file); descriptor.readExternal(descriptorFile.toURI().toURL()); return descriptor; } catch (XmlSerializationException e) { getLogger().info("Cannot load " + file, e); prepareLoadingPluginsErrorMessage("File '" + file.getName() + "' contains invalid plugin descriptor."); } catch (Throwable e) { getLogger().info("Cannot load " + file, e); } } return null; } @Nullable static IdeaPluginDescriptorImpl loadDescriptorFromJar(@NotNull File file, @NotNull String fileName) { try { String fileURL = StringUtil.replace(file.toURI().toASCIIString(), "!", "%21"); URL jarURL = new URL("jar:" + fileURL + "!/META-INF/" + fileName); ZipFile zipFile = ZipFileCache.acquire(file.getPath()); try { ZipEntry entry = zipFile.getEntry("META-INF/" + fileName); if (entry != null) { Document document = JDOMUtil.loadDocument(zipFile.getInputStream(entry)); IdeaPluginDescriptorImpl descriptor = new IdeaPluginDescriptorImpl(file); descriptor.readExternal(document, jarURL); return descriptor; } } finally { ZipFileCache.release(zipFile); } } catch (XmlSerializationException e) { getLogger().info("Cannot load " + file, e); prepareLoadingPluginsErrorMessage("File '" + file.getName() + "' contains invalid plugin descriptor."); } catch (Throwable e) { getLogger().info("Cannot load " + file, e); } return null; } @Nullable public static IdeaPluginDescriptorImpl loadDescriptorFromJar(@NotNull File file) { return loadDescriptorFromJar(file, PLUGIN_XML); } @Nullable public static IdeaPluginDescriptorImpl loadDescriptor(@NotNull final File file, @NotNull String fileName) { IdeaPluginDescriptorImpl descriptor = null; if (file.isDirectory()) { descriptor = loadDescriptorFromDir(file, fileName); if (descriptor == null) { File libDir = new File(file, "lib"); if (!libDir.isDirectory()) { return null; } final File[] files = libDir.listFiles(); if (files == null || files.length == 0) { return null; } Arrays.sort(files, new Comparator<File>() { @Override public int compare(@NotNull File o1, @NotNull File o2) { if (o2.getName().startsWith(file.getName())) return Integer.MAX_VALUE; if (o1.getName().startsWith(file.getName())) return -Integer.MAX_VALUE; if (o2.getName().startsWith("resources")) return -Integer.MAX_VALUE; if (o1.getName().startsWith("resources")) return Integer.MAX_VALUE; return 0; } }); for (final File f : files) { if (FileUtil.isJarOrZip(f)) { descriptor = loadDescriptorFromJar(f, fileName); if (descriptor != null) { descriptor.setPath(file); break; } // getLogger().warn("Cannot load descriptor from " + f.getName() + ""); } else if (f.isDirectory()) { IdeaPluginDescriptorImpl descriptor1 = loadDescriptorFromDir(f, fileName); if (descriptor1 != null) { if (descriptor != null) { getLogger().info("Cannot load " + file + " because two or more plugin.xml's detected"); return null; } descriptor = descriptor1; descriptor.setPath(file); } } } } } else if (StringUtil.endsWithIgnoreCase(file.getName(), ".jar") && file.exists()) { descriptor = loadDescriptorFromJar(file, fileName); } if (descriptor != null && descriptor.getOptionalConfigs() != null && !descriptor.getOptionalConfigs().isEmpty()) { final Map<PluginId, IdeaPluginDescriptorImpl> descriptors = new THashMap<PluginId, IdeaPluginDescriptorImpl>(descriptor.getOptionalConfigs().size()); for (Map.Entry<PluginId, String> entry : descriptor.getOptionalConfigs().entrySet()) { String optionalDescriptorName = entry.getValue(); assert !Comparing.equal(fileName, optionalDescriptorName) : "recursive dependency: " + fileName; IdeaPluginDescriptorImpl optionalDescriptor = loadDescriptor(file, optionalDescriptorName); if (optionalDescriptor == null && !FileUtil.isJarOrZip(file)) { for (URL url : getClassLoaderUrls()) { if ("file".equals(url.getProtocol())) { optionalDescriptor = loadDescriptor(new File(decodeUrl(url.getFile())), optionalDescriptorName); if (optionalDescriptor != null) { break; } } } } if (optionalDescriptor != null) { descriptors.put(entry.getKey(), optionalDescriptor); } else { getLogger().info("Cannot find optional descriptor " + optionalDescriptorName); } } descriptor.setOptionalDescriptors(descriptors); } return descriptor; } public static void loadDescriptors(String pluginsPath, List<IdeaPluginDescriptorImpl> result, @Nullable StartupProgress progress, int pluginsCount) { loadDescriptors(new File(pluginsPath), result, progress, pluginsCount); } public static void loadDescriptors(@NotNull File pluginsHome, List<IdeaPluginDescriptorImpl> result, @Nullable StartupProgress progress, int pluginsCount) { final File[] files = pluginsHome.listFiles(); if (files != null) { int i = result.size(); for (File file : files) { final IdeaPluginDescriptorImpl descriptor = loadDescriptor(file, PLUGIN_XML); if (descriptor == null) continue; if (progress != null) { progress.showProgress(descriptor.getName(), PLUGINS_PROGRESS_MAX_VALUE * ((float)++i / pluginsCount)); } int oldIndex = result.indexOf(descriptor); if (oldIndex >= 0) { final IdeaPluginDescriptorImpl oldDescriptor = result.get(oldIndex); if (StringUtil.compareVersionNumbers(oldDescriptor.getVersion(), descriptor.getVersion()) < 0) { result.set(oldIndex, descriptor); } } else { result.add(descriptor); } } } } @Nullable static String filterBadPlugins(List<? extends IdeaPluginDescriptor> result, final Map<String, String> disabledPluginNames) { final Map<PluginId, IdeaPluginDescriptor> idToDescriptorMap = new THashMap<PluginId, IdeaPluginDescriptor>(); final StringBuilder message = new StringBuilder(); boolean pluginsWithoutIdFound = false; for (Iterator<? extends IdeaPluginDescriptor> it = result.iterator(); it.hasNext();) { final IdeaPluginDescriptor descriptor = it.next(); final PluginId id = descriptor.getPluginId(); if (id == null) { pluginsWithoutIdFound = true; } else if (idToDescriptorMap.containsKey(id)) { message.append("<br>"); message.append(IdeBundle.message("message.duplicate.plugin.id")); message.append(id); it.remove(); } else if (descriptor.isEnabled()) { idToDescriptorMap.put(id, descriptor); } } addModulesAsDependents(idToDescriptorMap); final List<String> disabledPluginIds = new SmartList<String>(); final LinkedHashSet<String> faultyDescriptors = new LinkedHashSet<String>(); for (final Iterator<? extends IdeaPluginDescriptor> it = result.iterator(); it.hasNext();) { final IdeaPluginDescriptor pluginDescriptor = it.next(); checkDependants(pluginDescriptor, new Function<PluginId, IdeaPluginDescriptor>() { @Override public IdeaPluginDescriptor fun(final PluginId pluginId) { return idToDescriptorMap.get(pluginId); } }, new Condition<PluginId>() { @Override public boolean value(final PluginId pluginId) { if (!idToDescriptorMap.containsKey(pluginId)) { pluginDescriptor.setEnabled(false); if (!pluginId.getIdString().startsWith(MODULE_DEPENDENCY_PREFIX)) { faultyDescriptors.add(pluginId.getIdString()); disabledPluginIds.add(pluginDescriptor.getPluginId().getIdString()); message.append("<br>"); final String name = pluginDescriptor.getName(); final IdeaPluginDescriptor descriptor = idToDescriptorMap.get(pluginId); String pluginName; if (descriptor == null) { pluginName = pluginId.getIdString(); if (disabledPluginNames.containsKey(pluginName)) { pluginName = disabledPluginNames.get(pluginName); } } else { pluginName = descriptor.getName(); } message.append(getDisabledPlugins().contains(pluginId.getIdString()) ? IdeBundle.message("error.required.plugin.disabled", name, pluginName) : IdeBundle.message("error.required.plugin.not.installed", name, pluginName)); } it.remove(); return false; } return true; } }); } if (!disabledPluginIds.isEmpty()) { myPlugins2Disable = disabledPluginIds; myPlugins2Enable = faultyDescriptors; message.append("<br>"); message.append("<br>").append("<a href=\"" + DISABLE + "\">Disable "); if (disabledPluginIds.size() == 1) { final PluginId pluginId2Disable = PluginId.getId(disabledPluginIds.iterator().next()); message.append(idToDescriptorMap.containsKey(pluginId2Disable) ? idToDescriptorMap.get(pluginId2Disable).getName() : pluginId2Disable.getIdString()); } else { message.append("not loaded plugins"); } message.append("</a>"); boolean possibleToEnable = true; for (String descriptor : faultyDescriptors) { if (disabledPluginNames.get(descriptor) == null) { possibleToEnable = false; break; } } if (possibleToEnable) { message.append("<br>").append("<a href=\"" + ENABLE + "\">Enable ").append(faultyDescriptors.size() == 1 ? disabledPluginNames.get(faultyDescriptors.iterator().next()) : " all necessary plugins").append("</a>"); } message.append("<br>").append("<a href=\"" + EDIT + "\">Open plugin manager</a>"); } if (pluginsWithoutIdFound) { message.append("<br>"); message.append(IdeBundle.message("error.plugins.without.id.found")); } if (message.length() > 0) { message.insert(0, IdeBundle.message("error.problems.found.loading.plugins")); return message.toString(); } return ""; } static void loadDescriptorsFromClassPath(@NotNull List<IdeaPluginDescriptorImpl> result, @Nullable StartupProgress progress) { Collection<URL> urls = getClassLoaderUrls(); String platformPrefix = System.getProperty(PlatformUtils.PLATFORM_PREFIX_KEY); int i = 0; for (URL url : urls) { i++; if ("file".equals(url.getProtocol())) { File file = new File(decodeUrl(url.getFile())); IdeaPluginDescriptorImpl platformPluginDescriptor = null; if (platformPrefix != null) { platformPluginDescriptor = loadDescriptor(file, platformPrefix + "Plugin.xml"); if (platformPluginDescriptor != null && !result.contains(platformPluginDescriptor)) { platformPluginDescriptor.setUseCoreClassLoader(true); result.add(platformPluginDescriptor); } } IdeaPluginDescriptorImpl pluginDescriptor = loadDescriptor(file, PLUGIN_XML); if (platformPrefix != null && pluginDescriptor != null && pluginDescriptor.getName().equals(SPECIAL_IDEA_PLUGIN)) { continue; } if (pluginDescriptor != null && !result.contains(pluginDescriptor)) { if (platformPluginDescriptor != null) { // if we found a regular plugin.xml in the same .jar/root as a platform-prefixed descriptor, use the core loader for it too pluginDescriptor.setUseCoreClassLoader(true); } result.add(pluginDescriptor); if (progress != null) { progress.showProgress("Plugin loaded: " + pluginDescriptor.getName(), PLUGINS_PROGRESS_MAX_VALUE * ((float)i / urls.size())); } } } } } @SuppressWarnings("deprecation") private static String decodeUrl(String file) { String quotePluses = StringUtil.replace(file, "+", "%2B"); return URLDecoder.decode(quotePluses); } static void loadDescriptorsFromProperty(final List<IdeaPluginDescriptorImpl> result) { final String pathProperty = System.getProperty(PROPERTY_PLUGIN_PATH); if (pathProperty == null) return; for (StringTokenizer t = new StringTokenizer(pathProperty, File.pathSeparator + ","); t.hasMoreTokens();) { String s = t.nextToken(); final IdeaPluginDescriptorImpl ideaPluginDescriptor = loadDescriptor(new File(s), PLUGIN_XML); if (ideaPluginDescriptor != null) { result.add(ideaPluginDescriptor); } } } public static IdeaPluginDescriptorImpl[] loadDescriptors(@Nullable StartupProgress progress) { if (ClassUtilCore.isLoadingOfExternalPluginsDisabled()) { return IdeaPluginDescriptorImpl.EMPTY_ARRAY; } final List<IdeaPluginDescriptorImpl> result = new ArrayList<IdeaPluginDescriptorImpl>(); int pluginsCount = countPlugins(PathManager.getPluginsPath()) + countPlugins(PathManager.getPreInstalledPluginsPath()); loadDescriptors(PathManager.getPluginsPath(), result, progress, pluginsCount); Application application = ApplicationManager.getApplication(); boolean fromSources = false; if (application == null || !application.isUnitTestMode()) { int size = result.size(); loadDescriptors(PathManager.getPreInstalledPluginsPath(), result, progress, pluginsCount); fromSources = size == result.size(); } loadDescriptorsFromProperty(result); loadDescriptorsFromClassPath(result, fromSources ? progress : null); IdeaPluginDescriptorImpl[] pluginDescriptors = result.toArray(new IdeaPluginDescriptorImpl[result.size()]); final Map<PluginId, IdeaPluginDescriptorImpl> idToDescriptorMap = new THashMap<PluginId, IdeaPluginDescriptorImpl>(); for (IdeaPluginDescriptorImpl descriptor : pluginDescriptors) { idToDescriptorMap.put(descriptor.getPluginId(), descriptor); } Arrays.sort(pluginDescriptors, getPluginDescriptorComparator(idToDescriptorMap)); return pluginDescriptors; } static void mergeOptionalConfigs(Map<PluginId, IdeaPluginDescriptorImpl> descriptors) { final Map<PluginId, IdeaPluginDescriptorImpl> descriptorsWithModules = new THashMap<PluginId, IdeaPluginDescriptorImpl>(descriptors); addModulesAsDependents(descriptorsWithModules); for (IdeaPluginDescriptorImpl descriptor : descriptors.values()) { final Map<PluginId, IdeaPluginDescriptorImpl> optionalDescriptors = descriptor.getOptionalDescriptors(); if (optionalDescriptors != null && !optionalDescriptors.isEmpty()) { for (Map.Entry<PluginId, IdeaPluginDescriptorImpl> entry: optionalDescriptors.entrySet()) { if (descriptorsWithModules.containsKey(entry.getKey())) { descriptor.mergeOptionalConfig(entry.getValue()); } } } } } public static void initClassLoader(@NotNull ClassLoader parentLoader, @NotNull IdeaPluginDescriptorImpl descriptor) { final List<File> classPath = descriptor.getClassPath(); final ClassLoader loader = createPluginClassLoader(classPath.toArray(new File[classPath.size()]), new ClassLoader[]{parentLoader}, descriptor); descriptor.setLoader(loader); } static BuildNumber getBuildNumber() { if (ourBuildNumber == null) { ourBuildNumber = BuildNumber.fromString(System.getProperty("idea.plugins.compatible.build")); if (ourBuildNumber == null) { ourBuildNumber = BUILD_NUMBER == null ? null : BuildNumber.fromString(BUILD_NUMBER); if (ourBuildNumber == null) { ourBuildNumber = BuildNumber.fallback(); } } } return ourBuildNumber; } static boolean shouldSkipPlugin(final IdeaPluginDescriptor descriptor, IdeaPluginDescriptor[] loaded) { final String idString = descriptor.getPluginId().getIdString(); if (CORE_PLUGIN_ID.equals(idString)) { return false; } //noinspection HardCodedStringLiteral final String pluginId = System.getProperty("idea.load.plugins.id"); if (pluginId == null) { if (descriptor instanceof IdeaPluginDescriptorImpl && !descriptor.isEnabled()) return true; if (!shouldLoadPlugins()) return true; } final List<String> pluginIds = pluginId == null ? null : StringUtil.split(pluginId, ","); final boolean checkModuleDependencies = !ourModulesToContainingPlugins.isEmpty() && !ourModulesToContainingPlugins.containsKey("com.intellij.modules.all"); if (checkModuleDependencies && !hasModuleDependencies(descriptor)) { return true; } boolean shouldLoad; //noinspection HardCodedStringLiteral final String loadPluginCategory = System.getProperty("idea.load.plugins.category"); if (loadPluginCategory != null) { shouldLoad = loadPluginCategory.equals(descriptor.getCategory()); } else { if (pluginIds != null) { shouldLoad = pluginIds.contains(idString); if (!shouldLoad) { Map<PluginId,IdeaPluginDescriptor> map = new THashMap<PluginId, IdeaPluginDescriptor>(); for (IdeaPluginDescriptor pluginDescriptor : loaded) { map.put(pluginDescriptor.getPluginId(), pluginDescriptor); } addModulesAsDependents(map); for (String id : pluginIds) { final IdeaPluginDescriptor descriptorFromProperty = map.get(PluginId.getId(id)); if (descriptorFromProperty != null && isDependent(descriptorFromProperty, descriptor.getPluginId(), map, checkModuleDependencies)) { shouldLoad = true; break; } } } } else { shouldLoad = !getDisabledPlugins().contains(idString); } if (shouldLoad && descriptor instanceof IdeaPluginDescriptorImpl) { if (isIncompatible(descriptor)) return true; } } return !shouldLoad; } public static boolean isIncompatible(final IdeaPluginDescriptor descriptor) { return isIncompatible(descriptor, getBuildNumber()); } public static boolean isIncompatible(final IdeaPluginDescriptor descriptor, @Nullable BuildNumber buildNumber) { if (buildNumber == null) { buildNumber = getBuildNumber(); } try { if (!StringUtil.isEmpty(descriptor.getSinceBuild())) { BuildNumber sinceBuild = BuildNumber.fromString(descriptor.getSinceBuild(), descriptor.getName()); if (sinceBuild.compareTo(buildNumber) > 0) { return true; } } if (!StringUtil.isEmpty(descriptor.getUntilBuild()) && !buildNumber.isSnapshot()) { BuildNumber untilBuild = BuildNumber.fromString(descriptor.getUntilBuild(), descriptor.getName()); if (untilBuild.compareTo(buildNumber) < 0) { return true; } } } catch (RuntimeException ignored) { } return false; } public static boolean shouldSkipPlugin(final IdeaPluginDescriptor descriptor) { if (descriptor instanceof IdeaPluginDescriptorImpl) { IdeaPluginDescriptorImpl descriptorImpl = (IdeaPluginDescriptorImpl)descriptor; Boolean skipped = descriptorImpl.getSkipped(); if (skipped != null) { return skipped.booleanValue(); } boolean result = shouldSkipPlugin(descriptor, ourPlugins) || isBrokenPlugin(descriptor); descriptorImpl.setSkipped(result); return result; } return shouldSkipPlugin(descriptor, ourPlugins) || isBrokenPlugin(descriptor); } static void initializePlugins(@Nullable StartupProgress progress) { configureExtensions(); final IdeaPluginDescriptorImpl[] pluginDescriptors = loadDescriptors(progress); final Class callerClass = ReflectionUtil.findCallerClass(1); assert callerClass != null; final ClassLoader parentLoader = callerClass.getClassLoader(); final List<IdeaPluginDescriptorImpl> result = new ArrayList<IdeaPluginDescriptorImpl>(); final Map<String, String> disabledPluginNames = new THashMap<String, String>(); List<String> brokenPluginsList = new SmartList<String>(); for (IdeaPluginDescriptorImpl descriptor : pluginDescriptors) { boolean skipped = shouldSkipPlugin(descriptor, pluginDescriptors); if (!skipped) { if (isBrokenPlugin(descriptor)) { brokenPluginsList.add(descriptor.getName()); skipped = true; } } if (!skipped) { final List<String> modules = descriptor.getModules(); if (modules != null) { for (String module : modules) { if (!ourModulesToContainingPlugins.containsKey(module)) { ourModulesToContainingPlugins.put(module, descriptor); } } } result.add(descriptor); } else { descriptor.setEnabled(false); disabledPluginNames.put(descriptor.getPluginId().getIdString(), descriptor.getName()); initClassLoader(parentLoader, descriptor); } } String errorMessage = filterBadPlugins(result, disabledPluginNames); if (!brokenPluginsList.isEmpty()) { if (!StringUtil.isEmptyOrSpaces(errorMessage)) { errorMessage += "<br>"; } errorMessage += "Following plugins are incompatible with current IDE build: " + StringUtil.join(brokenPluginsList, ", ") + "<br>\n" + StringUtil.notNullize(errorMessage); } final Map<PluginId, IdeaPluginDescriptorImpl> idToDescriptorMap = new THashMap<PluginId, IdeaPluginDescriptorImpl>(); for (IdeaPluginDescriptorImpl descriptor : result) { idToDescriptorMap.put(descriptor.getPluginId(), descriptor); } final IdeaPluginDescriptor corePluginDescriptor = idToDescriptorMap.get(PluginId.getId(CORE_PLUGIN_ID)); assert corePluginDescriptor != null : CORE_PLUGIN_ID + " not found; platform prefix is " + System.getProperty(PlatformUtils.PLATFORM_PREFIX_KEY); for (IdeaPluginDescriptorImpl descriptor : result) { if (descriptor != corePluginDescriptor) { descriptor.insertDependency(corePluginDescriptor); } } mergeOptionalConfigs(idToDescriptorMap); addModulesAsDependents(idToDescriptorMap); final Graph<PluginId> graph = createPluginIdGraph(idToDescriptorMap); final DFSTBuilder<PluginId> builder = new DFSTBuilder<PluginId>(graph); if (!builder.isAcyclic()) { if (!StringUtil.isEmptyOrSpaces(errorMessage)) { errorMessage += "<br>"; } final String cyclePresentation; if (ApplicationManager.getApplication().isInternal()) { final List<String> cycles = new ArrayList<String>(); builder.getSCCs().forEach(new TIntProcedure() { int myTNumber = 0; @Override public boolean execute(int size) { if (size > 1) { String cycle = ""; for (int j = 0; j < size; j++) { cycle += builder.getNodeByTNumber(myTNumber + j).getIdString() + " "; } cycles.add(cycle); } myTNumber += size; return true; } }); cyclePresentation = ": " + StringUtil.join(cycles, ";"); } else { final Couple<PluginId> circularDependency = builder.getCircularDependency(); final PluginId id = circularDependency.getFirst(); final PluginId parentId = circularDependency.getSecond(); cyclePresentation = id + "->" + parentId + "->...->" + id; } errorMessage += IdeBundle.message("error.plugins.should.not.have.cyclic.dependencies") + cyclePresentation; } prepareLoadingPluginsErrorMessage(errorMessage); final Comparator<PluginId> idComparator = builder.comparator(); // sort descriptors according to plugin dependencies Collections.sort(result, new Comparator<IdeaPluginDescriptor>() { @Override public int compare(@NotNull IdeaPluginDescriptor o1, @NotNull IdeaPluginDescriptor o2) { return idComparator.compare(o1.getPluginId(), o2.getPluginId()); } }); for (int i = 0; i < result.size(); i++) { ourId2Index.put(result.get(i).getPluginId(), i); } int i = 0; for (final IdeaPluginDescriptorImpl pluginDescriptor : result) { if (pluginDescriptor.getPluginId().getIdString().equals(CORE_PLUGIN_ID) || pluginDescriptor.isUseCoreClassLoader()) { pluginDescriptor.setLoader(parentLoader); } else { final List<File> classPath = pluginDescriptor.getClassPath(); final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds(); final ClassLoader[] parentLoaders = getParentLoaders(idToDescriptorMap, dependentPluginIds); final ClassLoader pluginClassLoader = createPluginClassLoader(classPath.toArray(new File[classPath.size()]), parentLoaders.length > 0 ? parentLoaders : new ClassLoader[] {parentLoader}, pluginDescriptor); pluginDescriptor.setLoader(pluginClassLoader); } if (progress != null) { progress.showProgress("", PLUGINS_PROGRESS_MAX_VALUE + (i++ / (float)result.size()) * 0.35f); } } registerExtensionPointsAndExtensions(Extensions.getRootArea(), result); Extensions.getRootArea().getExtensionPoint(Extensions.AREA_LISTENER_EXTENSION_POINT).registerExtension(new AreaListener() { @Override public void areaCreated(@NotNull String areaClass, @NotNull AreaInstance areaInstance) { registerExtensionPointsAndExtensions(Extensions.getArea(areaInstance), result); } @Override public void areaDisposing(@NotNull String areaClass, @NotNull AreaInstance areaInstance) { } }); ourPlugins = pluginDescriptors; } private static void registerExtensionPointsAndExtensions(ExtensionsArea area, List<IdeaPluginDescriptorImpl> loadedPlugins) { for (IdeaPluginDescriptorImpl descriptor : loadedPlugins) { descriptor.registerExtensionPoints(area); } ExtensionPoint[] extensionPoints = area.getExtensionPoints(); Set<String> epNames = new THashSet<String>(extensionPoints.length); for (ExtensionPoint point : extensionPoints) { epNames.add(point.getName()); } for (IdeaPluginDescriptorImpl descriptor : loadedPlugins) { for (String epName : epNames) { descriptor.registerExtensions(area, epName); } } } public static void initPlugins(@Nullable StartupProgress progress) { long start = System.currentTimeMillis(); try { initializePlugins(progress); } catch (RuntimeException e) { getLogger().error(e); throw e; } getLogger().info(ourPlugins.length + " plugins initialized in " + (System.currentTimeMillis() - start) + " ms"); logPlugins(); ClassUtilCore.clearJarURLCache(); } private static class LoggerHolder { private static final Logger ourLogger = Logger.getInstance("#com.intellij.ide.plugins.PluginManager"); } private static class IdeaLogProvider implements LogProvider { @Override public void error(String message) { getLogger().error(message); } @Override public void error(String message, Throwable t) { getLogger().error(message, t); } @Override public void error(Throwable t) { getLogger().error(t); } @Override public void warn(String message) { getLogger().info(message); } @Override public void warn(String message, Throwable t) { getLogger().info(message, t); } @Override public void warn(Throwable t) { getLogger().info(t); } } }
platform/core-impl/src/com/intellij/ide/plugins/PluginManagerCore.java
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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.intellij.ide.plugins; import com.intellij.ide.ClassUtilCore; import com.intellij.ide.IdeBundle; import com.intellij.ide.StartupProgress; import com.intellij.ide.plugins.cl.PluginClassLoader; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.ExtensionAreas; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.*; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.StreamUtil; import com.intellij.openapi.util.io.ZipFileCache; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.*; import com.intellij.util.containers.MultiMap; import com.intellij.util.execution.ParametersListUtil; import com.intellij.util.graph.CachingSemiGraph; import com.intellij.util.graph.DFSTBuilder; import com.intellij.util.graph.Graph; import com.intellij.util.graph.GraphGenerator; import com.intellij.util.xmlb.XmlSerializationException; import gnu.trove.THashMap; import gnu.trove.THashSet; import gnu.trove.TIntProcedure; import org.jdom.Document; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.net.URLDecoder; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class PluginManagerCore { @NonNls public static final String DISABLED_PLUGINS_FILENAME = "disabled_plugins.txt"; @NonNls public static final String CORE_PLUGIN_ID = "com.intellij"; @NonNls public static final String META_INF = "META-INF"; @NonNls public static final String PLUGIN_XML = "plugin.xml"; public static final float PLUGINS_PROGRESS_MAX_VALUE = 0.3f; private static final Map<PluginId,Integer> ourId2Index = new THashMap<PluginId, Integer>(); @NonNls static final String MODULE_DEPENDENCY_PREFIX = "com.intellij.module"; private static final Map<String, IdeaPluginDescriptorImpl> ourModulesToContainingPlugins = new THashMap<String, IdeaPluginDescriptorImpl>(); private static final PluginClassCache ourPluginClasses = new PluginClassCache(); @NonNls static final String SPECIAL_IDEA_PLUGIN = "IDEA CORE"; static final String DISABLE = "disable"; static final String ENABLE = "enable"; static final String EDIT = "edit"; @NonNls private static final String PROPERTY_PLUGIN_PATH = "plugin.path"; static List<String> ourDisabledPlugins; private static MultiMap<String, String> ourBrokenPluginVersions; private static IdeaPluginDescriptor[] ourPlugins; static String myPluginError; static List<String> myPlugins2Disable = null; static LinkedHashSet<String> myPlugins2Enable = null; public static String BUILD_NUMBER; private static BuildNumber ourBuildNumber; /** * do not call this method during bootstrap, should be called in a copy of PluginManager, loaded by IdeaClassLoader */ public static synchronized IdeaPluginDescriptor[] getPlugins() { if (ourPlugins == null) { initPlugins(null); } return ourPlugins; } public static void loadDisabledPlugins(final String configPath, final Collection<String> disabledPlugins) { final File file = new File(configPath, DISABLED_PLUGINS_FILENAME); if (file.isFile()) { try { BufferedReader reader = new BufferedReader(new FileReader(file)); try { String id; while ((id = reader.readLine()) != null) { disabledPlugins.add(id.trim()); } } finally { reader.close(); } } catch (IOException ignored) { } } } @NotNull public static List<String> getDisabledPlugins() { if (ourDisabledPlugins == null) { ourDisabledPlugins = new ArrayList<String>(); if (System.getProperty("idea.ignore.disabled.plugins") == null && !isUnitTestMode()) { loadDisabledPlugins(PathManager.getConfigPath(), ourDisabledPlugins); } } return ourDisabledPlugins; } public static boolean isBrokenPlugin(IdeaPluginDescriptor descriptor) { return getBrokenPluginVersions().get(descriptor.getPluginId().getIdString()).contains(descriptor.getVersion()); } public static MultiMap<String, String> getBrokenPluginVersions() { if (ourBrokenPluginVersions == null) { ourBrokenPluginVersions = MultiMap.createSet(); if (System.getProperty("idea.ignore.disabled.plugins") == null && !isUnitTestMode()) { BufferedReader br = new BufferedReader(new InputStreamReader(PluginManagerCore.class.getResourceAsStream("/brokenPlugins.txt"))); try { String s; while ((s = br.readLine()) != null) { s = s.trim(); if (s.startsWith("//")) continue; List<String> tokens = ParametersListUtil.parse(s); if (tokens.isEmpty()) continue; if (tokens.size() == 1) { throw new RuntimeException("brokenPlugins.txt is broken. The line contains plugin name, but does not contains version: " + s); } String pluginId = tokens.get(0); List<String> versions = tokens.subList(1, tokens.size()); ourBrokenPluginVersions.putValues(pluginId, versions); } } catch (IOException e) { throw new RuntimeException("Failed to read /brokenPlugins.txt", e); } finally { StreamUtil.closeStream(br); } } } return ourBrokenPluginVersions; } static boolean isUnitTestMode() { final Application app = ApplicationManager.getApplication(); return app != null && app.isUnitTestMode(); } public static void savePluginsList(@NotNull Collection<String> ids, boolean append, @NotNull File plugins) throws IOException { if (!plugins.isFile()) { FileUtil.ensureCanCreateFile(plugins); } PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(plugins, append))); try { for (String id : ids) { printWriter.println(id); } printWriter.flush(); } finally { printWriter.close(); } } public static boolean disablePlugin(String id) { List<String> disabledPlugins = getDisabledPlugins(); if (disabledPlugins.contains(id)) { return false; } disabledPlugins.add(id); try { saveDisabledPlugins(disabledPlugins, false); } catch (IOException e) { return false; } return true; } public static boolean enablePlugin(String id) { if (!getDisabledPlugins().contains(id)) return false; getDisabledPlugins().remove(id); try { saveDisabledPlugins(getDisabledPlugins(), false); } catch (IOException e) { return false; } return true; } public static void saveDisabledPlugins(Collection<String> ids, boolean append) throws IOException { File plugins = new File(PathManager.getConfigPath(), DISABLED_PLUGINS_FILENAME); savePluginsList(ids, append, plugins); ourDisabledPlugins = null; } public static Logger getLogger() { return LoggerHolder.ourLogger; } public static int getPluginLoadingOrder(PluginId id) { return ourId2Index.get(id); } public static boolean isModuleDependency(final PluginId dependentPluginId) { return dependentPluginId.getIdString().startsWith(MODULE_DEPENDENCY_PREFIX); } public static void checkDependants(final IdeaPluginDescriptor pluginDescriptor, final Function<PluginId, IdeaPluginDescriptor> pluginId2Descriptor, final Condition<PluginId> check) { checkDependants(pluginDescriptor, pluginId2Descriptor, check, new THashSet<PluginId>()); } private static boolean checkDependants(final IdeaPluginDescriptor pluginDescriptor, final Function<PluginId, IdeaPluginDescriptor> pluginId2Descriptor, final Condition<PluginId> check, final Set<PluginId> processed) { processed.add(pluginDescriptor.getPluginId()); final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds(); final Set<PluginId> optionalDependencies = new THashSet<PluginId>(Arrays.asList(pluginDescriptor.getOptionalDependentPluginIds())); for (final PluginId dependentPluginId : dependentPluginIds) { if (processed.contains(dependentPluginId)) { continue; } if (isModuleDependency(dependentPluginId) && (ourModulesToContainingPlugins.isEmpty() || ourModulesToContainingPlugins.containsKey( dependentPluginId.getIdString()))) { continue; } if (!optionalDependencies.contains(dependentPluginId)) { if (!check.value(dependentPluginId)) { return false; } final IdeaPluginDescriptor dependantPluginDescriptor = pluginId2Descriptor.fun(dependentPluginId); if (dependantPluginDescriptor != null && !checkDependants(dependantPluginDescriptor, pluginId2Descriptor, check, processed)) { return false; } } } return true; } public static void addPluginClass(@NotNull String className, PluginId pluginId, boolean loaded) { ourPluginClasses.addPluginClass(className, pluginId, loaded); } @Nullable public static PluginId getPluginByClassName(@NotNull String className) { return ourPluginClasses.getPluginByClassName(className); } public static void dumpPluginClassStatistics() { ourPluginClasses.dumpPluginClassStatistics(); } static boolean isDependent(final IdeaPluginDescriptor descriptor, final PluginId on, Map<PluginId, IdeaPluginDescriptor> map, final boolean checkModuleDependencies) { for (PluginId id: descriptor.getDependentPluginIds()) { if (ArrayUtil.contains(id, (Object[])descriptor.getOptionalDependentPluginIds())) { continue; } if (!checkModuleDependencies && isModuleDependency(id)) { continue; } if (id.equals(on)) { return true; } final IdeaPluginDescriptor depDescriptor = map.get(id); if (depDescriptor != null && isDependent(depDescriptor, on, map, checkModuleDependencies)) { return true; } } return false; } static boolean hasModuleDependencies(final IdeaPluginDescriptor descriptor) { final PluginId[] dependentPluginIds = descriptor.getDependentPluginIds(); for (PluginId dependentPluginId : dependentPluginIds) { if (isModuleDependency(dependentPluginId)) { return true; } } return false; } static boolean shouldLoadPlugins() { try { // no plugins during bootstrap Class.forName("com.intellij.openapi.extensions.Extensions"); } catch (ClassNotFoundException e) { return false; } //noinspection HardCodedStringLiteral final String loadPlugins = System.getProperty("idea.load.plugins"); return loadPlugins == null || Boolean.TRUE.toString().equals(loadPlugins); } static void configureExtensions() { Extensions.setLogProvider(new IdeaLogProvider()); Extensions.registerAreaClass(ExtensionAreas.IDEA_PROJECT, null); Extensions.registerAreaClass(ExtensionAreas.IDEA_MODULE, ExtensionAreas.IDEA_PROJECT); } private static Method getAddUrlMethod(final ClassLoader loader) { return ReflectionUtil.getDeclaredMethod(loader instanceof URLClassLoader ? URLClassLoader.class : loader.getClass(), "addURL", URL.class); } @Nullable static ClassLoader createPluginClassLoader(@NotNull File[] classPath, @NotNull ClassLoader[] parentLoaders, @NotNull IdeaPluginDescriptor pluginDescriptor) { if (pluginDescriptor.getUseIdeaClassLoader()) { try { final ClassLoader loader = PluginManagerCore.class.getClassLoader(); final Method addUrlMethod = getAddUrlMethod(loader); for (File aClassPath : classPath) { final File file = aClassPath.getCanonicalFile(); addUrlMethod.invoke(loader, file.toURI().toURL()); } return loader; } catch (IOException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } PluginId pluginId = pluginDescriptor.getPluginId(); File pluginRoot = pluginDescriptor.getPath(); //if (classPath.length == 0) return null; if (isUnitTestMode()) return null; try { final List<URL> urls = new ArrayList<URL>(classPath.length); for (File aClassPath : classPath) { final File file = aClassPath.getCanonicalFile(); // it is critical not to have "." and ".." in classpath elements urls.add(file.toURI().toURL()); } return new PluginClassLoader(urls, parentLoaders, pluginId, pluginDescriptor.getVersion(), pluginRoot); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static void invalidatePlugins() { ourPlugins = null; ourDisabledPlugins = null; } public static boolean isPluginClass(String className) { return ourPlugins != null && getPluginByClassName(className) != null; } static void logPlugins() { List<String> loadedBundled = new ArrayList<String>(); List<String> disabled = new ArrayList<String>(); List<String> loadedCustom = new ArrayList<String>(); for (IdeaPluginDescriptor descriptor : ourPlugins) { final String version = descriptor.getVersion(); String s = descriptor.getName() + (version != null ? " (" + version + ")" : ""); if (descriptor.isEnabled()) { if (descriptor.isBundled() || SPECIAL_IDEA_PLUGIN.equals(descriptor.getName())) loadedBundled.add(s); else loadedCustom.add(s); } else { disabled.add(s); } } Collections.sort(loadedBundled); Collections.sort(loadedCustom); Collections.sort(disabled); getLogger().info("Loaded bundled plugins: " + StringUtil.join(loadedBundled, ", ")); if (!loadedCustom.isEmpty()) { getLogger().info("Loaded custom plugins: " + StringUtil.join(loadedCustom, ", ")); } if (!disabled.isEmpty()) { getLogger().info("Disabled plugins: " + StringUtil.join(disabled, ", ")); } } static ClassLoader[] getParentLoaders(Map<PluginId, ? extends IdeaPluginDescriptor> idToDescriptorMap, PluginId[] pluginIds) { if (isUnitTestMode()) return new ClassLoader[0]; final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(); for (final PluginId id : pluginIds) { IdeaPluginDescriptor pluginDescriptor = idToDescriptorMap.get(id); if (pluginDescriptor == null) { continue; // Might be an optional dependency } final ClassLoader loader = pluginDescriptor.getPluginClassLoader(); if (loader == null) { getLogger().error("Plugin class loader should be initialized for plugin " + id); } classLoaders.add(loader); } return classLoaders.toArray(new ClassLoader[classLoaders.size()]); } static int countPlugins(String pluginsPath) { File configuredPluginsDir = new File(pluginsPath); if (configuredPluginsDir.exists()) { String[] list = configuredPluginsDir.list(); if (list != null) { return list.length; } } return 0; } static Collection<URL> getClassLoaderUrls() { final ClassLoader classLoader = PluginManagerCore.class.getClassLoader(); final Class<? extends ClassLoader> aClass = classLoader.getClass(); try { @SuppressWarnings("unchecked") List<URL> urls = (List<URL>)aClass.getMethod("getUrls").invoke(classLoader); return urls; } catch (IllegalAccessException ignored) { } catch (InvocationTargetException ignored) { } catch (NoSuchMethodException ignored) { } if (classLoader instanceof URLClassLoader) { return Arrays.asList(((URLClassLoader)classLoader).getURLs()); } return Collections.emptyList(); } static void prepareLoadingPluginsErrorMessage(final String errorMessage) { if (!StringUtil.isEmptyOrSpaces(errorMessage)) { if (ApplicationManager.getApplication() != null && !ApplicationManager.getApplication().isHeadlessEnvironment() && !ApplicationManager.getApplication().isUnitTestMode()) { if (myPluginError == null) { myPluginError = errorMessage; } else { myPluginError += "\n" + errorMessage; } } else { getLogger().error(errorMessage); } } } private static void addModulesAsDependents(Map<PluginId, ? super IdeaPluginDescriptorImpl> map) { for (Map.Entry<String, IdeaPluginDescriptorImpl> entry : ourModulesToContainingPlugins.entrySet()) { map.put(PluginId.getId(entry.getKey()), entry.getValue()); } } static Comparator<IdeaPluginDescriptor> getPluginDescriptorComparator(final Map<PluginId, ? extends IdeaPluginDescriptor> idToDescriptorMap) { final Graph<PluginId> graph = createPluginIdGraph(idToDescriptorMap); final DFSTBuilder<PluginId> builder = new DFSTBuilder<PluginId>(graph); if (!builder.isAcyclic()) { builder.getSCCs().forEach(new TIntProcedure() { int myTNumber = 0; @Override public boolean execute(int size) { if (size > 1) { for (int j = 0; j < size; j++) { idToDescriptorMap.get(builder.getNodeByTNumber(myTNumber + j)).setEnabled(false); } } myTNumber += size; return true; } }); } final Comparator<PluginId> idComparator = builder.comparator(); return new Comparator<IdeaPluginDescriptor>() { @Override public int compare(@NotNull IdeaPluginDescriptor o1, @NotNull IdeaPluginDescriptor o2) { final PluginId pluginId1 = o1.getPluginId(); final PluginId pluginId2 = o2.getPluginId(); if (pluginId1.getIdString().equals(CORE_PLUGIN_ID)) return -1; if (pluginId2.getIdString().equals(CORE_PLUGIN_ID)) return 1; return idComparator.compare(pluginId1, pluginId2); } }; } private static Graph<PluginId> createPluginIdGraph(final Map<PluginId, ? extends IdeaPluginDescriptor> idToDescriptorMap) { final List<PluginId> ids = new ArrayList<PluginId>(idToDescriptorMap.keySet()); // this magic ensures that the dependent plugins always follow their dependencies in lexicographic order // needed to make sure that extensions are always in the same order Collections.sort(ids, new Comparator<PluginId>() { @Override public int compare(@NotNull PluginId o1, @NotNull PluginId o2) { return o2.getIdString().compareTo(o1.getIdString()); } }); return GraphGenerator.create(CachingSemiGraph.create(new GraphGenerator.SemiGraph<PluginId>() { @Override public Collection<PluginId> getNodes() { return ids; } @Override public Iterator<PluginId> getIn(PluginId pluginId) { final IdeaPluginDescriptor descriptor = idToDescriptorMap.get(pluginId); ArrayList<PluginId> plugins = new ArrayList<PluginId>(); for (PluginId dependentPluginId : descriptor.getDependentPluginIds()) { // check for missing optional dependency IdeaPluginDescriptor dep = idToDescriptorMap.get(dependentPluginId); if (dep != null) { plugins.add(dep.getPluginId()); } } return plugins.iterator(); } })); } @Nullable static IdeaPluginDescriptorImpl loadDescriptorFromDir(@NotNull File file, @NotNull String fileName) { File descriptorFile = new File(file, META_INF + File.separator + fileName); if (descriptorFile.exists()) { try { IdeaPluginDescriptorImpl descriptor = new IdeaPluginDescriptorImpl(file); descriptor.readExternal(descriptorFile.toURI().toURL()); return descriptor; } catch (XmlSerializationException e) { getLogger().info("Cannot load " + file, e); prepareLoadingPluginsErrorMessage("File '" + file.getName() + "' contains invalid plugin descriptor."); } catch (Throwable e) { getLogger().info("Cannot load " + file, e); } } return null; } @Nullable static IdeaPluginDescriptorImpl loadDescriptorFromJar(@NotNull File file, @NotNull String fileName) { try { String fileURL = StringUtil.replace(file.toURI().toASCIIString(), "!", "%21"); URL jarURL = new URL("jar:" + fileURL + "!/META-INF/" + fileName); ZipFile zipFile = ZipFileCache.acquire(file.getPath()); try { ZipEntry entry = zipFile.getEntry("META-INF/" + fileName); if (entry != null) { Document document = JDOMUtil.loadDocument(zipFile.getInputStream(entry)); IdeaPluginDescriptorImpl descriptor = new IdeaPluginDescriptorImpl(file); descriptor.readExternal(document, jarURL); return descriptor; } } finally { ZipFileCache.release(zipFile); } } catch (XmlSerializationException e) { getLogger().info("Cannot load " + file, e); prepareLoadingPluginsErrorMessage("File '" + file.getName() + "' contains invalid plugin descriptor."); } catch (Throwable e) { getLogger().info("Cannot load " + file, e); } return null; } @Nullable public static IdeaPluginDescriptorImpl loadDescriptorFromJar(@NotNull File file) { return loadDescriptorFromJar(file, PLUGIN_XML); } @Nullable public static IdeaPluginDescriptorImpl loadDescriptor(@NotNull final File file, @NotNull String fileName) { IdeaPluginDescriptorImpl descriptor = null; if (file.isDirectory()) { descriptor = loadDescriptorFromDir(file, fileName); if (descriptor == null) { File libDir = new File(file, "lib"); if (!libDir.isDirectory()) { return null; } final File[] files = libDir.listFiles(); if (files == null || files.length == 0) { return null; } Arrays.sort(files, new Comparator<File>() { @Override public int compare(@NotNull File o1, @NotNull File o2) { if (o2.getName().startsWith(file.getName())) return Integer.MAX_VALUE; if (o1.getName().startsWith(file.getName())) return -Integer.MAX_VALUE; if (o2.getName().startsWith("resources")) return -Integer.MAX_VALUE; if (o1.getName().startsWith("resources")) return Integer.MAX_VALUE; return 0; } }); for (final File f : files) { if (FileUtil.isJarOrZip(f)) { descriptor = loadDescriptorFromJar(f, fileName); if (descriptor != null) { descriptor.setPath(file); break; } // getLogger().warn("Cannot load descriptor from " + f.getName() + ""); } else if (f.isDirectory()) { IdeaPluginDescriptorImpl descriptor1 = loadDescriptorFromDir(f, fileName); if (descriptor1 != null) { if (descriptor != null) { getLogger().info("Cannot load " + file + " because two or more plugin.xml's detected"); return null; } descriptor = descriptor1; descriptor.setPath(file); } } } } } else if (StringUtil.endsWithIgnoreCase(file.getName(), ".jar") && file.exists()) { descriptor = loadDescriptorFromJar(file, fileName); } if (descriptor != null && descriptor.getOptionalConfigs() != null && !descriptor.getOptionalConfigs().isEmpty()) { final Map<PluginId, IdeaPluginDescriptorImpl> descriptors = new THashMap<PluginId, IdeaPluginDescriptorImpl>(descriptor.getOptionalConfigs().size()); for (Map.Entry<PluginId, String> entry: descriptor.getOptionalConfigs().entrySet()) { String optionalDescriptorName = entry.getValue(); assert !Comparing.equal(fileName, optionalDescriptorName) : "recursive dependency: "+ fileName; IdeaPluginDescriptorImpl optionalDescriptor = loadDescriptor(file, optionalDescriptorName); if (optionalDescriptor == null && !FileUtil.isJarOrZip(file)) { for (URL url : getClassLoaderUrls()) { if ("file".equals(url.getProtocol())) { optionalDescriptor = loadDescriptor(new File(decodeUrl(url.getFile())), optionalDescriptorName); if (optionalDescriptor != null) { break; } } } } if (optionalDescriptor != null) { descriptors.put(entry.getKey(), optionalDescriptor); } else { getLogger().info("Cannot find optional descriptor " + optionalDescriptorName); } } descriptor.setOptionalDescriptors(descriptors); } return descriptor; } public static void loadDescriptors(String pluginsPath, List<IdeaPluginDescriptorImpl> result, @Nullable StartupProgress progress, int pluginsCount) { loadDescriptors(new File(pluginsPath), result, progress, pluginsCount); } public static void loadDescriptors(@NotNull File pluginsHome, List<IdeaPluginDescriptorImpl> result, @Nullable StartupProgress progress, int pluginsCount) { final File[] files = pluginsHome.listFiles(); if (files != null) { int i = result.size(); for (File file : files) { final IdeaPluginDescriptorImpl descriptor = loadDescriptor(file, PLUGIN_XML); if (descriptor == null) continue; if (progress != null) { progress.showProgress(descriptor.getName(), PLUGINS_PROGRESS_MAX_VALUE * ((float)++i / pluginsCount)); } int oldIndex = result.indexOf(descriptor); if (oldIndex >= 0) { final IdeaPluginDescriptorImpl oldDescriptor = result.get(oldIndex); if (StringUtil.compareVersionNumbers(oldDescriptor.getVersion(), descriptor.getVersion()) < 0) { result.set(oldIndex, descriptor); } } else { result.add(descriptor); } } } } @Nullable static String filterBadPlugins(List<? extends IdeaPluginDescriptor> result, final Map<String, String> disabledPluginNames) { final Map<PluginId, IdeaPluginDescriptor> idToDescriptorMap = new THashMap<PluginId, IdeaPluginDescriptor>(); final StringBuilder message = new StringBuilder(); boolean pluginsWithoutIdFound = false; for (Iterator<? extends IdeaPluginDescriptor> it = result.iterator(); it.hasNext();) { final IdeaPluginDescriptor descriptor = it.next(); final PluginId id = descriptor.getPluginId(); if (id == null) { pluginsWithoutIdFound = true; } else if (idToDescriptorMap.containsKey(id)) { message.append("<br>"); message.append(IdeBundle.message("message.duplicate.plugin.id")); message.append(id); it.remove(); } else if (descriptor.isEnabled()) { idToDescriptorMap.put(id, descriptor); } } addModulesAsDependents(idToDescriptorMap); final List<String> disabledPluginIds = new SmartList<String>(); final LinkedHashSet<String> faultyDescriptors = new LinkedHashSet<String>(); for (final Iterator<? extends IdeaPluginDescriptor> it = result.iterator(); it.hasNext();) { final IdeaPluginDescriptor pluginDescriptor = it.next(); checkDependants(pluginDescriptor, new Function<PluginId, IdeaPluginDescriptor>() { @Override public IdeaPluginDescriptor fun(final PluginId pluginId) { return idToDescriptorMap.get(pluginId); } }, new Condition<PluginId>() { @Override public boolean value(final PluginId pluginId) { if (!idToDescriptorMap.containsKey(pluginId)) { pluginDescriptor.setEnabled(false); if (!pluginId.getIdString().startsWith(MODULE_DEPENDENCY_PREFIX)) { faultyDescriptors.add(pluginId.getIdString()); disabledPluginIds.add(pluginDescriptor.getPluginId().getIdString()); message.append("<br>"); final String name = pluginDescriptor.getName(); final IdeaPluginDescriptor descriptor = idToDescriptorMap.get(pluginId); String pluginName; if (descriptor == null) { pluginName = pluginId.getIdString(); if (disabledPluginNames.containsKey(pluginName)) { pluginName = disabledPluginNames.get(pluginName); } } else { pluginName = descriptor.getName(); } message.append(getDisabledPlugins().contains(pluginId.getIdString()) ? IdeBundle.message("error.required.plugin.disabled", name, pluginName) : IdeBundle.message("error.required.plugin.not.installed", name, pluginName)); } it.remove(); return false; } return true; } }); } if (!disabledPluginIds.isEmpty()) { myPlugins2Disable = disabledPluginIds; myPlugins2Enable = faultyDescriptors; message.append("<br>"); message.append("<br>").append("<a href=\"" + DISABLE + "\">Disable "); if (disabledPluginIds.size() == 1) { final PluginId pluginId2Disable = PluginId.getId(disabledPluginIds.iterator().next()); message.append(idToDescriptorMap.containsKey(pluginId2Disable) ? idToDescriptorMap.get(pluginId2Disable).getName() : pluginId2Disable.getIdString()); } else { message.append("not loaded plugins"); } message.append("</a>"); boolean possibleToEnable = true; for (String descriptor : faultyDescriptors) { if (disabledPluginNames.get(descriptor) == null) { possibleToEnable = false; break; } } if (possibleToEnable) { message.append("<br>").append("<a href=\"" + ENABLE + "\">Enable ").append(faultyDescriptors.size() == 1 ? disabledPluginNames.get(faultyDescriptors.iterator().next()) : " all necessary plugins").append("</a>"); } message.append("<br>").append("<a href=\"" + EDIT + "\">Open plugin manager</a>"); } if (pluginsWithoutIdFound) { message.append("<br>"); message.append(IdeBundle.message("error.plugins.without.id.found")); } if (message.length() > 0) { message.insert(0, IdeBundle.message("error.problems.found.loading.plugins")); return message.toString(); } return ""; } static void loadDescriptorsFromClassPath(@NotNull List<IdeaPluginDescriptorImpl> result, @Nullable StartupProgress progress) { Collection<URL> urls = getClassLoaderUrls(); String platformPrefix = System.getProperty(PlatformUtils.PLATFORM_PREFIX_KEY); int i = 0; for (URL url : urls) { i++; if ("file".equals(url.getProtocol())) { File file = new File(decodeUrl(url.getFile())); IdeaPluginDescriptorImpl platformPluginDescriptor = null; if (platformPrefix != null) { platformPluginDescriptor = loadDescriptor(file, platformPrefix + "Plugin.xml"); if (platformPluginDescriptor != null && !result.contains(platformPluginDescriptor)) { platformPluginDescriptor.setUseCoreClassLoader(true); result.add(platformPluginDescriptor); } } IdeaPluginDescriptorImpl pluginDescriptor = loadDescriptor(file, PLUGIN_XML); if (platformPrefix != null && pluginDescriptor != null && pluginDescriptor.getName().equals(SPECIAL_IDEA_PLUGIN)) { continue; } if (pluginDescriptor != null && !result.contains(pluginDescriptor)) { if (platformPluginDescriptor != null) { // if we found a regular plugin.xml in the same .jar/root as a platform-prefixed descriptor, use the core loader for it too pluginDescriptor.setUseCoreClassLoader(true); } result.add(pluginDescriptor); if (progress != null) { progress.showProgress("Plugin loaded: " + pluginDescriptor.getName(), PLUGINS_PROGRESS_MAX_VALUE * ((float)i / urls.size())); } } } } } @SuppressWarnings("deprecation") private static String decodeUrl(String file) { String quotePluses = StringUtil.replace(file, "+", "%2B"); return URLDecoder.decode(quotePluses); } static void loadDescriptorsFromProperty(final List<IdeaPluginDescriptorImpl> result) { final String pathProperty = System.getProperty(PROPERTY_PLUGIN_PATH); if (pathProperty == null) return; for (StringTokenizer t = new StringTokenizer(pathProperty, File.pathSeparator + ","); t.hasMoreTokens();) { String s = t.nextToken(); final IdeaPluginDescriptorImpl ideaPluginDescriptor = loadDescriptor(new File(s), PLUGIN_XML); if (ideaPluginDescriptor != null) { result.add(ideaPluginDescriptor); } } } public static IdeaPluginDescriptorImpl[] loadDescriptors(@Nullable StartupProgress progress) { if (ClassUtilCore.isLoadingOfExternalPluginsDisabled()) { return IdeaPluginDescriptorImpl.EMPTY_ARRAY; } final List<IdeaPluginDescriptorImpl> result = new ArrayList<IdeaPluginDescriptorImpl>(); int pluginsCount = countPlugins(PathManager.getPluginsPath()) + countPlugins(PathManager.getPreInstalledPluginsPath()); loadDescriptors(PathManager.getPluginsPath(), result, progress, pluginsCount); Application application = ApplicationManager.getApplication(); boolean fromSources = false; if (application == null || !application.isUnitTestMode()) { int size = result.size(); loadDescriptors(PathManager.getPreInstalledPluginsPath(), result, progress, pluginsCount); fromSources = size == result.size(); } loadDescriptorsFromProperty(result); loadDescriptorsFromClassPath(result, fromSources ? progress : null); IdeaPluginDescriptorImpl[] pluginDescriptors = result.toArray(new IdeaPluginDescriptorImpl[result.size()]); final Map<PluginId, IdeaPluginDescriptorImpl> idToDescriptorMap = new THashMap<PluginId, IdeaPluginDescriptorImpl>(); for (IdeaPluginDescriptorImpl descriptor : pluginDescriptors) { idToDescriptorMap.put(descriptor.getPluginId(), descriptor); } Arrays.sort(pluginDescriptors, getPluginDescriptorComparator(idToDescriptorMap)); return pluginDescriptors; } static void mergeOptionalConfigs(Map<PluginId, IdeaPluginDescriptorImpl> descriptors) { final Map<PluginId, IdeaPluginDescriptorImpl> descriptorsWithModules = new THashMap<PluginId, IdeaPluginDescriptorImpl>(descriptors); addModulesAsDependents(descriptorsWithModules); for (IdeaPluginDescriptorImpl descriptor : descriptors.values()) { final Map<PluginId, IdeaPluginDescriptorImpl> optionalDescriptors = descriptor.getOptionalDescriptors(); if (optionalDescriptors != null && !optionalDescriptors.isEmpty()) { for (Map.Entry<PluginId, IdeaPluginDescriptorImpl> entry: optionalDescriptors.entrySet()) { if (descriptorsWithModules.containsKey(entry.getKey())) { descriptor.mergeOptionalConfig(entry.getValue()); } } } } } public static void initClassLoader(@NotNull ClassLoader parentLoader, @NotNull IdeaPluginDescriptorImpl descriptor) { final List<File> classPath = descriptor.getClassPath(); final ClassLoader loader = createPluginClassLoader(classPath.toArray(new File[classPath.size()]), new ClassLoader[]{parentLoader}, descriptor); descriptor.setLoader(loader); } static BuildNumber getBuildNumber() { if (ourBuildNumber == null) { ourBuildNumber = BuildNumber.fromString(System.getProperty("idea.plugins.compatible.build")); if (ourBuildNumber == null) { ourBuildNumber = BUILD_NUMBER == null ? null : BuildNumber.fromString(BUILD_NUMBER); if (ourBuildNumber == null) { ourBuildNumber = BuildNumber.fallback(); } } } return ourBuildNumber; } static boolean shouldSkipPlugin(final IdeaPluginDescriptor descriptor, IdeaPluginDescriptor[] loaded) { final String idString = descriptor.getPluginId().getIdString(); if (CORE_PLUGIN_ID.equals(idString)) { return false; } //noinspection HardCodedStringLiteral final String pluginId = System.getProperty("idea.load.plugins.id"); if (pluginId == null) { if (descriptor instanceof IdeaPluginDescriptorImpl && !descriptor.isEnabled()) return true; if (!shouldLoadPlugins()) return true; } final List<String> pluginIds = pluginId == null ? null : StringUtil.split(pluginId, ","); final boolean checkModuleDependencies = !ourModulesToContainingPlugins.isEmpty() && !ourModulesToContainingPlugins.containsKey("com.intellij.modules.all"); if (checkModuleDependencies && !hasModuleDependencies(descriptor)) { return true; } boolean shouldLoad; //noinspection HardCodedStringLiteral final String loadPluginCategory = System.getProperty("idea.load.plugins.category"); if (loadPluginCategory != null) { shouldLoad = loadPluginCategory.equals(descriptor.getCategory()); } else { if (pluginIds != null) { shouldLoad = pluginIds.contains(idString); if (!shouldLoad) { Map<PluginId,IdeaPluginDescriptor> map = new THashMap<PluginId, IdeaPluginDescriptor>(); for (IdeaPluginDescriptor pluginDescriptor : loaded) { map.put(pluginDescriptor.getPluginId(), pluginDescriptor); } addModulesAsDependents(map); for (String id : pluginIds) { final IdeaPluginDescriptor descriptorFromProperty = map.get(PluginId.getId(id)); if (descriptorFromProperty != null && isDependent(descriptorFromProperty, descriptor.getPluginId(), map, checkModuleDependencies)) { shouldLoad = true; break; } } } } else { shouldLoad = !getDisabledPlugins().contains(idString); } if (shouldLoad && descriptor instanceof IdeaPluginDescriptorImpl) { if (isIncompatible(descriptor)) return true; } } return !shouldLoad; } public static boolean isIncompatible(final IdeaPluginDescriptor descriptor) { return isIncompatible(descriptor, getBuildNumber()); } public static boolean isIncompatible(final IdeaPluginDescriptor descriptor, @Nullable BuildNumber buildNumber) { if (buildNumber == null) { buildNumber = getBuildNumber(); } try { if (!StringUtil.isEmpty(descriptor.getSinceBuild())) { BuildNumber sinceBuild = BuildNumber.fromString(descriptor.getSinceBuild(), descriptor.getName()); if (sinceBuild.compareTo(buildNumber) > 0) { return true; } } if (!StringUtil.isEmpty(descriptor.getUntilBuild()) && !buildNumber.isSnapshot()) { BuildNumber untilBuild = BuildNumber.fromString(descriptor.getUntilBuild(), descriptor.getName()); if (untilBuild.compareTo(buildNumber) < 0) { return true; } } } catch (RuntimeException ignored) { } return false; } public static boolean shouldSkipPlugin(final IdeaPluginDescriptor descriptor) { if (descriptor instanceof IdeaPluginDescriptorImpl) { IdeaPluginDescriptorImpl descriptorImpl = (IdeaPluginDescriptorImpl)descriptor; Boolean skipped = descriptorImpl.getSkipped(); if (skipped != null) { return skipped.booleanValue(); } boolean result = shouldSkipPlugin(descriptor, ourPlugins) || isBrokenPlugin(descriptor); descriptorImpl.setSkipped(result); return result; } return shouldSkipPlugin(descriptor, ourPlugins) || isBrokenPlugin(descriptor); } static void initializePlugins(@Nullable StartupProgress progress) { configureExtensions(); final IdeaPluginDescriptorImpl[] pluginDescriptors = loadDescriptors(progress); final Class callerClass = ReflectionUtil.findCallerClass(1); assert callerClass != null; final ClassLoader parentLoader = callerClass.getClassLoader(); final List<IdeaPluginDescriptorImpl> result = new ArrayList<IdeaPluginDescriptorImpl>(); final Map<String, String> disabledPluginNames = new THashMap<String, String>(); List<String> brokenPluginsList = new SmartList<String>(); for (IdeaPluginDescriptorImpl descriptor : pluginDescriptors) { boolean skipped = shouldSkipPlugin(descriptor, pluginDescriptors); if (!skipped) { if (isBrokenPlugin(descriptor)) { brokenPluginsList.add(descriptor.getName()); skipped = true; } } if (!skipped) { final List<String> modules = descriptor.getModules(); if (modules != null) { for (String module : modules) { if (!ourModulesToContainingPlugins.containsKey(module)) { ourModulesToContainingPlugins.put(module, descriptor); } } } result.add(descriptor); } else { descriptor.setEnabled(false); disabledPluginNames.put(descriptor.getPluginId().getIdString(), descriptor.getName()); initClassLoader(parentLoader, descriptor); } } String errorMessage = filterBadPlugins(result, disabledPluginNames); if (!brokenPluginsList.isEmpty()) { if (!StringUtil.isEmptyOrSpaces(errorMessage)) { errorMessage += "<br>"; } errorMessage += "Following plugins are incompatible with current IDE build: " + StringUtil.join(brokenPluginsList, ", ") + "<br>\n" + StringUtil.notNullize(errorMessage); } final Map<PluginId, IdeaPluginDescriptorImpl> idToDescriptorMap = new THashMap<PluginId, IdeaPluginDescriptorImpl>(); for (IdeaPluginDescriptorImpl descriptor : result) { idToDescriptorMap.put(descriptor.getPluginId(), descriptor); } final IdeaPluginDescriptor corePluginDescriptor = idToDescriptorMap.get(PluginId.getId(CORE_PLUGIN_ID)); assert corePluginDescriptor != null : CORE_PLUGIN_ID + " not found; platform prefix is " + System.getProperty(PlatformUtils.PLATFORM_PREFIX_KEY); for (IdeaPluginDescriptorImpl descriptor : result) { if (descriptor != corePluginDescriptor) { descriptor.insertDependency(corePluginDescriptor); } } mergeOptionalConfigs(idToDescriptorMap); addModulesAsDependents(idToDescriptorMap); final Graph<PluginId> graph = createPluginIdGraph(idToDescriptorMap); final DFSTBuilder<PluginId> builder = new DFSTBuilder<PluginId>(graph); if (!builder.isAcyclic()) { if (!StringUtil.isEmptyOrSpaces(errorMessage)) { errorMessage += "<br>"; } final String cyclePresentation; if (ApplicationManager.getApplication().isInternal()) { final List<String> cycles = new ArrayList<String>(); builder.getSCCs().forEach(new TIntProcedure() { int myTNumber = 0; @Override public boolean execute(int size) { if (size > 1) { String cycle = ""; for (int j = 0; j < size; j++) { cycle += builder.getNodeByTNumber(myTNumber + j).getIdString() + " "; } cycles.add(cycle); } myTNumber += size; return true; } }); cyclePresentation = ": " + StringUtil.join(cycles, ";"); } else { final Couple<PluginId> circularDependency = builder.getCircularDependency(); final PluginId id = circularDependency.getFirst(); final PluginId parentId = circularDependency.getSecond(); cyclePresentation = id + "->" + parentId + "->...->" + id; } errorMessage += IdeBundle.message("error.plugins.should.not.have.cyclic.dependencies") + cyclePresentation; } prepareLoadingPluginsErrorMessage(errorMessage); final Comparator<PluginId> idComparator = builder.comparator(); // sort descriptors according to plugin dependencies Collections.sort(result, new Comparator<IdeaPluginDescriptor>() { @Override public int compare(@NotNull IdeaPluginDescriptor o1, @NotNull IdeaPluginDescriptor o2) { return idComparator.compare(o1.getPluginId(), o2.getPluginId()); } }); for (int i = 0; i < result.size(); i++) { ourId2Index.put(result.get(i).getPluginId(), i); } int i = 0; for (final IdeaPluginDescriptorImpl pluginDescriptor : result) { if (pluginDescriptor.getPluginId().getIdString().equals(CORE_PLUGIN_ID) || pluginDescriptor.isUseCoreClassLoader()) { pluginDescriptor.setLoader(parentLoader); } else { final List<File> classPath = pluginDescriptor.getClassPath(); final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds(); final ClassLoader[] parentLoaders = getParentLoaders(idToDescriptorMap, dependentPluginIds); final ClassLoader pluginClassLoader = createPluginClassLoader(classPath.toArray(new File[classPath.size()]), parentLoaders.length > 0 ? parentLoaders : new ClassLoader[] {parentLoader}, pluginDescriptor); pluginDescriptor.setLoader(pluginClassLoader); } if (progress != null) { progress.showProgress("", PLUGINS_PROGRESS_MAX_VALUE + (i++ / (float)result.size()) * 0.35f); } } registerExtensionPointsAndExtensions(Extensions.getRootArea(), result); Extensions.getRootArea().getExtensionPoint(Extensions.AREA_LISTENER_EXTENSION_POINT).registerExtension(new AreaListener() { @Override public void areaCreated(@NotNull String areaClass, @NotNull AreaInstance areaInstance) { registerExtensionPointsAndExtensions(Extensions.getArea(areaInstance), result); } @Override public void areaDisposing(@NotNull String areaClass, @NotNull AreaInstance areaInstance) { } }); ourPlugins = pluginDescriptors; } private static void registerExtensionPointsAndExtensions(ExtensionsArea area, List<IdeaPluginDescriptorImpl> loadedPlugins) { for (IdeaPluginDescriptorImpl descriptor : loadedPlugins) { descriptor.registerExtensionPoints(area); } ExtensionPoint[] extensionPoints = area.getExtensionPoints(); Set<String> epNames = new THashSet<String>(extensionPoints.length); for (ExtensionPoint point : extensionPoints) { epNames.add(point.getName()); } for (IdeaPluginDescriptorImpl descriptor : loadedPlugins) { for (String epName : epNames) { descriptor.registerExtensions(area, epName); } } } public static void initPlugins(@Nullable StartupProgress progress) { long start = System.currentTimeMillis(); try { initializePlugins(progress); } catch (RuntimeException e) { getLogger().error(e); throw e; } getLogger().info(ourPlugins.length + " plugins initialized in " + (System.currentTimeMillis() - start) + " ms"); logPlugins(); ClassUtilCore.clearJarURLCache(); } private static class LoggerHolder { private static final Logger ourLogger = Logger.getInstance("#com.intellij.ide.plugins.PluginManager"); } private static class IdeaLogProvider implements LogProvider { @Override public void error(String message) { getLogger().error(message); } @Override public void error(String message, Throwable t) { getLogger().error(message, t); } @Override public void error(Throwable t) { getLogger().error(t); } @Override public void warn(String message) { getLogger().info(message); } @Override public void warn(String message, Throwable t) { getLogger().info(message, t); } @Override public void warn(Throwable t) { getLogger().info(t); } } }
Cleanup (formatting)
platform/core-impl/src/com/intellij/ide/plugins/PluginManagerCore.java
Cleanup (formatting)
<ide><path>latform/core-impl/src/com/intellij/ide/plugins/PluginManagerCore.java <ide> descriptor = loadDescriptorFromDir(file, fileName); <ide> <ide> if (descriptor == null) { <del> File libDir = new File(file, "lib"); <del> if (!libDir.isDirectory()) { <del> return null; <del> } <del> final File[] files = libDir.listFiles(); <del> if (files == null || files.length == 0) { <del> return null; <del> } <del> Arrays.sort(files, new Comparator<File>() { <del> @Override <del> public int compare(@NotNull File o1, @NotNull File o2) { <del> if (o2.getName().startsWith(file.getName())) return Integer.MAX_VALUE; <del> if (o1.getName().startsWith(file.getName())) return -Integer.MAX_VALUE; <del> if (o2.getName().startsWith("resources")) return -Integer.MAX_VALUE; <del> if (o1.getName().startsWith("resources")) return Integer.MAX_VALUE; <del> return 0; <del> } <del> }); <del> for (final File f : files) { <del> if (FileUtil.isJarOrZip(f)) { <del> descriptor = loadDescriptorFromJar(f, fileName); <del> if (descriptor != null) { <del> descriptor.setPath(file); <del> break; <del> } <del>// getLogger().warn("Cannot load descriptor from " + f.getName() + ""); <del> } <del> else if (f.isDirectory()) { <del> IdeaPluginDescriptorImpl descriptor1 = loadDescriptorFromDir(f, fileName); <del> if (descriptor1 != null) { <del> if (descriptor != null) { <del> getLogger().info("Cannot load " + file + " because two or more plugin.xml's detected"); <del> return null; <del> } <del> descriptor = descriptor1; <del> descriptor.setPath(file); <del> } <del> } <del> } <del> } <add> File libDir = new File(file, "lib"); <add> if (!libDir.isDirectory()) { <add> return null; <add> } <add> final File[] files = libDir.listFiles(); <add> if (files == null || files.length == 0) { <add> return null; <add> } <add> Arrays.sort(files, new Comparator<File>() { <add> @Override <add> public int compare(@NotNull File o1, @NotNull File o2) { <add> if (o2.getName().startsWith(file.getName())) return Integer.MAX_VALUE; <add> if (o1.getName().startsWith(file.getName())) return -Integer.MAX_VALUE; <add> if (o2.getName().startsWith("resources")) return -Integer.MAX_VALUE; <add> if (o1.getName().startsWith("resources")) return Integer.MAX_VALUE; <add> return 0; <add> } <add> }); <add> for (final File f : files) { <add> if (FileUtil.isJarOrZip(f)) { <add> descriptor = loadDescriptorFromJar(f, fileName); <add> if (descriptor != null) { <add> descriptor.setPath(file); <add> break; <add> } <add> // getLogger().warn("Cannot load descriptor from " + f.getName() + ""); <add> } <add> else if (f.isDirectory()) { <add> IdeaPluginDescriptorImpl descriptor1 = loadDescriptorFromDir(f, fileName); <add> if (descriptor1 != null) { <add> if (descriptor != null) { <add> getLogger().info("Cannot load " + file + " because two or more plugin.xml's detected"); <add> return null; <add> } <add> descriptor = descriptor1; <add> descriptor.setPath(file); <add> } <add> } <add> } <add> } <ide> } <ide> else if (StringUtil.endsWithIgnoreCase(file.getName(), ".jar") && file.exists()) { <ide> descriptor = loadDescriptorFromJar(file, fileName); <ide> } <ide> <ide> if (descriptor != null && descriptor.getOptionalConfigs() != null && !descriptor.getOptionalConfigs().isEmpty()) { <del> final Map<PluginId, IdeaPluginDescriptorImpl> descriptors = new THashMap<PluginId, IdeaPluginDescriptorImpl>(descriptor.getOptionalConfigs().size()); <del> for (Map.Entry<PluginId, String> entry: descriptor.getOptionalConfigs().entrySet()) { <add> final Map<PluginId, IdeaPluginDescriptorImpl> descriptors = <add> new THashMap<PluginId, IdeaPluginDescriptorImpl>(descriptor.getOptionalConfigs().size()); <add> for (Map.Entry<PluginId, String> entry : descriptor.getOptionalConfigs().entrySet()) { <ide> String optionalDescriptorName = entry.getValue(); <del> assert !Comparing.equal(fileName, optionalDescriptorName) : "recursive dependency: "+ fileName; <add> assert !Comparing.equal(fileName, optionalDescriptorName) : "recursive dependency: " + fileName; <ide> <ide> IdeaPluginDescriptorImpl optionalDescriptor = loadDescriptor(file, optionalDescriptorName); <ide> if (optionalDescriptor == null && !FileUtil.isJarOrZip(file)) { <ide> } <ide> descriptor.setOptionalDescriptors(descriptors); <ide> } <add> <ide> return descriptor; <ide> } <ide>
Java
apache-2.0
f09cfa2b66f02c3a735e02e72faab49b07534fe3
0
rupertlssmith/lojix,rupertlssmith/lojix,rupertlssmith/lojix
/* * Copyright The Sett Ltd, 2005 to 2014. * * 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.thesett.aima.logic.fol.wam.machine; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; import java.util.Iterator; import java.util.Set; import com.thesett.aima.logic.fol.Variable; import com.thesett.aima.logic.fol.wam.compiler.WAMCallPoint; import com.thesett.aima.logic.fol.wam.compiler.WAMInstruction; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.ALLOCATE; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.ALLOCATE_N; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.CALL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.CON; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.CONTINUE; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.CUT; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.DEALLOCATE; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.EXECUTE; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.GET_CONST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.GET_LEVEL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.GET_LIST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.GET_STRUC; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.GET_VAL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.GET_VAR; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.LIS; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.NECK_CUT; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.NO_OP; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.PROCEED; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.PUT_CONST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.PUT_LIST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.PUT_STRUC; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.PUT_UNSAFE_VAL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.PUT_VAL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.PUT_VAR; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.REF; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.RETRY; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.RETRY_ME_ELSE; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SET_CONST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SET_LOCAL_VAL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SET_VAL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SET_VAR; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SET_VOID; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.STACK_ADDR; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.STR; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SUSPEND; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SWITCH_ON_CONST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SWITCH_ON_STRUC; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SWITCH_ON_TERM; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.TRUST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.TRUST_ME; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.TRY; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.TRY_ME_ELSE; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.UNIFY_CONST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.UNIFY_LOCAL_VAL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.UNIFY_VAL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.UNIFY_VAR; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.UNIFY_VOID; import com.thesett.common.util.SequenceIterator; import com.thesett.common.util.doublemaps.SymbolTable; /** * WAMResolvingJavaMachine is a byte code interpreter for WAM written in java. This is a direct implementation of the * instruction interpretations given in "Warren's Abstract Machine: A Tutorial Reconstruction". The pseudo algorithm * presented there can be read in the comments interspersed with the code. There are a couple of challenges to be solved * that are not presented in the book: * * <p/> * <ul> * <li>The book describes a STORE[addr] operation that loads or stores a heap, register or stack address. In the L1 and * L0 machines, only heap and register addresses had to be catered for. This made things easier because the registers * could be held at the top of the heap and a single common address range used for both. With increasing numbers of data * areas in the machine, and Java unable to use direct pointers into memory, a choice between having separate arrays for * each data area, or building all data areas within a single array has to be made. The single array approach was * chosen, because otherwise the addressing mode would need to be passed down into the 'deref' and 'unify' operations, * which would be complicated by having to choose amongst which of several arrays to operate on. An addressing mode has * had to be added to the instruction set, so that instructions loading data from registers or stack, can specify which. * Once addresses are resolved relative to the register or stack basis, the plain addresses offset to the base of the * whole data area are used, and it is these addresses that are passed to the 'deref' and 'unify' operations. * <li>The memory layout for the WAM is described in Appendix B.3. of the book. The same layout is usd for this machine * with the exception that the code area is held in a separate array. This follows the x86 machine convention of * separating code and data segments in memory, and also caters well for the sharing of the code area with the JVM as a * byte buffer. * <li>The deref operation is presented in the book as a recursive function. It was turned into an equivalent iterative * looping function instead. The deref operation returns multiple parameters, but as Java only supports single return * types, a choice had to be made between creating a simple class to hold the return types, or storing the return values * in member variables, and reading them from there. The member variables solution was chosen.</li> * </ul> * * <pre><p/><table id="crc"><caption>CRC Card</caption> * <tr><th> Responsibilities <th> Collaborations * <tr><td> Execute compiled WAM programs and queries. * <tr><td> Provide access to the heap. * </table></pre> * * @author Rupert Smith * @todo Think about unloading of byte code as well as insertion of of byte code. For example, would it be possible to * unload a program, and replace it with a different one? This would require re-linking of any references to the * original. So maybe want to add an index to reverse references. Call instructions should have their jumps * pre-calculated for speed, but perhaps should also put the bare f/n into them, for the case where they may * need to be updated. Also, add a semaphore to all call instructions, or at the entry point of all programs, * this would be used to synchronize live updates to programs in a running machine, as well as to add debugging * break points. * @todo Think about ability to grow (and shrink?) the heap. Might be best to do this at the same time as the first * garbage collector. */ public class WAMResolvingJavaMachine extends WAMResolvingMachine { /** Used for debugging. */ /* private static final Logger log = Logger.getLogger(WAMResolvingJavaMachine.class.getName()); */ /** Used for tracing instruction executions. */ private static final java.util.logging.Logger trace = java.util.logging.Logger.getLogger("TRACE.WAMResolvingJavaMachine"); /** The mask to extract an address from a tagged heap cell. */ public static final int AMASK = 0x3FFFFFFF; /** * The mask to extract a constant from a tagged heap cell. Arity of atomic constants is always zero, so just the * functor name needs to be stored and loaded to the heap cell. */ public static final int CMASK = 0xFFFFFFF; /** The shift to position the tag within a tagged heap cell. */ public static final int TSHIFT = 30; /** Defines the register capacity for the virtual machine. */ private static final int REG_SIZE = 256; /** Defines the heap size to use for the virtual machine. */ private static final int HEAP_SIZE = 10000; /** Defines the offset of the base of the heap in the data area. */ private static final int HEAP_BASE = REG_SIZE; /** Defines the stack size to use for the virtual machine. */ private static final int STACK_SIZE = 10000; /** Defines the offset of the base of the stack in the data area. */ private static final int STACK_BASE = REG_SIZE + HEAP_SIZE; /** Defines the trail size to use for the virtual machine. */ private static final int TRAIL_SIZE = 10000; /** Defines the offset of the base of the trail in the data area. */ private static final int TRAIL_BASE = REG_SIZE + HEAP_SIZE + STACK_SIZE; /** Defines the max unification stack depth for the virtual machine. */ private static final int PDL_SIZE = 1000; /** Defines the highest address in the data area of the virtual machine. */ private static final int TOP = REG_SIZE + HEAP_SIZE + STACK_SIZE + TRAIL_SIZE + PDL_SIZE; /** Defines the initial code area size for the virtual machine. */ private static final int CODE_SIZE = 10000; /** Holds the current instruction pointer into the code. */ private int ip; /** Holds the entire data segment of the machine. All registers, heaps and stacks are held in here. */ private IntBuffer data; /** Holds the heap pointer. */ private int hp; /** Holds the top of heap at the latest choice point. */ private int hbp; /** Holds the secondary heap pointer, used for the heap address of the next term to match. */ private int sp; /** Holds the unification stack pointer. */ private int up; /** Holds the environment base pointer. */ private int ep; /** Holds the choice point base pointer. */ private int bp; /** Holds the last call choice point pointer. */ private int b0; /** Holds the trail pointer. */ private int trp; /** Used to record whether the machine is in structure read or write mode. */ private boolean writeMode; /** Holds the heap cell tag from the most recent dereference. */ private byte derefTag; /** Holds the heap call value from the most recent dereference. */ private int derefVal; /** Indicates that the machine has been suspended, upon finding a solution. */ private boolean suspended; /** * Creates a unifying virtual machine for WAM with default heap sizes. * * @param symbolTable The symbol table for the machine. */ public WAMResolvingJavaMachine(SymbolTable<Integer, String, Object> symbolTable) { super(symbolTable); // Reset the machine to its initial state. reset(); } /** * Resets the machine, to its initial state. This clears any programs from the machine, and clears all of its stacks * and heaps. */ public void reset() { // Create fresh heaps, code areas and stacks. data = ByteBuffer.allocateDirect(TOP << 2).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer(); codeBuffer = ByteBuffer.allocateDirect(CODE_SIZE); codeBuffer.order(ByteOrder.LITTLE_ENDIAN); // Registers are on the top of the data area, the heap comes next. hp = HEAP_BASE; hbp = HEAP_BASE; sp = HEAP_BASE; // The stack comes after the heap. Pointers are zero initially, since no stack frames exist yet. ep = 0; bp = 0; b0 = 0; // The trail comes after the stack. trp = TRAIL_BASE; // The unification stack (PDL) is a push down stack at the end of the data area. up = TOP; // Turn off write mode. writeMode = false; // Reset the instruction pointer to that start of the code area, ready for fresh code to be loaded there. ip = 0; // Could probably not bother resetting these, but will do it anyway just to be sure. derefTag = 0; derefVal = 0; // The machine is initially not suspended. suspended = false; // Ensure that the overridden reset method of WAMBaseMachine is run too, to clear the call table. super.reset(); // Notify any debug monitor that the machine has been reset. if (monitor != null) { monitor.onReset(this); } } /** * Provides an iterator that generates all solutions on demand as a sequence of variable bindings. * * @return An iterator that generates all solutions on demand as a sequence of variable bindings. */ public Iterator<Set<Variable>> iterator() { return new SequenceIterator<Set<Variable>>() { public Set<Variable> nextInSequence() { return resolve(); } }; } /** * Sets the maximum number of search steps that a search method may take. If it fails to find a solution before this * number of steps has been reached its search method should fail and return null. What exactly constitutes a single * step, and the granularity of the step size, is open to different interpretation by different search algorithms. * The guideline is that this is the maximum number of states on which the goal test should be performed. * * @param max The maximum number of states to goal test. If this is zero or less then the maximum number of steps * will not be checked for. */ public void setMaxSteps(int max) { throw new UnsupportedOperationException("WAMResolvingJavaMachine does not support max steps limit on search."); } /** {@inheritDoc} */ public IntBuffer getDataBuffer() { return data; } /** {@inheritDoc} */ public WAMInternalRegisters getInternalRegisters() { return new WAMInternalRegisters(ip, hp, hbp, sp, up, ep, bp, b0, trp, writeMode); } /** {@inheritDoc} */ public WAMMemoryLayout getMemoryLayout() { return new WAMMemoryLayout(0, REG_SIZE, HEAP_BASE, HEAP_SIZE, STACK_BASE, STACK_SIZE, TRAIL_BASE, TRAIL_SIZE, TOP - PDL_SIZE, PDL_SIZE); } /** * {@inheritDoc} * * <p/>Does nothing. */ protected void codeAdded(ByteBuffer codeBuffer, int codeOffset, int length) { } /** {@inheritDoc} */ protected int derefStack(int a) { /*log.fine("Stack deref from " + (a + ep + 3) + ", ep = " + ep);*/ return deref(a + ep + 3); } /** {@inheritDoc} */ protected boolean execute(WAMCallPoint callPoint) { /*log.fine("protected boolean execute(WAMCallPoint callPoint): called");*/ boolean failed; // Check if the machine is being woken up from being suspended, in which case immediately fail in order to // trigger back-tracking to find more solutions. if (suspended) { failed = true; suspended = false; } else { ip = callPoint.entryPoint; uClear(); failed = false; } int numOfArgs = 0; // Holds the current continuation point. int cp = codeBuffer.position(); // Notify any debug monitor that execution is starting. if (monitor != null) { monitor.onExecute(this); } //while (!failed && (ip < code.length)) while (true) { // Attempt to backtrack on failure. if (failed) { failed = backtrack(); if (failed) { break; } } // Grab next instruction and switch on it. byte instruction = codeBuffer.get(ip); switch (instruction) { // put_struc Xi, f/n: case PUT_STRUC: { // grab addr, f/n byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); int fn = codeBuffer.getInt(ip + 3); trace.fine(ip + ": PUT_STRUC " + printSlot(xi, mode) + ", " + fn); // heap[h] <- STR, h + 1 data.put(hp, fn); // Xi <- heap[h] data.put(xi, structureAt(hp)); // h <- h + 2 hp += 1; // P <- instruction_size(P) ip += 7; break; } // set_var Xi: case SET_VAR: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": SET_VAR " + printSlot(xi, mode)); // heap[h] <- REF, h data.put(hp, refTo(hp)); // Xi <- heap[h] data.put(xi, data.get(hp)); // h <- h + 1 hp++; // P <- instruction_size(P) ip += 3; break; } // set_val Xi: case SET_VAL: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": SET_VAL " + printSlot(xi, mode)); // heap[h] <- Xi data.put(hp, data.get(xi)); // h <- h + 1 hp++; // P <- instruction_size(P) ip += 3; break; } // get_struc Xi, case GET_STRUC: { // grab addr, f/n byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); int fn = codeBuffer.getInt(ip + 3); trace.fine(ip + ": GET_STRUC " + printSlot(xi, mode) + ", " + fn); // addr <- deref(Xi); int addr = deref(xi); byte tag = derefTag; int a = derefVal; // switch STORE[addr] switch (tag) { // case REF: case REF: { // heap[h] <- STR, h + 1 data.put(hp, structureAt(hp + 1)); // heap[h+1] <- f/n data.put(hp + 1, fn); // bind(addr, h) bind(addr, hp); // h <- h + 2 hp += 2; // mode <- write writeMode = true; trace.fine("-> write mode"); break; } // case STR, a: case STR: { // if heap[a] = f/n if (data.get(a) == fn) { // s <- a + 1 sp = a + 1; // mode <- read writeMode = false; trace.fine("-> read mode"); } else { // fail failed = true; } break; } default: { // fail failed = true; } } // P <- instruction_size(P) ip += 7; break; } // unify_var Xi: case UNIFY_VAR: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": UNIFY_VAR " + printSlot(xi, mode)); // switch mode if (!writeMode) { // case read: // Xi <- heap[s] data.put(xi, data.get(sp)); } else { // case write: // heap[h] <- REF, h data.put(hp, refTo(hp)); // Xi <- heap[h] data.put(xi, data.get(hp)); // h <- h + 1 hp++; } // s <- s + 1 sp++; // P <- P + instruction_size(P) ip += 3; break; } // unify_val Xi: case UNIFY_VAL: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": UNIFY_VAL " + printSlot(xi, mode)); // switch mode if (!writeMode) { // case read: // unify (Xi, s) failed = !unify(xi, sp); } else { // case write: // heap[h] <- Xi data.put(hp, data.get(xi)); // h <- h + 1 hp++; } // s <- s + 1 sp++; // P <- P + instruction_size(P) ip += 3; break; } // put_var Xn, Ai: case PUT_VAR: { // grab addr, Ai byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); byte ai = codeBuffer.get(ip + 3); trace.fine(ip + ": PUT_VAR " + printSlot(xi, mode) + ", A" + ai); if (mode == WAMInstruction.REG_ADDR) { // heap[h] <- REF, H data.put(hp, refTo(hp)); // Xn <- heap[h] data.put(xi, data.get(hp)); // Ai <- heap[h] data.put(ai, data.get(hp)); } else { // STACK[addr] <- REF, addr data.put(xi, refTo(xi)); // Ai <- STACK[addr] data.put(ai, data.get(xi)); } // h <- h + 1 hp++; // P <- P + instruction_size(P) ip += 4; break; } // put_val Xn, Ai: case PUT_VAL: { // grab addr, Ai byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); byte ai = codeBuffer.get(ip + 3); trace.fine(ip + ": PUT_VAL " + printSlot(xi, mode) + ", A" + ai); // Ai <- Xn data.put(ai, data.get(xi)); // P <- P + instruction_size(P) ip += 4; break; } // get var Xn, Ai: case GET_VAR: { // grab addr, Ai byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); byte ai = codeBuffer.get(ip + 3); trace.fine(ip + ": GET_VAR " + printSlot(xi, mode) + ", A" + ai); // Xn <- Ai data.put(xi, data.get(ai)); // P <- P + instruction_size(P) ip += 4; break; } // get_val Xn, Ai: case GET_VAL: { // grab addr, Ai byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); byte ai = codeBuffer.get(ip + 3); trace.fine(ip + ": GET_VAL " + printSlot(xi, mode) + ", A" + ai); // unify (Xn, Ai) failed = !unify(xi, ai); // P <- P + instruction_size(P) ip += 4; break; } case PUT_CONST: { // grab addr, f/n byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); int fn = codeBuffer.getInt(ip + 3); trace.fine(ip + ": PUT_CONST " + printSlot(xi, mode) + ", " + fn); // Xi <- heap[h] data.put(xi, constantCell(fn)); // P <- instruction_size(P) ip += 7; break; } case GET_CONST: { // grab addr, Ai byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); int fn = codeBuffer.getInt(ip + 3); trace.fine(ip + ": GET_CONST " + printSlot(xi, mode) + ", " + fn); // addr <- deref(Xi) int addr = deref(xi); int tag = derefTag; int val = derefVal; failed = !unifyConst(fn, xi); // P <- P + instruction_size(P) ip += 7; break; } case SET_CONST: { int fn = codeBuffer.getInt(ip + 1); trace.fine(ip + ": SET_CONST " + fn); // heap[h] <- <CON, c> data.put(hp, constantCell(fn)); // h <- h + 1 hp++; // P <- instruction_size(P) ip += 5; break; } case UNIFY_CONST: { int fn = codeBuffer.getInt(ip + 1); trace.fine(ip + ": UNIFY_CONST " + fn); // switch mode if (!writeMode) { // case read: // addr <- deref(S) // unifyConst(fn, addr) failed = !unifyConst(fn, sp); } else { // case write: // heap[h] <- <CON, c> data.put(hp, constantCell(fn)); // h <- h + 1 hp++; } // s <- s + 1 sp++; // P <- P + instruction_size(P) ip += 5; break; } case PUT_LIST: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": PUT_LIST " + printSlot(xi, mode)); // Xi <- <LIS, H> data.put(xi, listCell(hp)); // P <- P + instruction_size(P) ip += 3; break; } case GET_LIST: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": GET_LIST " + printSlot(xi, mode)); int addr = deref(xi); int tag = derefTag; int val = derefVal; // case STORE[addr] of switch (tag) { case REF: { // <REF, _> : // HEAP[H] <- <LIS, H+1> data.put(hp, listCell(hp + 1)); // bind(addr, H) bind(addr, hp); // H <- H + 1 hp += 1; // mode <- write writeMode = true; trace.fine("-> write mode"); break; } case LIS: { // <LIS, a> : // S <- a sp = val; // mode <- read writeMode = false; trace.fine("-> read mode"); break; } default: { // other: fail <- true; failed = true; } } // P <- P + instruction_size(P) ip += 3; break; } case SET_VOID: { // grab N int n = (int) codeBuffer.get(ip + 1); trace.fine(ip + ": SET_VOID " + n); // for i <- H to H + n - 1 do // HEAP[i] <- <REF, i> for (int addr = hp; addr < (hp + n); addr++) { data.put(addr, refTo(addr)); } // H <- H + n hp += n; // P <- P + instruction_size(P) ip += 2; break; } case UNIFY_VOID: { // grab N int n = (int) codeBuffer.get(ip + 1); trace.fine(ip + ": UNIFY_VOID " + n); // case mode of if (!writeMode) { // read: S <- S + n sp += n; } else { // write: // for i <- H to H + n -1 do // HEAP[i] <- <REF, i> for (int addr = hp; addr < (hp + n); addr++) { data.put(addr, refTo(addr)); } // H <- H + n hp += n; } // P <- P + instruction_size(P) ip += 2; break; } // put_unsafe_val Yn, Ai: case PUT_UNSAFE_VAL: { // grab addr, Ai byte mode = codeBuffer.get(ip + 1); int yi = (int) codeBuffer.get(ip + 2) + (ep + 3); byte ai = codeBuffer.get(ip + 3); trace.fine(ip + ": PUT_UNSAFE_VAL " + printSlot(yi, WAMInstruction.STACK_ADDR) + ", A" + ai); int addr = deref(yi); if (addr < ep) { // Ai <- Xn data.put(ai, data.get(addr)); } else { data.put(hp, refTo(hp)); bind(addr, hp); data.put(ai, data.get(hp)); hp++; } // P <- P + instruction_size(P) ip += 4; break; } // set_local_val Xi: case SET_LOCAL_VAL: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": SET_LOCAL_VAL " + printSlot(xi, mode)); int addr = deref(xi); if (addr < ep) { data.put(hp, data.get(addr)); } else { data.put(hp, refTo(hp)); bind(addr, hp); } // h <- h + 1 hp++; // P <- P + instruction_size(P) ip += 3; break; } // unify_local_val Xi: case UNIFY_LOCAL_VAL: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": UNIFY_LOCAL_VAL " + printSlot(xi, mode)); // switch mode if (!writeMode) { // case read: // unify (Xi, s) failed = !unify(xi, sp); } else { // case write: int addr = deref(xi); if (addr < ep) { data.put(hp, data.get(addr)); } else { data.put(hp, refTo(hp)); bind(addr, hp); } // h <- h + 1 hp++; } // s <- s + 1 sp++; // P <- P + instruction_size(P) ip += 3; break; } // call @(p/n), perms: case CALL: { // grab @(p/n), perms int pn = codeBuffer.getInt(ip + 1); int n = codeBuffer.get(ip + 5); int numPerms = (int) codeBuffer.get(ip + 6); // num_of_args <- n numOfArgs = n; // Ensure that the predicate to call is known and linked in, otherwise fail. if (pn == -1) { failed = true; break; } // STACK[E + 2] <- numPerms data.put(ep + 2, numPerms); // CP <- P + instruction_size(P) cp = ip + 7; trace.fine(ip + ": CALL " + pn + "/" + n + ", " + numPerms + " (cp = " + cp + ")]"); // B0 <- B b0 = bp; // P <- @(p/n) ip = pn; break; } // execute @(p/n): case EXECUTE: { // grab @(p/n) int pn = codeBuffer.getInt(ip + 1); int n = codeBuffer.get(ip + 5); // num_of_args <- n numOfArgs = n; trace.fine(ip + ": EXECUTE " + pn + "/" + n + " (cp = " + cp + ")]"); // Ensure that the predicate to call is known and linked in, otherwise fail. if (pn == -1) { failed = true; break; } // B0 <- B b0 = bp; // P <- @(p/n) ip = pn; break; } // proceed: case PROCEED: { trace.fine(ip + ": PROCEED" + " (cp = " + cp + ")]"); // P <- CP ip = cp; break; } // allocate: case ALLOCATE: { // if E > B // then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 int esp = nextStackFrame(); // STACK[newE] <- E data.put(esp, ep); // STACK[E + 1] <- CP data.put(esp + 1, cp); // STACK[E + 2] <- N data.put(esp + 2, 0); // E <- newE // newE <- E + n + 3 ep = esp; trace.fine(ip + ": ALLOCATE"); trace.fine("-> env @ " + ep + " " + traceEnvFrame()); // P <- P + instruction_size(P) ip += 1; break; } // allocate N: case ALLOCATE_N: { // grab N int n = (int) codeBuffer.get(ip + 1); // if E > B // then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 int esp = nextStackFrame(); // STACK[newE] <- E data.put(esp, ep); // STACK[E + 1] <- CP data.put(esp + 1, cp); // STACK[E + 2] <- N data.put(esp + 2, n); // E <- newE // newE <- E + n + 3 ep = esp; trace.fine(ip + ": ALLOCATE_N " + n); trace.fine("-> env @ " + ep + " " + traceEnvFrame()); // P <- P + instruction_size(P) ip += 2; break; } // deallocate: case DEALLOCATE: { int newip = data.get(ep + 1); // E <- STACK[E] ep = data.get(ep); trace.fine(ip + ": DEALLOCATE"); trace.fine("<- env @ " + ep + " " + traceEnvFrame()); // CP <- STACK[E + 1] cp = newip; // P <- P + instruction_size(P) ip += 1; break; } // try me else L: case TRY_ME_ELSE: { // grab L int l = codeBuffer.getInt(ip + 1); // if E > B // then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 int esp = nextStackFrame(); // STACK[newB] <- num_of_args // n <- STACK[newB] int n = numOfArgs; data.put(esp, n); // for i <- 1 to n do STACK[newB + i] <- Ai for (int i = 0; i < n; i++) { data.put(esp + i + 1, data.get(i)); } // STACK[newB + n + 1] <- E data.put(esp + n + 1, ep); // STACK[newB + n + 2] <- CP data.put(esp + n + 2, cp); // STACK[newB + n + 3] <- B data.put(esp + n + 3, bp); // STACK[newB + n + 4] <- L data.put(esp + n + 4, l); // STACK[newB + n + 5] <- TR data.put(esp + n + 5, trp); // STACK[newB + n + 6] <- H data.put(esp + n + 6, hp); // STACK[newB + n + 7] <- B0 data.put(esp + n + 7, b0); // B <- new B bp = esp; // HB <- H hbp = hp; trace.fine(ip + ": TRY_ME_ELSE"); trace.fine("-> chp @ " + bp + " " + traceChoiceFrame()); // P <- P + instruction_size(P) ip += 5; break; } // retry me else L: case RETRY_ME_ELSE: { // grab L int l = codeBuffer.getInt(ip + 1); // n <- STACK[B] int n = data.get(bp); // for i <- 1 to n do Ai <- STACK[B + i] for (int i = 0; i < n; i++) { data.put(i, data.get(bp + i + 1)); } // E <- STACK[B + n + 1] ep = data.get(bp + n + 1); // CP <- STACK[B + n + 2] cp = data.get(bp + n + 2); // STACK[B + n + 4] <- L data.put(bp + n + 4, l); // unwind_trail(STACK[B + n + 5], TR) unwindTrail(data.get(bp + n + 5), trp); // TR <- STACK[B + n + 5] trp = data.get(bp + n + 5); // H <- STACK[B + n + 6] hp = data.get(bp + n + 6); // HB <- H hbp = hp; trace.fine(ip + ": RETRY_ME_ELSE"); trace.fine("-- chp @ " + bp + " " + traceChoiceFrame()); // P <- P + instruction_size(P) ip += 5; break; } // trust me (else fail): case TRUST_ME: { // n <- STACK[B] int n = data.get(bp); // for i <- 1 to n do Ai <- STACK[B + i] for (int i = 0; i < n; i++) { data.put(i, data.get(bp + i + 1)); } // E <- STACK[B + n + 1] ep = data.get(bp + n + 1); // CP <- STACK[B + n + 2] cp = data.get(bp + n + 2); // unwind_trail(STACK[B + n + 5], TR) unwindTrail(data.get(bp + n + 5), trp); // TR <- STACK[B + n + 5] trp = data.get(bp + n + 5); // H <- STACK[B + n + 6] hp = data.get(bp + n + 6); // HB <- STACK[B + n + 6] hbp = hp; // B <- STACK[B + n + 3] bp = data.get(bp + n + 3); trace.fine(ip + ": TRUST_ME"); trace.fine("<- chp @ " + bp + " " + traceChoiceFrame()); // P <- P + instruction_size(P) ip += 1; break; } case SWITCH_ON_TERM: { // grab labels int v = codeBuffer.getInt(ip + 1); int c = codeBuffer.getInt(ip + 5); int l = codeBuffer.getInt(ip + 9); int s = codeBuffer.getInt(ip + 13); int addr = deref(1); int tag = derefTag; // case STORE[deref(A1)] of switch (tag) { case REF: // <REF, _> : P <- V ip = v; break; case CON: // <CON, _> : P <- C ip = c; break; case LIS: // <LIS, _> : P <- L ip = l; break; case STR: // <STR, _> : P <- S ip = s; break; } break; } case SWITCH_ON_CONST: { // grab labels int t = codeBuffer.getInt(ip + 1); int n = codeBuffer.getInt(ip + 5); // <tag, val> <- STORE[deref(A1)] deref(1); int val = derefVal; // <found, inst> <- get_hash(val, T, N) int inst = getHash(val, t, n); // if found if (inst > 0) { // then P <- inst ip = inst; } else { // else backtrack failed = true; } break; } case SWITCH_ON_STRUC: { // grab labels int t = codeBuffer.getInt(ip + 1); int n = codeBuffer.getInt(ip + 5); // <tag, val> <- STORE[deref(A1)] deref(1); int val = derefVal; // <found, inst> <- get_hash(val, T, N) int inst = getHash(val, t, n); // if found if (inst > 0) { // then P <- inst ip = inst; } else { // else backtrack failed = true; } break; } case TRY: { // grab L int l = codeBuffer.getInt(ip + 1); // if E > B // then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 int esp = nextStackFrame(); // STACK[newB] <- num_of_args // n <- STACK[newB] int n = numOfArgs; data.put(esp, n); // for i <- 1 to n do STACK[newB + i] <- Ai for (int i = 0; i < n; i++) { data.put(esp + i + 1, data.get(i)); } // STACK[newB + n + 1] <- E data.put(esp + n + 1, ep); // STACK[newB + n + 2] <- CP data.put(esp + n + 2, cp); // STACK[newB + n + 3] <- B data.put(esp + n + 3, bp); // STACK[newB + n + 4] <- L data.put(esp + n + 4, ip + 5); // STACK[newB + n + 5] <- TR data.put(esp + n + 5, trp); // STACK[newB + n + 6] <- H data.put(esp + n + 6, hp); // STACK[newB + n + 7] <- B0 data.put(esp + n + 7, b0); // B <- new B bp = esp; // HB <- H hbp = hp; trace.fine(ip + ": TRY"); trace.fine("-> chp @ " + bp + " " + traceChoiceFrame()); // P <- L ip = l; break; } case RETRY: { // grab L int l = codeBuffer.getInt(ip + 1); // n <- STACK[B] int n = data.get(bp); // for i <- 1 to n do Ai <- STACK[B + i] for (int i = 0; i < n; i++) { data.put(i, data.get(bp + i + 1)); } // E <- STACK[B + n + 1] ep = data.get(bp + n + 1); // CP <- STACK[B + n + 2] cp = data.get(bp + n + 2); // STACK[B + n + 4] <- L data.put(bp + n + 4, ip + 5); // unwind_trail(STACK[B + n + 5], TR) unwindTrail(data.get(bp + n + 5), trp); // TR <- STACK[B + n + 5] trp = data.get(bp + n + 5); // H <- STACK[B + n + 6] hp = data.get(bp + n + 6); // HB <- H hbp = hp; trace.fine(ip + ": RETRY"); trace.fine("-- chp @ " + bp + " " + traceChoiceFrame()); // P <- L ip = l; break; } case TRUST: { // grab L int l = codeBuffer.getInt(ip + 1); // n <- STACK[B] int n = data.get(bp); // for i <- 1 to n do Ai <- STACK[B + i] for (int i = 0; i < n; i++) { data.put(i, data.get(bp + i + 1)); } // E <- STACK[B + n + 1] ep = data.get(bp + n + 1); // CP <- STACK[B + n + 2] cp = data.get(bp + n + 2); // unwind_trail(STACK[B + n + 5], TR) unwindTrail(data.get(bp + n + 5), trp); // TR <- STACK[B + n + 5] trp = data.get(bp + n + 5); // H <- STACK[B + n + 6] hp = data.get(bp + n + 6); // HB <- STACK[B + n + 6] hbp = hp; // B <- STACK[B + n + 3] bp = data.get(bp + n + 3); trace.fine(ip + ": TRUST"); trace.fine("<- chp @ " + bp + " " + traceChoiceFrame()); // P <- L ip = l; break; } case NECK_CUT: { if (bp > b0) { bp = b0; tidyTrail(); } ip += 1; break; } case GET_LEVEL: { int yn = (int) codeBuffer.get(ip + 1) + (ep + 3); data.put(yn, b0); ip += 2; break; } case CUT: { int yn = (int) codeBuffer.get(ip + 1) + (ep + 3); if (bp > yn) { bp = yn; tidyTrail(); } ip += 2; break; } case CONTINUE: { // grab L int l = codeBuffer.getInt(ip + 1); trace.fine(ip + ": CONTINUE " + l); ip = l; break; } case NO_OP: { trace.fine(ip + ": NO_OP"); ip += 1; break; } // suspend on success: case SUSPEND: { trace.fine(ip + ": SUSPEND"); ip += 1; suspended = true; return true; } } // Notify any debug monitor that the machine has been stepped. if (monitor != null) { monitor.onStep(this); } } return !failed; } /** * Pretty prints the current environment frame, for debugging purposes. * * @return The current environment frame, pretty printed. */ protected String traceEnvFrame() { return "env: [ ep = " + data.get(ep) + ", cp = " + data.get(ep + 1) + ", n = " + data.get(ep + 2) + "]"; } /** * Pretty prints the current choice point frame, for debugging purposes. * * @return The current choice point frame, pretty printed. */ protected String traceChoiceFrame() { if (bp == 0) { return ""; } int n = data.get(bp); return "choice: [ n = " + data.get(bp) + ", ep = " + data.get(bp + n + 1) + ", cp = " + data.get(bp + n + 2) + ", bp = " + data.get(bp + n + 3) + ", l = " + data.get(bp + n + 4) + ", trp = " + data.get(bp + n + 5) + ", hp = " + data.get(bp + n + 6) + ", b0 = " + data.get(bp + n + 7); } /** {@inheritDoc} */ protected int deref(int a) { // tag, value <- STORE[a] int addr = a; int tmp = data.get(a); derefTag = (byte) (tmp >>> TSHIFT); derefVal = tmp & AMASK; // while tag = REF and value != a while ((derefTag == WAMInstruction.REF)) { // tag, value <- STORE[a] addr = derefVal; tmp = data.get(derefVal); derefTag = (byte) (tmp >>> TSHIFT); tmp = tmp & AMASK; // Break on free var. if (derefVal == tmp) { break; } derefVal = tmp; } return addr; } /** * Gets the heap cell tag for the most recent dereference operation. * * @return The heap cell tag for the most recent dereference operation. */ protected byte getDerefTag() { return derefTag; } /** * Gets the heap cell value for the most recent dereference operation. * * @return The heap cell value for the most recent dereference operation. */ protected int getDerefVal() { return derefVal; } /** * Gets the value of the heap cell at the specified location. * * @param addr The address to fetch from the heap. * * @return The heap cell at the specified location. */ protected int getHeap(int addr) { return data.get(addr); } /** * Looks up a value (an interned name referring to a constant or structure), in the hash table of size n referred * to. * * @param val The value to look up. * @param t The offset of the start of the hash table. * @param n The size of the hash table in bytes. * * @return <tt>0</tt> iff no match is found, or a pointer into the code area of the matching branch. */ private int getHash(int val, int t, int n) { return 0; } /** * Creates a heap cell contents containing a structure tag, and the address of the structure. * * <p/>Note: This only creates the contents of the cell, it does not write it to the heap. * * @param addr The address of the structure. * * @return The heap cell contents referencing the structure. */ private int structureAt(int addr) { return (WAMInstruction.STR << TSHIFT) | (addr & AMASK); } /** * Creates a heap cell contents containing a reference. * * <p/>Note: This only creates the contents of the cell, it does not write it to the heap. * * @param addr The references address. * * @return The heap cell contents containing the reference. */ private int refTo(int addr) { return (WAMInstruction.REF << TSHIFT) | (addr & AMASK); } /** * Creates a heap cell contents containing a constant. * * <p/>Note: This only creates the contents of the cell, it does not write it to the heap. * * <p/>See the comment on {@link #CMASK} about the arity always being zero on a constant. * * @param fn The functor name and arity of the constant. Arity should always be zero. * * @return The heap cell contents containing the constant. */ private int constantCell(int fn) { return (CON << TSHIFT) | (fn & CMASK); } /** * Creates a heap cell contents containing a list pointer. * * <p/>Note: This only creates the contents of the cell, it does not write it to the heap. * * @param addr The address of the list contents. * * @return The heap cell contents containing the list pointer. */ private int listCell(int addr) { return (WAMInstruction.LIS << TSHIFT) | (addr & AMASK); } /** * Loads the contents of a register, or a stack slot, depending on the mode. * * @param mode The mode, {@link WAMInstruction#REG_ADDR} for register addressing, {@link WAMInstruction#STACK_ADDR} * for stack addressing. * * @return The contents of the register or stack slot. */ private int getRegisterOrStackSlot(byte mode) { return (int) codeBuffer.get(ip + 2) + ((mode == STACK_ADDR) ? (ep + 3) : 0); } /** * Computes the start of the next stack frame. This depends on whether the most recent stack frame is an environment * frame or a choice point frame, as these have different sizes. The size of the most recent type of frame is * computed and added to the current frame pointer to give the start of the next frame. * * @return The start of the next stack frame. */ private int nextStackFrame() { // if E > B // then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 if (ep == bp) { return STACK_BASE; } else if (ep > bp) { return ep + data.get(ep + 2) + 3; } else { return bp + data.get(bp) + 8; } } /** * Backtracks to the continuation label stored in the current choice point frame, if there is one. Otherwise returns * a fail to indicate that there are no more choice points, so no backtracking can be done. * * @return <tt>true</tt> iff this is the final failure, and there are no more choice points. */ private boolean backtrack() { // if B = bottom_of_stack if (bp == 0) { // then fail_and_exit_program return true; } else { // B0 <- STACK[B + STACK[B} + 7] b0 = data.get(bp + data.get(bp) + 7); // P <- STACK[B + STACK[B] + 4] ip = data.get(bp + data.get(bp) + 4); return false; } } /** * Creates a binding of one variable onto another. One of the supplied addresses must be an unbound variable. If * both are unbound variables, the higher (newer) address is bound to the lower (older) one. * * @param a1 The address of the first potential unbound variable to bind. * @param a2 The address of the second potential unbound variable to bind. */ private void bind(int a1, int a2) { // <t1, _> <- STORE[a1] int t1 = (byte) (data.get(a1) >>> TSHIFT); // <t2, _> <- STORE[a2] int t2 = (byte) (data.get(a2) >>> TSHIFT); // if (t1 = REF) /\ ((t2 != REF) \/ (a2 < a1)) if ((t1 == WAMInstruction.REF) && ((t2 != WAMInstruction.REF) || (a2 < a1))) { // STORE[a1] <- STORE[a2] data.put(a1, refTo(a2)); // trail(a1) trail(a1); } else if (t2 == WAMInstruction.REF) { // STORE[a2] <- STORE[a1] data.put(a2, refTo(a1)); // tail(a2) trail(a2); } } /** * Records the address of a binding onto the 'trail'. The trail pointer is advanced by one as part of this * operation. * * @param addr The binding address to add to the trail. */ private void trail(int addr) { // if (a < HB) \/ ((H < a) /\ (a < B)) if ((addr < hbp) || ((hp < addr) && (addr < bp))) { // TRAIL[TR] <- a data.put(trp, addr); // TR <- TR + 1 trp++; } } /** * Undoes variable bindings that have been recorded on the 'trail'. Addresses recorded on the trail are reset to REF * to self. * * @param a1 The start address within the trail to get the first binding address to clear. * @param a2 The end address within the trail, this is one higher than the last address to clear. */ private void unwindTrail(int a1, int a2) { // for i <- a1 to a2 - 1 do for (int addr = a1; addr < a2; addr++) { // STORE[TRAIL[i]] <- <REF, TRAIL[i]> int tmp = data.get(addr); data.put(tmp, refTo(tmp)); } } /** * Tidies trail when a choice point is being discarded, and a previous choice point it being made the current one. * * <p/>Copies trail bindings created since the choice point, into the trail as known to the previous choice point. * That is bindings on the heap created during the choice point (between HB and H). */ private void tidyTrail() { // Check that there is a current choice point to tidy down to. if (bp == 0) { return; } int i = data.get(bp + data.get(bp) + 5); while (i < trp) { int addr = data.get(i); if ((addr < hbp) || ((hp < addr) && (addr < bp))) { i++; } else { data.put(i, data.get(trp - 1)); trp--; } } } /** * Attempts to unify structures or references on the heap, given two references to them. Structures are matched * element by element, free references become bound. * * @param a1 The address of the first structure or reference. * @param a2 The address of the second structure or reference. * * @return <tt>true</tt> if the two structures unify, <tt>false</tt> otherwise. */ private boolean unify(int a1, int a2) { // pdl.push(a1) // pdl.push(a2) uPush(a1); uPush(a2); // fail <- false boolean fail = false; // while !empty(PDL) and not failed while (!uEmpty() && !fail) { // d1 <- deref(pdl.pop()) // d2 <- deref(pdl.pop()) // t1, v1 <- STORE[d1] // t2, v2 <- STORE[d2] int d1 = deref(uPop()); int t1 = derefTag; int v1 = derefVal; int d2 = deref(uPop()); int t2 = derefTag; int v2 = derefVal; // if (d1 != d2) if (d1 != d2) { // if (t1 = REF or t2 = REF) // bind(d1, d2) if ((t1 == WAMInstruction.REF)) { bind(d1, d2); } else if (t2 == WAMInstruction.REF) { bind(d1, d2); } else if (t2 == WAMInstruction.STR) { // f1/n1 <- STORE[v1] // f2/n2 <- STORE[v2] int fn1 = data.get(v1); int fn2 = data.get(v2); byte n1 = (byte) (fn1 >>> 24); // if f1 = f2 and n1 = n2 if (fn1 == fn2) { // for i <- 1 to n1 for (int i = 1; i <= n1; i++) { // pdl.push(v1 + i) // pdl.push(v2 + i) uPush(v1 + i); uPush(v2 + i); } } else { // fail <- true fail = true; } } else if (t2 == WAMInstruction.CON) { if ((t1 != WAMInstruction.CON) || (v1 != v2)) { fail = true; } } else if (t2 == WAMInstruction.LIS) { if (t1 != WAMInstruction.LIS) { fail = true; } else { uPush(v1); uPush(v2); uPush(v1 + 1); uPush(v2 + 1); } } } } return !fail; } /** * A simplified unification algorithm, for unifying against a constant. * * <p/>Attempts to unify a constant or references on the heap, with a constant. If the address leads to a free * variable on dereferencing, the variable is bound to the constant. If the address leads to a constant it is * compared with the passed in constant for equality, and unification succeeds when they are equal. * * @param fn The constant to unify with. * @param addr The address of the first constant or reference. * * @return <tt>true</tt> if the two constant unify, <tt>false</tt> otherwise. */ private boolean unifyConst(int fn, int addr) { boolean success; int deref = deref(addr); int tag = derefTag; int val = derefVal; // case STORE[addr] of switch (tag) { case REF: { // <REF, _> : // STORE[addr] <- <CON, c> data.put(deref, constantCell(fn)); // trail(addr) trail(deref); success = true; break; } case CON: { // <CON, c'> : // fail <- (c != c'); success = val == fn; break; } default: { // other: fail <- true; success = false; } } return success; } /** * Pushes a value onto the unification stack. * * @param val The value to push onto the stack. */ private void uPush(int val) { data.put(--up, val); } /** * Pops a value from the unification stack. * * @return The top value from the unification stack. */ private int uPop() { return data.get(up++); } /** Clears the unification stack. */ private void uClear() { up = TOP; } /** * Checks if the unification stack is empty. * * @return <tt>true</tt> if the unification stack is empty, <tt>false</tt> otherwise. */ private boolean uEmpty() { return up >= TOP; } /** * Pretty prints a variable allocation slot for tracing purposes. * * @param xi The allocation slot to print. * @param mode The addressing mode, stack or register. * * @return The pretty printed slot. */ private String printSlot(int xi, int mode) { return ((mode == STACK_ADDR) ? "Y" : "X") + ((mode == STACK_ADDR) ? (xi - ep - 3) : xi); } }
lojix/wam_prolog/src/main/com/thesett/aima/logic/fol/wam/machine/WAMResolvingJavaMachine.java
/* * Copyright The Sett Ltd, 2005 to 2014. * * 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.thesett.aima.logic.fol.wam.machine; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; import java.util.Iterator; import java.util.Set; import com.thesett.aima.logic.fol.Variable; import com.thesett.aima.logic.fol.wam.compiler.WAMCallPoint; import com.thesett.aima.logic.fol.wam.compiler.WAMInstruction; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.ALLOCATE; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.ALLOCATE_N; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.CALL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.CON; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.CONTINUE; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.CUT; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.DEALLOCATE; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.EXECUTE; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.GET_CONST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.GET_LEVEL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.GET_LIST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.GET_STRUC; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.GET_VAL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.GET_VAR; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.LIS; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.NECK_CUT; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.NO_OP; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.PROCEED; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.PUT_CONST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.PUT_LIST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.PUT_STRUC; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.PUT_UNSAFE_VAL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.PUT_VAL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.PUT_VAR; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.REF; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.RETRY; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.RETRY_ME_ELSE; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SET_CONST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SET_LOCAL_VAL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SET_VAL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SET_VAR; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SET_VOID; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.STACK_ADDR; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.STR; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SUSPEND; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SWITCH_ON_CONST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SWITCH_ON_STRUC; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.SWITCH_ON_TERM; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.TRUST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.TRUST_ME; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.TRY; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.TRY_ME_ELSE; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.UNIFY_CONST; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.UNIFY_LOCAL_VAL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.UNIFY_VAL; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.UNIFY_VAR; import static com.thesett.aima.logic.fol.wam.compiler.WAMInstruction.UNIFY_VOID; import com.thesett.common.util.SequenceIterator; import com.thesett.common.util.doublemaps.SymbolTable; /** * WAMResolvingJavaMachine is a byte code interpreter for WAM written in java. This is a direct implementation of the * instruction interpretations given in "Warren's Abstract Machine: A Tutorial Reconstruction". The pseudo algorithm * presented there can be read in the comments interspersed with the code. There are a couple of challenges to be solved * that are not presented in the book: * * <p/> * <ul> * <li>The book describes a STORE[addr] operation that loads or stores a heap, register or stack address. In the L1 and * L0 machines, only heap and register addresses had to be catered for. This made things easier because the registers * could be held at the top of the heap and a single common address range used for both. With increasing numbers of data * areas in the machine, and Java unable to use direct pointers into memory, a choice between having separate arrays for * each data area, or building all data areas within a single array has to be made. The single array approach was * chosen, because otherwise the addressing mode would need to be passed down into the 'deref' and 'unify' operations, * which would be complicated by having to choose amongst which of several arrays to operate on. An addressing mode has * had to be added to the instruction set, so that instructions loading data from registers or stack, can specify which. * Once addresses are resolved relative to the register or stack basis, the plain addresses offset to the base of the * whole data area are used, and it is these addresses that are passed to the 'deref' and 'unify' operations. * <li>The memory layout for the WAM is described in Appendix B.3. of the book. The same layout is usd for this machine * with the exception that the code area is held in a separate array. This follows the x86 machine convention of * separating code and data segments in memory, and also caters well for the sharing of the code area with the JVM as a * byte buffer. * <li>The deref operation is presented in the book as a recursive function. It was turned into an equivalent iterative * looping function instead. The deref operation returns multiple parameters, but as Java only supports single return * types, a choice had to be made between creating a simple class to hold the return types, or storing the return values * in member variables, and reading them from there. The member variables solution was chosen.</li> * </ul> * * <pre><p/><table id="crc"><caption>CRC Card</caption> * <tr><th> Responsibilities <th> Collaborations * <tr><td> Execute compiled WAM programs and queries. * <tr><td> Provide access to the heap. * </table></pre> * * @author Rupert Smith * @todo Think about unloading of byte code as well as insertion of of byte code. For example, would it be possible to * unload a program, and replace it with a different one? This would require re-linking of any references to the * original. So maybe want to add an index to reverse references. Call instructions should have their jumps * pre-calculated for speed, but perhaps should also put the bare f/n into them, for the case where they may * need to be updated. Also, add a semaphore to all call instructions, or at the entry point of all programs, * this would be used to synchronize live updates to programs in a running machine, as well as to add debugging * break points. * @todo Think about ability to grow (and shrink?) the heap. Might be best to do this at the same time as the first * garbage collector. */ public class WAMResolvingJavaMachine extends WAMResolvingMachine { /** Used for debugging. */ /* private static final Logger log = Logger.getLogger(WAMResolvingJavaMachine.class.getName()); */ /** Used for tracing instruction executions. */ private static final java.util.logging.Logger trace = java.util.logging.Logger.getLogger("TRACE.WAMResolvingJavaMachine"); /** The mask to extract an address from a tagged heap cell. */ public static final int AMASK = 0x3FFFFFFF; /** * The mask to extract a constant from a tagged heap cell. Arity of atomic constants is always zero, so just the * functor name needs to be stored and loaded to the heap cell. */ public static final int CMASK = 0xFFFFFFF; /** The shift to position the tag within a tagged heap cell. */ public static final int TSHIFT = 30; /** Defines the register capacity for the virtual machine. */ private static final int REG_SIZE = 256; /** Defines the heap size to use for the virtual machine. */ private static final int HEAP_SIZE = 10000; /** Defines the offset of the base of the heap in the data area. */ private static final int HEAP_BASE = REG_SIZE; /** Defines the stack size to use for the virtual machine. */ private static final int STACK_SIZE = 10000; /** Defines the offset of the base of the stack in the data area. */ private static final int STACK_BASE = REG_SIZE + HEAP_SIZE; /** Defines the trail size to use for the virtual machine. */ private static final int TRAIL_SIZE = 10000; /** Defines the offset of the base of the trail in the data area. */ private static final int TRAIL_BASE = REG_SIZE + HEAP_SIZE + STACK_SIZE; /** Defines the max unification stack depth for the virtual machine. */ private static final int PDL_SIZE = 1000; /** Defines the highest address in the data area of the virtual machine. */ private static final int TOP = REG_SIZE + HEAP_SIZE + STACK_SIZE + TRAIL_SIZE + PDL_SIZE; /** Defines the initial code area size for the virtual machine. */ private static final int CODE_SIZE = 10000; /** Holds the current instruction pointer into the code. */ private int ip; /** Holds the entire data segment of the machine. All registers, heaps and stacks are held in here. */ private IntBuffer data; /** Holds the heap pointer. */ private int hp; /** Holds the top of heap at the latest choice point. */ private int hbp; /** Holds the secondary heap pointer, used for the heap address of the next term to match. */ private int sp; /** Holds the unification stack pointer. */ private int up; /** Holds the environment base pointer. */ private int ep; /** Holds the choice point base pointer. */ private int bp; /** Holds the last call choice point pointer. */ private int b0; /** Holds the trail pointer. */ private int trp; /** Used to record whether the machine is in structure read or write mode. */ private boolean writeMode; /** Holds the heap cell tag from the most recent dereference. */ private byte derefTag; /** Holds the heap call value from the most recent dereference. */ private int derefVal; /** Indicates that the machine has been suspended, upon finding a solution. */ private boolean suspended; /** * Creates a unifying virtual machine for WAM with default heap sizes. * * @param symbolTable The symbol table for the machine. */ public WAMResolvingJavaMachine(SymbolTable<Integer, String, Object> symbolTable) { super(symbolTable); // Reset the machine to its initial state. reset(); } /** * Resets the machine, to its initial state. This clears any programs from the machine, and clears all of its stacks * and heaps. */ public void reset() { // Create fresh heaps, code areas and stacks. data = ByteBuffer.allocateDirect(TOP << 2).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer(); codeBuffer = ByteBuffer.allocateDirect(CODE_SIZE); codeBuffer.order(ByteOrder.LITTLE_ENDIAN); // Registers are on the top of the data area, the heap comes next. hp = HEAP_BASE; hbp = HEAP_BASE; sp = HEAP_BASE; // The stack comes after the heap. Pointers are zero initially, since no stack frames exist yet. ep = 0; bp = 0; b0 = 0; // The trail comes after the stack. trp = TRAIL_BASE; // The unification stack (PDL) is a push down stack at the end of the data area. up = TOP; // Turn off write mode. writeMode = false; // Reset the instruction pointer to that start of the code area, ready for fresh code to be loaded there. ip = 0; // Could probably not bother resetting these, but will do it anyway just to be sure. derefTag = 0; derefVal = 0; // The machine is initially not suspended. suspended = false; // Ensure that the overridden reset method of WAMBaseMachine is run too, to clear the call table. super.reset(); // Notify any debug monitor that the machine has been reset. if (monitor != null) { monitor.onReset(this); } } /** * Provides an iterator that generates all solutions on demand as a sequence of variable bindings. * * @return An iterator that generates all solutions on demand as a sequence of variable bindings. */ public Iterator<Set<Variable>> iterator() { return new SequenceIterator<Set<Variable>>() { public Set<Variable> nextInSequence() { return resolve(); } }; } /** * Sets the maximum number of search steps that a search method may take. If it fails to find a solution before this * number of steps has been reached its search method should fail and return null. What exactly constitutes a single * step, and the granularity of the step size, is open to different interpretation by different search algorithms. * The guideline is that this is the maximum number of states on which the goal test should be performed. * * @param max The maximum number of states to goal test. If this is zero or less then the maximum number of steps * will not be checked for. */ public void setMaxSteps(int max) { throw new UnsupportedOperationException("WAMResolvingJavaMachine does not support max steps limit on search."); } /** {@inheritDoc} */ public IntBuffer getDataBuffer() { return data; } /** {@inheritDoc} */ public WAMInternalRegisters getInternalRegisters() { return new WAMInternalRegisters(ip, hp, hbp, sp, up, ep, bp, b0, trp, writeMode); } /** {@inheritDoc} */ public WAMMemoryLayout getMemoryLayout() { return new WAMMemoryLayout(0, REG_SIZE, HEAP_BASE, HEAP_SIZE, STACK_BASE, STACK_SIZE, TRAIL_BASE, TRAIL_SIZE, TOP - PDL_SIZE, PDL_SIZE); } /** * {@inheritDoc} * * <p/>Does nothing. */ protected void codeAdded(ByteBuffer codeBuffer, int codeOffset, int length) { } /** {@inheritDoc} */ protected int derefStack(int a) { /*log.fine("Stack deref from " + (a + ep + 3) + ", ep = " + ep);*/ return deref(a + ep + 3); } /** {@inheritDoc} */ protected boolean execute(WAMCallPoint callPoint) { /*log.fine("protected boolean execute(WAMCallPoint callPoint): called");*/ boolean failed; // Check if the machine is being woken up from being suspended, in which case immediately fail in order to // trigger back-tracking to find more solutions. if (suspended) { failed = true; suspended = false; } else { ip = callPoint.entryPoint; uClear(); failed = false; } int numOfArgs = 0; // Holds the current continuation point. int cp = codeBuffer.position(); // Notify any debug monitor that execution is starting. if (monitor != null) { monitor.onExecute(this); } //while (!failed && (ip < code.length)) while (true) { // Attempt to backtrack on failure. if (failed) { failed = backtrack(); if (failed) { break; } } // Grab next instruction and switch on it. byte instruction = codeBuffer.get(ip); switch (instruction) { // put_struc Xi, f/n: case PUT_STRUC: { // grab addr, f/n byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); int fn = codeBuffer.getInt(ip + 3); trace.fine(ip + ": PUT_STRUC " + printSlot(xi, mode) + ", " + fn); // heap[h] <- STR, h + 1 data.put(hp, fn); // Xi <- heap[h] data.put(xi, structureAt(hp)); // h <- h + 2 hp += 1; // P <- instruction_size(P) ip += 7; break; } // set_var Xi: case SET_VAR: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": SET_VAR " + printSlot(xi, mode)); // heap[h] <- REF, h data.put(hp, refTo(hp)); // Xi <- heap[h] data.put(xi, data.get(hp)); // h <- h + 1 hp++; // P <- instruction_size(P) ip += 3; break; } // set_val Xi: case SET_VAL: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": SET_VAL " + printSlot(xi, mode)); // heap[h] <- Xi data.put(hp, data.get(xi)); // h <- h + 1 hp++; // P <- instruction_size(P) ip += 3; break; } // get_struc Xi, case GET_STRUC: { // grab addr, f/n byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); int fn = codeBuffer.getInt(ip + 3); trace.fine(ip + ": GET_STRUC " + printSlot(xi, mode) + ", " + fn); // addr <- deref(Xi); int addr = deref(xi); byte tag = derefTag; int a = derefVal; // switch STORE[addr] switch (tag) { // case REF: case REF: { // heap[h] <- STR, h + 1 data.put(hp, structureAt(hp + 1)); // heap[h+1] <- f/n data.put(hp + 1, fn); // bind(addr, h) bind(addr, hp); // h <- h + 2 hp += 2; // mode <- write writeMode = true; trace.fine("-> write mode"); break; } // case STR, a: case STR: { // if heap[a] = f/n if (data.get(a) == fn) { // s <- a + 1 sp = a + 1; // mode <- read writeMode = false; trace.fine("-> read mode"); } else { // fail failed = true; } break; } default: { // fail failed = true; } } // P <- instruction_size(P) ip += 7; break; } // unify_var Xi: case UNIFY_VAR: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": UNIFY_VAR " + printSlot(xi, mode)); // switch mode if (!writeMode) { // case read: // Xi <- heap[s] data.put(xi, data.get(sp)); } else { // case write: // heap[h] <- REF, h data.put(hp, refTo(hp)); // Xi <- heap[h] data.put(xi, data.get(hp)); // h <- h + 1 hp++; } // s <- s + 1 sp++; // P <- P + instruction_size(P) ip += 3; break; } // unify_val Xi: case UNIFY_VAL: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": UNIFY_VAL " + printSlot(xi, mode)); // switch mode if (!writeMode) { // case read: // unify (Xi, s) failed = !unify(xi, sp); } else { // case write: // heap[h] <- Xi data.put(hp, data.get(xi)); // h <- h + 1 hp++; } // s <- s + 1 sp++; // P <- P + instruction_size(P) ip += 3; break; } // put_var Xn, Ai: case PUT_VAR: { // grab addr, Ai byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); byte ai = codeBuffer.get(ip + 3); trace.fine(ip + ": PUT_VAR " + printSlot(xi, mode) + ", A" + ai); if (mode == WAMInstruction.REG_ADDR) { // heap[h] <- REF, H data.put(hp, refTo(hp)); // Xn <- heap[h] data.put(xi, data.get(hp)); // Ai <- heap[h] data.put(ai, data.get(hp)); } else { // STACK[addr] <- REF, addr data.put(xi, refTo(xi)); // Ai <- STACK[addr] data.put(ai, data.get(xi)); } // h <- h + 1 hp++; // P <- P + instruction_size(P) ip += 4; break; } // put_val Xn, Ai: case PUT_VAL: { // grab addr, Ai byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); byte ai = codeBuffer.get(ip + 3); trace.fine(ip + ": PUT_VAL " + printSlot(xi, mode) + ", A" + ai); // Ai <- Xn data.put(ai, data.get(xi)); // P <- P + instruction_size(P) ip += 4; break; } // get var Xn, Ai: case GET_VAR: { // grab addr, Ai byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); byte ai = codeBuffer.get(ip + 3); trace.fine(ip + ": GET_VAR " + printSlot(xi, mode) + ", A" + ai); // Xn <- Ai data.put(xi, data.get(ai)); // P <- P + instruction_size(P) ip += 4; break; } // get_val Xn, Ai: case GET_VAL: { // grab addr, Ai byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); byte ai = codeBuffer.get(ip + 3); trace.fine(ip + ": GET_VAL " + printSlot(xi, mode) + ", A" + ai); // unify (Xn, Ai) failed = !unify(xi, ai); // P <- P + instruction_size(P) ip += 4; break; } case PUT_CONST: { // grab addr, f/n byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); int fn = codeBuffer.getInt(ip + 3); trace.fine(ip + ": PUT_CONST " + printSlot(xi, mode) + ", " + fn); // Xi <- heap[h] data.put(xi, constantCell(fn)); // P <- instruction_size(P) ip += 7; break; } case GET_CONST: { // grab addr, Ai byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); int fn = codeBuffer.getInt(ip + 3); trace.fine(ip + ": GET_CONST " + printSlot(xi, mode) + ", " + fn); // addr <- deref(Xi) int addr = deref(xi); int tag = derefTag; int val = derefVal; failed = !unifyConst(fn, xi); // P <- P + instruction_size(P) ip += 7; break; } case SET_CONST: { int fn = codeBuffer.getInt(ip + 1); trace.fine(ip + ": SET_CONST " + fn); // heap[h] <- <CON, c> data.put(hp, constantCell(fn)); // h <- h + 1 hp++; // P <- instruction_size(P) ip += 5; break; } case UNIFY_CONST: { int fn = codeBuffer.getInt(ip + 1); trace.fine(ip + ": UNIFY_CONST " + fn); // switch mode if (!writeMode) { // case read: // addr <- deref(S) // unifyConst(fn, addr) failed = !unifyConst(fn, sp); } else { // case write: // heap[h] <- <CON, c> data.put(hp, constantCell(fn)); // h <- h + 1 hp++; } // s <- s + 1 sp++; // P <- P + instruction_size(P) ip += 5; break; } case PUT_LIST: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": PUT_LIST " + printSlot(xi, mode)); // Xi <- <LIS, H> data.put(xi, listCell(hp)); // P <- P + instruction_size(P) ip += 3; break; } case GET_LIST: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": GET_LIST " + printSlot(xi, mode)); int addr = deref(xi); int tag = derefTag; int val = derefVal; // case STORE[addr] of switch (tag) { case REF: { // <REF, _> : // HEAP[H] <- <LIS, H+1> data.put(hp, listCell(hp + 1)); // bind(addr, H) bind(addr, hp); // H <- H + 1 hp += 1; // mode <- write writeMode = true; trace.fine("-> write mode"); break; } case LIS: { // <LIS, a> : // S <- a sp = val; // mode <- read writeMode = false; trace.fine("-> read mode"); break; } default: { // other: fail <- true; failed = true; } } // P <- P + instruction_size(P) ip += 3; break; } case SET_VOID: { // grab N int n = (int) codeBuffer.get(ip + 1); trace.fine(ip + ": SET_VOID " + n); // for i <- H to H + n - 1 do // HEAP[i] <- <REF, i> for (int addr = hp; addr < (hp + n); addr++) { data.put(addr, refTo(addr)); } // H <- H + n hp += n; // P <- P + instruction_size(P) ip += 2; break; } case UNIFY_VOID: { // grab N int n = (int) codeBuffer.get(ip + 1); trace.fine(ip + ": UNIFY_VOID " + n); // case mode of if (!writeMode) { // read: S <- S + n sp += n; } else { // write: // for i <- H to H + n -1 do // HEAP[i] <- <REF, i> for (int addr = hp; addr < (hp + n); addr++) { data.put(addr, refTo(addr)); } // H <- H + n hp += n; } // P <- P + instruction_size(P) ip += 2; break; } // put_unsafe_val Yn, Ai: case PUT_UNSAFE_VAL: { // grab addr, Ai byte mode = codeBuffer.get(ip + 1); int yi = (int) codeBuffer.get(ip + 2) + (ep + 3); byte ai = codeBuffer.get(ip + 3); trace.fine(ip + ": PUT_UNSAFE_VAL " + printSlot(yi, WAMInstruction.STACK_ADDR) + ", A" + ai); int addr = deref(yi); if (addr < ep) { // Ai <- Xn data.put(ai, data.get(addr)); } else { data.put(hp, refTo(hp)); bind(addr, hp); data.put(ai, data.get(hp)); hp++; } // P <- P + instruction_size(P) ip += 4; break; } // set_local_val Xi: case SET_LOCAL_VAL: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": SET_LOCAL_VAL " + printSlot(xi, mode)); int addr = deref(xi); if (addr < ep) { data.put(hp, data.get(addr)); } else { data.put(hp, refTo(hp)); bind(addr, hp); } // h <- h + 1 hp++; // P <- P + instruction_size(P) ip += 3; break; } // unify_local_val Xi: case UNIFY_LOCAL_VAL: { // grab addr byte mode = codeBuffer.get(ip + 1); int xi = getRegisterOrStackSlot(mode); trace.fine(ip + ": UNIFY_LOCAL_VAL " + printSlot(xi, mode)); // switch mode if (!writeMode) { // case read: // unify (Xi, s) failed = !unify(xi, sp); } else { // case write: int addr = deref(xi); if (addr < ep) { data.put(hp, data.get(addr)); } else { data.put(hp, refTo(hp)); bind(addr, hp); } // h <- h + 1 hp++; } // s <- s + 1 sp++; // P <- P + instruction_size(P) ip += 3; break; } // call @(p/n), perms: case CALL: { // grab @(p/n), perms int pn = codeBuffer.getInt(ip + 1); int n = codeBuffer.get(ip + 5); int numPerms = (int) codeBuffer.get(ip + 6); // num_of_args <- n numOfArgs = n; // Ensure that the predicate to call is known and linked in, otherwise fail. if (pn == -1) { failed = true; break; } // STACK[E + 2] <- numPerms data.put(ep + 2, numPerms); // CP <- P + instruction_size(P) cp = ip + 7; trace.fine(ip + ": CALL " + pn + "/" + n + ", " + numPerms + " (cp = " + cp + ")]"); // B0 <- B b0 = bp; // P <- @(p/n) ip = pn; break; } // execute @(p/n): case EXECUTE: { // grab @(p/n) int pn = codeBuffer.getInt(ip + 1); int n = codeBuffer.get(ip + 5); // num_of_args <- n numOfArgs = n; trace.fine(ip + ": EXECUTE " + pn + "/" + n + " (cp = " + cp + ")]"); // Ensure that the predicate to call is known and linked in, otherwise fail. if (pn == -1) { failed = true; break; } // B0 <- B b0 = bp; // P <- @(p/n) ip = pn; break; } // proceed: case PROCEED: { trace.fine(ip + ": PROCEED" + " (cp = " + cp + ")]"); // P <- CP ip = cp; break; } // allocate: case ALLOCATE: { // if E > B // then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 int esp = nextStackFrame(); // STACK[newE] <- E data.put(esp, ep); // STACK[E + 1] <- CP data.put(esp + 1, cp); // STACK[E + 2] <- N data.put(esp + 2, 0); // E <- newE // newE <- E + n + 3 ep = esp; trace.fine(ip + ": ALLOCATE"); trace.fine("-> env @ " + ep + " " + traceEnvFrame()); // P <- P + instruction_size(P) ip += 1; break; } // allocate N: case ALLOCATE_N: { // grab N int n = (int) codeBuffer.get(ip + 1); // if E > B // then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 int esp = nextStackFrame(); // STACK[newE] <- E data.put(esp, ep); // STACK[E + 1] <- CP data.put(esp + 1, cp); // STACK[E + 2] <- N data.put(esp + 2, n); // E <- newE // newE <- E + n + 3 ep = esp; trace.fine(ip + ": ALLOCATE_N " + n); trace.fine("-> env @ " + ep + " " + traceEnvFrame()); // P <- P + instruction_size(P) ip += 2; break; } // deallocate: case DEALLOCATE: { int newip = data.get(ep + 1); // E <- STACK[E] ep = data.get(ep); trace.fine(ip + ": DEALLOCATE"); trace.fine("<- env @ " + ep + " " + traceEnvFrame()); // CP <- STACK[E + 1] cp = newip; // P <- P + instruction_size(P) ip += 1; break; } // try me else L: case TRY_ME_ELSE: { // grab L int l = codeBuffer.getInt(ip + 1); // if E > B // then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 int esp = nextStackFrame(); // STACK[newB] <- num_of_args // n <- STACK[newB] int n = numOfArgs; data.put(esp, n); // for i <- 1 to n do STACK[newB + i] <- Ai for (int i = 0; i < n; i++) { data.put(esp + i + 1, data.get(i)); } // STACK[newB + n + 1] <- E data.put(esp + n + 1, ep); // STACK[newB + n + 2] <- CP data.put(esp + n + 2, cp); // STACK[newB + n + 3] <- B data.put(esp + n + 3, bp); // STACK[newB + n + 4] <- L data.put(esp + n + 4, l); // STACK[newB + n + 5] <- TR data.put(esp + n + 5, trp); // STACK[newB + n + 6] <- H data.put(esp + n + 6, hp); // STACK[newB + n + 7] <- B0 data.put(esp + n + 7, b0); // B <- new B bp = esp; // HB <- H hbp = hp; trace.fine(ip + ": TRY_ME_ELSE"); trace.fine("-> chp @ " + bp + " " + traceChoiceFrame()); // P <- P + instruction_size(P) ip += 5; break; } // retry me else L: case RETRY_ME_ELSE: { // grab L int l = codeBuffer.getInt(ip + 1); // n <- STACK[B] int n = data.get(bp); // for i <- 1 to n do Ai <- STACK[B + i] for (int i = 0; i < n; i++) { data.put(i, data.get(bp + i + 1)); } // E <- STACK[B + n + 1] ep = data.get(bp + n + 1); // CP <- STACK[B + n + 2] cp = data.get(bp + n + 2); // STACK[B + n + 4] <- L data.put(bp + n + 4, l); // unwind_trail(STACK[B + n + 5], TR) unwindTrail(data.get(bp + n + 5), trp); // TR <- STACK[B + n + 5] trp = data.get(bp + n + 5); // H <- STACK[B + n + 6] hp = data.get(bp + n + 6); // HB <- H hbp = hp; trace.fine(ip + ": RETRY_ME_ELSE"); trace.fine("-- chp @ " + bp + " " + traceChoiceFrame()); // P <- P + instruction_size(P) ip += 5; break; } // trust me (else fail): case TRUST_ME: { // n <- STACK[B] int n = data.get(bp); // for i <- 1 to n do Ai <- STACK[B + i] for (int i = 0; i < n; i++) { data.put(i, data.get(bp + i + 1)); } // E <- STACK[B + n + 1] ep = data.get(bp + n + 1); // CP <- STACK[B + n + 2] cp = data.get(bp + n + 2); // unwind_trail(STACK[B + n + 5], TR) unwindTrail(data.get(bp + n + 5), trp); // TR <- STACK[B + n + 5] trp = data.get(bp + n + 5); // H <- STACK[B + n + 6] hp = data.get(bp + n + 6); // HB <- STACK[B + n + 6] hbp = hp; // B <- STACK[B + n + 3] bp = data.get(bp + n + 3); trace.fine(ip + ": TRUST_ME"); trace.fine("<- chp @ " + bp + " " + traceChoiceFrame()); // P <- P + instruction_size(P) ip += 1; break; } case SWITCH_ON_TERM: { // grab labels int v = codeBuffer.getInt(ip + 1); int c = codeBuffer.getInt(ip + 5); int l = codeBuffer.getInt(ip + 9); int s = codeBuffer.getInt(ip + 13); int addr = deref(1); int tag = derefTag; // case STORE[deref(A1)] of switch (tag) { case REF: // <REF, _> : P <- V ip = v; break; case CON: // <CON, _> : P <- C ip = c; break; case LIS: // <LIS, _> : P <- L ip = l; break; case STR: // <STR, _> : P <- S ip = s; break; } break; } case SWITCH_ON_CONST: { // grab labels int t = codeBuffer.getInt(ip + 1); int n = codeBuffer.getInt(ip + 5); // <tag, val> <- STORE[deref(A1)] deref(1); int val = derefVal; // <found, inst> <- get_hash(val, T, N) int inst = getHash(val, t, n); // if found if (inst > 0) { // then P <- inst ip = inst; } else { // else backtrack failed = true; } break; } case SWITCH_ON_STRUC: { // grab labels int t = codeBuffer.getInt(ip + 1); int n = codeBuffer.getInt(ip + 5); // <tag, val> <- STORE[deref(A1)] deref(1); int val = derefVal; // <found, inst> <- get_hash(val, T, N) int inst = getHash(val, t, n); // if found if (inst > 0) { // then P <- inst ip = inst; } else { // else backtrack failed = true; } break; } case TRY: { // grab L int l = codeBuffer.getInt(ip + 1); // if E > B // then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 int esp = nextStackFrame(); // STACK[newB] <- num_of_args // n <- STACK[newB] int n = numOfArgs; data.put(esp, n); // for i <- 1 to n do STACK[newB + i] <- Ai for (int i = 0; i < n; i++) { data.put(esp + i + 1, data.get(i)); } // STACK[newB + n + 1] <- E data.put(esp + n + 1, ep); // STACK[newB + n + 2] <- CP data.put(esp + n + 2, cp); // STACK[newB + n + 3] <- B data.put(esp + n + 3, bp); // STACK[newB + n + 4] <- L data.put(esp + n + 4, ip + 5); // STACK[newB + n + 5] <- TR data.put(esp + n + 5, trp); // STACK[newB + n + 6] <- H data.put(esp + n + 6, hp); // STACK[newB + n + 7] <- B0 data.put(esp + n + 7, b0); // B <- new B bp = esp; // HB <- H hbp = hp; trace.fine(ip + ": TRY"); trace.fine("-> chp @ " + bp + " " + traceChoiceFrame()); // P <- L ip = l; break; } case RETRY: { // grab L int l = codeBuffer.getInt(ip + 1); // n <- STACK[B] int n = data.get(bp); // for i <- 1 to n do Ai <- STACK[B + i] for (int i = 0; i < n; i++) { data.put(i, data.get(bp + i + 1)); } // E <- STACK[B + n + 1] ep = data.get(bp + n + 1); // CP <- STACK[B + n + 2] cp = data.get(bp + n + 2); // STACK[B + n + 4] <- L data.put(bp + n + 4, ip + 5); // unwind_trail(STACK[B + n + 5], TR) unwindTrail(data.get(bp + n + 5), trp); // TR <- STACK[B + n + 5] trp = data.get(bp + n + 5); // H <- STACK[B + n + 6] hp = data.get(bp + n + 6); // HB <- H hbp = hp; trace.fine(ip + ": RETRY"); trace.fine("-- chp @ " + bp + " " + traceChoiceFrame()); // P <- L ip = l; break; } case TRUST: { // grab L int l = codeBuffer.getInt(ip + 1); // n <- STACK[B] int n = data.get(bp); // for i <- 1 to n do Ai <- STACK[B + i] for (int i = 0; i < n; i++) { data.put(i, data.get(bp + i + 1)); } // E <- STACK[B + n + 1] ep = data.get(bp + n + 1); // CP <- STACK[B + n + 2] cp = data.get(bp + n + 2); // unwind_trail(STACK[B + n + 5], TR) unwindTrail(data.get(bp + n + 5), trp); // TR <- STACK[B + n + 5] trp = data.get(bp + n + 5); // H <- STACK[B + n + 6] hp = data.get(bp + n + 6); // HB <- STACK[B + n + 6] hbp = hp; // B <- STACK[B + n + 3] bp = data.get(bp + n + 3); trace.fine(ip + ": TRUST"); trace.fine("<- chp @ " + bp + " " + traceChoiceFrame()); // P <- L ip = l; break; } case NECK_CUT: { if (bp > b0) { bp = b0; tidyTrail(); } ip += 1; break; } case GET_LEVEL: { int yn = (int) codeBuffer.get(ip + 1) + (ep + 3); data.put(yn, b0); ip += 2; break; } case CUT: { int yn = (int) codeBuffer.get(ip + 1) + (ep + 3); if (bp > yn) { bp = yn; tidyTrail(); } ip += 2; break; } case CONTINUE: { // grab L int l = codeBuffer.getInt(ip + 1); trace.fine(ip + ": CONTINUE " + l); ip = l; break; } case NO_OP: { trace.fine(ip + ": NO_OP"); ip += 1; break; } // suspend on success: case SUSPEND: { trace.fine(ip + ": SUSPEND"); ip += 1; suspended = true; return true; } } // Notify any debug monitor that the machine has been stepped. if (monitor != null) { monitor.onStep(this); } } return !failed; } /** * Pretty prints the current environment frame, for debugging purposes. * * @return The current environment frame, pretty printed. */ protected String traceEnvFrame() { return "env: [ ep = " + data.get(ep) + ", cp = " + data.get(ep + 1) + ", n = " + data.get(ep + 2) + "]"; } /** * Pretty prints the current choice point frame, for debugging purposes. * * @return The current choice point frame, pretty printed. */ protected String traceChoiceFrame() { if (bp == 0) { return ""; } int n = data.get(bp); return "choice: [ n = " + data.get(bp) + ", ep = " + data.get(bp + n + 1) + ", cp = " + data.get(bp + n + 2) + ", bp = " + data.get(bp + n + 3) + ", l = " + data.get(bp + n + 4) + ", trp = " + data.get(bp + n + 5) + ", hp = " + data.get(bp + n + 6) + ", b0 = " + data.get(bp + n + 7); } /** {@inheritDoc} */ protected int deref(int a) { // tag, value <- STORE[a] int addr = a; int tmp = data.get(a); derefTag = (byte) (tmp >>> TSHIFT); derefVal = tmp & AMASK; // while tag = REF and value != a while ((derefTag == WAMInstruction.REF)) { // tag, value <- STORE[a] addr = derefVal; tmp = data.get(derefVal); derefTag = (byte) (tmp >>> TSHIFT); tmp = tmp & AMASK; // Break on free var. if (derefVal == tmp) { break; } derefVal = tmp; } return addr; } /** * Gets the heap cell tag for the most recent dereference operation. * * @return The heap cell tag for the most recent dereference operation. */ protected byte getDerefTag() { return derefTag; } /** * Gets the heap cell value for the most recent dereference operation. * * @return The heap cell value for the most recent dereference operation. */ protected int getDerefVal() { return derefVal; } /** * Gets the value of the heap cell at the specified location. * * @param addr The address to fetch from the heap. * * @return The heap cell at the specified location. */ protected int getHeap(int addr) { return data.get(addr); } /** * Looks up a value (an interned name referring to a constant or structure), in the hash table of size n referred * to. * * @param val The value to look up. * @param t The offset of the start of the hash table. * @param n The size of the hash table in bytes. * * @return <tt>0</tt> iff no match is found, or a pointer into the code area of the matching branch. */ private int getHash(int val, int t, int n) { return 0; } /** * Creates a heap cell contents containing a structure tag, and the address of the structure. * * <p/>Note: This only creates the contents of the cell, it does not write it to the heap. * * @param addr The address of the structure. * * @return The heap cell contents referencing the structure. */ private int structureAt(int addr) { return (WAMInstruction.STR << TSHIFT) | (addr & AMASK); } /** * Creates a heap cell contents containing a reference. * * <p/>Note: This only creates the contents of the cell, it does not write it to the heap. * * @param addr The references address. * * @return The heap cell contents containing the reference. */ private int refTo(int addr) { return (WAMInstruction.REF << TSHIFT) | (addr & AMASK); } /** * Creates a heap cell contents containing a constant. * * <p/>Note: This only creates the contents of the cell, it does not write it to the heap. * * <p/>See the comment on {@link #CMASK} about the arity always being zero on a constant. * * @param fn The functor name and arity of the constant. Arity should always be zero. * * @return The heap cell contents containing the constant. */ private int constantCell(int fn) { return (CON << TSHIFT) | (fn & CMASK); } /** * Creates a heap cell contents containing a list pointer. * * <p/>Note: This only creates the contents of the cell, it does not write it to the heap. * * @param addr The address of the list contents. * * @return The heap cell contents containing the list pointer. */ private int listCell(int addr) { return (WAMInstruction.LIS << TSHIFT) | (addr & AMASK); } /** * Loads the contents of a register, or a stack slot, depending on the mode. * * @param mode The mode, {@link WAMInstruction#REG_ADDR} for register addressing, {@link WAMInstruction#STACK_ADDR} * for stack addressing. * * @return The contents of the register or stack slot. */ private int getRegisterOrStackSlot(byte mode) { return (int) codeBuffer.get(ip + 2) + ((mode == STACK_ADDR) ? (ep + 3) : 0); } /** * Computes the start of the next stack frame. This depends on whether the most recent stack frame is an environment * frame or a choice point frame, as these have different sizes. The size of the most recent type of frame is * computed and added to the current frame pointer to give the start of the next frame. * * @return The start of the next stack frame. */ private int nextStackFrame() { // if E > B // then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 if (ep == bp) { return STACK_BASE; } else if (ep > bp) { return ep + data.get(ep + 2) + 3; } else { return bp + data.get(bp) + 8; } } /** * Backtracks to the continuation label stored in the current choice point frame, if there is one. Otherwise returns * a fail to indicate that there are no more choice points, so no backtracking can be done. * * @return <tt>true</tt> iff this is the final failure, and there are no more choice points. */ private boolean backtrack() { // if B = bottom_of_stack if (bp == 0) { // then fail_and_exit_program return true; } else { // B0 <- STACK[B + STACK[B} + 7] b0 = data.get(bp + data.get(bp) + 7); // P <- STACK[B + STACK[B] + 4] ip = data.get(bp + data.get(bp) + 4); return false; } } /** * Creates a binding of one variable onto another. One of the supplied addresses must be an unbound variable. If * both are unbound variables, the higher (newer) address is bound to the lower (older) one. * * @param a1 The address of the first potential unbound variable to bind. * @param a2 The address of the second potential unbound variable to bind. */ private void bind(int a1, int a2) { // <t1, _> <- STORE[a1] int t1 = (byte) (data.get(a1) >>> TSHIFT); // <t2, _> <- STORE[a2] int t2 = (byte) (data.get(a2) >>> TSHIFT); // if (t1 = REF) /\ ((t2 != REF) \/ (a2 < a1)) if ((t1 == WAMInstruction.REF) && ((t2 != WAMInstruction.REF) || (a2 < a1))) { // STORE[a1] <- STORE[a2] data.put(a1, refTo(a2)); // trail(a1) trail(a1); } else if (t2 == WAMInstruction.REF) { // STORE[a2] <- STORE[a1] data.put(a2, refTo(a1)); // tail(a2) trail(a2); } } /** * Records the address of a binding onto the 'trail'. The trail pointer is advanced by one as part of this * operation. * * @param addr The binding address to add to the trail. */ private void trail(int addr) { // if (a < HB) \/ ((H < a) /\ (a < B)) if ((addr < hbp) || ((hp < addr) && (addr < bp))) { // TRAIL[TR] <- a data.put(trp, addr); // TR <- TR + 1 trp++; } } /** * Undoes variable bindings that have been recorded on the 'trail'. Addresses recorded on the trail are reset to REF * to self. * * @param a1 The start address within the trail to get the first binding address to clear. * @param a2 The end address within the trail, this is one higher than the last address to clear. */ private void unwindTrail(int a1, int a2) { // for i <- a1 to a2 - 1 do for (int addr = a1; addr < a2; addr++) { // STORE[TRAIL[i]] <- <REF, TRAIL[i]> int tmp = data.get(addr); data.put(tmp, refTo(tmp)); } } private void tidyTrail() { int i = data.get(bp + data.get(bp) + 5); while (i < trp) { int addr = data.get(i); if ((addr < hbp) || ((hp < addr) && (addr < bp))) { i++; } else { data.put(i, data.get(trp - 1)); trp--; } } } /** * Attempts to unify structures or references on the heap, given two references to them. Structures are matched * element by element, free references become bound. * * @param a1 The address of the first structure or reference. * @param a2 The address of the second structure or reference. * * @return <tt>true</tt> if the two structures unify, <tt>false</tt> otherwise. */ private boolean unify(int a1, int a2) { // pdl.push(a1) // pdl.push(a2) uPush(a1); uPush(a2); // fail <- false boolean fail = false; // while !empty(PDL) and not failed while (!uEmpty() && !fail) { // d1 <- deref(pdl.pop()) // d2 <- deref(pdl.pop()) // t1, v1 <- STORE[d1] // t2, v2 <- STORE[d2] int d1 = deref(uPop()); int t1 = derefTag; int v1 = derefVal; int d2 = deref(uPop()); int t2 = derefTag; int v2 = derefVal; // if (d1 != d2) if (d1 != d2) { // if (t1 = REF or t2 = REF) // bind(d1, d2) if ((t1 == WAMInstruction.REF)) { bind(d1, d2); } else if (t2 == WAMInstruction.REF) { bind(d1, d2); } else if (t2 == WAMInstruction.STR) { // f1/n1 <- STORE[v1] // f2/n2 <- STORE[v2] int fn1 = data.get(v1); int fn2 = data.get(v2); byte n1 = (byte) (fn1 >>> 24); // if f1 = f2 and n1 = n2 if (fn1 == fn2) { // for i <- 1 to n1 for (int i = 1; i <= n1; i++) { // pdl.push(v1 + i) // pdl.push(v2 + i) uPush(v1 + i); uPush(v2 + i); } } else { // fail <- true fail = true; } } else if (t2 == WAMInstruction.CON) { if ((t1 != WAMInstruction.CON) || (v1 != v2)) { fail = true; } } else if (t2 == WAMInstruction.LIS) { if (t1 != WAMInstruction.LIS) { fail = true; } else { uPush(v1); uPush(v2); uPush(v1 + 1); uPush(v2 + 1); } } } } return !fail; } /** * A simplified unification algorithm, for unifying against a constant. * * <p/>Attempts to unify a constant or references on the heap, with a constant. If the address leads to a free * variable on dereferencing, the variable is bound to the constant. If the address leads to a constant it is * compared with the passed in constant for equality, and unification succeeds when they are equal. * * @param fn The constant to unify with. * @param addr The address of the first constant or reference. * * @return <tt>true</tt> if the two constant unify, <tt>false</tt> otherwise. */ private boolean unifyConst(int fn, int addr) { boolean success; int deref = deref(addr); int tag = derefTag; int val = derefVal; // case STORE[addr] of switch (tag) { case REF: { // <REF, _> : // STORE[addr] <- <CON, c> data.put(deref, constantCell(fn)); // trail(addr) trail(deref); success = true; break; } case CON: { // <CON, c'> : // fail <- (c != c'); success = val == fn; break; } default: { // other: fail <- true; success = false; } } return success; } /** * Pushes a value onto the unification stack. * * @param val The value to push onto the stack. */ private void uPush(int val) { data.put(--up, val); } /** * Pops a value from the unification stack. * * @return The top value from the unification stack. */ private int uPop() { return data.get(up++); } /** Clears the unification stack. */ private void uClear() { up = TOP; } /** * Checks if the unification stack is empty. * * @return <tt>true</tt> if the unification stack is empty, <tt>false</tt> otherwise. */ private boolean uEmpty() { return up >= TOP; } /** * Pretty prints a variable allocation slot for tracing purposes. * * @param xi The allocation slot to print. * @param mode The addressing mode, stack or register. * * @return The pretty printed slot. */ private String printSlot(int xi, int mode) { return ((mode == STACK_ADDR) ? "Y" : "X") + ((mode == STACK_ADDR) ? (xi - ep - 3) : xi); } }
Added a guard onto tidy trail, so tidying only occurs when moving back to a previous choice point, not when discarding the last one.
lojix/wam_prolog/src/main/com/thesett/aima/logic/fol/wam/machine/WAMResolvingJavaMachine.java
Added a guard onto tidy trail, so tidying only occurs when moving back to a previous choice point, not when discarding the last one.
<ide><path>ojix/wam_prolog/src/main/com/thesett/aima/logic/fol/wam/machine/WAMResolvingJavaMachine.java <ide> } <ide> } <ide> <add> /** <add> * Tidies trail when a choice point is being discarded, and a previous choice point it being made the current one. <add> * <add> * <p/>Copies trail bindings created since the choice point, into the trail as known to the previous choice point. <add> * That is bindings on the heap created during the choice point (between HB and H). <add> */ <ide> private void tidyTrail() <ide> { <add> // Check that there is a current choice point to tidy down to. <add> if (bp == 0) <add> { <add> return; <add> } <add> <ide> int i = data.get(bp + data.get(bp) + 5); <ide> <ide> while (i < trp)
Java
mit
13c28ef03442e1a04b695553a6f4481d3656a208
0
DeludedFruitcakesAnonymous/VelocityAngles
package ga.deluded_fruitcakes_anonymous.velocityangles; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.MotionEvent; import android.view.View; import android.widget.Toast; /** * Created by Isaac on 8/3/2016. */ public class GameView extends View { float centerX, centerY; float borderHeight, MinHeight,MaxWidth, MinWidth; String Message = "hello"; DrawableObject drawableObject; PhysicalObject physicalObject; float x2; float y2; Bitmap bitmapBase = BitmapFactory.decodeResource(getResources(), R.drawable.joystick_base); Bitmap bitmapTop = BitmapFactory.decodeResource(getResources(), R.drawable.joystick_top); public GameView(Context context, float sHeight, float sWidth) { super(context); borderHeight = sHeight * 0.1f; centerX = sWidth * 0.5f; centerY = sHeight * 0.5f; CreateJoystick(); } public void CreateJoystick(){ drawableObject = new DrawableObject(bitmapBase,centerX, centerY,200,200); physicalObject = new PhysicalObject(bitmapTop,centerX,centerY,100,100); } @Override public boolean onTouchEvent(MotionEvent e) { // MotionEvent reports input details from the touch screen // and other input controls. In this case, you are only // interested in events where the touch position changed. float x = e.getX(); float y = e.getY(); x2 = x; y2 = y; if (y >= borderHeight) { switch (e.getAction()) { case MotionEvent.ACTION_DOWN: Toast.makeText(getContext(), "Joystick moved to " + (x - centerX) + ", " + (y - centerY), Toast.LENGTH_SHORT).show(); physicalObject.xAcceleration = x-centerX; physicalObject.yAcceleration = y-centerY; break; case MotionEvent.ACTION_UP: joystickReturn(); break; } } return true; } public void joystickReturn(){ physicalObject.xPos = centerX; physicalObject.yPos = centerY; physicalObject.xAcceleration = 0; physicalObject.yAcceleration = 0; physicalObject.xVelocity = 0; physicalObject.yVelocity = 0; } public void onDraw(Canvas canvas){ drawableObject.update(canvas); physicalObject.update(canvas); Paint paint = new Paint(); paint.setTextSize(100); paint.setColor(Color.BLACK); canvas.drawText(Message,100,100,paint); if((physicalObject.yPos <= y2 +5) && (physicalObject.yPos >= y2-5) ){ Message = " Y = true"; if((physicalObject.xPos <=x2 +5) && (physicalObject.xPos >= x2-5) ){ Message = " X = true"; physicalObject.xVelocity = 0; physicalObject.yVelocity = 0; physicalObject.xAcceleration = 0; physicalObject.yAcceleration = 0; }} try{ Thread.sleep(100); }catch(InterruptedException e){ } invalidate();} }
app/src/main/java/ga/deluded_fruitcakes_anonymous/velocityangles/GameView.java
package ga.deluded_fruitcakes_anonymous.velocityangles; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.MotionEvent; import android.view.View; import android.widget.Toast; /** * Created by Isaac on 8/3/2016. */ public class GameView extends View { float centerX, centerY; float borderHeight, MinHeight,MaxWidth, MinWidth; String Message = "hello"; DrawableObject drawableObject; PhysicalObject physicalObject; Bitmap bitmapBase = BitmapFactory.decodeResource(getResources(), R.drawable.joystick_base); Bitmap bitmapTop = BitmapFactory.decodeResource(getResources(), R.drawable.joystick_top); public GameView(Context context, float sHeight, float sWidth) { super(context); borderHeight = sHeight * 0.1f; centerX = sWidth * 0.5f; centerY = sHeight * 0.5f; CreateJoystick(); } public void CreateJoystick(){ drawableObject = new DrawableObject(bitmapBase,centerX, centerY,200,200); physicalObject = new PhysicalObject(bitmapTop,centerX,centerY,100,100); } @Override public boolean onTouchEvent(MotionEvent e) { // MotionEvent reports input details from the touch screen // and other input controls. In this case, you are only // interested in events where the touch position changed. float x = e.getX(); float y = e.getY(); if (y >= borderHeight) { switch (e.getAction()) { case MotionEvent.ACTION_DOWN: Toast.makeText(getContext(), "Joystick moved to " + (x - centerX) + ", " + (y - centerY), Toast.LENGTH_SHORT).show(); physicalObject.xAcceleration = x-centerX; physicalObject.yAcceleration = y-centerY; break; case MotionEvent.ACTION_UP: joystickReturn(); break; } } return true; } public void joystickReturn(){ physicalObject.xPos = centerX; physicalObject.yPos = centerY; physicalObject.xAcceleration = 0; physicalObject.yAcceleration = 0; physicalObject.xVelocity = 0; physicalObject.yVelocity = 0; } public void onDraw(Canvas canvas){ drawableObject.update(canvas); physicalObject.update(canvas); Paint paint = new Paint(); paint.setTextSize(100); paint.setColor(Color.BLACK); canvas.drawText(Message,100,100,paint); if((physicalObject.yPos <= y +5) && (physicalObject.yPos >= y-5) ){ Message = " Y = true"; if((physicalObject.xPos <=x +5) && (physicalObject.xPos >= x-5) ){ Message = " X = true"; physicalObject.xVelocity = 0; physicalObject.yVelocity = 0; physicalObject.xAcceleration = 0; physicalObject.yAcceleration = 0; }} try{ Thread.sleep(100); }catch(InterruptedException e){ } invalidate();} }
FAT MAN FAT MEN
app/src/main/java/ga/deluded_fruitcakes_anonymous/velocityangles/GameView.java
FAT MAN
<ide><path>pp/src/main/java/ga/deluded_fruitcakes_anonymous/velocityangles/GameView.java <ide> String Message = "hello"; <ide> DrawableObject drawableObject; <ide> PhysicalObject physicalObject; <add> float x2; <add> float y2; <ide> Bitmap bitmapBase = BitmapFactory.decodeResource(getResources(), R.drawable.joystick_base); <ide> Bitmap bitmapTop = BitmapFactory.decodeResource(getResources(), R.drawable.joystick_top); <ide> public GameView(Context context, float sHeight, float sWidth) { <ide> <ide> float x = e.getX(); <ide> float y = e.getY(); <add> x2 = x; <add> y2 = y; <ide> if (y >= borderHeight) { <ide> switch (e.getAction()) { <ide> case MotionEvent.ACTION_DOWN: <ide> paint.setTextSize(100); <ide> paint.setColor(Color.BLACK); <ide> canvas.drawText(Message,100,100,paint); <del> if((physicalObject.yPos <= y +5) && (physicalObject.yPos >= y-5) ){ <add> if((physicalObject.yPos <= y2 +5) && (physicalObject.yPos >= y2-5) ){ <ide> Message = " Y = true"; <del> if((physicalObject.xPos <=x +5) && (physicalObject.xPos >= x-5) ){ <add> if((physicalObject.xPos <=x2 +5) && (physicalObject.xPos >= x2-5) ){ <ide> Message = " X = true"; <ide> <ide> physicalObject.xVelocity = 0;
Java
lgpl-2.1
3b6cff07f8335ca25d7bef7e155f855ea9b6130d
0
EnFlexIT/AgentWorkbench,EnFlexIT/AgentWorkbench,EnFlexIT/AgentWorkbench,EnFlexIT/AgentWorkbench
/** * *************************************************************** * Agent.GUI is a framework to develop Multi-agent based simulation * applications based on the JADE - Framework in compliance with the * FIPA specifications. * Copyright (C) 2010 Christian Derksen and DAWIS * http://www.dawis.wiwi.uni-due.de * http://sourceforge.net/projects/agentgui/ * http://www.agentgui.org * * GNU Lesser General Public License * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * ************************************************************** */ package agentgui.envModel.graph.controller.ui; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.event.ContainerAdapter; import java.awt.event.ContainerEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Observable; import java.util.Observer; import java.util.Set; import java.util.Vector; import javax.imageio.ImageIO; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JToolBar; import org.apache.commons.collections15.Transformer; import agentgui.core.application.Application; import agentgui.core.gui.imaging.ConfigurableFileFilter; import agentgui.core.gui.imaging.ImageFileView; import agentgui.core.gui.imaging.ImagePreview; import agentgui.core.gui.imaging.ImageUtils; import agentgui.envModel.graph.GraphGlobals; import agentgui.envModel.graph.commands.RenameNetworkComponent.NetworkComponentRenamed; import agentgui.envModel.graph.controller.GraphEnvironmentController; import agentgui.envModel.graph.controller.GraphEnvironmentControllerGUI; import agentgui.envModel.graph.networkModel.ComponentTypeSettings; import agentgui.envModel.graph.networkModel.EdgeShapePolyline; import agentgui.envModel.graph.networkModel.GeneralGraphSettings4MAS; import agentgui.envModel.graph.networkModel.GraphEdge; import agentgui.envModel.graph.networkModel.GraphElement; import agentgui.envModel.graph.networkModel.GraphElementLayout; import agentgui.envModel.graph.networkModel.GraphNode; import agentgui.envModel.graph.networkModel.NetworkComponent; import agentgui.envModel.graph.networkModel.NetworkModelNotification; import edu.uci.ics.jung.algorithms.layout.Layout; import edu.uci.ics.jung.algorithms.layout.StaticLayout; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.visualization.FourPassImageShaper; import edu.uci.ics.jung.visualization.GraphZoomScrollPane; import edu.uci.ics.jung.visualization.Layer; import edu.uci.ics.jung.visualization.LayeredIcon; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.CrossoverScalingControl; import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse; import edu.uci.ics.jung.visualization.control.PluggableGraphMouse; import edu.uci.ics.jung.visualization.control.SatelliteVisualizationViewer; import edu.uci.ics.jung.visualization.control.ScalingControl; import edu.uci.ics.jung.visualization.decorators.AbstractEdgeShapeTransformer; import edu.uci.ics.jung.visualization.decorators.AbstractVertexShapeTransformer; import edu.uci.ics.jung.visualization.decorators.ConstantDirectionalEdgeValueTransformer; import edu.uci.ics.jung.visualization.decorators.EdgeShape; import edu.uci.ics.jung.visualization.picking.PickedState; import edu.uci.ics.jung.visualization.picking.ShapePickSupport; import edu.uci.ics.jung.visualization.renderers.Checkmark; /** * This class implements a GUI component for displaying visualizations for JUNG graphs. <br> * This class also has a toolbar component which provides various features for editing, importing and interacting with the graph. * * @see GraphEnvironmentControllerGUI * @see GraphEnvironmentMousePlugin * * @author Nils Loose - DAWIS - ICB University of Duisburg - Essen * @author Satyadeep Karnati - CSE - Indian Institute of Technology, Guwahati * @author Christian Derksen - DAWIS - ICB - University of Duisburg - Essen */ public class BasicGraphGui extends JPanel implements Observer { private static final long serialVersionUID = 5764679914667183305L; /** * The enumeration ToolBarType describes the toolbar type available in the {@link BasicGraphGui}. */ public enum ToolBarType { ViewControl, EditControl } /** * The enumeration ToolBarSurrounding describes, if a customised toolbar button is to be shown during configuration or during runtime. */ public enum ToolBarSurrounding { Both, ConfigurationOnly, RuntimeOnly } /** Environment model controller, to be passed by the parent GUI. */ private GraphEnvironmentController graphController; /** The GUI's main component, either the graph visualization, or an empty JPanel if no graph is loaded */ private GraphZoomScrollPane graphZoomScrollPane; /** The ToolBar for this component */ private BasicGraphGuiTools graphGuiTools; private JPanel jPanelToolBars; /** Graph visualisation component */ private BasicGraphGuiVisViewer<GraphNode, GraphEdge> visView; private boolean isCreatedVisualizationViewer; private SatelliteDialog satelliteDialog; private SatelliteVisualizationViewer<GraphNode, GraphEdge> visViewSatellite; /** JUNG object handling zooming */ private ScalingControl scalingControl = new CrossoverScalingControl(); /** the margin of the graph for the visualization */ private double graphMargin = 25; private Point2D defaultScaleAtPoint = new Point2D.Double(graphMargin, graphMargin); /** Indicates that the initial scaling is allowed */ private boolean allowInitialScaling = true; private PluggableGraphMouse pluggableGraphMouse; private GraphEnvironmentMousePlugin graphEnvironmentMousePlugin; private GraphEnvironmentPopupPlugin<GraphNode, GraphEdge> graphEnvironmentPopupPlugin; private DefaultModalGraphMouse<GraphNode, GraphEdge> defaultModalGraphMouse; /** * This is the default constructor * @param controller The Graph Environment controller */ public BasicGraphGui(GraphEnvironmentController controller) { this.graphController = controller; this.graphController.addObserver(this); this.initialize(); this.reLoadGraph(); } /** * This method initializes this */ private void initialize() { // --- Set appearance ----------------------------- this.setVisible(true); this.setSize(300, 300); this.setLayout(new BorderLayout()); this.setDoubleBuffered(true); // --- Add components ----------------------------- this.add(this.getJPanelToolBars(), BorderLayout.WEST); this.add(this.getGraphZoomScrollPane(), BorderLayout.CENTER); this.addContainerListener(new ContainerAdapter() { boolean doneAdded = false; @Override public void componentAdded(ContainerEvent ce) { if (doneAdded==false) { validate(); zoomSetInitialScalingAndMovement(getVisualizationViewer()); doneAdded=true; } } }); } /** * Returns the instance of the BasicGraphGuiTools. * @return the BasicGraphGuiTools */ private BasicGraphGuiTools getBasicGraphGuiTools() { if (graphGuiTools==null) { graphGuiTools = new BasicGraphGuiTools(this.graphController); } return graphGuiTools; } /** * Returns the specified JToolBar of the {@link BasicGraphGui}. * * @param toolBarType the tool bar type * @return the j tool bar */ public JToolBar getJToolBar(ToolBarType toolBarType) { JToolBar toolBar = null; switch (toolBarType) { case EditControl: toolBar = this.getBasicGraphGuiTools().getJToolBarEdit(); break; case ViewControl: toolBar = this.getBasicGraphGuiTools().getJToolBarView(); break; } return toolBar; } /** * Returns the JPanel with the tool bars. * @return the j panel tool bars */ private JPanel getJPanelToolBars() { if (jPanelToolBars==null) { jPanelToolBars = new JPanel(); jPanelToolBars.setLayout(new BoxLayout(jPanelToolBars, BoxLayout.X_AXIS)); jPanelToolBars.add(this.getBasicGraphGuiTools().getJToolBarView(), null); // --- In case of editing the simulation setup ---------- if (this.graphController.getProject()!=null) { jPanelToolBars.add(this.getBasicGraphGuiTools().getJToolBarEdit(), null); } } return jPanelToolBars; } /** * Dispose this panel. */ public void dispose() { this.disposeSatelliteView(); this.setVisualizationViewer(null); } /** * Gets the graph environment controller. * @return the controller */ public GraphEnvironmentController getGraphEnvironmentController() { return this.graphController; } /** * Gets the scaling control. * @return the scalingControl */ private ScalingControl getScalingControl() { return this.scalingControl; } /** * Returns the PluggableGraphMouse. * @return the pluggableGraphMouse */ public PluggableGraphMouse getPluggableGraphMouse() { if (pluggableGraphMouse==null) { pluggableGraphMouse = new PluggableGraphMouse(); pluggableGraphMouse.add(this.getGraphEnvironmentMousePlugin()); pluggableGraphMouse.add(this.getGraphEnvironmentPopupPlugin()); } return pluggableGraphMouse; } /** * Returns the {@link GraphEnvironmentMousePlugin} * @return the graph environment mouse plugin */ private GraphEnvironmentMousePlugin getGraphEnvironmentMousePlugin() { if (graphEnvironmentMousePlugin==null) { graphEnvironmentMousePlugin = new GraphEnvironmentMousePlugin(this); } return graphEnvironmentMousePlugin; } /** * Returns the GraphEnvironmentPopupPlugin. * @return the graph environment popup plugin */ private GraphEnvironmentPopupPlugin<GraphNode, GraphEdge> getGraphEnvironmentPopupPlugin() { if (graphEnvironmentPopupPlugin==null) { graphEnvironmentPopupPlugin = new GraphEnvironmentPopupPlugin<GraphNode, GraphEdge>(this); graphEnvironmentPopupPlugin.setEdgePopup(this.getBasicGraphGuiTools().getEdgePopup()); graphEnvironmentPopupPlugin.setVertexPopup(this.getBasicGraphGuiTools().getVertexPopup()); } return graphEnvironmentPopupPlugin; } /** * Gets the DefaultModalGraphMouse. * @return the default modal graph mouse */ private DefaultModalGraphMouse<GraphNode, GraphEdge> getDefaultModalGraphMouse() { if (defaultModalGraphMouse == null) { defaultModalGraphMouse = new DefaultModalGraphMouse<GraphNode, GraphEdge>(1/1.1f, 1.1f); } return defaultModalGraphMouse; } /** * Gets the default point to scale at for zooming. * @return the default scale at point */ private Point2D getDefaultScaleAtPoint() { Rectangle2D rectVis = this.getVisualizationViewer().getVisibleRect(); if (rectVis.isEmpty()==false) { this.defaultScaleAtPoint = new Point2D.Double(rectVis.getCenterX(), rectVis.getCenterY()); } return defaultScaleAtPoint; } /** * Sets the default point to scale at for zooming.. * @param scalePoint the new default scale at point */ private void setDefaultScaleAtPoint(Point2D scalePoint) { defaultScaleAtPoint = scalePoint; } /** * This method assigns a graph to a new VisualizationViewer and adds it to the GUI. */ private void reLoadGraph() { // --- Display the current Graph ------------------ Graph<GraphNode, GraphEdge> graph = this.getGraph(); this.getVisualizationViewer().getGraphLayout().setGraph(graph); this.validate(); this.zoomFit2Window(this.getVisualizationViewer()); this.getSatelliteVisualizationViewer().getGraphLayout().setGraph(graph); // this.reloadSatelliteView(); this.zoomFit2Window(this.getSatelliteVisualizationViewer()); } /** * Gets the current Graph and repaints the visualisation viewer. */ private void repaintGraph() { Graph<GraphNode, GraphEdge> graph = this.getGraph(); if (graph!=null && this.getVisualizationViewer().getGraphLayout().getGraph()!=graph) { this.getVisualizationViewer().getGraphLayout().setGraph(graph); } this.getVisualizationViewer().repaint(); } /** * Controls the shape, size, and aspect ratio for each vertex. * * @author Satyadeep Karnati - CSE - Indian Institute of Technology, Guwahati * @author Christian Derksen - DAWIS - ICB - University of Duisburg - Essen */ private final class VertexShapeSizeAspect<V, E> extends AbstractVertexShapeTransformer<GraphNode> implements Transformer<GraphNode, Shape> { private Map<String, Shape> shapeMap = new HashMap<String, Shape>(); public VertexShapeSizeAspect() { this.setSizeTransformer(new Transformer<GraphNode, Integer>() { @Override public Integer transform(GraphNode node) { return (int) node.getGraphElementLayout(graphController.getNetworkModel()).getSize(); } }); } /* * (non-Javadoc) * * @see org.apache.commons.collections15.Transformer#transform(java.lang.Object) */ @Override public Shape transform(GraphNode node) { Shape shape = factory.getEllipse(node); // DEFAULT String shapeForm = node.getGraphElementLayout(graphController.getNetworkModel()).getShapeForm(); if (shapeForm==null) { // --- nothing to do here ---- } else if (shapeForm.equals(GeneralGraphSettings4MAS.SHAPE_RECTANGLE)) { shape = factory.getRectangle(node); } else if (shapeForm.equals(GeneralGraphSettings4MAS.SHAPE_ROUND_RECTANGLE)) { shape = factory.getRoundRectangle(node); } else if (shapeForm.equals(GeneralGraphSettings4MAS.SHAPE_REGULAR_POLYGON)) { shape = factory.getRegularPolygon(node, 6); } else if (shapeForm.equals(GeneralGraphSettings4MAS.SHAPE_REGULAR_STAR)) { shape = factory.getRegularStar(node, 6); } else if (shapeForm.equals(GeneralGraphSettings4MAS.SHAPE_IMAGE_SHAPE)) { String imageRef = node.getGraphElementLayout(graphController.getNetworkModel()).getImageReference(); //TODO only rebuild if changed //shape = shapeMap.get(imageRef); Shape imageShape = null; ImageIcon imageIcon = GraphGlobals.getImageIcon(imageRef); if (imageIcon != null) { Image image = imageIcon.getImage(); imageShape = FourPassImageShaper.getShape(image, 30); if (imageShape .getBounds().getWidth() > 0 && imageShape .getBounds().getHeight() > 0) { // don't cache a zero-sized shape, wait for the image to be ready int width = image.getWidth(null); int height = image.getHeight(null); AffineTransform transform = AffineTransform.getTranslateInstance(-width / 2, -height / 2); imageShape = transform.createTransformedShape(imageShape ); this.shapeMap.put(imageRef, imageShape ); } } else { System.err.println("Could not find node image '" + imageRef + "'"); } if (imageShape!=null) shape = imageShape; } return shape; } } /** * Returns the current graph. * @return the graph */ private Graph<GraphNode, GraphEdge> getGraph() { return this.graphController.getNetworkModel().getGraph(); } /** * Gets the graph zoom scroll pane. * @return the graph zoom scroll pane */ public GraphZoomScrollPane getGraphZoomScrollPane() { if (graphZoomScrollPane==null) { graphZoomScrollPane = new GraphZoomScrollPane(this.getVisualizationViewer()); } return graphZoomScrollPane; } /** * Returns if the visualization viewer was fully created. * @return true, if is created visualization viewer */ public boolean isCreatedVisualizationViewer() { return isCreatedVisualizationViewer; } /** * Sets the VisualizationViewer. * @param newVisView the new VisualizationViewer */ private void setVisualizationViewer(BasicGraphGuiVisViewer<GraphNode, GraphEdge> newVisView) { this.visView = newVisView; } /** * Gets the VisualizationViewer * @return The VisualizationViewer */ public BasicGraphGuiVisViewer<GraphNode, GraphEdge> getVisualizationViewer() { if (visView==null) { // ---------------------------------------------------------------- // --- Get the current graph -------------------------------------- // ---------------------------------------------------------------- Graph<GraphNode, GraphEdge> graph = this.getGraph(); // ---------------------------------------------------------------- // --- Define graph layout ---------------------------------------- // ---------------------------------------------------------------- Layout<GraphNode, GraphEdge> layout = new StaticLayout<GraphNode, GraphEdge>(graph); Rectangle2D graphDimension = GraphGlobals.getGraphSpreadDimension(graph); layout.setSize(new Dimension((int) (graphDimension.getWidth() + 2 * graphMargin), (int) (graphDimension.getHeight() + 2 * graphMargin))); layout.setInitializer(new Transformer<GraphNode, Point2D>() { @Override public Point2D transform(GraphNode node) { return node.getPosition(); // The position is specified in the GraphNode instance } }); // ---------------------------------------------------------------- // --- Create a new VisualizationViewer instance ------------------ // ---------------------------------------------------------------- visView = new BasicGraphGuiVisViewer<GraphNode, GraphEdge>(layout); visView.setBackground(Color.WHITE); visView.setDoubleBuffered(true); // --- Configure mouse and key interaction ------------------------ visView.setGraphMouse(this.getPluggableGraphMouse()); visView.addKeyListener(this.getGraphEnvironmentMousePlugin()); // --- Set the pick size of the visualisation viewer -------- ((ShapePickSupport<GraphNode, GraphEdge>) visView.getPickSupport()).setPickSize(5); // ---------------------------------------------------------------- // --- Define edge and node ToolTip --------------------- Start --- // ---------------------------------------------------------------- // --- Edge ------------------------------------------------------- visView.setVertexToolTipTransformer(new Transformer<GraphNode, String>() { @Override public String transform(GraphNode node) { HashSet<NetworkComponent> netCompsAtNode = graphController.getNetworkModel().getNetworkComponents(node); NetworkComponent netCompDisNode = graphController.getNetworkModel().getDistributionNode(netCompsAtNode); // --- Generally define the toolTip ----------------------- String toolTip = "<html><b>GraphNode: " + node.getId() + "</b>"; if (netCompDisNode!=null) { // --- In case of a distribution node ----------------- String type = netCompDisNode.getType(); String domain = "unknown"; String isAgent = "?"; ComponentTypeSettings cts = graphController.getGeneralGraphSettings4MAS().getCurrentCTS().get(type); if (cts!=null) { domain = cts.getDomain(); if (cts.getAgentClass()==null) { isAgent = "No"; } else { isAgent = "Yes"; } } // --- Define the ToolTip ----------------------------- toolTip += "<br><b>NetworkComponent: " + netCompDisNode.getId() + "</b><br>(Domain: " + domain + ", Type: " + type + ", isAgent: " + isAgent + ")"; } // --- Show position in edit mode only -------------------- if (graphController.getProject()!=null) { toolTip += "<br>(x=" + node.getPosition().getX() + " - y=" + node.getPosition().getY() + ")"; } toolTip += "</html>"; return toolTip; } }); // --- Node ------------------------------------------------------- visView.setEdgeToolTipTransformer(new Transformer<GraphEdge, String>() { @Override public String transform(GraphEdge edge) { String toolTip = null; NetworkComponent netComp = graphController.getNetworkModel().getNetworkComponent(edge); if (netComp!=null) { String type = netComp.getType(); String domain = "unknown"; String isAgent = "?"; ComponentTypeSettings cts = graphController.getGeneralGraphSettings4MAS().getCurrentCTS().get(type); if (cts!=null) { domain = cts.getDomain(); if (cts.getAgentClass()==null) { isAgent = "No"; } else { isAgent = "Yes"; } } // --- Define the ToolTip ----------------------------- toolTip = "<html>"; toolTip += "<b>NetworkComponent: " + netComp.getId() + "</b><br>(Domain: " + domain + ", Type: " + type + ", isAgent: " + isAgent + ")"; toolTip += "</html>"; } return toolTip; } }); // ---------------------------------------------------------------- // --- Define edge and node ToolTip ------------------------ End--- // ---------------------------------------------------------------- // ---------------------------------------------------------------- // --- Node configurations ------------------------------ Start --- // ---------------------------------------------------------------- // --- Configure the node shape and size -------------------------- visView.getRenderContext().setVertexShapeTransformer(new VertexShapeSizeAspect<GraphNode, GraphEdge>()); // --- Configure node icons, if configured ------------------------ visView.getRenderContext().setVertexIconTransformer(new Transformer<GraphNode, Icon>() { private final String pickedPostfix = "[picked]"; private HashMap<String, LayeredIcon> iconHash = new HashMap<String, LayeredIcon>(); @Override public Icon transform(GraphNode node) { Icon icon = null; GraphElementLayout nodeLayout = node.getGraphElementLayout(graphController.getNetworkModel()); boolean picked = visView.getPickedVertexState().isPicked(node); String nodeImagePath = nodeLayout.getImageReference(); if (nodeImagePath != null) { if (nodeImagePath.equals("MissingIcon")==false) { // --- 1. Search in the local Hash ------ LayeredIcon layeredIcon = null; Color currentColor = nodeLayout.getColor(); String colorPostfix = "[" + currentColor.getRGB() + "]"; if (picked == true) { layeredIcon = this.iconHash.get(nodeImagePath + colorPostfix + this.pickedPostfix); } else { layeredIcon = this.iconHash.get(nodeImagePath + colorPostfix); } // --- 2. If necessary, load the image -- if (layeredIcon == null) { ImageIcon imageIcon = GraphGlobals.getImageIcon(nodeImagePath); // --- Prepare the image --------- BufferedImage bufferedImage; if (currentColor.equals(Color.WHITE) || currentColor.equals(Color.BLACK)) { // --- If the color is set to black or white, just use the unchanged image ---------- bufferedImage = convertToBufferedImage(imageIcon.getImage()); } else { // --- Otherwise, replace the defined basic color with the one specified in the node layout --------- bufferedImage = exchangeColor(convertToBufferedImage(imageIcon.getImage()), GeneralGraphSettings4MAS.IMAGE_ICON_BASIC_COLOR, currentColor); if (node.getId().equals("PP100")) { String imgFileName = "PP100_R"+currentColor.getRed()+"_G"+currentColor.getGreen()+"_B"+currentColor.getBlue()+".png"; File imgFile = new File("D:\\Temp\\"+imgFileName); try { ImageIO.write(bufferedImage, "png", imgFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (bufferedImage != null) { // --- 3. Remind this images ---- LayeredIcon layeredIconUnPicked = new LayeredIcon(bufferedImage); this.iconHash.put(nodeImagePath + colorPostfix, layeredIconUnPicked); LayeredIcon layeredIconPicked = new LayeredIcon(bufferedImage); layeredIconPicked.add(new Checkmark(nodeLayout.getColorPicked())); this.iconHash.put(nodeImagePath + colorPostfix + this.pickedPostfix, layeredIconPicked); // --- 4. Return the right one -- if (picked == true) { layeredIcon = layeredIconPicked; } else { layeredIcon = layeredIconUnPicked; } } } icon = layeredIcon; } } return icon; } }); // --- Configure node colors -------------------------------------- visView.getRenderContext().setVertexFillPaintTransformer(new Transformer<GraphNode, Paint>() { @Override public Paint transform(GraphNode node) { if (visView.getPickedVertexState().isPicked(node)) { return node.getGraphElementLayout(graphController.getNetworkModel()).getColorPicked(); } return node.getGraphElementLayout(graphController.getNetworkModel()).getColor(); } }); // --- Configure to show node labels ------------------------------ visView.getRenderContext().setVertexLabelTransformer(new Transformer<GraphNode, String>() { @Override public String transform(GraphNode node) { if (node.getGraphElementLayout(graphController.getNetworkModel()).isShowLabel()==true) { return node.getGraphElementLayout(graphController.getNetworkModel()).getLabelText(); } return null; } }); // ---------------------------------------------------------------- // --- Edge configurations ------------------------------ Start --- // ---------------------------------------------------------------- // --- Configure edge label position ------------------------------ visView.getRenderContext().setLabelOffset(6); visView.getRenderContext().setEdgeLabelClosenessTransformer(new ConstantDirectionalEdgeValueTransformer<GraphNode, GraphEdge>(.5, .5)); // --- Set the EdgeShape of the Visualisation Viewer -------------- this.setEdgeShapeTransformer(visView); // --- Set edge width --------------------------------------------- visView.getRenderContext().setEdgeStrokeTransformer(new Transformer<GraphEdge, Stroke>() { @Override public Stroke transform(GraphEdge edge) { return new BasicStroke(edge.getGraphElementLayout(graphController.getNetworkModel()).getSize()); } }); // --- Configure edge color --------------------------------------- Transformer<GraphEdge, Paint> edgeColorTransformer = new Transformer<GraphEdge, Paint>() { @Override public Paint transform(GraphEdge edge) { Color initColor = edge.getGraphElementLayout(graphController.getNetworkModel()).getColor(); if (visView.getPickedEdgeState().isPicked(edge)) { initColor = edge.getGraphElementLayout(graphController.getNetworkModel()).getColorPicked(); } return initColor; }}; visView.getRenderContext().setEdgeDrawPaintTransformer(edgeColorTransformer); visView.getRenderContext().setArrowFillPaintTransformer(edgeColorTransformer); visView.getRenderContext().setArrowDrawPaintTransformer(edgeColorTransformer); // --- Configure Edge Image Labels -------------------------------- visView.getRenderContext().setEdgeLabelTransformer(new Transformer<GraphEdge, String>() { @Override public String transform(GraphEdge edge) { // --- Get the needed info -------------------------------- String imageRef = edge.getGraphElementLayout(graphController.getNetworkModel()).getImageReference(); boolean showLabel = edge.getGraphElementLayout(graphController.getNetworkModel()).isShowLabel(); // --- Configure color ------------------------------------ Color color = Color.BLACK; if (visView.getPickedEdgeState().isPicked(edge)) { color = edge.getGraphElementLayout(graphController.getNetworkModel()).getColorPicked(); } String htmlColor = String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue()); // --- Get the text / image content ----------------------- String content = ""; if (showLabel) { content = edge.getId(); } if (imageRef!= null) { URL url = getImageURL(imageRef); if (url != null) { if (showLabel) { content = content + "<br><img src='" + url + "'>"; } else { content = "<img src='" + url + "'>"; } } } // --- Set the return value ------------------------------- String textDisplay = "<html><center><font color='[COLOR]'>[CONTENT]</font></center></html>"; textDisplay = textDisplay.replace("[COLOR]", htmlColor); textDisplay = textDisplay.replace("[CONTENT]", content); return textDisplay; } }); // --- Set edge renderer for a background color of an edge -------- visView.getRenderer().setEdgeRenderer(new GraphEnvironmentEdgeRenderer() { @Override public boolean isShowMarker(GraphEdge edge) { return edge.getGraphElementLayout(graphController.getNetworkModel()).isMarkerShow(); } @Override public float getMarkerStrokeWidth(GraphEdge edge) { return edge.getGraphElementLayout(graphController.getNetworkModel()).getMarkerStrokeWidth(); } @Override public Color getMarkerColor(GraphEdge edge) { return edge.getGraphElementLayout(graphController.getNetworkModel()).getMarkerColor(); } }); this.isCreatedVisualizationViewer=true; } return visView; } /** * Searches and returns the image url for the specified image reference. * * @param imageRef the image reference * @return the URL of the image */ private URL getImageURL(String imageRef){ // --- Abort URL generation --------------------------------- if (imageRef.equals("MissingIcon")==true) return null; // --- Resource by the class loader, as configured ---------- URL url = getClass().getResource(imageRef); if (url!=null) return url; // --- Prepare folder for projects -------------------------- String projectsFolder = Application.getGlobalInfo().getPathProjects(); projectsFolder = projectsFolder.replace("\\", "/"); // --- Resource by file, in projects, absolute -------------- String extImageRef = (projectsFolder + imageRef).replace("//", "/"); try { url = new URL("file", null, -1, extImageRef); if (url!=null) return url; } catch (MalformedURLException urlEx) { //urlEx.printStackTrace(); } // --- Nothing found ---------------------------------------- return null; } /** * Sets the edge shape transformer according to the {@link GeneralGraphSettings4MAS}. * @see GeneralGraphSettings4MAS#getEdgeShape() */ public void setEdgeShapeTransformer() { this.setEdgeShapeTransformer(this.getVisualizationViewer()); } /** * Sets the edge shape transformer according to the {@link GeneralGraphSettings4MAS}. * @see GeneralGraphSettings4MAS#getEdgeShape() * @param visViewer the vis viewer */ public void setEdgeShapeTransformer(BasicGraphGuiVisViewer<GraphNode, GraphEdge> visViewer) { // --- Use straight lines as edges ? ------------------------------ AbstractEdgeShapeTransformer<GraphNode, GraphEdge> edgeShapeTransformer = null; switch (this.getGraphEnvironmentController().getNetworkModelAdapter().getGeneralGraphSettings4MAS().getEdgeShape()) { case BentLine: edgeShapeTransformer = new EdgeShape.BentLine<GraphNode, GraphEdge>(); break; case Box: edgeShapeTransformer = new EdgeShape.Box<GraphNode, GraphEdge>(); break; case CubicCurve: edgeShapeTransformer = new EdgeShape.CubicCurve<GraphNode, GraphEdge>(); break; case Line: edgeShapeTransformer = new EdgeShape.Line<GraphNode, GraphEdge>(); break; case Polyline: edgeShapeTransformer = new EdgeShapePolyline<GraphNode, GraphEdge>(); break; case Loop: edgeShapeTransformer = new EdgeShape.Loop<GraphNode, GraphEdge>(); break; case Orthogonal: edgeShapeTransformer = new EdgeShape.Orthogonal<GraphNode, GraphEdge>(); break; case QuadCurve: edgeShapeTransformer = new EdgeShape.QuadCurve<GraphNode, GraphEdge>(); break; case SimpleLoop: edgeShapeTransformer = new EdgeShape.SimpleLoop<GraphNode, GraphEdge>(); break; case Wedge: edgeShapeTransformer = new EdgeShape.Wedge<GraphNode, GraphEdge>(5); break; default: edgeShapeTransformer = new EdgeShape.Line<GraphNode, GraphEdge>(); break; } visViewer.getRenderContext().setEdgeShapeTransformer(edgeShapeTransformer); visViewer.repaint(); } /** * This method notifies the observers about a graph object selection * @param pickedObject The selected object */ public void handleObjectLeftClick(Object pickedObject) { this.selectObject(pickedObject); } /** * Notifies the observers that this object is right clicked * @param pickedObject the selected object */ public void handleObjectRightClick(Object pickedObject) { this.selectObject(pickedObject); } /** * Invoked when a graph node or edge is double clicked (left or right) * @param pickedObject */ public void handleObjectDoubleClick(Object pickedObject) { this.selectObject(pickedObject); if (pickedObject instanceof GraphNode) { // --- Set the local variable --------------------------- GraphNode graphNode = (GraphNode) pickedObject; // --- Is the GraphNode a DistributionNode ? ------------ NetworkComponent networkComponent = this.graphController.getNetworkModel().isDistributionNode(graphNode); if (networkComponent!=null) { // --- Yes! Show the PopUp menu for this node ------- NetworkModelNotification nmn = new NetworkModelNotification(NetworkModelNotification.NETWORK_MODEL_ShowPopUpMenue); nmn.setInfoObject(pickedObject); this.graphController.notifyObservers(nmn); return; } } // --- Notify about the editing request for a component ----- NetworkModelNotification nmNote = new NetworkModelNotification(NetworkModelNotification.NETWORK_MODEL_EditComponentSettings); nmNote.setInfoObject(pickedObject); this.graphController.notifyObservers(nmNote); } /** * Clears the picked nodes and edges */ private void clearPickedObjects() { this.getVisualizationViewer().getPickedVertexState().clear(); this.getVisualizationViewer().getPickedEdgeState().clear(); } /** * Sets a node or edge as picked * @param object The GraphNode or GraphEdge to pick */ private void setPickedObject(GraphElement object) { if (object instanceof GraphEdge) { this.getVisualizationViewer().getPickedEdgeState().pick((GraphEdge) object, true); } else if (object instanceof GraphNode) { this.getVisualizationViewer().getPickedVertexState().pick((GraphNode) object, true); } } /** * Marks a group of objects as picked * @param objects The objects */ private void setPickedObjects(Vector<GraphElement> objects) { Iterator<GraphElement> objIter = objects.iterator(); while (objIter.hasNext()) { this.setPickedObject(objIter.next()); } } /** * Returns the node which is picked. If multiple nodes are picked, returns null. * @return GraphNode - the GraphNode which is picked. */ public GraphNode getPickedSingleNode() { Set<GraphNode> nodeSet = this.getVisualizationViewer().getPickedVertexState().getPicked(); if (nodeSet.size() == 1) { return nodeSet.iterator().next(); } return null; } /** * Gets the Set<GraphNode> of picked nodes. * @return the picked nodes */ public Set<GraphNode> getPickedNodes() { PickedState<GraphNode> nodesPicked = this.getVisualizationViewer().getPickedVertexState(); if (nodesPicked!=null) { return nodesPicked.getPicked(); } return null; } /** * Returns the edge which is picked. If multiple nodes are picked, returns null. * @return GraphEdge - the GraphNode which is picked. */ public GraphEdge getPickedSingleEdge() { Set<GraphEdge> edgeSet = this.getVisualizationViewer().getPickedEdgeState().getPicked(); if (edgeSet.size() == 1) { return edgeSet.iterator().next(); } return null; } /** * Gets the Set<GraphEdge> of picked edges. * @return the picked edges */ public Set<GraphEdge> getPickedEdges() { PickedState<GraphEdge> edgesPicked = this.getVisualizationViewer().getPickedEdgeState(); if (edgesPicked!=null) { return edgesPicked.getPicked(); } return null; } /** * Same as selectObject but optionally shows component settings dialog * * @param object * @param showComponentSettingsDialog - shows the dialog if true */ private void selectObject(Object object) { this.clearPickedObjects(); if (object instanceof GraphNode) { this.setPickedObject((GraphElement) object); // --- Is that node a distribution node? ---------------- HashSet<NetworkComponent> netComps = graphController.getNetworkModelAdapter().getNetworkComponents((GraphNode) object); NetworkComponent disNode = graphController.getNetworkModelAdapter().containsDistributionNode(netComps); if (disNode != null) { this.graphController.getNetworkModelAdapter().selectNetworkComponent(disNode); } if (netComps.size() == 1) { this.graphController.getNetworkModelAdapter().selectNetworkComponent(netComps.iterator().next()); this.clearPickedObjects(); this.setPickedObject((GraphElement) object); } } else if (object instanceof GraphEdge) { NetworkComponent netComp = graphController.getNetworkModelAdapter().getNetworkComponent((GraphEdge) object); this.setPickedObjects(graphController.getNetworkModelAdapter().getGraphElementsFromNetworkComponent(netComp)); this.graphController.getNetworkModelAdapter().selectNetworkComponent(netComp); } else if (object instanceof NetworkComponent) { this.setPickedObjects(graphController.getNetworkModelAdapter().getGraphElementsFromNetworkComponent((NetworkComponent) object)); } } /** * Returns the selected graph objects. These are either all selected {@link NetworkComponent}'s * or, in case of the selection of a single {@link GraphNode} * @return the selected graph object */ public Set<Object> getSelectedGraphObject() { HashSet<Object> selectedGraphObject = new HashSet<Object>(); Set<GraphNode> nodesSelected = this.getPickedNodes(); Set<GraphEdge> edgesSelected = this.getPickedEdges(); if (edgesSelected.size()==0 && nodesSelected.size()==0) { // --- Nothing selected ----------------------- return null; } else { // --- Something selected --------------------- HashSet<NetworkComponent> fsNetComps = this.graphController.getNetworkModel().getNetworkComponentsFullySelected(nodesSelected); if (fsNetComps==null || fsNetComps.size()==0) { if (nodesSelected.size()==1) { selectedGraphObject.add(nodesSelected.iterator().next()); } } else { selectedGraphObject.addAll(fsNetComps); } } return selectedGraphObject; } /** * Export the current graph as image by using a file selection dialog. */ private void exportAsImage() { String currentFolder = null; if (Application.getGlobalInfo() != null) { // --- Get the last selected folder of Agent.GUI --- currentFolder = Application.getGlobalInfo().getLastSelectedFolderAsString(); } // --- Create instance of JFileChooser ----------------- JFileChooser jfc = new JFileChooser(); jfc.setMultiSelectionEnabled(false); jfc.setAcceptAllFileFilterUsed(false); // --- Add custom icons for file types. ---------------- jfc.setFileView(new ImageFileView()); // --- Add the preview pane. --------------------------- jfc.setAccessory(new ImagePreview(jfc)); // --- Set the file filter ----------------------------- String[] extensionsJPEG = { ImageUtils.jpg, ImageUtils.jpeg }; ConfigurableFileFilter filterJPG = new ConfigurableFileFilter(extensionsJPEG, "JPEG - Image"); ConfigurableFileFilter filterPNG = new ConfigurableFileFilter(ImageUtils.png, "PNG - File"); ConfigurableFileFilter filterGIF = new ConfigurableFileFilter(ImageUtils.gif, "GIF - Image"); jfc.addChoosableFileFilter(filterGIF); jfc.addChoosableFileFilter(filterJPG); jfc.addChoosableFileFilter(filterPNG); jfc.setFileFilter(filterPNG); // --- Maybe set the current directory ----------------- if (currentFolder != null) { jfc.setCurrentDirectory(new File(currentFolder)); } // === Show dialog and wait on user action ============= int state = jfc.showSaveDialog(this); if (state == JFileChooser.APPROVE_OPTION) { ConfigurableFileFilter cff = (ConfigurableFileFilter) jfc.getFileFilter(); String selectedExtension = cff.getFileExtension()[0]; String mustExtension = "." + selectedExtension; File selectedFile = jfc.getSelectedFile(); if (selectedFile != null) { String selectedPath = selectedFile.getAbsolutePath(); if (selectedPath.endsWith(mustExtension) == false) { selectedPath = selectedPath + mustExtension; } // --------------------------------------------- // --- Export current display to image --------- // --------------------------------------------- this.exportAsImage(this.getVisualizationViewer(), selectedPath, selectedExtension); // --------------------------------------------- if (Application.getGlobalInfo() != null) { Application.getGlobalInfo().setLastSelectedFolder(jfc.getCurrentDirectory()); } } } // end APPROVE_OPTION } /** * Export the current graph as image by using specified parameters. * * @param vv the VisualizationViewer * @param file the current file to export to */ private void exportAsImage(BasicGraphGuiVisViewer<GraphNode, GraphEdge> vv, String path2File, String extension) { // --- If the VisualizationViewer is null --------- if (vv == null) { return; } // --- Overwrite existing file ? ------------------ File writeFile = new File(path2File); if (writeFile.exists()) { String msgHead = "Overwrite?"; String msgText = "Overwrite existing file?"; int msgAnswer = JOptionPane.showConfirmDialog(this, msgText, msgHead, JOptionPane.YES_NO_OPTION); if (msgAnswer == JOptionPane.NO_OPTION) { return; } } // --- Lets go ! ---------------------------------- int width = vv.getSize().width; int height = vv.getSize().height; BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics2D graphics = bi.createGraphics(); graphics.fillRect(0, 0, width, height); boolean wasDoubleBuffered=vv.isDoubleBuffered(); vv.setDoubleBuffered(false); vv.paint(graphics); vv.paintComponents(graphics); vv.setDoubleBuffered(wasDoubleBuffered); try { ImageIO.write(bi, extension, writeFile); } catch (Exception e) { e.printStackTrace(); } } /** * Zooms and fits to the window. * @param visViewer the vis viewer */ private void zoomFit2Window(VisualizationViewer<GraphNode, GraphEdge> visViewer) { visViewer.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).setToIdentity(); visViewer.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW).setToIdentity(); this.allowInitialScaling = true; this.zoomSetInitialScalingAndMovement(visViewer); } /** * Sets the initial scaling for the graph on the VisualizationViewer. */ private void zoomSetInitialScalingAndMovement(VisualizationViewer<GraphNode, GraphEdge> visViewer) { if (this.allowInitialScaling == false) return; Graph<GraphNode, GraphEdge> currGraph = visViewer.getGraphLayout().getGraph(); Rectangle2D rectGraph = GraphGlobals.getGraphSpreadDimension(currGraph); Rectangle2D rectVis = visViewer.getVisibleRect(); if (rectVis.isEmpty()) return; Point2D scaleAt = new Point2D.Double(0, 0); this.setDefaultScaleAtPoint(scaleAt); // --- Calculate the scaling -------------------------------- double graphWidth = rectGraph.getWidth() + 2 * this.graphMargin; double graphHeight = rectGraph.getHeight() + 2 * this.graphMargin; double visWidth = rectVis.getWidth(); double visHeight = rectVis.getHeight(); float scaleX = (float) (visWidth / graphWidth); float scaleY = (float) (visHeight / graphHeight); if (scaleX > 1) scaleX = 1; if (scaleY > 1) scaleY = 1; float scale = scaleX; if (scaleX > scaleY) { scale = scaleY; } // --- Calculate the movement in the view ------------------- double moveX = 0; double moveY = 0; if (rectGraph.getX() != 0) { moveX = rectGraph.getX() * (-1) + this.graphMargin; } if (rectGraph.getY() != 0) { moveY = rectGraph.getY() * (-1) + this.graphMargin; } // --- Set movement ----------- visViewer.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW).translate(moveX, moveY); // --- Set scaling ------------ if (scale != 0 && scale != 1) { this.scalingControl.scale(visViewer, scale, scaleAt); } this.allowInitialScaling = false; } /** * Zoom one to one and move the focus, so that the elements as visible. * @param visViewer the VisualizationViewer */ private void zoomOneToOneMoveFocus(VisualizationViewer<GraphNode, GraphEdge> visViewer) { visViewer.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).setToIdentity(); visViewer.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW).setToIdentity(); Graph<GraphNode, GraphEdge> graph = visViewer.getGraphLayout().getGraph(); Rectangle2D graphDimension = GraphGlobals.getGraphSpreadDimension(graph); double moveXOnVisView = graphDimension.getX(); double moveYOnVisView = graphDimension.getX(); if (moveXOnVisView<=graphMargin) { moveXOnVisView = 0; } else { moveXOnVisView = (graphMargin-graphDimension.getX()); } if (moveYOnVisView<=graphMargin) { moveYOnVisView = 0; } else { moveYOnVisView = (graphMargin-graphDimension.getY()); } if ((moveXOnVisView!=0 || moveYOnVisView!=0)) { visViewer.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).translate(moveXOnVisView, moveYOnVisView); } } /** * Zoom component. */ private void zoomComponent() { Set<GraphNode> nodesPicked = this.getVisualizationViewer().getPickedVertexState().getPicked(); if (nodesPicked.size()!=0) { HashSet<NetworkComponent> components = this.graphController.getNetworkModelAdapter().getNetworkComponentsFullySelected(nodesPicked); if (components!=null && components.size()!=0) { // --- Get the dimension of the selected nodes ------ Rectangle2D areaSelected = GraphGlobals.getGraphSpreadDimension(nodesPicked); Point2D areaCenter = new Point2D.Double(areaSelected.getCenterX(), areaSelected.getCenterY()); // --- Create temporary GraphNode ------------------- GraphNode tmpNode = new GraphNode("tmPCenter", areaCenter); this.getVisualizationViewer().getGraphLayout().getGraph().addVertex(tmpNode); // --- Get the needed positions --------------------- Point2D tmpNodePos = this.getVisualizationViewer().getGraphLayout().transform(tmpNode); Point2D visViewCenter = this.getVisualizationViewer().getRenderContext().getMultiLayerTransformer().inverseTransform(this.getVisualizationViewer().getCenter()); // --- Calculate movement --------------------------- final double dx = (visViewCenter.getX() - tmpNodePos.getX()); final double dy = (visViewCenter.getY() - tmpNodePos.getY()); // --- Remove temporary GraphNode and move view ----- this.getVisualizationViewer().getGraphLayout().getGraph().removeVertex(tmpNode); this.getVisualizationViewer().getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).translate(dx, dy); } } } /** * Gets the VisualizationViewer for the satellite view * @return The VisualizationViewer */ public SatelliteVisualizationViewer<GraphNode, GraphEdge> getSatelliteVisualizationViewer() { if (visViewSatellite==null) { // --- Set dimension and create a new SatelliteVisualizationViewer ---- visViewSatellite = new SatelliteVisualizationViewer<GraphNode, GraphEdge>(this.getVisualizationViewer(), this.getDimensionOfSatelliteVisualizationViewer()); visViewSatellite.scaleToLayout(this.scalingControl); visViewSatellite.setGraphMouse(new SatelliteGraphMouse(1/1.1f, 1.1f)); // --- Configure the node shape and size ------------------------------ visViewSatellite.getRenderContext().setVertexShapeTransformer(this.getVisualizationViewer().getRenderContext().getVertexShapeTransformer()); // --- Configure node icons, if configured ---------------------------- visViewSatellite.getRenderContext().setVertexIconTransformer(this.getVisualizationViewer().getRenderContext().getVertexIconTransformer()); // --- Configure node colors ------------------------------------------ visViewSatellite.getRenderContext().setVertexFillPaintTransformer(this.getVisualizationViewer().getRenderContext().getVertexFillPaintTransformer()); // --- Configure node label transformer ------------------------------- visViewSatellite.getRenderContext().setVertexLabelTransformer(this.getVisualizationViewer().getRenderContext().getVertexLabelTransformer()); // --- Use straight lines as edges ------------------------------------ visViewSatellite.getRenderContext().setEdgeShapeTransformer(this.getVisualizationViewer().getRenderContext().getEdgeShapeTransformer()); // --- Set edge width ------------------------------------------------- visViewSatellite.getRenderContext().setEdgeStrokeTransformer(this.getVisualizationViewer().getRenderContext().getEdgeStrokeTransformer()); // --- Configure edge color ------------------------------------------- visViewSatellite.getRenderContext().setEdgeDrawPaintTransformer(this.getVisualizationViewer().getRenderContext().getEdgeDrawPaintTransformer()); visViewSatellite.getRenderContext().setArrowFillPaintTransformer(this.getVisualizationViewer().getRenderContext().getEdgeDrawPaintTransformer()); visViewSatellite.getRenderContext().setArrowDrawPaintTransformer(this.getVisualizationViewer().getRenderContext().getEdgeDrawPaintTransformer()); // --- Configure Edge Image Labels ------------------------------------ visViewSatellite.getRenderContext().setEdgeLabelTransformer(this.getVisualizationViewer().getRenderContext().getEdgeLabelTransformer()); // --- Set edge renderer for a background color of an edge ------------ visViewSatellite.getRenderer().setEdgeRenderer(this.getVisualizationViewer().getRenderer().getEdgeRenderer()); } return visViewSatellite; } /** * Returns the dimension of the SatelliteVisualizationViewer. * @return the vis view satellite dimension */ private Dimension getDimensionOfSatelliteVisualizationViewer() { double ratio = 0.3; Dimension vvSize = this.getVisualizationViewer().getSize(); Dimension visViewSateliteSize = new Dimension((int)(vvSize.getWidth()*ratio), (int) (vvSize.getHeight()*ratio)); return visViewSateliteSize; } /** * Returns the satellite view. * @return the satellite view */ private SatelliteDialog getSatelliteDialog() { if (satelliteDialog==null){ Frame ownerFrame = Application.getGlobalInfo().getOwnerFrameForComponent(this); if (ownerFrame!=null) { satelliteDialog = new SatelliteDialog(ownerFrame, this.graphController, this); } else { Dialog ownerDialog = Application.getGlobalInfo().getOwnerDialogForComponent(this); satelliteDialog = new SatelliteDialog(ownerDialog, this.graphController, this); } satelliteDialog.setSize(this.getDimensionOfSatelliteVisualizationViewer()); } return satelliteDialog; } /** * Sets the satellite view. * @param satelliteDialog the new satellite view */ private void setSatelliteDialog(SatelliteDialog satelliteDialog) { this.satelliteDialog = satelliteDialog; } /** * Disposes the satellite view. */ private void disposeSatelliteView() { if (this.satelliteDialog!=null) { this.satelliteDialog.setVisible(false); this.satelliteDialog.dispose(); this.setSatelliteDialog(null); } } /** * Converts an {@link Image} to a {@link BufferedImage} * @param image The image * @return The buffered image */ private BufferedImage convertToBufferedImage(Image image){ BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D biGraphics = bufferedImage.createGraphics(); biGraphics.drawImage(image, 0, 0, null); biGraphics.dispose(); return bufferedImage; } /** * Replaces a specified color with another one in an image. * @param image The image * @param oldColor The color that will be replaced * @param newColor The new color * @return The image */ private BufferedImage exchangeColor(BufferedImage image, Color oldColor, Color newColor){ for(int x=0; x<image.getWidth(); x++){ for(int y=0; y<image.getHeight(); y++){ Color currentColor = new Color(image.getRGB(x, y)); if(currentColor.equals(oldColor)){ image.setRGB(x, y, newColor.getRGB()); } } } return image; } /* (non-Javadoc) * @see java.util.Observer#update(java.util.Observable, java.lang.Object) */ @Override public void update(Observable observable, Object object) { if (object instanceof NetworkModelNotification) { NetworkModelNotification nmNotification = (NetworkModelNotification) object; int reason = nmNotification.getReason(); Object infoObject = nmNotification.getInfoObject(); switch (reason) { case NetworkModelNotification.NETWORK_MODEL_Reload: this.reLoadGraph(); break; case NetworkModelNotification.NETWORK_MODEL_Satellite_View: Boolean visible = (Boolean) infoObject; this.getSatelliteDialog().setVisible(visible); this.zoomFit2Window(this.getSatelliteVisualizationViewer()); break; case NetworkModelNotification.NETWORK_MODEL_Repaint: this.repaintGraph(); break; case NetworkModelNotification.NETWORK_MODEL_Component_Added: case NetworkModelNotification.NETWORK_MODEL_Component_Removed: case NetworkModelNotification.NETWORK_MODEL_Nodes_Merged: case NetworkModelNotification.NETWORK_MODEL_Nodes_Splited: case NetworkModelNotification.NETWORK_MODEL_Merged_With_Supplement_NetworkModel: this.clearPickedObjects(); this.repaintGraph(); break; case NetworkModelNotification.NETWORK_MODEL_Component_Renamed: this.clearPickedObjects(); NetworkComponentRenamed renamed = (NetworkComponentRenamed) infoObject; this.selectObject(renamed.getNetworkComponent()); break; case NetworkModelNotification.NETWORK_MODEL_Component_Select: this.selectObject(infoObject); break; case NetworkModelNotification.NETWORK_MODEL_Zoom_Fit2Window: this.zoomFit2Window(this.getVisualizationViewer()); break; case NetworkModelNotification.NETWORK_MODEL_Zoom_One2One: this.zoomOneToOneMoveFocus(this.getVisualizationViewer()); break; case NetworkModelNotification.NETWORK_MODEL_Zoom_Component: this.zoomComponent(); break; case NetworkModelNotification.NETWORK_MODEL_Zoom_In: this.getScalingControl().scale(this.getVisualizationViewer(), 1.1f, this.getDefaultScaleAtPoint()); break; case NetworkModelNotification.NETWORK_MODEL_Zoom_Out: this.getScalingControl().scale(this.getVisualizationViewer(), 1 / 1.1f, this.getDefaultScaleAtPoint()); break; case NetworkModelNotification.NETWORK_MODEL_ExportGraphAsImage: this.exportAsImage(); break; case NetworkModelNotification.NETWORK_MODEL_GraphMouse_Picking: this.getVisualizationViewer().setGraphMouse(this.getPluggableGraphMouse()); break; case NetworkModelNotification.NETWORK_MODEL_GraphMouse_Transforming: this.getVisualizationViewer().setGraphMouse(this.getDefaultModalGraphMouse()); break; default: break; } } } }
eclipseProjects/org.agentgui/bundles/org.agentgui.core/src/agentgui/envModel/graph/controller/ui/BasicGraphGui.java
/** * *************************************************************** * Agent.GUI is a framework to develop Multi-agent based simulation * applications based on the JADE - Framework in compliance with the * FIPA specifications. * Copyright (C) 2010 Christian Derksen and DAWIS * http://www.dawis.wiwi.uni-due.de * http://sourceforge.net/projects/agentgui/ * http://www.agentgui.org * * GNU Lesser General Public License * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * ************************************************************** */ package agentgui.envModel.graph.controller.ui; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.event.ContainerAdapter; import java.awt.event.ContainerEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Observable; import java.util.Observer; import java.util.Set; import java.util.Vector; import javax.imageio.ImageIO; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JToolBar; import org.apache.commons.collections15.Transformer; import agentgui.core.application.Application; import agentgui.core.gui.imaging.ConfigurableFileFilter; import agentgui.core.gui.imaging.ImageFileView; import agentgui.core.gui.imaging.ImagePreview; import agentgui.core.gui.imaging.ImageUtils; import agentgui.envModel.graph.GraphGlobals; import agentgui.envModel.graph.commands.RenameNetworkComponent.NetworkComponentRenamed; import agentgui.envModel.graph.controller.GraphEnvironmentController; import agentgui.envModel.graph.controller.GraphEnvironmentControllerGUI; import agentgui.envModel.graph.networkModel.ComponentTypeSettings; import agentgui.envModel.graph.networkModel.EdgeShapePolyline; import agentgui.envModel.graph.networkModel.GeneralGraphSettings4MAS; import agentgui.envModel.graph.networkModel.GraphEdge; import agentgui.envModel.graph.networkModel.GraphElement; import agentgui.envModel.graph.networkModel.GraphElementLayout; import agentgui.envModel.graph.networkModel.GraphNode; import agentgui.envModel.graph.networkModel.NetworkComponent; import agentgui.envModel.graph.networkModel.NetworkModelNotification; import edu.uci.ics.jung.algorithms.layout.Layout; import edu.uci.ics.jung.algorithms.layout.StaticLayout; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.visualization.FourPassImageShaper; import edu.uci.ics.jung.visualization.GraphZoomScrollPane; import edu.uci.ics.jung.visualization.Layer; import edu.uci.ics.jung.visualization.LayeredIcon; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.CrossoverScalingControl; import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse; import edu.uci.ics.jung.visualization.control.PluggableGraphMouse; import edu.uci.ics.jung.visualization.control.SatelliteVisualizationViewer; import edu.uci.ics.jung.visualization.control.ScalingControl; import edu.uci.ics.jung.visualization.decorators.AbstractEdgeShapeTransformer; import edu.uci.ics.jung.visualization.decorators.AbstractVertexShapeTransformer; import edu.uci.ics.jung.visualization.decorators.ConstantDirectionalEdgeValueTransformer; import edu.uci.ics.jung.visualization.decorators.EdgeShape; import edu.uci.ics.jung.visualization.picking.PickedState; import edu.uci.ics.jung.visualization.picking.ShapePickSupport; import edu.uci.ics.jung.visualization.renderers.Checkmark; /** * This class implements a GUI component for displaying visualizations for JUNG graphs. <br> * This class also has a toolbar component which provides various features for editing, importing and interacting with the graph. * * @see GraphEnvironmentControllerGUI * @see GraphEnvironmentMousePlugin * * @author Nils Loose - DAWIS - ICB University of Duisburg - Essen * @author Satyadeep Karnati - CSE - Indian Institute of Technology, Guwahati * @author Christian Derksen - DAWIS - ICB - University of Duisburg - Essen */ public class BasicGraphGui extends JPanel implements Observer { private static final long serialVersionUID = 5764679914667183305L; /** * The enumeration ToolBarType describes the toolbar type available in the {@link BasicGraphGui}. */ public enum ToolBarType { ViewControl, EditControl } /** * The enumeration ToolBarSurrounding describes, if a customised toolbar button is to be shown during configuration or during runtime. */ public enum ToolBarSurrounding { Both, ConfigurationOnly, RuntimeOnly } /** Environment model controller, to be passed by the parent GUI. */ private GraphEnvironmentController graphController; /** The GUI's main component, either the graph visualization, or an empty JPanel if no graph is loaded */ private GraphZoomScrollPane graphZoomScrollPane; /** The ToolBar for this component */ private BasicGraphGuiTools graphGuiTools; private JPanel jPanelToolBars; /** Graph visualisation component */ private BasicGraphGuiVisViewer<GraphNode, GraphEdge> visView; private boolean isCreatedVisualizationViewer; private SatelliteDialog satelliteDialog; private SatelliteVisualizationViewer<GraphNode, GraphEdge> visViewSatellite; /** JUNG object handling zooming */ private ScalingControl scalingControl = new CrossoverScalingControl(); /** the margin of the graph for the visualization */ private double graphMargin = 25; private Point2D defaultScaleAtPoint = new Point2D.Double(graphMargin, graphMargin); /** Indicates that the initial scaling is allowed */ private boolean allowInitialScaling = true; private PluggableGraphMouse pluggableGraphMouse; private GraphEnvironmentMousePlugin graphEnvironmentMousePlugin; private GraphEnvironmentPopupPlugin<GraphNode, GraphEdge> graphEnvironmentPopupPlugin; private DefaultModalGraphMouse<GraphNode, GraphEdge> defaultModalGraphMouse; /** * This is the default constructor * @param controller The Graph Environment controller */ public BasicGraphGui(GraphEnvironmentController controller) { this.graphController = controller; this.graphController.addObserver(this); this.initialize(); this.reLoadGraph(); } /** * This method initializes this */ private void initialize() { // --- Set appearance ----------------------------- this.setVisible(true); this.setSize(300, 300); this.setLayout(new BorderLayout()); this.setDoubleBuffered(true); // --- Add components ----------------------------- this.add(this.getJPanelToolBars(), BorderLayout.WEST); this.add(this.getGraphZoomScrollPane(), BorderLayout.CENTER); this.addContainerListener(new ContainerAdapter() { boolean doneAdded = false; @Override public void componentAdded(ContainerEvent ce) { if (doneAdded==false) { validate(); zoomSetInitialScalingAndMovement(getVisualizationViewer()); doneAdded=true; } } }); } /** * Returns the instance of the BasicGraphGuiTools. * @return the BasicGraphGuiTools */ private BasicGraphGuiTools getBasicGraphGuiTools() { if (graphGuiTools==null) { graphGuiTools = new BasicGraphGuiTools(this.graphController); } return graphGuiTools; } /** * Returns the specified JToolBar of the {@link BasicGraphGui}. * * @param toolBarType the tool bar type * @return the j tool bar */ public JToolBar getJToolBar(ToolBarType toolBarType) { JToolBar toolBar = null; switch (toolBarType) { case EditControl: toolBar = this.getBasicGraphGuiTools().getJToolBarEdit(); break; case ViewControl: toolBar = this.getBasicGraphGuiTools().getJToolBarView(); break; } return toolBar; } /** * Returns the JPanel with the tool bars. * @return the j panel tool bars */ private JPanel getJPanelToolBars() { if (jPanelToolBars==null) { jPanelToolBars = new JPanel(); jPanelToolBars.setLayout(new BoxLayout(jPanelToolBars, BoxLayout.X_AXIS)); jPanelToolBars.add(this.getBasicGraphGuiTools().getJToolBarView(), null); // --- In case of editing the simulation setup ---------- if (this.graphController.getProject()!=null) { jPanelToolBars.add(this.getBasicGraphGuiTools().getJToolBarEdit(), null); } } return jPanelToolBars; } /** * Dispose this panel. */ public void dispose() { this.disposeSatelliteView(); this.setVisualizationViewer(null); } /** * Gets the graph environment controller. * @return the controller */ public GraphEnvironmentController getGraphEnvironmentController() { return this.graphController; } /** * Gets the scaling control. * @return the scalingControl */ private ScalingControl getScalingControl() { return this.scalingControl; } /** * Returns the PluggableGraphMouse. * @return the pluggableGraphMouse */ public PluggableGraphMouse getPluggableGraphMouse() { if (pluggableGraphMouse==null) { pluggableGraphMouse = new PluggableGraphMouse(); pluggableGraphMouse.add(this.getGraphEnvironmentMousePlugin()); pluggableGraphMouse.add(this.getGraphEnvironmentPopupPlugin()); } return pluggableGraphMouse; } /** * Returns the {@link GraphEnvironmentMousePlugin} * @return the graph environment mouse plugin */ private GraphEnvironmentMousePlugin getGraphEnvironmentMousePlugin() { if (graphEnvironmentMousePlugin==null) { graphEnvironmentMousePlugin = new GraphEnvironmentMousePlugin(this); } return graphEnvironmentMousePlugin; } /** * Returns the GraphEnvironmentPopupPlugin. * @return the graph environment popup plugin */ private GraphEnvironmentPopupPlugin<GraphNode, GraphEdge> getGraphEnvironmentPopupPlugin() { if (graphEnvironmentPopupPlugin==null) { graphEnvironmentPopupPlugin = new GraphEnvironmentPopupPlugin<GraphNode, GraphEdge>(this); graphEnvironmentPopupPlugin.setEdgePopup(this.getBasicGraphGuiTools().getEdgePopup()); graphEnvironmentPopupPlugin.setVertexPopup(this.getBasicGraphGuiTools().getVertexPopup()); } return graphEnvironmentPopupPlugin; } /** * Gets the DefaultModalGraphMouse. * @return the default modal graph mouse */ private DefaultModalGraphMouse<GraphNode, GraphEdge> getDefaultModalGraphMouse() { if (defaultModalGraphMouse == null) { defaultModalGraphMouse = new DefaultModalGraphMouse<GraphNode, GraphEdge>(1/1.1f, 1.1f); } return defaultModalGraphMouse; } /** * Gets the default point to scale at for zooming. * @return the default scale at point */ private Point2D getDefaultScaleAtPoint() { Rectangle2D rectVis = this.getVisualizationViewer().getVisibleRect(); if (rectVis.isEmpty()==false) { this.defaultScaleAtPoint = new Point2D.Double(rectVis.getCenterX(), rectVis.getCenterY()); } return defaultScaleAtPoint; } /** * Sets the default point to scale at for zooming.. * @param scalePoint the new default scale at point */ private void setDefaultScaleAtPoint(Point2D scalePoint) { defaultScaleAtPoint = scalePoint; } /** * This method assigns a graph to a new VisualizationViewer and adds it to the GUI. */ private void reLoadGraph() { // --- Display the current Graph ------------------ Graph<GraphNode, GraphEdge> graph = this.getGraph(); this.getVisualizationViewer().getGraphLayout().setGraph(graph); this.validate(); this.zoomFit2Window(this.getVisualizationViewer()); this.getSatelliteVisualizationViewer().getGraphLayout().setGraph(graph); // this.reloadSatelliteView(); this.zoomFit2Window(this.getSatelliteVisualizationViewer()); } /** * Gets the current Graph and repaints the visualisation viewer. */ private void repaintGraph() { Graph<GraphNode, GraphEdge> graph = this.getGraph(); if (graph!=null && this.getVisualizationViewer().getGraphLayout().getGraph()!=graph) { this.getVisualizationViewer().getGraphLayout().setGraph(graph); } this.getVisualizationViewer().repaint(); } /** * Controls the shape, size, and aspect ratio for each vertex. * * @author Satyadeep Karnati - CSE - Indian Institute of Technology, Guwahati * @author Christian Derksen - DAWIS - ICB - University of Duisburg - Essen */ private final class VertexShapeSizeAspect<V, E> extends AbstractVertexShapeTransformer<GraphNode> implements Transformer<GraphNode, Shape> { private Map<String, Shape> shapeMap = new HashMap<String, Shape>(); public VertexShapeSizeAspect() { this.setSizeTransformer(new Transformer<GraphNode, Integer>() { @Override public Integer transform(GraphNode node) { return (int) node.getGraphElementLayout(graphController.getNetworkModel()).getSize(); } }); } /* * (non-Javadoc) * * @see org.apache.commons.collections15.Transformer#transform(java.lang.Object) */ @Override public Shape transform(GraphNode node) { Shape shape = factory.getEllipse(node); // DEFAULT String shapeForm = node.getGraphElementLayout(graphController.getNetworkModel()).getShapeForm(); if (shapeForm==null) { // --- nothing to do here ---- } else if (shapeForm.equals(GeneralGraphSettings4MAS.SHAPE_RECTANGLE)) { shape = factory.getRectangle(node); } else if (shapeForm.equals(GeneralGraphSettings4MAS.SHAPE_ROUND_RECTANGLE)) { shape = factory.getRoundRectangle(node); } else if (shapeForm.equals(GeneralGraphSettings4MAS.SHAPE_REGULAR_POLYGON)) { shape = factory.getRegularPolygon(node, 6); } else if (shapeForm.equals(GeneralGraphSettings4MAS.SHAPE_REGULAR_STAR)) { shape = factory.getRegularStar(node, 6); } else if (shapeForm.equals(GeneralGraphSettings4MAS.SHAPE_IMAGE_SHAPE)) { String imageRef = node.getGraphElementLayout(graphController.getNetworkModel()).getImageReference(); //TODO only rebuild if changed //shape = shapeMap.get(imageRef); Shape imageShape = null; ImageIcon imageIcon = GraphGlobals.getImageIcon(imageRef); if (imageIcon != null) { Image image = imageIcon.getImage(); imageShape = FourPassImageShaper.getShape(image, 30); if (imageShape .getBounds().getWidth() > 0 && imageShape .getBounds().getHeight() > 0) { // don't cache a zero-sized shape, wait for the image to be ready int width = image.getWidth(null); int height = image.getHeight(null); AffineTransform transform = AffineTransform.getTranslateInstance(-width / 2, -height / 2); imageShape = transform.createTransformedShape(imageShape ); this.shapeMap.put(imageRef, imageShape ); } } else { System.err.println("Could not find node image '" + imageRef + "'"); } if (imageShape!=null) shape = imageShape; } return shape; } } /** * Returns the current graph. * @return the graph */ private Graph<GraphNode, GraphEdge> getGraph() { return this.graphController.getNetworkModel().getGraph(); } /** * Gets the graph zoom scroll pane. * @return the graph zoom scroll pane */ public GraphZoomScrollPane getGraphZoomScrollPane() { if (graphZoomScrollPane==null) { graphZoomScrollPane = new GraphZoomScrollPane(this.getVisualizationViewer()); } return graphZoomScrollPane; } /** * Returns if the visualization viewer was fully created. * @return true, if is created visualization viewer */ public boolean isCreatedVisualizationViewer() { return isCreatedVisualizationViewer; } /** * Sets the VisualizationViewer. * @param newVisView the new VisualizationViewer */ private void setVisualizationViewer(BasicGraphGuiVisViewer<GraphNode, GraphEdge> newVisView) { this.visView = newVisView; } /** * Gets the VisualizationViewer * @return The VisualizationViewer */ public BasicGraphGuiVisViewer<GraphNode, GraphEdge> getVisualizationViewer() { if (visView==null) { // ---------------------------------------------------------------- // --- Get the current graph -------------------------------------- // ---------------------------------------------------------------- Graph<GraphNode, GraphEdge> graph = this.getGraph(); // ---------------------------------------------------------------- // --- Define graph layout ---------------------------------------- // ---------------------------------------------------------------- Layout<GraphNode, GraphEdge> layout = new StaticLayout<GraphNode, GraphEdge>(graph); Rectangle2D graphDimension = GraphGlobals.getGraphSpreadDimension(graph); layout.setSize(new Dimension((int) (graphDimension.getWidth() + 2 * graphMargin), (int) (graphDimension.getHeight() + 2 * graphMargin))); layout.setInitializer(new Transformer<GraphNode, Point2D>() { @Override public Point2D transform(GraphNode node) { return node.getPosition(); // The position is specified in the GraphNode instance } }); // ---------------------------------------------------------------- // --- Create a new VisualizationViewer instance ------------------ // ---------------------------------------------------------------- visView = new BasicGraphGuiVisViewer<GraphNode, GraphEdge>(layout); visView.setBackground(Color.WHITE); visView.setDoubleBuffered(true); // --- Configure mouse and key interaction ------------------------ visView.setGraphMouse(this.getPluggableGraphMouse()); visView.addKeyListener(this.getGraphEnvironmentMousePlugin()); // --- Set the pick size of the visualisation viewer -------- ((ShapePickSupport<GraphNode, GraphEdge>) visView.getPickSupport()).setPickSize(5); // ---------------------------------------------------------------- // --- Define edge and node ToolTip --------------------- Start --- // ---------------------------------------------------------------- // --- Edge ------------------------------------------------------- visView.setVertexToolTipTransformer(new Transformer<GraphNode, String>() { @Override public String transform(GraphNode node) { HashSet<NetworkComponent> netCompsAtNode = graphController.getNetworkModel().getNetworkComponents(node); NetworkComponent netCompDisNode = graphController.getNetworkModel().getDistributionNode(netCompsAtNode); // --- Generally define the toolTip ----------------------- String toolTip = "<html><b>GraphNode: " + node.getId() + "</b>"; if (netCompDisNode!=null) { // --- In case of a distribution node ----------------- String type = netCompDisNode.getType(); String domain = "unknown"; String isAgent = "?"; ComponentTypeSettings cts = graphController.getGeneralGraphSettings4MAS().getCurrentCTS().get(type); if (cts!=null) { domain = cts.getDomain(); if (cts.getAgentClass()==null) { isAgent = "No"; } else { isAgent = "Yes"; } } // --- Define the ToolTip ----------------------------- toolTip += "<br><b>NetworkComponent: " + netCompDisNode.getId() + "</b><br>(Domain: " + domain + ", Type: " + type + ", isAgent: " + isAgent + ")"; } // --- Show position in edit mode only -------------------- if (graphController.getProject()!=null) { toolTip += "<br>(x=" + node.getPosition().getX() + " - y=" + node.getPosition().getY() + ")"; } toolTip += "</html>"; return toolTip; } }); // --- Node ------------------------------------------------------- visView.setEdgeToolTipTransformer(new Transformer<GraphEdge, String>() { @Override public String transform(GraphEdge edge) { String toolTip = null; NetworkComponent netComp = graphController.getNetworkModel().getNetworkComponent(edge); if (netComp!=null) { String type = netComp.getType(); String domain = "unknown"; String isAgent = "?"; ComponentTypeSettings cts = graphController.getGeneralGraphSettings4MAS().getCurrentCTS().get(type); if (cts!=null) { domain = cts.getDomain(); if (cts.getAgentClass()==null) { isAgent = "No"; } else { isAgent = "Yes"; } } // --- Define the ToolTip ----------------------------- toolTip = "<html>"; toolTip += "<b>NetworkComponent: " + netComp.getId() + "</b><br>(Domain: " + domain + ", Type: " + type + ", isAgent: " + isAgent + ")"; toolTip += "</html>"; } return toolTip; } }); // ---------------------------------------------------------------- // --- Define edge and node ToolTip ------------------------ End--- // ---------------------------------------------------------------- // ---------------------------------------------------------------- // --- Node configurations ------------------------------ Start --- // ---------------------------------------------------------------- // --- Configure the node shape and size -------------------------- visView.getRenderContext().setVertexShapeTransformer(new VertexShapeSizeAspect<GraphNode, GraphEdge>()); // --- Configure node icons, if configured ------------------------ visView.getRenderContext().setVertexIconTransformer(new Transformer<GraphNode, Icon>() { private final String pickedPostfix = "[picked]"; private HashMap<String, LayeredIcon> iconHash = new HashMap<String, LayeredIcon>(); @Override public Icon transform(GraphNode node) { Icon icon = null; GraphElementLayout nodeLayout = node.getGraphElementLayout(graphController.getNetworkModel()); boolean picked = visView.getPickedVertexState().isPicked(node); String nodeImagePath = nodeLayout.getImageReference(); if (nodeImagePath != null) { if (nodeImagePath.equals("MissingIcon")==false) { // --- 1. Search in the local Hash ------ LayeredIcon layeredIcon = null; Color currentColor = nodeLayout.getColor(); String colorPostfix = "[" + currentColor.getRGB() + "]"; if (picked == true) { layeredIcon = this.iconHash.get(nodeImagePath + colorPostfix + this.pickedPostfix); } else { layeredIcon = this.iconHash.get(nodeImagePath + colorPostfix); } // --- 2. If necessary, load the image -- if (layeredIcon == null) { ImageIcon imageIcon = GraphGlobals.getImageIcon(nodeImagePath); // --- Prepare the image --------- BufferedImage bufferedImage; if (currentColor.equals(Color.WHITE) || currentColor.equals(Color.BLACK)) { // --- If the color is set to black or white, just use the unchanged image ---------- bufferedImage = convertToBufferedImage(imageIcon.getImage()); } else { // --- Otherwise, replace the defined basic color with the one specified in the node layout --------- bufferedImage = exchangeColor(convertToBufferedImage(imageIcon.getImage()), GeneralGraphSettings4MAS.IMAGE_ICON_BASIC_COLOR, currentColor); } if (bufferedImage != null) { // --- 3. Remind this images ---- LayeredIcon layeredIconUnPicked = new LayeredIcon(bufferedImage); this.iconHash.put(nodeImagePath + colorPostfix, layeredIconUnPicked); LayeredIcon layeredIconPicked = new LayeredIcon(bufferedImage); layeredIconPicked.add(new Checkmark(nodeLayout.getColorPicked())); this.iconHash.put(nodeImagePath + colorPostfix + this.pickedPostfix, layeredIconPicked); // --- 4. Return the right one -- if (picked == true) { layeredIcon = layeredIconPicked; } else { layeredIcon = layeredIconUnPicked; } } } icon = layeredIcon; } } return icon; } }); // --- Configure node colors -------------------------------------- visView.getRenderContext().setVertexFillPaintTransformer(new Transformer<GraphNode, Paint>() { @Override public Paint transform(GraphNode node) { if (visView.getPickedVertexState().isPicked(node)) { return node.getGraphElementLayout(graphController.getNetworkModel()).getColorPicked(); } return node.getGraphElementLayout(graphController.getNetworkModel()).getColor(); } }); // --- Configure to show node labels ------------------------------ visView.getRenderContext().setVertexLabelTransformer(new Transformer<GraphNode, String>() { @Override public String transform(GraphNode node) { if (node.getGraphElementLayout(graphController.getNetworkModel()).isShowLabel()==true) { return node.getGraphElementLayout(graphController.getNetworkModel()).getLabelText(); } return null; } }); // ---------------------------------------------------------------- // --- Edge configurations ------------------------------ Start --- // ---------------------------------------------------------------- // --- Configure edge label position ------------------------------ visView.getRenderContext().setLabelOffset(6); visView.getRenderContext().setEdgeLabelClosenessTransformer(new ConstantDirectionalEdgeValueTransformer<GraphNode, GraphEdge>(.5, .5)); // --- Set the EdgeShape of the Visualisation Viewer -------------- this.setEdgeShapeTransformer(visView); // --- Set edge width --------------------------------------------- visView.getRenderContext().setEdgeStrokeTransformer(new Transformer<GraphEdge, Stroke>() { @Override public Stroke transform(GraphEdge edge) { return new BasicStroke(edge.getGraphElementLayout(graphController.getNetworkModel()).getSize()); } }); // --- Configure edge color --------------------------------------- Transformer<GraphEdge, Paint> edgeColorTransformer = new Transformer<GraphEdge, Paint>() { @Override public Paint transform(GraphEdge edge) { Color initColor = edge.getGraphElementLayout(graphController.getNetworkModel()).getColor(); if (visView.getPickedEdgeState().isPicked(edge)) { initColor = edge.getGraphElementLayout(graphController.getNetworkModel()).getColorPicked(); } return initColor; }}; visView.getRenderContext().setEdgeDrawPaintTransformer(edgeColorTransformer); visView.getRenderContext().setArrowFillPaintTransformer(edgeColorTransformer); visView.getRenderContext().setArrowDrawPaintTransformer(edgeColorTransformer); // --- Configure Edge Image Labels -------------------------------- visView.getRenderContext().setEdgeLabelTransformer(new Transformer<GraphEdge, String>() { @Override public String transform(GraphEdge edge) { // --- Get the needed info -------------------------------- String imageRef = edge.getGraphElementLayout(graphController.getNetworkModel()).getImageReference(); boolean showLabel = edge.getGraphElementLayout(graphController.getNetworkModel()).isShowLabel(); // --- Configure color ------------------------------------ Color color = Color.BLACK; if (visView.getPickedEdgeState().isPicked(edge)) { color = edge.getGraphElementLayout(graphController.getNetworkModel()).getColorPicked(); } String htmlColor = String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue()); // --- Get the text / image content ----------------------- String content = ""; if (showLabel) { content = edge.getId(); } if (imageRef!= null) { URL url = getImageURL(imageRef); if (url != null) { if (showLabel) { content = content + "<br><img src='" + url + "'>"; } else { content = "<img src='" + url + "'>"; } } } // --- Set the return value ------------------------------- String textDisplay = "<html><center><font color='[COLOR]'>[CONTENT]</font></center></html>"; textDisplay = textDisplay.replace("[COLOR]", htmlColor); textDisplay = textDisplay.replace("[CONTENT]", content); return textDisplay; } }); // --- Set edge renderer for a background color of an edge -------- visView.getRenderer().setEdgeRenderer(new GraphEnvironmentEdgeRenderer() { @Override public boolean isShowMarker(GraphEdge edge) { return edge.getGraphElementLayout(graphController.getNetworkModel()).isMarkerShow(); } @Override public float getMarkerStrokeWidth(GraphEdge edge) { return edge.getGraphElementLayout(graphController.getNetworkModel()).getMarkerStrokeWidth(); } @Override public Color getMarkerColor(GraphEdge edge) { return edge.getGraphElementLayout(graphController.getNetworkModel()).getMarkerColor(); } }); this.isCreatedVisualizationViewer=true; } return visView; } /** * Searches and returns the image url for the specified image reference. * * @param imageRef the image reference * @return the URL of the image */ private URL getImageURL(String imageRef){ // --- Abort URL generation --------------------------------- if (imageRef.equals("MissingIcon")==true) return null; // --- Resource by the class loader, as configured ---------- URL url = getClass().getResource(imageRef); if (url!=null) return url; // --- Prepare folder for projects -------------------------- String projectsFolder = Application.getGlobalInfo().getPathProjects(); projectsFolder = projectsFolder.replace("\\", "/"); // --- Resource by file, in projects, absolute -------------- String extImageRef = (projectsFolder + imageRef).replace("//", "/"); try { url = new URL("file", null, -1, extImageRef); if (url!=null) return url; } catch (MalformedURLException urlEx) { //urlEx.printStackTrace(); } // --- Nothing found ---------------------------------------- return null; } /** * Sets the edge shape transformer according to the {@link GeneralGraphSettings4MAS}. * @see GeneralGraphSettings4MAS#getEdgeShape() */ public void setEdgeShapeTransformer() { this.setEdgeShapeTransformer(this.getVisualizationViewer()); } /** * Sets the edge shape transformer according to the {@link GeneralGraphSettings4MAS}. * @see GeneralGraphSettings4MAS#getEdgeShape() * @param visViewer the vis viewer */ public void setEdgeShapeTransformer(BasicGraphGuiVisViewer<GraphNode, GraphEdge> visViewer) { // --- Use straight lines as edges ? ------------------------------ AbstractEdgeShapeTransformer<GraphNode, GraphEdge> edgeShapeTransformer = null; switch (this.getGraphEnvironmentController().getNetworkModelAdapter().getGeneralGraphSettings4MAS().getEdgeShape()) { case BentLine: edgeShapeTransformer = new EdgeShape.BentLine<GraphNode, GraphEdge>(); break; case Box: edgeShapeTransformer = new EdgeShape.Box<GraphNode, GraphEdge>(); break; case CubicCurve: edgeShapeTransformer = new EdgeShape.CubicCurve<GraphNode, GraphEdge>(); break; case Line: edgeShapeTransformer = new EdgeShape.Line<GraphNode, GraphEdge>(); break; case Polyline: edgeShapeTransformer = new EdgeShapePolyline<GraphNode, GraphEdge>(); break; case Loop: edgeShapeTransformer = new EdgeShape.Loop<GraphNode, GraphEdge>(); break; case Orthogonal: edgeShapeTransformer = new EdgeShape.Orthogonal<GraphNode, GraphEdge>(); break; case QuadCurve: edgeShapeTransformer = new EdgeShape.QuadCurve<GraphNode, GraphEdge>(); break; case SimpleLoop: edgeShapeTransformer = new EdgeShape.SimpleLoop<GraphNode, GraphEdge>(); break; case Wedge: edgeShapeTransformer = new EdgeShape.Wedge<GraphNode, GraphEdge>(5); break; default: edgeShapeTransformer = new EdgeShape.Line<GraphNode, GraphEdge>(); break; } visViewer.getRenderContext().setEdgeShapeTransformer(edgeShapeTransformer); visViewer.repaint(); } /** * This method notifies the observers about a graph object selection * @param pickedObject The selected object */ public void handleObjectLeftClick(Object pickedObject) { this.selectObject(pickedObject); } /** * Notifies the observers that this object is right clicked * @param pickedObject the selected object */ public void handleObjectRightClick(Object pickedObject) { this.selectObject(pickedObject); } /** * Invoked when a graph node or edge is double clicked (left or right) * @param pickedObject */ public void handleObjectDoubleClick(Object pickedObject) { this.selectObject(pickedObject); if (pickedObject instanceof GraphNode) { // --- Set the local variable --------------------------- GraphNode graphNode = (GraphNode) pickedObject; // --- Is the GraphNode a DistributionNode ? ------------ NetworkComponent networkComponent = this.graphController.getNetworkModel().isDistributionNode(graphNode); if (networkComponent!=null) { // --- Yes! Show the PopUp menu for this node ------- NetworkModelNotification nmn = new NetworkModelNotification(NetworkModelNotification.NETWORK_MODEL_ShowPopUpMenue); nmn.setInfoObject(pickedObject); this.graphController.notifyObservers(nmn); return; } } // --- Notify about the editing request for a component ----- NetworkModelNotification nmNote = new NetworkModelNotification(NetworkModelNotification.NETWORK_MODEL_EditComponentSettings); nmNote.setInfoObject(pickedObject); this.graphController.notifyObservers(nmNote); } /** * Clears the picked nodes and edges */ private void clearPickedObjects() { this.getVisualizationViewer().getPickedVertexState().clear(); this.getVisualizationViewer().getPickedEdgeState().clear(); } /** * Sets a node or edge as picked * @param object The GraphNode or GraphEdge to pick */ private void setPickedObject(GraphElement object) { if (object instanceof GraphEdge) { this.getVisualizationViewer().getPickedEdgeState().pick((GraphEdge) object, true); } else if (object instanceof GraphNode) { this.getVisualizationViewer().getPickedVertexState().pick((GraphNode) object, true); } } /** * Marks a group of objects as picked * @param objects The objects */ private void setPickedObjects(Vector<GraphElement> objects) { Iterator<GraphElement> objIter = objects.iterator(); while (objIter.hasNext()) { this.setPickedObject(objIter.next()); } } /** * Returns the node which is picked. If multiple nodes are picked, returns null. * @return GraphNode - the GraphNode which is picked. */ public GraphNode getPickedSingleNode() { Set<GraphNode> nodeSet = this.getVisualizationViewer().getPickedVertexState().getPicked(); if (nodeSet.size() == 1) { return nodeSet.iterator().next(); } return null; } /** * Gets the Set<GraphNode> of picked nodes. * @return the picked nodes */ public Set<GraphNode> getPickedNodes() { PickedState<GraphNode> nodesPicked = this.getVisualizationViewer().getPickedVertexState(); if (nodesPicked!=null) { return nodesPicked.getPicked(); } return null; } /** * Returns the edge which is picked. If multiple nodes are picked, returns null. * @return GraphEdge - the GraphNode which is picked. */ public GraphEdge getPickedSingleEdge() { Set<GraphEdge> edgeSet = this.getVisualizationViewer().getPickedEdgeState().getPicked(); if (edgeSet.size() == 1) { return edgeSet.iterator().next(); } return null; } /** * Gets the Set<GraphEdge> of picked edges. * @return the picked edges */ public Set<GraphEdge> getPickedEdges() { PickedState<GraphEdge> edgesPicked = this.getVisualizationViewer().getPickedEdgeState(); if (edgesPicked!=null) { return edgesPicked.getPicked(); } return null; } /** * Same as selectObject but optionally shows component settings dialog * * @param object * @param showComponentSettingsDialog - shows the dialog if true */ private void selectObject(Object object) { this.clearPickedObjects(); if (object instanceof GraphNode) { this.setPickedObject((GraphElement) object); // --- Is that node a distribution node? ---------------- HashSet<NetworkComponent> netComps = graphController.getNetworkModelAdapter().getNetworkComponents((GraphNode) object); NetworkComponent disNode = graphController.getNetworkModelAdapter().containsDistributionNode(netComps); if (disNode != null) { this.graphController.getNetworkModelAdapter().selectNetworkComponent(disNode); } if (netComps.size() == 1) { this.graphController.getNetworkModelAdapter().selectNetworkComponent(netComps.iterator().next()); this.clearPickedObjects(); this.setPickedObject((GraphElement) object); } } else if (object instanceof GraphEdge) { NetworkComponent netComp = graphController.getNetworkModelAdapter().getNetworkComponent((GraphEdge) object); this.setPickedObjects(graphController.getNetworkModelAdapter().getGraphElementsFromNetworkComponent(netComp)); this.graphController.getNetworkModelAdapter().selectNetworkComponent(netComp); } else if (object instanceof NetworkComponent) { this.setPickedObjects(graphController.getNetworkModelAdapter().getGraphElementsFromNetworkComponent((NetworkComponent) object)); } } /** * Returns the selected graph objects. These are either all selected {@link NetworkComponent}'s * or, in case of the selection of a single {@link GraphNode} * @return the selected graph object */ public Set<Object> getSelectedGraphObject() { HashSet<Object> selectedGraphObject = new HashSet<Object>(); Set<GraphNode> nodesSelected = this.getPickedNodes(); Set<GraphEdge> edgesSelected = this.getPickedEdges(); if (edgesSelected.size()==0 && nodesSelected.size()==0) { // --- Nothing selected ----------------------- return null; } else { // --- Something selected --------------------- HashSet<NetworkComponent> fsNetComps = this.graphController.getNetworkModel().getNetworkComponentsFullySelected(nodesSelected); if (fsNetComps==null || fsNetComps.size()==0) { if (nodesSelected.size()==1) { selectedGraphObject.add(nodesSelected.iterator().next()); } } else { selectedGraphObject.addAll(fsNetComps); } } return selectedGraphObject; } /** * Export the current graph as image by using a file selection dialog. */ private void exportAsImage() { String currentFolder = null; if (Application.getGlobalInfo() != null) { // --- Get the last selected folder of Agent.GUI --- currentFolder = Application.getGlobalInfo().getLastSelectedFolderAsString(); } // --- Create instance of JFileChooser ----------------- JFileChooser jfc = new JFileChooser(); jfc.setMultiSelectionEnabled(false); jfc.setAcceptAllFileFilterUsed(false); // --- Add custom icons for file types. ---------------- jfc.setFileView(new ImageFileView()); // --- Add the preview pane. --------------------------- jfc.setAccessory(new ImagePreview(jfc)); // --- Set the file filter ----------------------------- String[] extensionsJPEG = { ImageUtils.jpg, ImageUtils.jpeg }; ConfigurableFileFilter filterJPG = new ConfigurableFileFilter(extensionsJPEG, "JPEG - Image"); ConfigurableFileFilter filterPNG = new ConfigurableFileFilter(ImageUtils.png, "PNG - File"); ConfigurableFileFilter filterGIF = new ConfigurableFileFilter(ImageUtils.gif, "GIF - Image"); jfc.addChoosableFileFilter(filterGIF); jfc.addChoosableFileFilter(filterJPG); jfc.addChoosableFileFilter(filterPNG); jfc.setFileFilter(filterPNG); // --- Maybe set the current directory ----------------- if (currentFolder != null) { jfc.setCurrentDirectory(new File(currentFolder)); } // === Show dialog and wait on user action ============= int state = jfc.showSaveDialog(this); if (state == JFileChooser.APPROVE_OPTION) { ConfigurableFileFilter cff = (ConfigurableFileFilter) jfc.getFileFilter(); String selectedExtension = cff.getFileExtension()[0]; String mustExtension = "." + selectedExtension; File selectedFile = jfc.getSelectedFile(); if (selectedFile != null) { String selectedPath = selectedFile.getAbsolutePath(); if (selectedPath.endsWith(mustExtension) == false) { selectedPath = selectedPath + mustExtension; } // --------------------------------------------- // --- Export current display to image --------- // --------------------------------------------- this.exportAsImage(this.getVisualizationViewer(), selectedPath, selectedExtension); // --------------------------------------------- if (Application.getGlobalInfo() != null) { Application.getGlobalInfo().setLastSelectedFolder(jfc.getCurrentDirectory()); } } } // end APPROVE_OPTION } /** * Export the current graph as image by using specified parameters. * * @param vv the VisualizationViewer * @param file the current file to export to */ private void exportAsImage(BasicGraphGuiVisViewer<GraphNode, GraphEdge> vv, String path2File, String extension) { // --- If the VisualizationViewer is null --------- if (vv == null) { return; } // --- Overwrite existing file ? ------------------ File writeFile = new File(path2File); if (writeFile.exists()) { String msgHead = "Overwrite?"; String msgText = "Overwrite existing file?"; int msgAnswer = JOptionPane.showConfirmDialog(this, msgText, msgHead, JOptionPane.YES_NO_OPTION); if (msgAnswer == JOptionPane.NO_OPTION) { return; } } // --- Lets go ! ---------------------------------- int width = vv.getSize().width; int height = vv.getSize().height; BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics2D graphics = bi.createGraphics(); graphics.fillRect(0, 0, width, height); boolean wasDoubleBuffered=vv.isDoubleBuffered(); vv.setDoubleBuffered(false); vv.paint(graphics); vv.paintComponents(graphics); vv.setDoubleBuffered(wasDoubleBuffered); try { ImageIO.write(bi, extension, writeFile); } catch (Exception e) { e.printStackTrace(); } } /** * Zooms and fits to the window. * @param visViewer the vis viewer */ private void zoomFit2Window(VisualizationViewer<GraphNode, GraphEdge> visViewer) { visViewer.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).setToIdentity(); visViewer.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW).setToIdentity(); this.allowInitialScaling = true; this.zoomSetInitialScalingAndMovement(visViewer); } /** * Sets the initial scaling for the graph on the VisualizationViewer. */ private void zoomSetInitialScalingAndMovement(VisualizationViewer<GraphNode, GraphEdge> visViewer) { if (this.allowInitialScaling == false) return; Graph<GraphNode, GraphEdge> currGraph = visViewer.getGraphLayout().getGraph(); Rectangle2D rectGraph = GraphGlobals.getGraphSpreadDimension(currGraph); Rectangle2D rectVis = visViewer.getVisibleRect(); if (rectVis.isEmpty()) return; Point2D scaleAt = new Point2D.Double(0, 0); this.setDefaultScaleAtPoint(scaleAt); // --- Calculate the scaling -------------------------------- double graphWidth = rectGraph.getWidth() + 2 * this.graphMargin; double graphHeight = rectGraph.getHeight() + 2 * this.graphMargin; double visWidth = rectVis.getWidth(); double visHeight = rectVis.getHeight(); float scaleX = (float) (visWidth / graphWidth); float scaleY = (float) (visHeight / graphHeight); if (scaleX > 1) scaleX = 1; if (scaleY > 1) scaleY = 1; float scale = scaleX; if (scaleX > scaleY) { scale = scaleY; } // --- Calculate the movement in the view ------------------- double moveX = 0; double moveY = 0; if (rectGraph.getX() != 0) { moveX = rectGraph.getX() * (-1) + this.graphMargin; } if (rectGraph.getY() != 0) { moveY = rectGraph.getY() * (-1) + this.graphMargin; } // --- Set movement ----------- visViewer.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW).translate(moveX, moveY); // --- Set scaling ------------ if (scale != 0 && scale != 1) { this.scalingControl.scale(visViewer, scale, scaleAt); } this.allowInitialScaling = false; } /** * Zoom one to one and move the focus, so that the elements as visible. * @param visViewer the VisualizationViewer */ private void zoomOneToOneMoveFocus(VisualizationViewer<GraphNode, GraphEdge> visViewer) { visViewer.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).setToIdentity(); visViewer.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW).setToIdentity(); Graph<GraphNode, GraphEdge> graph = visViewer.getGraphLayout().getGraph(); Rectangle2D graphDimension = GraphGlobals.getGraphSpreadDimension(graph); double moveXOnVisView = graphDimension.getX(); double moveYOnVisView = graphDimension.getX(); if (moveXOnVisView<=graphMargin) { moveXOnVisView = 0; } else { moveXOnVisView = (graphMargin-graphDimension.getX()); } if (moveYOnVisView<=graphMargin) { moveYOnVisView = 0; } else { moveYOnVisView = (graphMargin-graphDimension.getY()); } if ((moveXOnVisView!=0 || moveYOnVisView!=0)) { visViewer.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).translate(moveXOnVisView, moveYOnVisView); } } /** * Zoom component. */ private void zoomComponent() { Set<GraphNode> nodesPicked = this.getVisualizationViewer().getPickedVertexState().getPicked(); if (nodesPicked.size()!=0) { HashSet<NetworkComponent> components = this.graphController.getNetworkModelAdapter().getNetworkComponentsFullySelected(nodesPicked); if (components!=null && components.size()!=0) { // --- Get the dimension of the selected nodes ------ Rectangle2D areaSelected = GraphGlobals.getGraphSpreadDimension(nodesPicked); Point2D areaCenter = new Point2D.Double(areaSelected.getCenterX(), areaSelected.getCenterY()); // --- Create temporary GraphNode ------------------- GraphNode tmpNode = new GraphNode("tmPCenter", areaCenter); this.getVisualizationViewer().getGraphLayout().getGraph().addVertex(tmpNode); // --- Get the needed positions --------------------- Point2D tmpNodePos = this.getVisualizationViewer().getGraphLayout().transform(tmpNode); Point2D visViewCenter = this.getVisualizationViewer().getRenderContext().getMultiLayerTransformer().inverseTransform(this.getVisualizationViewer().getCenter()); // --- Calculate movement --------------------------- final double dx = (visViewCenter.getX() - tmpNodePos.getX()); final double dy = (visViewCenter.getY() - tmpNodePos.getY()); // --- Remove temporary GraphNode and move view ----- this.getVisualizationViewer().getGraphLayout().getGraph().removeVertex(tmpNode); this.getVisualizationViewer().getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).translate(dx, dy); } } } /** * Gets the VisualizationViewer for the satellite view * @return The VisualizationViewer */ public SatelliteVisualizationViewer<GraphNode, GraphEdge> getSatelliteVisualizationViewer() { if (visViewSatellite==null) { // --- Set dimension and create a new SatelliteVisualizationViewer ---- visViewSatellite = new SatelliteVisualizationViewer<GraphNode, GraphEdge>(this.getVisualizationViewer(), this.getDimensionOfSatelliteVisualizationViewer()); visViewSatellite.scaleToLayout(this.scalingControl); visViewSatellite.setGraphMouse(new SatelliteGraphMouse(1/1.1f, 1.1f)); // --- Configure the node shape and size ------------------------------ visViewSatellite.getRenderContext().setVertexShapeTransformer(this.getVisualizationViewer().getRenderContext().getVertexShapeTransformer()); // --- Configure node icons, if configured ---------------------------- visViewSatellite.getRenderContext().setVertexIconTransformer(this.getVisualizationViewer().getRenderContext().getVertexIconTransformer()); // --- Configure node colors ------------------------------------------ visViewSatellite.getRenderContext().setVertexFillPaintTransformer(this.getVisualizationViewer().getRenderContext().getVertexFillPaintTransformer()); // --- Configure node label transformer ------------------------------- visViewSatellite.getRenderContext().setVertexLabelTransformer(this.getVisualizationViewer().getRenderContext().getVertexLabelTransformer()); // --- Use straight lines as edges ------------------------------------ visViewSatellite.getRenderContext().setEdgeShapeTransformer(this.getVisualizationViewer().getRenderContext().getEdgeShapeTransformer()); // --- Set edge width ------------------------------------------------- visViewSatellite.getRenderContext().setEdgeStrokeTransformer(this.getVisualizationViewer().getRenderContext().getEdgeStrokeTransformer()); // --- Configure edge color ------------------------------------------- visViewSatellite.getRenderContext().setEdgeDrawPaintTransformer(this.getVisualizationViewer().getRenderContext().getEdgeDrawPaintTransformer()); visViewSatellite.getRenderContext().setArrowFillPaintTransformer(this.getVisualizationViewer().getRenderContext().getEdgeDrawPaintTransformer()); visViewSatellite.getRenderContext().setArrowDrawPaintTransformer(this.getVisualizationViewer().getRenderContext().getEdgeDrawPaintTransformer()); // --- Configure Edge Image Labels ------------------------------------ visViewSatellite.getRenderContext().setEdgeLabelTransformer(this.getVisualizationViewer().getRenderContext().getEdgeLabelTransformer()); // --- Set edge renderer for a background color of an edge ------------ visViewSatellite.getRenderer().setEdgeRenderer(this.getVisualizationViewer().getRenderer().getEdgeRenderer()); } return visViewSatellite; } /** * Returns the dimension of the SatelliteVisualizationViewer. * @return the vis view satellite dimension */ private Dimension getDimensionOfSatelliteVisualizationViewer() { double ratio = 0.3; Dimension vvSize = this.getVisualizationViewer().getSize(); Dimension visViewSateliteSize = new Dimension((int)(vvSize.getWidth()*ratio), (int) (vvSize.getHeight()*ratio)); return visViewSateliteSize; } /** * Returns the satellite view. * @return the satellite view */ private SatelliteDialog getSatelliteDialog() { if (satelliteDialog==null){ Frame ownerFrame = Application.getGlobalInfo().getOwnerFrameForComponent(this); if (ownerFrame!=null) { satelliteDialog = new SatelliteDialog(ownerFrame, this.graphController, this); } else { Dialog ownerDialog = Application.getGlobalInfo().getOwnerDialogForComponent(this); satelliteDialog = new SatelliteDialog(ownerDialog, this.graphController, this); } satelliteDialog.setSize(this.getDimensionOfSatelliteVisualizationViewer()); } return satelliteDialog; } /** * Sets the satellite view. * @param satelliteDialog the new satellite view */ private void setSatelliteDialog(SatelliteDialog satelliteDialog) { this.satelliteDialog = satelliteDialog; } /** * Disposes the satellite view. */ private void disposeSatelliteView() { if (this.satelliteDialog!=null) { this.satelliteDialog.setVisible(false); this.satelliteDialog.dispose(); this.setSatelliteDialog(null); } } /** * Converts an {@link Image} to a {@link BufferedImage} * @param image The image * @return The buffered image */ private BufferedImage convertToBufferedImage(Image image){ BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D biGraphics = bufferedImage.createGraphics(); biGraphics.drawImage(image, 0, 0, null); biGraphics.dispose(); return bufferedImage; } /** * Replaces a specified color with another one in an image. * @param image The image * @param oldColor The color that will be replaced * @param newColor The new color * @return The image */ private BufferedImage exchangeColor(BufferedImage image, Color oldColor, Color newColor){ for(int x=0; x<image.getWidth(); x++){ for(int y=0; y<image.getHeight(); y++){ if(image.getRGB(x, y) == oldColor.getRGB()){ image.setRGB(x, y, newColor.getRGB()); } } } return image; } /* (non-Javadoc) * @see java.util.Observer#update(java.util.Observable, java.lang.Object) */ @Override public void update(Observable observable, Object object) { if (object instanceof NetworkModelNotification) { NetworkModelNotification nmNotification = (NetworkModelNotification) object; int reason = nmNotification.getReason(); Object infoObject = nmNotification.getInfoObject(); switch (reason) { case NetworkModelNotification.NETWORK_MODEL_Reload: this.reLoadGraph(); break; case NetworkModelNotification.NETWORK_MODEL_Satellite_View: Boolean visible = (Boolean) infoObject; this.getSatelliteDialog().setVisible(visible); this.zoomFit2Window(this.getSatelliteVisualizationViewer()); break; case NetworkModelNotification.NETWORK_MODEL_Repaint: this.repaintGraph(); break; case NetworkModelNotification.NETWORK_MODEL_Component_Added: case NetworkModelNotification.NETWORK_MODEL_Component_Removed: case NetworkModelNotification.NETWORK_MODEL_Nodes_Merged: case NetworkModelNotification.NETWORK_MODEL_Nodes_Splited: case NetworkModelNotification.NETWORK_MODEL_Merged_With_Supplement_NetworkModel: this.clearPickedObjects(); this.repaintGraph(); break; case NetworkModelNotification.NETWORK_MODEL_Component_Renamed: this.clearPickedObjects(); NetworkComponentRenamed renamed = (NetworkComponentRenamed) infoObject; this.selectObject(renamed.getNetworkComponent()); break; case NetworkModelNotification.NETWORK_MODEL_Component_Select: this.selectObject(infoObject); break; case NetworkModelNotification.NETWORK_MODEL_Zoom_Fit2Window: this.zoomFit2Window(this.getVisualizationViewer()); break; case NetworkModelNotification.NETWORK_MODEL_Zoom_One2One: this.zoomOneToOneMoveFocus(this.getVisualizationViewer()); break; case NetworkModelNotification.NETWORK_MODEL_Zoom_Component: this.zoomComponent(); break; case NetworkModelNotification.NETWORK_MODEL_Zoom_In: this.getScalingControl().scale(this.getVisualizationViewer(), 1.1f, this.getDefaultScaleAtPoint()); break; case NetworkModelNotification.NETWORK_MODEL_Zoom_Out: this.getScalingControl().scale(this.getVisualizationViewer(), 1 / 1.1f, this.getDefaultScaleAtPoint()); break; case NetworkModelNotification.NETWORK_MODEL_ExportGraphAsImage: this.exportAsImage(); break; case NetworkModelNotification.NETWORK_MODEL_GraphMouse_Picking: this.getVisualizationViewer().setGraphMouse(this.getPluggableGraphMouse()); break; case NetworkModelNotification.NETWORK_MODEL_GraphMouse_Transforming: this.getVisualizationViewer().setGraphMouse(this.getDefaultModalGraphMouse()); break; default: break; } } } }
Fixed strange color comparison problem
eclipseProjects/org.agentgui/bundles/org.agentgui.core/src/agentgui/envModel/graph/controller/ui/BasicGraphGui.java
Fixed strange color comparison problem
<ide><path>clipseProjects/org.agentgui/bundles/org.agentgui.core/src/agentgui/envModel/graph/controller/ui/BasicGraphGui.java <ide> import java.awt.geom.Rectangle2D; <ide> import java.awt.image.BufferedImage; <ide> import java.io.File; <add>import java.io.IOException; <ide> import java.net.MalformedURLException; <ide> import java.net.URL; <ide> import java.util.HashMap; <ide> } else { <ide> // --- Otherwise, replace the defined basic color with the one specified in the node layout --------- <ide> bufferedImage = exchangeColor(convertToBufferedImage(imageIcon.getImage()), GeneralGraphSettings4MAS.IMAGE_ICON_BASIC_COLOR, currentColor); <add> if (node.getId().equals("PP100")) { <add> String imgFileName = "PP100_R"+currentColor.getRed()+"_G"+currentColor.getGreen()+"_B"+currentColor.getBlue()+".png"; <add> File imgFile = new File("D:\\Temp\\"+imgFileName); <add> try { <add> ImageIO.write(bufferedImage, "png", imgFile); <add> } catch (IOException e) { <add> // TODO Auto-generated catch block <add> e.printStackTrace(); <add> } <add> <add> } <ide> } <ide> <ide> if (bufferedImage != null) { <ide> private BufferedImage exchangeColor(BufferedImage image, Color oldColor, Color newColor){ <ide> for(int x=0; x<image.getWidth(); x++){ <ide> for(int y=0; y<image.getHeight(); y++){ <del> if(image.getRGB(x, y) == oldColor.getRGB()){ <add> Color currentColor = new Color(image.getRGB(x, y)); <add> if(currentColor.equals(oldColor)){ <ide> image.setRGB(x, y, newColor.getRGB()); <ide> } <ide> } <add> <ide> } <ide> return image; <ide> }
JavaScript
bsd-3-clause
a88c71cd5319c3523ce602a742e62dc5dc90d45a
0
rgrempel/core,alexiamcdonald/elm-core,isaacsanders/core,simonh1000/core,rick68/core,laszlopandy/core,Dandandan/core,suryagaddipati/core,bradurani/core,Pisys/core,vilterp/core,colinmccabe/core,colinmccabe/core,vilterp/core,rgrempel/core,ThomasWeiser/core,ThomasWeiser/core,simonh1000/core,Dandandan/core,laszlopandy/core,bradurani/core,martinos/core,Pisys/core,eeue56/core,alexiamcdonald/elm-core,eeue56/core,isaacsanders/core,suryagaddipati/core,rick68/core,martinos/core
Elm.Native.Task = {}; Elm.Native.Task.make = function(localRuntime) { localRuntime.Native = localRuntime.Native || {}; localRuntime.Native.Task = localRuntime.Native.Task || {}; if (localRuntime.Native.Task.values) { return localRuntime.Native.Task.values; } var Result = Elm.Result.make(localRuntime); var Signal; var Utils = Elm.Native.Utils.make(localRuntime); // CONSTRUCTORS function succeed(value) { return { tag: 'Succeed', value: value }; } function fail(error) { return { tag: 'Fail', value: error }; } function asyncFunction(func) { return { tag: 'Async', asyncFunction: func }; } function andThen(task, callback) { return { tag: 'AndThen', task: task, callback: callback }; } function catch_(task, callback) { return { tag: 'Catch', task: task, callback: callback }; } // RUNNER function perform(task) { runTask({ task: task }, function() {}); } function performSignal(name, signal) { var workQueue = []; function onComplete() { workQueue.shift(); setTimeout(function() { if (workQueue.length > 0) { runTask(workQueue[0], onComplete); } }, 0); } function register(task) { var root = { task: task }; workQueue.push(root); if (workQueue.length === 1) { runTask(root, onComplete); } } if (!Signal) { Signal = Elm.Native.Signal.make(localRuntime); } Signal.output('perform-tasks-' + name, register, signal); return signal; } function mark(status, task) { return { status: status, task: task }; } function runTask(root, onComplete) { var result = mark('runnable', root.task); while (result.status === 'runnable') { result = stepTask(onComplete, root, result.task); } if (result.status === 'done') { root.task = result.task; onComplete(); } if (result.status === 'blocked') { root.task = result.task; } } function stepTask(onComplete, root, task) { var tag = task.tag; if (tag === 'Succeed' || tag === 'Fail') { return mark('done', task); } if (tag === 'Async') { var placeHolder = {}; var couldBeSync = true; var wasSync = false; task.asyncFunction(function(result) { placeHolder.tag = result.tag; placeHolder.value = result.value; if (couldBeSync) { wasSync = true; } else { runTask(root, onComplete); } }); couldBeSync = false; return mark(wasSync ? 'done' : 'blocked', placeHolder); } if (tag === 'AndThen' || tag === 'Catch') { var result = mark('runnable', task.task); while (result.status === 'runnable') { result = stepTask(onComplete, root, result.task); } if (result.status === 'done') { var activeTask = result.task; var activeTag = activeTask.tag; var succeedChain = activeTag === 'Succeed' && tag === 'AndThen'; var failChain = activeTag === 'Fail' && tag === 'Catch'; return (succeedChain || failChain) ? mark('runnable', task.callback(activeTask.value)) : mark('runnable', activeTask); } if (result.status === 'blocked') { return mark('blocked', { tag: tag, task: result.task, callback: task.callback }); } } } // THREADS function sleep(time) { return asyncFunction(function(callback) { setTimeout(function() { callback(succeed(Utils.Tuple0)); }, time); }); } function spawn(task) { return asyncFunction(function(callback) { var id = setTimeout(function() { perform(task); }, 0); callback(succeed(id)); }); } return localRuntime.Native.Task.values = { succeed: succeed, fail: fail, asyncFunction: asyncFunction, andThen: F2(andThen), catch_: F2(catch_), perform: perform, performSignal: performSignal, spawn: spawn, sleep: sleep }; };
src/Native/Task.js
Elm.Native.Task = {}; Elm.Native.Task.make = function(localRuntime) { localRuntime.Native = localRuntime.Native || {}; localRuntime.Native.Task = localRuntime.Native.Task || {}; if (localRuntime.Native.Task.values) { return localRuntime.Native.Task.values; } var Result = Elm.Result.make(localRuntime); var Signal; var Utils = Elm.Native.Utils.make(localRuntime); // CONSTRUCTORS function succeed(value) { return { tag: 'Succeed', value: value }; } function fail(error) { return { tag: 'Fail', value: error }; } function asyncFunction(func) { return { tag: 'Async', asyncFunction: func }; } function andThen(task, callback) { return { tag: 'AndThen', task: task, callback: callback }; } function catch_(task, callback) { return { tag: 'Catch', task: task, callback: callback }; } // RUNNER function perform(task) { runTask({ task: task }, function() {}); } function performSignal(name, signal) { var workQueue = []; function onComplete() { workQueue.shift(); setTimeout(function() { if (workQueue.length > 0) { runTask(workQueue[0], onComplete); } }, 0); } function register(task) { var root = { task: task }; workQueue.push(root); if (workQueue.length === 1) { runTask(root, onComplete); } } if (!Signal) { Signal = Elm.Native.Signal.make(localRuntime); } Signal.output('perform-tasks-' + name, register, stream); return signal; } function mark(status, task) { return { status: status, task: task }; } function runTask(root, onComplete) { var result = mark('runnable', root.task); while (result.status === 'runnable') { result = stepTask(onComplete, root, result.task); } if (result.status === 'done') { root.task = result.task; onComplete(); } if (result.status === 'blocked') { root.task = result.task; } } function stepTask(onComplete, root, task) { var tag = task.tag; if (tag === 'Succeed' || tag === 'Fail') { return mark('done', task); } if (tag === 'Async') { var placeHolder = {}; var couldBeSync = true; var wasSync = false; task.asyncFunction(function(result) { placeHolder.tag = result.tag; placeHolder.value = result.value; if (couldBeSync) { wasSync = true; } else { runTask(root, onComplete); } }); couldBeSync = false; return mark(wasSync ? 'done' : 'blocked', placeHolder); } if (tag === 'AndThen' || tag === 'Catch') { var result = mark('runnable', task.task); while (result.status === 'runnable') { result = stepTask(onComplete, root, result.task); } if (result.status === 'done') { var activeTask = result.task; var activeTag = activeTask.tag; var succeedChain = activeTag === 'Succeed' && tag === 'AndThen'; var failChain = activeTag === 'Fail' && tag === 'Catch'; return (succeedChain || failChain) ? mark('runnable', task.callback(activeTask.value)) : mark('runnable', activeTask); } if (result.status === 'blocked') { return mark('blocked', { tag: tag, task: result.task, callback: task.callback }); } } } // THREADS function sleep(time) { return asyncFunction(function(callback) { setTimeout(function() { callback(succeed(Utils.Tuple0)); }, time); }); } function spawn(task) { return asyncFunction(function(callback) { var id = setTimeout(function() { perform(task); }, 0); callback(succeed(id)); }); } return localRuntime.Native.Task.values = { succeed: succeed, fail: fail, asyncFunction: asyncFunction, andThen: F2(andThen), catch_: F2(catch_), perform: perform, performSignal: performSignal, spawn: spawn, sleep: sleep }; };
Fix undefined variable, wrong name
src/Native/Task.js
Fix undefined variable, wrong name
<ide><path>rc/Native/Task.js <ide> { <ide> Signal = Elm.Native.Signal.make(localRuntime); <ide> } <del> Signal.output('perform-tasks-' + name, register, stream); <add> Signal.output('perform-tasks-' + name, register, signal); <ide> <ide> return signal; <ide> }
Java
mit
a6aa228378ef760de2dddf6e3f1dff9808d8b7f7
0
DemigodsRPG/Demigods3
package com.censoredsoftware.Demigods.Engine.Object.Player; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.bukkit.inventory.ItemStack; import redis.clients.johm.*; import com.censoredsoftware.Demigods.Engine.Demigods; import com.censoredsoftware.Demigods.Engine.Object.Ability.Devotion; import com.censoredsoftware.Demigods.Engine.Object.General.DemigodsItemStack; import com.google.common.collect.Sets; @Model public class PlayerCharacterMeta { @Id private Long id; @Attribute private Integer ascensions; @Attribute private Integer favor; @Attribute private Integer maxFavor; @CollectionMap(key = String.class, value = Long.class) private Map<String, Long> bindingData; @CollectionMap(key = String.class, value = Boolean.class) private Map<String, Boolean> abilityData; @CollectionMap(key = String.class, value = Boolean.class) private Map<String, Boolean> taskData; @CollectionMap(key = String.class, value = Boolean.class) private Map<String, Devotion> devotionData; void initializeMaps() { this.abilityData = new HashMap<String, Boolean>(); this.bindingData = new HashMap<String, Long>(); this.taskData = new HashMap<String, Boolean>(); this.devotionData = new HashMap<String, Devotion>(); } public static PlayerCharacterMeta create() { PlayerCharacterMeta charMeta = new PlayerCharacterMeta(); charMeta.initializeMaps(); charMeta.setAscensions(Demigods.config.getSettingInt("character.defaults.ascensions")); charMeta.setFavor(Demigods.config.getSettingInt("character.defaults.favor")); charMeta.setMaxFavor(Demigods.config.getSettingInt("character.defaults.max_favor")); charMeta.addDevotion(Devotion.create(Devotion.Type.OFFENSE)); charMeta.addDevotion(Devotion.create(Devotion.Type.DEFENSE)); charMeta.addDevotion(Devotion.create(Devotion.Type.PASSIVE)); charMeta.addDevotion(Devotion.create(Devotion.Type.STEALTH)); charMeta.addDevotion(Devotion.create(Devotion.Type.SUPPORT)); charMeta.addDevotion(Devotion.create(Devotion.Type.ULTIMATE)); PlayerCharacterMeta.save(charMeta); return charMeta; } public long getId() { return this.id; } public void addDevotion(Devotion devotion) { if(!this.devotionData.containsKey(devotion.getType().toString())) this.devotionData.put(devotion.getType().toString(), devotion); save(this); } public Devotion getDevotion(Devotion.Type type) { if(this.devotionData.containsKey(type.toString())) { return this.devotionData.get(type.toString()); } else { addDevotion(Devotion.create(type)); return this.devotionData.get(type.toString()); } } public boolean isEnabledAbility(String ability) { return abilityData.containsKey(ability.toLowerCase()) && abilityData.get(ability.toLowerCase()); } public void toggleAbility(String ability, boolean option) { abilityData.put(ability.toLowerCase(), option); } public boolean isBound(String ability) { return getBind(ability.toLowerCase()) != null; } public boolean isBound(ItemStack item) { return getBind(item) != null; } public void setBound(String ability, ItemStack item, String identifier) { this.bindingData.put(ability.toLowerCase(), DemigodsItemStack.create(item, identifier).getId()); } public DemigodsItemStack getBind(String ability) { return this.bindingData.containsKey(ability.toLowerCase()) ? DemigodsItemStack.load(this.bindingData.get(ability.toLowerCase())) : null; } public DemigodsItemStack getBind(ItemStack item) { for(long bindId : this.bindingData.values()) { DemigodsItemStack bind = DemigodsItemStack.load(bindId); if(item.getItemMeta().getLore().get(item.getItemMeta().getLore().size()).contains(bind.getId().toString())) { return bind; } } return null; } public Set<DemigodsItemStack> getBindings() { Set<DemigodsItemStack> bindings = Sets.newHashSet(); for(Long id : this.bindingData.values()) { bindings.add(DemigodsItemStack.load(id)); } return bindings; } public void removeBind(String ability) { this.bindingData.remove(ability.toLowerCase()); } public void removeBind(ItemStack item) { if(isBound(item)) { DemigodsItemStack bind = getBind(item); this.bindingData.values().remove(bind); } } public boolean isFinishedTask(String taskName) { return taskData.containsKey(taskName) && taskData.get(taskName); } public void finishTask(String taskName, boolean option) { taskData.put(taskName, option); } public Integer getAscensions() { return this.ascensions; } public void addAscension() { this.ascensions += 1; save(this); } public void addAscensions(int amount) { this.ascensions += amount; save(this); } public void subtractAscensions(int amount) { this.ascensions -= amount; save(this); } public void setAscensions(int amount) { this.ascensions = amount; save(this); } public Integer getFavor() { return this.favor; } public void setFavor(int amount) { this.favor = amount; save(this); } public void addFavor(int amount) { if((this.favor + amount) > this.maxFavor) { this.favor = this.maxFavor; } else { this.favor += amount; } save(this); } public void subtractFavor(int amount) { if((this.favor - amount) < 0) { this.favor = 0; } else { this.favor -= amount; } save(this); } public Integer getMaxFavor() { return this.maxFavor; } public void addMaxFavor(int amount) { if((this.maxFavor + amount) > Demigods.config.getSettingInt("caps.favor")) { this.maxFavor = Demigods.config.getSettingInt("caps.favor"); } else { this.maxFavor += amount; } save(this); } public void setMaxFavor(int amount) { if(amount < 0) this.maxFavor = 0; if(amount > Demigods.config.getSettingInt("caps.favor")) this.maxFavor = Demigods.config.getSettingInt("caps.favor"); else this.maxFavor = amount; save(this); } public static void save(PlayerCharacterMeta playerCharacterMeta) { JOhm.save(playerCharacterMeta); } public static PlayerCharacterMeta load(long id) { return JOhm.get(PlayerCharacterMeta.class, id); } public static Set<PlayerCharacterMeta> loadAll() { return JOhm.getAll(PlayerCharacterMeta.class); } @Override public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } }
src/main/java/com/censoredsoftware/Demigods/Engine/Object/Player/PlayerCharacterMeta.java
package com.censoredsoftware.Demigods.Engine.Object.Player; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.bukkit.inventory.ItemStack; import redis.clients.johm.*; import com.censoredsoftware.Demigods.Engine.Demigods; import com.censoredsoftware.Demigods.Engine.Object.Ability.Devotion; import com.censoredsoftware.Demigods.Engine.Object.General.DemigodsItemStack; import com.google.common.collect.Sets; @Model public class PlayerCharacterMeta { @Id private Long id; @Attribute private Integer ascensions; @Attribute private Integer favor; @Attribute private Integer maxFavor; @CollectionMap(key = String.class, value = Long.class) private Map<String, Long> bindingData; @CollectionMap(key = String.class, value = Boolean.class) private Map<String, Boolean> abilityData; @CollectionMap(key = String.class, value = Boolean.class) private Map<String, Boolean> taskData; @CollectionMap(key = String.class, value = Boolean.class) private Map<String, Devotion> devotionData; void initializeMaps() { this.abilityData = new HashMap<String, Boolean>(); this.bindingData = new HashMap<String, Long>(); this.taskData = new HashMap<String, Boolean>(); this.devotionData = new HashMap<String, Devotion>(); } public static PlayerCharacterMeta create() { PlayerCharacterMeta charMeta = new PlayerCharacterMeta(); charMeta.initializeMaps(); charMeta.setAscensions(Demigods.config.getSettingInt("character.defaults.ascensions")); charMeta.setFavor(Demigods.config.getSettingInt("character.defaults.favor")); charMeta.setMaxFavor(Demigods.config.getSettingInt("character.defaults.max_favor")); charMeta.addDevotion(Devotion.create(Devotion.Type.OFFENSE)); charMeta.addDevotion(Devotion.create(Devotion.Type.DEFENSE)); charMeta.addDevotion(Devotion.create(Devotion.Type.PASSIVE)); charMeta.addDevotion(Devotion.create(Devotion.Type.STEALTH)); charMeta.addDevotion(Devotion.create(Devotion.Type.SUPPORT)); charMeta.addDevotion(Devotion.create(Devotion.Type.ULTIMATE)); PlayerCharacterMeta.save(charMeta); return charMeta; } public long getId() { return this.id; } public void addDevotion(Devotion devotion) { if(!this.devotionData.containsKey(devotion.getType().toString())) this.devotionData.put(devotion.getType().toString(), devotion); save(this); } public Devotion getDevotion(Devotion.Type type) { if(this.devotionData.containsKey(type.toString())) { return this.devotionData.get(type.toString()); } else { addDevotion(Devotion.create(type)); return this.devotionData.get(type.toString()); } } public boolean isEnabledAbility(String ability) { return abilityData.containsKey(ability.toLowerCase()) && abilityData.get(ability.toLowerCase()); } public void toggleAbility(String ability, boolean option) { abilityData.put(ability.toLowerCase(), option); } public boolean isBound(String ability) { return getBind(ability.toLowerCase()) != null; } public boolean isBound(ItemStack item) { return getBind(item) != null; } public void setBound(String ability, ItemStack item, String identifier) { this.bindingData.put(ability.toLowerCase(), DemigodsItemStack.create(item, identifier).getId()); } public DemigodsItemStack getBind(String ability) { return this.bindingData.containsKey(ability.toLowerCase()) ? DemigodsItemStack.load(this.bindingData.get(ability.toLowerCase())) : null; } public DemigodsItemStack getBind(ItemStack item) { for(long bindId : this.bindingData.values()) { DemigodsItemStack bind = DemigodsItemStack.load(bindId); if(item.getItemMeta().getLore().get(item.getItemMeta().getLore().size()).contains(bind.getId().toString())) ; { return bind; } } return null; } public Set<DemigodsItemStack> getBindings() { Set<DemigodsItemStack> bindings = Sets.newHashSet(); for(Long id : this.bindingData.values()) { bindings.add(DemigodsItemStack.load(id)); } return bindings; } public void removeBind(String ability) { this.bindingData.remove(ability.toLowerCase()); } public void removeBind(ItemStack item) { if(isBound(item)) { DemigodsItemStack bind = getBind(item); this.bindingData.values().remove(bind); } } public boolean isFinishedTask(String taskName) { return taskData.containsKey(taskName) && taskData.get(taskName); } public void finishTask(String taskName, boolean option) { taskData.put(taskName, option); } public Integer getAscensions() { return this.ascensions; } public void addAscension() { this.ascensions += 1; save(this); } public void addAscensions(int amount) { this.ascensions += amount; save(this); } public void subtractAscensions(int amount) { this.ascensions -= amount; save(this); } public void setAscensions(int amount) { this.ascensions = amount; save(this); } public Integer getFavor() { return this.favor; } public void setFavor(int amount) { this.favor = amount; save(this); } public void addFavor(int amount) { if((this.favor + amount) > this.maxFavor) { this.favor = this.maxFavor; } else { this.favor += amount; } save(this); } public void subtractFavor(int amount) { if((this.favor - amount) < 0) { this.favor = 0; } else { this.favor -= amount; } save(this); } public Integer getMaxFavor() { return this.maxFavor; } public void addMaxFavor(int amount) { if((this.maxFavor + amount) > Demigods.config.getSettingInt("caps.favor")) { this.maxFavor = Demigods.config.getSettingInt("caps.favor"); } else { this.maxFavor += amount; } save(this); } public void setMaxFavor(int amount) { if(amount < 0) this.maxFavor = 0; if(amount > Demigods.config.getSettingInt("caps.favor")) this.maxFavor = Demigods.config.getSettingInt("caps.favor"); else this.maxFavor = amount; save(this); } public static void save(PlayerCharacterMeta playerCharacterMeta) { JOhm.save(playerCharacterMeta); } public static PlayerCharacterMeta load(long id) { return JOhm.get(PlayerCharacterMeta.class, id); } public static Set<PlayerCharacterMeta> loadAll() { return JOhm.getAll(PlayerCharacterMeta.class); } @Override public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } }
Not sure why that was there.
src/main/java/com/censoredsoftware/Demigods/Engine/Object/Player/PlayerCharacterMeta.java
Not sure why that was there.
<ide><path>rc/main/java/com/censoredsoftware/Demigods/Engine/Object/Player/PlayerCharacterMeta.java <ide> for(long bindId : this.bindingData.values()) <ide> { <ide> DemigodsItemStack bind = DemigodsItemStack.load(bindId); <del> if(item.getItemMeta().getLore().get(item.getItemMeta().getLore().size()).contains(bind.getId().toString())) ; <add> if(item.getItemMeta().getLore().get(item.getItemMeta().getLore().size()).contains(bind.getId().toString())) <ide> { <ide> return bind; <ide> }
Java
apache-2.0
dd167e1f716b265f056d7c6653c767f5bfd26eaf
0
apache/commons-bsf,apache/commons-bsf,apache/commons-bsf
/* * The Apache Software License, Version 1.1 * * Copyright (c) 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 acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Apache BSF", "Apache", 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 names without prior written * permission of the Apache Group. * * 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 created by * Sanjiva Weerawarana and others at International Business Machines * Corporation. For more information on the Apache Software Foundation, * please see <http://www.apache.org/>. */ package org.apache.bsf.engines.javascript; import java.io.InputStream; import java.io.IOException; import java.util.Vector; import org.mozilla.javascript.Script; import org.mozilla.javascript.ClassDefinitionException; import org.mozilla.javascript.Context; import org.mozilla.javascript.EvaluatorException; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.PropertyException; import org.mozilla.javascript.NativeJavaObject; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.WrappedException; import org.mozilla.javascript.Wrapper; import org.mozilla.javascript.ImporterTopLevel; import org.apache.bsf.*; import org.apache.bsf.util.*; /** * This is the interface to Netscape's Rhino (JavaScript) from the * Bean Scripting Framework. * <p> * The original version of this code was first written by Adam Peller * for use in LotusXSL. Sanjiva took his code and adapted it for BSF. * * @author Adam Peller <[email protected]> * @author Sanjiva Weerawarana * @author Matthew J. Duftler * @author Norris Boyd */ public class JavaScriptEngine extends BSFEngineImpl { /** * The global script object, where all embedded functions are defined, * as well as the standard ECMA "core" objects. */ private Scriptable global; /** * Return an object from an extension. * @param object Object on which to make the call (ignored). * @param method The name of the method to call. * @param args an array of arguments to be * passed to the extension, which may be either * Vectors of Nodes, or Strings. */ public Object call(Object object, String method, Object[] args) throws BSFException { Object retval = null; Context cx; try { cx = Context.enter(); // REMIND: convert arg list Vectors here? Object fun = global.get(method, global); // NOTE: Source and line arguments are nonsense in a call(). // Any way to make these arguments *sensible? if (fun == Scriptable.NOT_FOUND) throw new EvaluatorException("function " + method + " not found.", "none", 0); cx.setOptimizationLevel(-1); cx.setGeneratingDebug(false); cx.setGeneratingSource(false); cx.setOptimizationLevel(0); cx.setDebugger(null, null); retval = ScriptRuntime.call(cx, fun, global, args, null); if (retval instanceof Wrapper) retval = ((Wrapper) retval).unwrap(); } catch (Throwable t) { handleError(t); } finally { Context.exit(); } return retval; } public void declareBean(BSFDeclaredBean bean) throws BSFException { if ((bean.bean instanceof Number) || (bean.bean instanceof String) || (bean.bean instanceof Boolean)) { global.put(bean.name, global, bean.bean); } else { // Must wrap non-scriptable objects before presenting to Rhino Scriptable wrapped = Context.toObject(bean.bean, global); global.put(bean.name, global, wrapped); } } /** * This is used by an application to evaluate a string containing * some expression. */ public Object eval(String source, int lineNo, int columnNo, Object oscript) throws BSFException { String scriptText = oscript.toString(); Object retval = null; Script script; Context cx; try { cx = Context.enter(); cx.setOptimizationLevel(-1); cx.setGeneratingDebug(false); cx.setGeneratingSource(false); cx.setOptimizationLevel(0); cx.setDebugger(null, null); retval = cx.evaluateString(global, scriptText, source, lineNo, null); if (retval instanceof NativeJavaObject) retval = ((NativeJavaObject) retval).unwrap(); } catch (Throwable t) { // includes JavaScriptException, rethrows Errors handleError(t); } finally { Context.exit(); } return retval; } private void handleError(Throwable t) throws BSFException { if (t instanceof WrappedException) t = ((WrappedException) t).getWrappedException(); String message = null; Throwable target = t; if (t instanceof JavaScriptException) { message = t.getLocalizedMessage(); // Is it an exception wrapped in a JavaScriptException? Object value = ((JavaScriptException) t).getValue(); if (value instanceof Throwable) { // likely a wrapped exception from a LiveConnect call. // Display its stack trace as a diagnostic target = (Throwable) value; } } else if (t instanceof EvaluatorException || t instanceof SecurityException) { message = t.getLocalizedMessage(); } else if (t instanceof RuntimeException) { message = "Internal Error: " + t.toString(); } else if (t instanceof StackOverflowError) { message = "Stack Overflow"; } if (message == null) message = t.toString(); if (t instanceof Error && !(t instanceof StackOverflowError)) { // Re-throw Errors because we're supposed to let the JVM see it // Don't re-throw StackOverflows, because we know we've // corrected the situation by aborting the loop and // a long stacktrace would end up on the user's console throw (Error) t; } else { throw new BSFException(BSFException.REASON_OTHER_ERROR, "JavaScript Error: " + message, target); } } /** * Initialize the engine. * Put the manager into the context-manager * map hashtable too. */ public void initialize(BSFManager mgr, String lang, Vector declaredBeans) throws BSFException { super.initialize(mgr, lang, declaredBeans); // Initialize context and global scope object try { Context cx = Context.enter(); global = new ImporterTopLevel(cx); Scriptable bsf = cx.toObject(new BSFFunctions(mgr, this), global); global.put("bsf", global, bsf); int size = declaredBeans.size(); for (int i = 0; i < size; i++) { declareBean((BSFDeclaredBean) declaredBeans.elementAt(i)); } } catch (Throwable t) { } finally { Context.exit(); } } public void undeclareBean(BSFDeclaredBean bean) throws BSFException { global.delete(bean.name); } }
src/org/apache/bsf/engines/javascript/JavaScriptEngine.java
/* * The Apache Software License, Version 1.1 * * Copyright (c) 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 acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Apache BSF", "Apache", 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 names without prior written * permission of the Apache Group. * * 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 created by * Sanjiva Weerawarana and others at International Business Machines * Corporation. For more information on the Apache Software Foundation, * please see <http://www.apache.org/>. */ package org.apache.bsf.engines.javascript; import java.io.InputStream; import java.io.IOException; import java.util.Vector; import org.mozilla.javascript.Script; import org.mozilla.javascript.ClassDefinitionException; import org.mozilla.javascript.Context; import org.mozilla.javascript.EvaluatorException; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.PropertyException; import org.mozilla.javascript.NativeJavaObject; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.WrappedException; import org.mozilla.javascript.Wrapper; import org.mozilla.javascript.ImporterTopLevel; import org.apache.bsf.*; import org.apache.bsf.util.*; /** * This is the interface to Netscape's Rhino (JavaScript) from the * Bean Scripting Framework. * <p> * The original version of this code was first written by Adam Peller * for use in LotusXSL. Sanjiva took his code and adapted it for BSF. * * @author Adam Peller <[email protected]> * @author Sanjiva Weerawarana * @author Matthew J. Duftler * @author Norris Boyd */ public class JavaScriptEngine extends BSFEngineImpl { /** * The global script object, where all embedded functions are defined, * as well as the standard ECMA "core" objects. */ private Scriptable global; /** * Return an object from an extension. * @param object Object on which to make the call (ignored). * @param method The name of the method to call. * @param args an array of arguments to be * passed to the extension, which may be either * Vectors of Nodes, or Strings. */ public Object call(Object object, String method, Object[] args) throws BSFException { Object retval = null; Context cx; try { cx = Context.enter(); // REMIND: convert arg list Vectors here? Object fun = global.get(method, global); if (fun == Scriptable.NOT_FOUND) throw new EvaluatorException("function " + method + " not found."); cx.setOptimizationLevel(-1); cx.setGeneratingDebug(false); cx.setGeneratingSource(false); cx.setOptimizationLevel(0); cx.setDebugger(null, null); retval = ScriptRuntime.call(cx, fun, global, args, null); if (retval instanceof Wrapper) retval = ((Wrapper) retval).unwrap(); } catch (Throwable t) { handleError(t); } finally { Context.exit(); } return retval; } public void declareBean(BSFDeclaredBean bean) throws BSFException { if ((bean.bean instanceof Number) || (bean.bean instanceof String) || (bean.bean instanceof Boolean)) { global.put(bean.name, global, bean.bean); } else { // Must wrap non-scriptable objects before presenting to Rhino Scriptable wrapped = Context.toObject(bean.bean, global); global.put(bean.name, global, wrapped); } } /** * This is used by an application to evaluate a string containing * some expression. */ public Object eval(String source, int lineNo, int columnNo, Object oscript) throws BSFException { String scriptText = oscript.toString(); Object retval = null; Script script; Context cx; try { cx = Context.enter(); cx.setOptimizationLevel(-1); cx.setGeneratingDebug(false); cx.setGeneratingSource(false); cx.setOptimizationLevel(0); cx.setDebugger(null, null); retval = cx.evaluateString(global, scriptText, source, lineNo, null); if (retval instanceof NativeJavaObject) retval = ((NativeJavaObject) retval).unwrap(); } catch (Throwable t) { // includes JavaScriptException, rethrows Errors handleError(t); } finally { Context.exit(); } return retval; } private void handleError(Throwable t) throws BSFException { if (t instanceof WrappedException) t = ((WrappedException) t).getWrappedException(); String message = null; Throwable target = t; if (t instanceof JavaScriptException) { message = t.getLocalizedMessage(); // Is it an exception wrapped in a JavaScriptException? Object value = ((JavaScriptException) t).getValue(); if (value instanceof Throwable) { // likely a wrapped exception from a LiveConnect call. // Display its stack trace as a diagnostic target = (Throwable) value; } } else if (t instanceof EvaluatorException || t instanceof SecurityException) { message = t.getLocalizedMessage(); } else if (t instanceof RuntimeException) { message = "Internal Error: " + t.toString(); } else if (t instanceof StackOverflowError) { message = "Stack Overflow"; } if (message == null) message = t.toString(); if (t instanceof Error && !(t instanceof StackOverflowError)) { // Re-throw Errors because we're supposed to let the JVM see it // Don't re-throw StackOverflows, because we know we've // corrected the situation by aborting the loop and // a long stacktrace would end up on the user's console throw (Error) t; } else { throw new BSFException(BSFException.REASON_OTHER_ERROR, "JavaScript Error: " + message, target); } } /** * Initialize the engine. * Put the manager into the context-manager * map hashtable too. */ public void initialize(BSFManager mgr, String lang, Vector declaredBeans) throws BSFException { super.initialize(mgr, lang, declaredBeans); // Initialize context and global scope object try { Context cx = Context.enter(); global = new ImporterTopLevel(cx); Scriptable bsf = cx.toObject(new BSFFunctions(mgr, this), global); global.put("bsf", global, bsf); int size = declaredBeans.size(); for (int i = 0; i < size; i++) { declareBean((BSFDeclaredBean) declaredBeans.elementAt(i)); } } catch (Throwable t) { } finally { Context.exit(); } } public void undeclareBean(BSFDeclaredBean bean) throws BSFException { global.delete(bean.name); } }
Fix a build break in the Rhino engine; The EvaluatorException constructor using a string argument only is now class protected, which means that we must use the public constuctor. However, the public constructor requires source and line number information...which makes no sense inside of a call(). Punting for now... git-svn-id: 8fbff3d54bc076206107a52135e3fa53429945fe@180423 13f79535-47bb-0310-9956-ffa450edef68
src/org/apache/bsf/engines/javascript/JavaScriptEngine.java
Fix a build break in the Rhino engine; The EvaluatorException constructor using a string argument only is now class protected, which means that we must use the public constuctor. However, the public constructor requires source and line number information...which makes no sense inside of a call(). Punting for now...
<ide><path>rc/org/apache/bsf/engines/javascript/JavaScriptEngine.java <ide> // REMIND: convert arg list Vectors here? <ide> <ide> Object fun = global.get(method, global); <add> // NOTE: Source and line arguments are nonsense in a call(). <add> // Any way to make these arguments *sensible? <ide> if (fun == Scriptable.NOT_FOUND) <del> throw new EvaluatorException("function " + method + " not found."); <add> throw new EvaluatorException("function " + method + <add> " not found.", "none", 0); <ide> <ide> cx.setOptimizationLevel(-1); <ide> cx.setGeneratingDebug(false);
Java
mit
error: pathspec 'src/main/java/dtprogrammer/github/io/common/TreeNode.java' did not match any file(s) known to git
b5f6aab68554214802bcb629c61d83007699791e
1
dtprogrammer/leetcode-solutions
package dtprogrammer.github.io.common; /** * Leetcode TreeNode class for testing and dedbugging */ public class TreeNode { public final int val; public TreeNode left; public TreeNode right; public TreeNode(int val) { this.val = val; } }
src/main/java/dtprogrammer/github/io/common/TreeNode.java
Add TreeNode class
src/main/java/dtprogrammer/github/io/common/TreeNode.java
Add TreeNode class
<ide><path>rc/main/java/dtprogrammer/github/io/common/TreeNode.java <add>package dtprogrammer.github.io.common; <add> <add>/** <add> * Leetcode TreeNode class for testing and dedbugging <add> */ <add>public class TreeNode { <add> public final int val; <add> public TreeNode left; <add> public TreeNode right; <add> <add> public TreeNode(int val) { <add> this.val = val; <add> } <add>}
Java
apache-2.0
fbe277ac1fae4b03711b537ae35ae8a80b465053
0
gabe-alex/ComputerAdaptiveTesting,gabe-alex/ComputerAdaptiveTesting
package com.policat.cat.services; import com.policat.cat.entities.Answer; import com.policat.cat.entities.Question; import com.policat.cat.entities.Quiz; import com.policat.cat.repositories.QuestionRepository; import com.policat.cat.repositories.QuizRepository; import com.policat.cat.temp_containers.OngoingQuiz; import com.policat.cat.temp_containers.QuestionResponse; import org.hibernate.Hibernate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.*; @Service public class QuizService { public static final int MAX_QUESTION_SCORE = 5; public static final int MIN_QUESTION_SCORE = 1; public static final int START_QUESTION_SCORE = 3; public static final int NUM_SETUP_QUESTIONS = 2; public static final int MIN_QUESTIONS = 5; public static final int MAX_QUESTIONS = 25; public static final int MAX_QUESTION_TIME = 60; //seconds public static final double ERROR_LIMIT = .2; @Autowired QuizRepository quizRepository; @Autowired QuestionRepository questionRepository; public Quiz getQuizWithQuestions(Long quizId) { Quiz quiz = quizRepository.findOne(quizId); Hibernate.initialize(quiz.getQuestions()); return quiz; } public Question getQuestionAnswers(Question question) { question = questionRepository.findOne(question.getId()); Hibernate.initialize(question.getAnswers()); return question; } public QuestionResponse getPreviousResponse(OngoingQuiz ongoingQuiz) { List<QuestionResponse> responses = ongoingQuiz.getQuestionsResponses(); return responses.get(responses.size()-1); } public Question getQuestionWithScore(Integer score, OngoingQuiz ongoingQuiz) { List<Long> usedQuestions = new ArrayList<>(); for(QuestionResponse questionResponse : ongoingQuiz.getQuestionsResponses()) { Question question = questionResponse.getQuestion(); usedQuestions.add(question.getId()); } List<Question> available; if(usedQuestions.isEmpty()) { available = questionRepository.findByScore(ongoingQuiz.getQuiz(), score); } else { available = questionRepository.findNewByScore(ongoingQuiz.getQuiz(), score, usedQuestions); } if(available.isEmpty()) { return null; } Random randGen = new Random(); Integer chosenPos = randGen.nextInt(available.size()); Question chosen = available.get(chosenPos); return getQuestionAnswers(chosen); } public Integer computedResponseScore(QuestionResponse questionResponse) { Integer questionScore = questionResponse.getQuestion().getScore(); if(questionResponse.isCorrect()) { questionScore = Math.min(++questionScore, MAX_QUESTION_SCORE); } else { --questionScore; } return questionScore; } public List<QuestionResponse> getScoreResponses(OngoingQuiz ongoingQuiz) { List<QuestionResponse> responses = ongoingQuiz.getQuestionsResponses(); if(responses.size() <= NUM_SETUP_QUESTIONS) { return responses.subList(responses.size(), responses.size()); } return responses.subList(NUM_SETUP_QUESTIONS, responses.size()); } public Double calcMean(OngoingQuiz ongoingQuiz) { Integer sumScores = 0; List<QuestionResponse> responses = getScoreResponses(ongoingQuiz); if(responses.size() == 0) { return 0.0; } for(QuestionResponse response : responses) { sumScores += computedResponseScore(response); } return sumScores/(double)responses.size(); } public Double calcError(OngoingQuiz ongoingQuiz) { //Standard deviation Double mean = calcMean(ongoingQuiz); Double devSum = 0.0; List<QuestionResponse> responses = getScoreResponses(ongoingQuiz); if(responses.size() == 0) { return 0.0; } for(QuestionResponse response : responses) { Integer questionScore = computedResponseScore(response); devSum += Math.pow((questionScore - mean), 2); } Double stdDev = Math.sqrt(devSum/responses.size()); //Standard error return stdDev/Math.sqrt(responses.size()); } public Question chooseNextQuestion(OngoingQuiz ongoingQuiz) { if (ongoingQuiz.getQuestionsResponses().isEmpty()) { return getQuestionWithScore(START_QUESTION_SCORE, ongoingQuiz); } else if (ongoingQuiz.getQuestionsResponses().size() >= MAX_QUESTIONS) { return null; } if (ongoingQuiz.getQuestionsResponses().size() > MIN_QUESTIONS && calcError(ongoingQuiz) < ERROR_LIMIT) { return null; } QuestionResponse lastResponse = getPreviousResponse(ongoingQuiz); Integer nextQuestionScore; if (lastResponse.isCorrect()) { nextQuestionScore = Math.min(lastResponse.getQuestion().getScore() + 1, MAX_QUESTION_SCORE); } else { nextQuestionScore = Math.max(lastResponse.getQuestion().getScore() - 1, MIN_QUESTION_SCORE); } return getQuestionWithScore(nextQuestionScore, ongoingQuiz); } public Integer calcFinalScore(OngoingQuiz ongoingQuiz) { Double mean = calcMean(ongoingQuiz); return (int)(100*mean/MAX_QUESTION_SCORE); } public void debugLastResponse(OngoingQuiz ongoingQuiz) { List<QuestionResponse> responses = ongoingQuiz.getQuestionsResponses(); QuestionResponse lastResponse = responses.get(ongoingQuiz.getQuestionsResponses().size() - 1); System.out.print("Question ID: "); System.out.println(lastResponse.getQuestion().getId()); System.out.print("Score: "); System.out.println(lastResponse.getQuestion().getScore()); System.out.print("Corect Answers IDs:"); for(Answer answer : lastResponse.getQuestion().getCorrectAnswers()) { System.out.print(" "); System.out.print(answer.getId()); } System.out.println(); System.out.print("Selected Answers IDs:"); for(Answer answer : lastResponse.getSelectedAnswers()) { System.out.print(" "); System.out.print(answer.getId()); } System.out.println(); System.out.print("Is Correct: "); System.out.println(lastResponse.isCorrect()); System.out.print("Current Score: "); System.out.println(calcMean(ongoingQuiz)); System.out.print("Current Error: "); System.out.println(calcError(ongoingQuiz)); } }
src/main/java/com/policat/cat/services/QuizService.java
package com.policat.cat.services; import com.policat.cat.entities.Answer; import com.policat.cat.entities.Question; import com.policat.cat.entities.Quiz; import com.policat.cat.repositories.QuestionRepository; import com.policat.cat.repositories.QuizRepository; import com.policat.cat.temp_containers.OngoingQuiz; import com.policat.cat.temp_containers.QuestionResponse; import org.hibernate.Hibernate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.*; @Service public class QuizService { public static final int MAX_QUESTION_SCORE = 5; public static final int MIN_QUESTION_SCORE = 1; public static final int MIN_QUESTIONS = 5; public static final int MAX_QUESTIONS = 25; public static final int MAX_QUESTION_TIME = 60; //seconds @Autowired QuizRepository quizRepository; @Autowired QuestionRepository questionRepository; public Quiz getQuizWithQuestions(Long quizId) { Quiz quiz = quizRepository.findOne(quizId); Hibernate.initialize(quiz.getQuestions()); return quiz; } public Question getQuestionAnswers(Question question) { question = questionRepository.findOne(question.getId()); Hibernate.initialize(question.getAnswers()); return question; } public QuestionResponse getPreviousResponse(OngoingQuiz ongoingQuiz) { List<QuestionResponse> responses = ongoingQuiz.getQuestionsResponses(); return responses.get(responses.size()-1); } public Question getQuestionWithScore(Integer score, OngoingQuiz ongoingQuiz) { List<Long> usedQuestions = new ArrayList<>(); for(QuestionResponse questionResponse : ongoingQuiz.getQuestionsResponses()) { Question question = questionResponse.getQuestion(); usedQuestions.add(question.getId()); } List<Question> available; if(usedQuestions.isEmpty()) { available = questionRepository.findByScore(ongoingQuiz.getQuiz(), score); } else { available = questionRepository.findNewByScore(ongoingQuiz.getQuiz(), score, usedQuestions); } if(available.isEmpty()) { return null; } Random randGen = new Random(); Integer chosenPos = randGen.nextInt(available.size()); Question chosen = available.get(chosenPos); return getQuestionAnswers(chosen); } public List<QuestionResponse> getCorrectResponses(OngoingQuiz ongoingQuiz) { List<QuestionResponse> correctResponses = new ArrayList<>(); List<QuestionResponse> responses = ongoingQuiz.getQuestionsResponses(); for(QuestionResponse response : responses) { if(response.isCorrect()) { correctResponses.add(response); } } return correctResponses; } public Double calcMean(OngoingQuiz ongoingQuiz) { Integer sumScores = 0; List<QuestionResponse> correctResponses = getCorrectResponses(ongoingQuiz); if(correctResponses.size() == 0) { return 0.0; } for(QuestionResponse response : correctResponses) { sumScores += response.getQuestion().getScore(); } return sumScores/(double)correctResponses.size(); } public Double calcError(OngoingQuiz ongoingQuiz) { //Standard deviation Double mean = calcMean(ongoingQuiz); Double devSum = 0.0; List<QuestionResponse> correctResponses = getCorrectResponses(ongoingQuiz); if(correctResponses.size() == 0) { return 0.0; } for(QuestionResponse response : correctResponses) { Integer questionScore = response.getQuestion().getScore(); devSum += Math.pow((questionScore - mean), 2); } Double stdDev = Math.sqrt(devSum/correctResponses.size()); //Standard error return stdDev/Math.sqrt(correctResponses.size()); } public Question chooseNextQuestion(OngoingQuiz ongoingQuiz) { if (ongoingQuiz.getQuestionsResponses().isEmpty()) { return getQuestionWithScore(5, ongoingQuiz); } else if (ongoingQuiz.getQuestionsResponses().size() >= MAX_QUESTIONS) { return null; } if (ongoingQuiz.getQuestionsResponses().size() > MIN_QUESTIONS && calcError(ongoingQuiz) < .4) { return null; } QuestionResponse lastResponse = getPreviousResponse(ongoingQuiz); Integer nextQuestionScore; if (lastResponse.isCorrect()) { nextQuestionScore = Math.min(lastResponse.getQuestion().getScore() + 1, MAX_QUESTION_SCORE); } else { nextQuestionScore = Math.max(lastResponse.getQuestion().getScore() - 1, MIN_QUESTION_SCORE); } return getQuestionWithScore(nextQuestionScore, ongoingQuiz); } public Integer calcFinalScore(OngoingQuiz ongoingQuiz) { Double mean = calcMean(ongoingQuiz); return (int)(100*mean/MAX_QUESTION_SCORE); } public void debugLastResponse(OngoingQuiz ongoingQuiz) { QuestionResponse lastResponse = ongoingQuiz.getQuestionsResponses().get(ongoingQuiz.getQuestionsResponses().size() - 1); System.out.print("Question ID: "); System.out.println(lastResponse.getQuestion().getId()); System.out.print("Score: "); System.out.println(lastResponse.getQuestion().getScore()); System.out.print("Corect Answers IDs:"); for(Answer answer : lastResponse.getQuestion().getCorrectAnswers()) { System.out.print(" "); System.out.print(answer.getId()); } System.out.println(); System.out.print("Selected Answers IDs:"); for(Answer answer : lastResponse.getSelectedAnswers()) { System.out.print(" "); System.out.print(answer.getId()); } System.out.println(); System.out.print("Is Correct: "); System.out.println(lastResponse.isCorrect()); } }
Improved scoring algorithm
src/main/java/com/policat/cat/services/QuizService.java
Improved scoring algorithm
<ide><path>rc/main/java/com/policat/cat/services/QuizService.java <ide> public static final int MAX_QUESTION_SCORE = 5; <ide> public static final int MIN_QUESTION_SCORE = 1; <ide> <add> public static final int START_QUESTION_SCORE = 3; <add> public static final int NUM_SETUP_QUESTIONS = 2; <add> <ide> public static final int MIN_QUESTIONS = 5; <ide> public static final int MAX_QUESTIONS = 25; <ide> public static final int MAX_QUESTION_TIME = 60; //seconds <add> public static final double ERROR_LIMIT = .2; <ide> <ide> <ide> @Autowired <ide> return getQuestionAnswers(chosen); <ide> } <ide> <del> public List<QuestionResponse> getCorrectResponses(OngoingQuiz ongoingQuiz) { <del> List<QuestionResponse> correctResponses = new ArrayList<>(); <add> public Integer computedResponseScore(QuestionResponse questionResponse) { <add> Integer questionScore = questionResponse.getQuestion().getScore(); <add> if(questionResponse.isCorrect()) { <add> questionScore = Math.min(++questionScore, MAX_QUESTION_SCORE); <add> } else { <add> --questionScore; <add> } <add> return questionScore; <add> } <add> <add> public List<QuestionResponse> getScoreResponses(OngoingQuiz ongoingQuiz) { <ide> List<QuestionResponse> responses = ongoingQuiz.getQuestionsResponses(); <del> for(QuestionResponse response : responses) { <del> if(response.isCorrect()) { <del> correctResponses.add(response); <del> } <add> if(responses.size() <= NUM_SETUP_QUESTIONS) { <add> return responses.subList(responses.size(), responses.size()); <ide> } <del> return correctResponses; <add> return responses.subList(NUM_SETUP_QUESTIONS, responses.size()); <ide> } <ide> <ide> public Double calcMean(OngoingQuiz ongoingQuiz) { <ide> Integer sumScores = 0; <del> List<QuestionResponse> correctResponses = getCorrectResponses(ongoingQuiz); <add> List<QuestionResponse> responses = getScoreResponses(ongoingQuiz); <ide> <del> if(correctResponses.size() == 0) { <add> if(responses.size() == 0) { <ide> return 0.0; <ide> } <ide> <del> for(QuestionResponse response : correctResponses) { <del> sumScores += response.getQuestion().getScore(); <add> for(QuestionResponse response : responses) { <add> sumScores += computedResponseScore(response); <ide> } <ide> <del> return sumScores/(double)correctResponses.size(); <add> return sumScores/(double)responses.size(); <ide> } <ide> <ide> public Double calcError(OngoingQuiz ongoingQuiz) { <ide> //Standard deviation <ide> Double mean = calcMean(ongoingQuiz); <ide> Double devSum = 0.0; <del> List<QuestionResponse> correctResponses = getCorrectResponses(ongoingQuiz); <add> List<QuestionResponse> responses = getScoreResponses(ongoingQuiz); <ide> <del> if(correctResponses.size() == 0) { <add> if(responses.size() == 0) { <ide> return 0.0; <ide> } <ide> <del> for(QuestionResponse response : correctResponses) { <del> Integer questionScore = response.getQuestion().getScore(); <add> for(QuestionResponse response : responses) { <add> Integer questionScore = computedResponseScore(response); <ide> devSum += Math.pow((questionScore - mean), 2); <ide> } <del> Double stdDev = Math.sqrt(devSum/correctResponses.size()); <add> Double stdDev = Math.sqrt(devSum/responses.size()); <ide> <ide> //Standard error <del> return stdDev/Math.sqrt(correctResponses.size()); <add> return stdDev/Math.sqrt(responses.size()); <ide> } <ide> <ide> public Question chooseNextQuestion(OngoingQuiz ongoingQuiz) { <ide> if (ongoingQuiz.getQuestionsResponses().isEmpty()) { <del> return getQuestionWithScore(5, ongoingQuiz); <add> return getQuestionWithScore(START_QUESTION_SCORE, ongoingQuiz); <ide> } else if (ongoingQuiz.getQuestionsResponses().size() >= MAX_QUESTIONS) { <ide> return null; <ide> } <ide> <del> if (ongoingQuiz.getQuestionsResponses().size() > MIN_QUESTIONS && calcError(ongoingQuiz) < .4) { <add> if (ongoingQuiz.getQuestionsResponses().size() > MIN_QUESTIONS && calcError(ongoingQuiz) < ERROR_LIMIT) { <ide> return null; <ide> } <ide> <ide> } <ide> <ide> public void debugLastResponse(OngoingQuiz ongoingQuiz) { <del> QuestionResponse lastResponse = ongoingQuiz.getQuestionsResponses().get(ongoingQuiz.getQuestionsResponses().size() - 1); <add> List<QuestionResponse> responses = ongoingQuiz.getQuestionsResponses(); <add> QuestionResponse lastResponse = responses.get(ongoingQuiz.getQuestionsResponses().size() - 1); <ide> <ide> System.out.print("Question ID: "); <ide> System.out.println(lastResponse.getQuestion().getId()); <ide> <ide> System.out.print("Is Correct: "); <ide> System.out.println(lastResponse.isCorrect()); <add> <add> System.out.print("Current Score: "); <add> System.out.println(calcMean(ongoingQuiz)); <add> <add> System.out.print("Current Error: "); <add> System.out.println(calcError(ongoingQuiz)); <ide> } <ide> }
Java
mit
56ef64fb0384184fa8f81adeb93333c9ab971e87
0
dscrobonia/appsensor,sanjaygouri/appsensor,jtmelton/appsensor,ProZachJ/appsensor,dscrobonia/appsensor,mahmoodm2/appsensor,mahmoodm2/appsensor,ashishmgupta/appsensor,jtmelton/appsensor,sanjaygouri/appsensor,mahmoodm2/appsensor,ProZachJ/appsensor,dscrobonia/appsensor,ProZachJ/appsensor,ashishmgupta/appsensor,jtmelton/appsensor,dscrobonia/appsensor,timothy22000/appsensor,dscrobonia/appsensor,timothy22000/appsensor,ProZachJ/appsensor,sims143/appsensor,dscrobonia/appsensor,timothy22000/appsensor,ProZachJ/appsensor,mahmoodm2/appsensor,jtmelton/appsensor,jtmelton/appsensor,ashishmgupta/appsensor,sims143/appsensor,timothy22000/appsensor,ksmaheshkumar/appsensor,jtmelton/appsensor,mahmoodm2/appsensor,ProZachJ/appsensor,ksmaheshkumar/appsensor
package org.owasp.appsensor.handler; import java.util.Collection; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import org.owasp.appsensor.AppSensorServer; import org.owasp.appsensor.Attack; import org.owasp.appsensor.Event; import org.owasp.appsensor.RequestHandler; import org.owasp.appsensor.Response; import org.owasp.appsensor.accesscontrol.Action; import org.owasp.appsensor.criteria.SearchCriteria; import org.owasp.appsensor.exceptions.NotAuthorizedException; import org.owasp.appsensor.rest.AccessControlUtils; import org.owasp.appsensor.util.StringUtils; /** * This is the restful endpoint that handles requests on the server-side. * * @author John Melton ([email protected]) http://www.jtmelton.com/ */ @Path("/api/v1.0") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class RestRequestHandler implements RequestHandler { @Context private ContainerRequestContext requestContext; /** * {@inheritDoc} */ @Override @POST @Path("/events") public void addEvent(Event event) throws NotAuthorizedException { AccessControlUtils.checkAuthorization(Action.ADD_EVENT, requestContext); AppSensorServer.getInstance().getEventStore().addEvent(event); } /** * {@inheritDoc} */ @Override @POST @Path("/attacks") public void addAttack(Attack attack) throws NotAuthorizedException { AccessControlUtils.checkAuthorization(Action.ADD_ATTACK, requestContext); AppSensorServer.getInstance().getAttackStore().addAttack(attack); } /** * {@inheritDoc} */ @Override @GET @Path("/responses") @Produces(MediaType.APPLICATION_JSON) public Collection<Response> getResponses(@QueryParam("earliest") Long earliest) throws NotAuthorizedException { AccessControlUtils.checkAuthorization(Action.GET_RESPONSES, requestContext); String clientApplicationName = (String)requestContext.getProperty(APPSENSOR_CLIENT_APPLICATION_IDENTIFIER_ATTR); SearchCriteria criteria = new SearchCriteria(). setDetectionSystemIds(StringUtils.toCollection(clientApplicationName)). setEarliest(earliest); return AppSensorServer.getInstance().getResponseStore().findResponses(criteria); } }
appsensor-ws-rest-server/src/main/java/org/owasp/appsensor/handler/RestRequestHandler.java
package org.owasp.appsensor.handler; import java.util.Collection; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import org.owasp.appsensor.AppSensorServer; import org.owasp.appsensor.Attack; import org.owasp.appsensor.ClientApplication; import org.owasp.appsensor.Event; import org.owasp.appsensor.RequestHandler; import org.owasp.appsensor.Response; import org.owasp.appsensor.accesscontrol.Action; import org.owasp.appsensor.exceptions.NotAuthorizedException; /** * This is the restful endpoint that handles requests on the server-side. * * @author John Melton ([email protected]) http://www.jtmelton.com/ */ @Path("/api/v1.0") @Produces("application/json") public class RestRequestHandler implements RequestHandler { public static String APPSENSOR_CLIENT_APPLICATION_IDENTIFIER_ATTR = "APPSENSOR_CLIENT_APPLICATION_IDENTIFIER_ATTR"; @Context private ContainerRequestContext requestContext; /** * {@inheritDoc} */ @Override @POST @Path("/events") public void addEvent(Event event) throws NotAuthorizedException { checkAuthorization(Action.ADD_EVENT); AppSensorServer.getInstance().getEventStore().addEvent(event); } /** * {@inheritDoc} */ @Override @POST @Path("/attacks") public void addAttack(Attack attack) throws NotAuthorizedException { checkAuthorization(Action.ADD_ATTACK); AppSensorServer.getInstance().getAttackStore().addAttack(attack); } /** * {@inheritDoc} */ @Override @GET @Path("/responses") @Produces(MediaType.APPLICATION_JSON) public Collection<Response> getResponses(@QueryParam("earliest") long earliest) throws NotAuthorizedException { checkAuthorization(Action.GET_RESPONSES); String clientApplicationName = (String)requestContext.getProperty(APPSENSOR_CLIENT_APPLICATION_IDENTIFIER_ATTR); return AppSensorServer.getInstance().getResponseStore().findResponses(clientApplicationName, earliest); } /** * Check authz before performing action. * @param action desired action * @throws NotAuthorizedException thrown if user does not have role. */ private void checkAuthorization(Action action) throws NotAuthorizedException { String clientApplicationName = (String)requestContext.getProperty(APPSENSOR_CLIENT_APPLICATION_IDENTIFIER_ATTR); ClientApplication clientApplication = AppSensorServer.getInstance().getConfiguration().findClientApplication(clientApplicationName); org.owasp.appsensor.accesscontrol.Context context = new org.owasp.appsensor.accesscontrol.Context(); AppSensorServer.getInstance().getAccessController().assertAuthorized(clientApplication, action, context); } }
use access control helper - clean up api usage
appsensor-ws-rest-server/src/main/java/org/owasp/appsensor/handler/RestRequestHandler.java
use access control helper - clean up api usage
<ide><path>ppsensor-ws-rest-server/src/main/java/org/owasp/appsensor/handler/RestRequestHandler.java <ide> <ide> import java.util.Collection; <ide> <add>import javax.ws.rs.Consumes; <ide> import javax.ws.rs.GET; <ide> import javax.ws.rs.POST; <ide> import javax.ws.rs.Path; <ide> <ide> import org.owasp.appsensor.AppSensorServer; <ide> import org.owasp.appsensor.Attack; <del>import org.owasp.appsensor.ClientApplication; <ide> import org.owasp.appsensor.Event; <ide> import org.owasp.appsensor.RequestHandler; <ide> import org.owasp.appsensor.Response; <ide> import org.owasp.appsensor.accesscontrol.Action; <add>import org.owasp.appsensor.criteria.SearchCriteria; <ide> import org.owasp.appsensor.exceptions.NotAuthorizedException; <add>import org.owasp.appsensor.rest.AccessControlUtils; <add>import org.owasp.appsensor.util.StringUtils; <ide> <ide> /** <ide> * This is the restful endpoint that handles requests on the server-side. <ide> * @author John Melton ([email protected]) http://www.jtmelton.com/ <ide> */ <ide> @Path("/api/v1.0") <del>@Produces("application/json") <add>@Produces(MediaType.APPLICATION_JSON) <add>@Consumes(MediaType.APPLICATION_JSON) <ide> public class RestRequestHandler implements RequestHandler { <ide> <del> public static String APPSENSOR_CLIENT_APPLICATION_IDENTIFIER_ATTR = "APPSENSOR_CLIENT_APPLICATION_IDENTIFIER_ATTR"; <del> <ide> @Context <ide> private ContainerRequestContext requestContext; <ide> <ide> @POST <ide> @Path("/events") <ide> public void addEvent(Event event) throws NotAuthorizedException { <del> checkAuthorization(Action.ADD_EVENT); <add> AccessControlUtils.checkAuthorization(Action.ADD_EVENT, requestContext); <ide> AppSensorServer.getInstance().getEventStore().addEvent(event); <ide> } <ide> <ide> @POST <ide> @Path("/attacks") <ide> public void addAttack(Attack attack) throws NotAuthorizedException { <del> checkAuthorization(Action.ADD_ATTACK); <add> AccessControlUtils.checkAuthorization(Action.ADD_ATTACK, requestContext); <ide> AppSensorServer.getInstance().getAttackStore().addAttack(attack); <ide> } <ide> <ide> @GET <ide> @Path("/responses") <ide> @Produces(MediaType.APPLICATION_JSON) <del> public Collection<Response> getResponses(@QueryParam("earliest") long earliest) throws NotAuthorizedException { <del> checkAuthorization(Action.GET_RESPONSES); <add> public Collection<Response> getResponses(@QueryParam("earliest") Long earliest) throws NotAuthorizedException { <add> AccessControlUtils.checkAuthorization(Action.GET_RESPONSES, requestContext); <ide> <ide> String clientApplicationName = (String)requestContext.getProperty(APPSENSOR_CLIENT_APPLICATION_IDENTIFIER_ATTR); <del> return AppSensorServer.getInstance().getResponseStore().findResponses(clientApplicationName, earliest); <add> <add> SearchCriteria criteria = new SearchCriteria(). <add> setDetectionSystemIds(StringUtils.toCollection(clientApplicationName)). <add> setEarliest(earliest); <add> <add> return AppSensorServer.getInstance().getResponseStore().findResponses(criteria); <ide> } <ide> <del> /** <del> * Check authz before performing action. <del> * @param action desired action <del> * @throws NotAuthorizedException thrown if user does not have role. <del> */ <del> private void checkAuthorization(Action action) throws NotAuthorizedException { <del> String clientApplicationName = (String)requestContext.getProperty(APPSENSOR_CLIENT_APPLICATION_IDENTIFIER_ATTR); <del> <del> ClientApplication clientApplication = AppSensorServer.getInstance().getConfiguration().findClientApplication(clientApplicationName); <del> <del> org.owasp.appsensor.accesscontrol.Context context = new org.owasp.appsensor.accesscontrol.Context(); <del> <del> AppSensorServer.getInstance().getAccessController().assertAuthorized(clientApplication, action, context); <del> } <ide> }
JavaScript
mit
adc01f8c54bfd617a6359a3b9080f93a50d981f6
0
apentu/apentu.github.io,apentu/apentu.github.io,apentu/apentu.github.io
"use strict"; if (!Array.from) { Array.from = (function () { var toStr = Object.prototype.toString; var isCallable = function (fn) { return typeof fn === 'function' || toStr.call(fn) === '[object Function]'; }; var toInteger = function (value) { var number = Number(value); if (isNaN(number)) { return 0; } if (number === 0 || !isFinite(number)) { return number; } return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number)); }; var maxSafeInteger = Math.pow(2, 53) - 1; var toLength = function (value) { var len = toInteger(value); return Math.min(Math.max(len, 0), maxSafeInteger); }; // The length property of the from method is 1. return function from(arrayLike/*, mapFn, thisArg */) { // 1. Let C be the this value. var C = this; // 2. Let items be ToObject(arrayLike). var items = Object(arrayLike); // 3. ReturnIfAbrupt(items). if (arrayLike == null) { throw new TypeError("Array.from requires an array-like object - not null or undefined"); } // 4. If mapfn is undefined, then let mapping be false. var mapFn = arguments.length > 1 ? arguments[1] : void undefined; var T; if (typeof mapFn !== 'undefined') { // 5. else // 5. a If IsCallable(mapfn) is false, throw a TypeError exception. if (!isCallable(mapFn)) { throw new TypeError('Array.from: when provided, the second argument must be a function'); } // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 2) { T = arguments[2]; } } // 10. Let lenValue be Get(items, "length"). // 11. Let len be ToLength(lenValue). var len = toLength(items.length); // 13. If IsConstructor(C) is true, then // 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len. // 14. a. Else, Let A be ArrayCreate(len). var A = isCallable(C) ? Object(new C(len)) : new Array(len); // 16. Let k be 0. var k = 0; // 17. Repeat, while k < len… (also steps a - h) var kValue; while (k < len) { kValue = items[k]; if (mapFn) { A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k); } else { A[k] = kValue; } k += 1; } // 18. Let putStatus be Put(A, "length", len, true). A.length = len; // 20. Return A. return A; }; }()); } var messages = Array.from(document.querySelectorAll('.messages li')); var viewportHeight = window.innerHeight; console.log("Height = " + viewportHeight); var showHideMessage = function showHideMessage(scrollPosition) { console.log("function ran"); console.log(scrollPosition); console.log(messages); for (var i = 0; i < messages.length; i++) { console.log("in for loop" + i); if (messages[i].offsetTop <= scrollPosition) { messages[i].classList.add('js-message'); } else { messages[i].classList.remove('js-message'); } } }; window.addEventListener('scroll', function (e) { var last_known_scroll_position = window.pageYOffset + (viewportHeight - 100); showHideMessage(last_known_scroll_position); console.log(last_known_scroll_position); });
assets/js/app.js
"use strict"; if (!Array.from) { Array.from = (function () { var toStr = Object.prototype.toString; var isCallable = function (fn) { return typeof fn === 'function' || toStr.call(fn) === '[object Function]'; }; var toInteger = function (value) { var number = Number(value); if (isNaN(number)) { return 0; } if (number === 0 || !isFinite(number)) { return number; } return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number)); }; var maxSafeInteger = Math.pow(2, 53) - 1; var toLength = function (value) { var len = toInteger(value); return Math.min(Math.max(len, 0), maxSafeInteger); }; // The length property of the from method is 1. return function from(arrayLike/*, mapFn, thisArg */) { // 1. Let C be the this value. var C = this; // 2. Let items be ToObject(arrayLike). var items = Object(arrayLike); // 3. ReturnIfAbrupt(items). if (arrayLike == null) { throw new TypeError("Array.from requires an array-like object - not null or undefined"); } // 4. If mapfn is undefined, then let mapping be false. var mapFn = arguments.length > 1 ? arguments[1] : void undefined; var T; if (typeof mapFn !== 'undefined') { // 5. else // 5. a If IsCallable(mapfn) is false, throw a TypeError exception. if (!isCallable(mapFn)) { throw new TypeError('Array.from: when provided, the second argument must be a function'); } // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 2) { T = arguments[2]; } } // 10. Let lenValue be Get(items, "length"). // 11. Let len be ToLength(lenValue). var len = toLength(items.length); // 13. If IsConstructor(C) is true, then // 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len. // 14. a. Else, Let A be ArrayCreate(len). var A = isCallable(C) ? Object(new C(len)) : new Array(len); // 16. Let k be 0. var k = 0; // 17. Repeat, while k < len… (also steps a - h) var kValue; while (k < len) { kValue = items[k]; if (mapFn) { A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k); } else { A[k] = kValue; } k += 1; } // 18. Let putStatus be Put(A, "length", len, true). A.length = len; // 20. Return A. return A; }; }()); } var messages = Array.from(document.querySelectorAll('.messages li')); var viewportHeight = window.innerHeight; var showHideMessage = function showHideMessage(scrollPosition) { console.log("function ran"); console.log(scrollPosition); console.log(messages); for (var i = 0; i < messages.length; i++) { console.log("in for loop" + i); if (messages[i].offsetTop <= scrollPosition) { messages[i].classList.add('js-message'); } else { messages[i].classList.remove('js-message'); } } }; window.addEventListener('scroll', function (e) { var last_known_scroll_position = window.pageYOffset + (viewportHeight - 100); showHideMessage(last_known_scroll_position); console.log(last_known_scroll_position); });
window height edit
assets/js/app.js
window height edit
<ide><path>ssets/js/app.js <ide> <ide> var messages = Array.from(document.querySelectorAll('.messages li')); <ide> var viewportHeight = window.innerHeight; <add>console.log("Height = " + viewportHeight); <ide> <ide> var showHideMessage = function showHideMessage(scrollPosition) { <ide> console.log("function ran");
Java
mit
6d397c7bddf31574ec254be2fbaf2b8e5db914bd
0
WatchBeam/interactive-minecraft
package pro.beam.minecraft.action; import pro.beam.interactive.net.packet.Protocol; public class TactileInput implements Input { protected final int code; protected final double threshold; public TactileInput(int code, double threshold) { this.code = code; this.threshold = threshold; } @Override public boolean isMet(Protocol.Report report) { for (Protocol.Report.TactileInfo info : report.getTactileList()) { if ((info.getId() == this.code) && (info.getPressFrequency() > 0)) { return true; } } return false; } public int code() { return this.code; } }
src/main/java/pro/beam/minecraft/action/TactileInput.java
package pro.beam.minecraft.action; import pro.beam.interactive.net.packet.Protocol; public class TactileInput implements Input { protected final int code; protected final double threshold; public TactileInput(int code, double threshold) { this.code = code; this.threshold = threshold; } @Override public boolean isMet(Protocol.Report report) { for (Protocol.Report.TactileInfo info : report.getTactileList()) { double holding = info.getHolding() / report.getUsers().getActive(); if ((info.getId() == this.code) && (holding >= this.threshold)) { return true; } } return false; } public int code() { return this.code; } }
Use PressFrequency analysis
src/main/java/pro/beam/minecraft/action/TactileInput.java
Use PressFrequency analysis
<ide><path>rc/main/java/pro/beam/minecraft/action/TactileInput.java <ide> @Override <ide> public boolean isMet(Protocol.Report report) { <ide> for (Protocol.Report.TactileInfo info : report.getTactileList()) { <del> double holding = info.getHolding() / report.getUsers().getActive(); <del> if ((info.getId() == this.code) && (holding >= this.threshold)) { <add> if ((info.getId() == this.code) && (info.getPressFrequency() > 0)) { <ide> return true; <ide> } <ide> }