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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
JavaScript | mit | fba81c366b09e59907a3fc47196307566577c94b | 0 | gerbengeeraerts/IAMDEVLOPR,gerbengeeraerts/IAMDEVLOPR,gerbengeeraerts/IAMDEVLOPR | var gulp = require('gulp'),
browserify = require('browserify'),
buffer = require('gulp-buffer'),
compass = require('gulp-compass'),
gutil = require('gulp-util'),
jshint = require('gulp-jshint'),
source = require('vinyl-source-stream'),
stylish = require('jshint-stylish'),
pngquant = require('imagemin-pngquant'),
uglify = require('gulp-uglify');
//package = require('./package.json');
gulp.task('styles', function(){
return gulp.src('./css/src/**/*.scss')
.pipe(compass({
config_file: './config.rb',
css: './css',
sass: 'css/src',
environment: 'production'
}))
.on('error', function(err){
gutil.log(err.message);
gutil.beep();
this.emit('end');
})
.pipe(gulp.dest('./css'))
});
gulp.task('lint', function(){
return gulp.src('js/src/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter(stylish));
});
gulp.task('scripts', ['lint'], function(){
var bundler = browserify({
entries: ['./js/src/script.js'],
debug: false
});
return bundler.bundle()
.on('error', function(err) {
gutil.log(err.message);
gutil.beep();
this.emit('end');
})
.pipe(source('script.dist.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest('./js'))
});
gulp.task('images', function () {
return gulp.src('img/src/**/*.png')
.pipe(pngquant({ quality: '65-80', speed: 4 })())
.pipe(gulp.dest('img/'));
});
gulp.task('watch', ['scripts', 'styles', 'images'], function(){
gulp.watch(['js/src/**/*.js'], ['scripts']);
gulp.watch(['css/src/**/*.scss'], ['styles']);
gulp.watch(['img/src/**/*.png'], ['images']);
});
| gulpfile.js | var gulp = require('gulp'),
browserify = require('browserify'),
buffer = require('gulp-buffer'),
compass = require('gulp-compass'),
gutil = require('gulp-util'),
jshint = require('gulp-jshint'),
source = require('vinyl-source-stream'),
sourcemaps = require('gulp-sourcemaps'),
stylish = require('jshint-stylish'),
pngquant = require('imagemin-pngquant'),
uglify = require('gulp-uglify');
//package = require('./package.json');
gulp.task('styles', function(){
return gulp.src('./css/src/**/*.scss')
.pipe(compass({
config_file: './config.rb',
css: './css',
sass: 'css/src',
environment: 'production'
}))
.on('error', function(err){
gutil.log(err.message);
gutil.beep();
this.emit('end');
})
.pipe(gulp.dest('./css'))
});
gulp.task('lint', function(){
return gulp.src('js/src/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter(stylish));
});
gulp.task('scripts', ['lint'], function(){
var bundler = browserify({
entries: ['./js/src/script.js'],
debug: true
});
return bundler.bundle()
.on('error', function(err) {
gutil.log(err.message);
gutil.beep();
this.emit('end');
})
.pipe(source('script.dist.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(uglify())
.pipe(sourcemaps.write('./', {
sourceRoot: '../'
}))
.pipe(gulp.dest('./js'))
});
gulp.task('images', function () {
return gulp.src('img/src/**/*.png')
.pipe(pngquant({ quality: '65-80', speed: 4 })())
.pipe(gulp.dest('img/'));
});
gulp.task('watch', ['scripts', 'styles', 'images'], function(){
gulp.watch(['js/src/**/*.js'], ['scripts']);
gulp.watch(['css/src/**/*.scss'], ['styles']);
gulp.watch(['img/src/**/*.png'], ['images']);
});
| Removed sourcemapping, due to a bug in console.
| gulpfile.js | Removed sourcemapping, due to a bug in console. | <ide><path>ulpfile.js
<ide> gutil = require('gulp-util'),
<ide> jshint = require('gulp-jshint'),
<ide> source = require('vinyl-source-stream'),
<del> sourcemaps = require('gulp-sourcemaps'),
<ide> stylish = require('jshint-stylish'),
<ide> pngquant = require('imagemin-pngquant'),
<ide> uglify = require('gulp-uglify');
<ide> gulp.task('scripts', ['lint'], function(){
<ide> var bundler = browserify({
<ide> entries: ['./js/src/script.js'],
<del> debug: true
<add> debug: false
<ide> });
<ide>
<ide> return bundler.bundle()
<ide> })
<ide> .pipe(source('script.dist.js'))
<ide> .pipe(buffer())
<del> .pipe(sourcemaps.init({loadMaps: true}))
<ide> .pipe(uglify())
<del> .pipe(sourcemaps.write('./', {
<del> sourceRoot: '../'
<del> }))
<ide> .pipe(gulp.dest('./js'))
<ide> });
<ide> |
|
Java | agpl-3.0 | a852b6b2b068762007abe6c3d1ec7de37f649fee | 0 | mnip91/proactive-component-monitoring,mnip91/programming-multiactivities,ow2-proactive/programming,ow2-proactive/programming,acontes/programming,acontes/programming,jrochas/scale-proactive,acontes/scheduling,mnip91/proactive-component-monitoring,PaulKh/scale-proactive,acontes/scheduling,acontes/scheduling,ow2-proactive/programming,PaulKh/scale-proactive,mnip91/programming-multiactivities,mnip91/programming-multiactivities,PaulKh/scale-proactive,fviale/programming,paraita/programming,lpellegr/programming,fviale/programming,ow2-proactive/programming,fviale/programming,jrochas/scale-proactive,PaulKh/scale-proactive,acontes/scheduling,acontes/programming,fviale/programming,ow2-proactive/programming,acontes/programming,acontes/scheduling,PaulKh/scale-proactive,mnip91/proactive-component-monitoring,paraita/programming,acontes/programming,mnip91/proactive-component-monitoring,fviale/programming,mnip91/programming-multiactivities,mnip91/programming-multiactivities,acontes/scheduling,paraita/programming,fviale/programming,ow2-proactive/programming,acontes/programming,lpellegr/programming,jrochas/scale-proactive,lpellegr/programming,acontes/scheduling,mnip91/proactive-component-monitoring,PaulKh/scale-proactive,jrochas/scale-proactive,lpellegr/programming,PaulKh/scale-proactive,paraita/programming,lpellegr/programming,paraita/programming,mnip91/proactive-component-monitoring,jrochas/scale-proactive,lpellegr/programming,mnip91/programming-multiactivities,acontes/programming,jrochas/scale-proactive,paraita/programming,jrochas/scale-proactive | /*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.body.ft.protocols.pmlrb.managers;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.objectweb.proactive.Body;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.UniqueID;
import org.objectweb.proactive.core.body.AbstractBody;
import org.objectweb.proactive.core.body.UniversalBody;
import org.objectweb.proactive.core.body.ft.checkpointing.Checkpoint;
import org.objectweb.proactive.core.body.ft.checkpointing.CheckpointInfo;
import org.objectweb.proactive.core.body.ft.internalmsg.FTMessage;
import org.objectweb.proactive.core.body.ft.protocols.FTManager;
import org.objectweb.proactive.core.body.ft.protocols.pmlrb.infos.CheckpointInfoPMLRB;
import org.objectweb.proactive.core.body.ft.protocols.pmlrb.infos.MessageInfoPMLRB;
import org.objectweb.proactive.core.body.ft.servers.recovery.RecoveryProcess;
import org.objectweb.proactive.core.body.future.FuturePool;
import org.objectweb.proactive.core.body.message.Message;
import org.objectweb.proactive.core.body.reply.Reply;
import org.objectweb.proactive.core.body.request.BlockingRequestQueue;
import org.objectweb.proactive.core.body.request.Request;
import org.objectweb.proactive.core.util.MutableLong;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.objectweb.proactive.ext.security.exceptions.RenegotiateSessionException;
/**
* This class defines the fault-tolerance manager for the Pessimistic Message Logging protocol,
* Receiver Based approach.
* @author cdelbe
* @since 3.0
*/
public class FTManagerPMLRB extends FTManager {
/** Incarantion is not used for PML. Set to a default value */
public static final int INC_VALUE = Integer.MAX_VALUE;
/** Value returned if the message is ignored */
public static final int IGNORED_MSG = -1;
//logger
protected static Logger logger = ProActiveLogger.getLogger(Loggers.FAULT_TOLERANCE_PML);
// index of the latest received messae per senderID
// UniqueID <-> MutableLong
private Hashtable latestReceivedIndex;
// true if this oa is recovering
private boolean isRecovering;
// timer
private long checkpointTimer;
//sequence number of sending for any messages
private char sendNumber;
private MessageInfoPMLRB replyInfos;
private MessageInfoPMLRB requestInfos;
// After a recovery, the last message of the log could be resend by its sender:
// if the failure has occured between the logging and the end of the RDV.
// Identify possible duplicatas
private transient UniqueID potentialDuplicataSender;
private transient long potentialDuplicataSequence;
/**
* FTManager initialization.
* @param owner the attached body.
*/
public int init(AbstractBody owner) throws ProActiveException {
super.init(owner);
this.latestReceivedIndex = new Hashtable();
this.isRecovering = false;
//checkpoint timer init: a checkpoint must be taken before any request service
this.checkpointTimer = 0;
// this.checkpointTimer = System.currentTimeMillis();
this.sendNumber = 0;
this.replyInfos = new MessageInfoPMLRB();
this.requestInfos = new MessageInfoPMLRB();
this.potentialDuplicataSender = null;
this.potentialDuplicataSequence = 0;
logger.info(" PML fault-tolerance is enabled for body " + this.ownerID);
return 0;
}
/**
* Message can be ignored if its index is l.t. lastestReceivedIndex[sender]
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onReceiveReply(org.objectweb.proactive.core.body.reply.Reply)
*/
public int onReceiveReply(Reply reply) {
// if the message is sent by a non ft object
if (reply.getMessageInfo() == null) {
reply.setFTManager(this);
return 0;
}
// Automatic continuation ---> Replies are not in sequence
// we thus cannot block ac replies
if (!reply.isAutomaticContinuation()) {
if (this.alreadyReceived(reply)) {
// this message has already been received. Ignore it
reply.setIgnoreIt(true);
return IGNORED_MSG;
}
}
reply.setFTManager(this);
return 0;
}
/**
* Message can be ignored if its index is l.t. lastestReceivedIndex[sender]
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onReceiveRequest(org.objectweb.proactive.core.body.request.Request)
*/
public int onReceiveRequest(Request request) {
// if the message is sent from a non ft object
if (request.getMessageInfo() == null) {
request.setFTManager(this);
return 0;
}
if (this.alreadyReceived(request)) {
// this message has already been received. Ignore it
request.setIgnoreIt(true);
return IGNORED_MSG;
}
request.setFTManager(this);
return 0;
}
/**
* Message must be synchronously logged before being delivered.
* The LatestRcvdIndex table is updated
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onDeliverReply(org.objectweb.proactive.core.body.reply.Reply)
*/
public int onDeliverReply(Reply reply) {
// if the ao is recovering, message are not logged
if (!this.isRecovering) {
try {
// log the message
this.storage.storeReply(this.ownerID, reply);
// update latestIndex table
this.updateLatestRvdIndexTable(reply);
} catch (RemoteException e) {
e.printStackTrace();
}
}
return 0;
}
/**
* Message must be synchronously logged before being delivered.
* The LatestRcvdIndex table is updated
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onReceiveRequest(org.objectweb.proactive.core.body.request.Request)
*/
public int onDeliverRequest(Request request) {
// if the ao is recovering, message are not logged
if (!this.isRecovering) {
try {
// log the message
this.storage.storeRequest(this.ownerID, request);
// update latestIndex table
this.updateLatestRvdIndexTable(request);
} catch (RemoteException e) {
e.printStackTrace();
}
}
return 0;
}
/*
* Set the value of m.sourceBody to m.seqNumber
*/
private void updateLatestRvdIndexTable(Message m) {
// the first message from this sender?
MutableLong index = (MutableLong) (this.latestReceivedIndex.get(m.getSourceBodyID()));
MessageInfoPMLRB mi = (MessageInfoPMLRB) (m.getMessageInfo());
if (mi == null) {
// from a not ft
return;
}
long msgIndex = mi.sentSequenceNumber;
if (index != null) {
index.setValue(msgIndex);
} else {
//first message
this.latestReceivedIndex.put(m.getSourceBodyID(),
new MutableLong(msgIndex));
}
}
/*
* Return true if this message has already been received
*/
private boolean alreadyReceived(Message m) {
if ((this.potentialDuplicataSender != null) &&
(m.getSourceBodyID().equals(this.potentialDuplicataSender)) &&
(m.getSequenceNumber() == this.potentialDuplicataSequence)) {
// this message has been already logged just before the failure of this.
// no more such message can appear...
this.potentialDuplicataSender = null;
return true;
} else {
long msgIndex = ((MessageInfoPMLRB) (m.getMessageInfo())).sentSequenceNumber;
MutableLong index = (MutableLong) (this.latestReceivedIndex.get(m.getSourceBodyID()));
return (index != null) && (msgIndex <= index.getValue());
}
}
/**
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onSendReplyBefore(org.objectweb.proactive.core.body.reply.Reply)
*/
public synchronized int onSendReplyBefore(Reply reply) {
this.replyInfos.sentSequenceNumber = this.getNextSendNumber();
reply.setMessageInfo(this.replyInfos);
return 0;
}
/**
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onSendReplyAfter(org.objectweb.proactive.core.body.reply.Reply, int, org.objectweb.proactive.core.body.UniversalBody)
*/
public int onSendReplyAfter(Reply reply, int rdvValue,
UniversalBody destination) {
return 0;
}
/**
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onSendRequestBefore(org.objectweb.proactive.core.body.request.Request)
*/
public synchronized int onSendRequestBefore(Request request) {
this.requestInfos.sentSequenceNumber = this.getNextSendNumber();
request.setMessageInfo(this.requestInfos);
return 0;
}
/**
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onSendRequestAfter(org.objectweb.proactive.core.body.request.Request, int, org.objectweb.proactive.core.body.UniversalBody)
*/
public int onSendRequestAfter(Request request, int rdvValue,
UniversalBody destination) throws RenegotiateSessionException {
return 0;
}
/**
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onServeRequestBefore(org.objectweb.proactive.core.body.request.Request)
*/
public int onServeRequestBefore(Request request) {
if (this.haveToCheckpoint()) {
this.checkpoint(request);
}
return 0;
}
/**
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onServeRequestAfter(org.objectweb.proactive.core.body.request.Request)
*/
public int onServeRequestAfter(Request request) {
return 0;
}
/**
* Message logs are contained in the checkpoint info structure.
*/
public int beforeRestartAfterRecovery(CheckpointInfo ci, int inc) {
// recovery mode: received message no longer logged
this.isRecovering = true;
//first must register incoming futures deserialized by the recovery thread
this.owner.registerIncomingFutures();
//get messages
List replies = ((CheckpointInfoPMLRB) ci).getReplyLog();
List request = ((CheckpointInfoPMLRB) ci).getRequestLog();
// deal with potential duplicata of request
// duplicata of replies are not treated since they are automaticaly ignored.
Request potentialDuplicata = (Request) (request.get(request.size() - 1));
this.potentialDuplicataSender = potentialDuplicata.getSourceBodyID();
this.potentialDuplicataSequence = potentialDuplicata.getSequenceNumber();
// add messages in the body context
Iterator itRequest = request.iterator();
BlockingRequestQueue queue = owner.getRequestQueue();
while (itRequest.hasNext()) {
queue.add((Request) (itRequest.next()));
}
// replies
Iterator itReplies = replies.iterator();
FuturePool fp = owner.getFuturePool();
try {
while (itReplies.hasNext()) {
Reply current = (Reply) (itReplies.next());
fp.receiveFutureValue(current.getSequenceNumber(),
current.getSourceBodyID(), current.getResult(), current);
}
} catch (IOException e) {
e.printStackTrace();
}
// add pending request to reuqestQueue
Request pendingRequest = ((CheckpointInfoPMLRB) ci).getPendingRequest();
// pending request could be null
if (pendingRequest != null) {
queue.addToFront(pendingRequest);
}
// normal mode
this.isRecovering = false;
// enable communication
this.owner.acceptCommunication();
try {
// update servers
this.location.updateLocation(ownerID, owner.getRemoteAdapter());
this.recovery.updateState(ownerID, RecoveryProcess.RUNNING);
} catch (RemoteException e) {
logger.error("Unable to connect with location server");
e.printStackTrace();
}
this.checkpointTimer = System.currentTimeMillis();
return 0;
}
/**
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#handleFTMessage(org.objectweb.proactive.core.body.ft.internalmsg.FTMessage)
*/
public Object handleFTMessage(FTMessage fte) {
return fte.handleFTMessage(this);
}
/////////////////////
// private methods //
/////////////////////
private boolean haveToCheckpoint() {
return ((this.checkpointTimer + this.ttc) < System.currentTimeMillis());
}
private void checkpoint(Request pending) {
//System.out.println("[PMLRB] Checkpointing...");
owner.blockCommunication();
// checkpoint the active object
try {
this.setCheckpointTag(true);
// create a checkpoint
Checkpoint c = new Checkpoint((Body) owner, this.additionalCodebase);
// create checkpoint info with the pending request
CheckpointInfoPMLRB ci = new CheckpointInfoPMLRB(pending);
// attach infos
c.setCheckpointInfo(ci);
// send it to server
this.storage.storeCheckpoint(c, FTManagerPMLRB.DEFAULT_TTC_VALUE); // SEE INC VALUE !
// reninit checkpoint values
this.checkpointTimer = System.currentTimeMillis();
this.setCheckpointTag(false);
} catch (RemoteException e) {
logger.error("[PMLRB] Unable to send checkpoint to the server");
e.printStackTrace();
}
owner.acceptCommunication();
}
private synchronized char getNextSendNumber() {
return ++sendNumber;
}
}
| src/org/objectweb/proactive/core/body/ft/protocols/pmlrb/managers/FTManagerPMLRB.java | /*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.body.ft.protocols.pmlrb.managers;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.objectweb.proactive.Body;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.body.AbstractBody;
import org.objectweb.proactive.core.body.UniversalBody;
import org.objectweb.proactive.core.body.ft.checkpointing.Checkpoint;
import org.objectweb.proactive.core.body.ft.checkpointing.CheckpointInfo;
import org.objectweb.proactive.core.body.ft.internalmsg.FTMessage;
import org.objectweb.proactive.core.body.ft.protocols.FTManager;
import org.objectweb.proactive.core.body.ft.protocols.pmlrb.infos.CheckpointInfoPMLRB;
import org.objectweb.proactive.core.body.ft.protocols.pmlrb.infos.MessageInfoPMLRB;
import org.objectweb.proactive.core.body.ft.servers.recovery.RecoveryProcess;
import org.objectweb.proactive.core.body.future.FuturePool;
import org.objectweb.proactive.core.body.message.Message;
import org.objectweb.proactive.core.body.reply.Reply;
import org.objectweb.proactive.core.body.request.BlockingRequestQueue;
import org.objectweb.proactive.core.body.request.Request;
import org.objectweb.proactive.core.util.MutableLong;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.objectweb.proactive.ext.security.exceptions.RenegotiateSessionException;
/**
* This class defines the fault-tolerance manager for the Pessimistic Message Logging protocol,
* Receiver Based approach.
* @author cdelbe
* @since 3.0
*/
public class FTManagerPMLRB extends FTManager {
/** Incarantion is not used for PML. Set to a default value */
public static final int INC_VALUE = Integer.MAX_VALUE;
/** Value returned if the message is ignored */
public static final int IGNORED_MSG = -1;
//logger
protected static Logger logger = ProActiveLogger.getLogger(Loggers.FAULT_TOLERANCE_PML);
// index of the latest received messae per senderID
// UniqueID <-> MutableLong
private Hashtable latestReceivedIndex;
// true if this oa is recovering
private boolean isRecovering;
// timer
private long checkpointTimer;
//sequence number of sending for any messages
private char sendNumber;
private MessageInfoPMLRB replyInfos;
private MessageInfoPMLRB requestInfos;
/**
* FTManager initialization.
* @param owner the attached body.
*/
public int init(AbstractBody owner) throws ProActiveException {
super.init(owner);
this.latestReceivedIndex = new Hashtable();
this.isRecovering = false;
//checkpoint timer init: a checkpoint must be taken before any request service
this.checkpointTimer = 0;
// this.checkpointTimer = System.currentTimeMillis();
this.sendNumber = 0;
this.replyInfos = new MessageInfoPMLRB();
this.requestInfos = new MessageInfoPMLRB();
logger.info(" PML fault-tolerance is enabled for body " + this.ownerID);
return 0;
}
/**
* Message can be ignored if its index is l.t. lastestReceivedIndex[sender]
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onReceiveReply(org.objectweb.proactive.core.body.reply.Reply)
*/
public int onReceiveReply(Reply reply) {
// if the message is sent by a non ft object
if (reply.getMessageInfo() == null) {
reply.setFTManager(this);
return 0;
}
// Automatic continuation ---> Replies are not in sequence
// we thus cannot block ac replies
if (!reply.isAutomaticContinuation()) {
if (this.alreadyReceived(reply)) {
// this message has already been received. Ignore it
reply.setIgnoreIt(true);
return IGNORED_MSG;
}
}
reply.setFTManager(this);
return 0;
}
/**
* Message can be ignored if its index is l.t. lastestReceivedIndex[sender]
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onReceiveRequest(org.objectweb.proactive.core.body.request.Request)
*/
public int onReceiveRequest(Request request) {
// if the message is sent from a non ft object
if (request.getMessageInfo() == null) {
request.setFTManager(this);
return 0;
}
if (this.alreadyReceived(request)) {
// this message has already been received. Ignore it
request.setIgnoreIt(true);
return IGNORED_MSG;
}
request.setFTManager(this);
return 0;
}
/**
* Message must be synchronously logged before being delivered.
* The LatestRcvdIndex table is updated
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onDeliverReply(org.objectweb.proactive.core.body.reply.Reply)
*/
public int onDeliverReply(Reply reply) {
// if the ao is recovering, message are not logged
if (!this.isRecovering) {
try {
// log the message
this.storage.storeReply(this.ownerID, reply);
// update latestIndex table
this.updateLatestRvdIndexTable(reply);
} catch (RemoteException e) {
e.printStackTrace();
}
}
return 0;
}
/**
* Message must be synchronously logged before being delivered.
* The LatestRcvdIndex table is updated
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onReceiveRequest(org.objectweb.proactive.core.body.request.Request)
*/
public int onDeliverRequest(Request request) {
// if the ao is recovering, message are not logged
if (!this.isRecovering) {
try {
// log the message
this.storage.storeRequest(this.ownerID, request);
// update latestIndex table
this.updateLatestRvdIndexTable(request);
} catch (RemoteException e) {
e.printStackTrace();
}
}
return 0;
}
/*
* Set the value of m.sourceBody to m.seqNumber
*/
private void updateLatestRvdIndexTable(Message m) {
// the first message from this sender?
MutableLong index = (MutableLong) (this.latestReceivedIndex.get(m.getSourceBodyID()));
MessageInfoPMLRB mi = (MessageInfoPMLRB) (m.getMessageInfo());
if (mi == null) {
// from a not ft
return;
}
long msgIndex = mi.sentSequenceNumber;
if (index != null) {
index.setValue(msgIndex);
} else {
//first message
this.latestReceivedIndex.put(m.getSourceBodyID(),
new MutableLong(msgIndex));
}
}
/*
* Return true if this message has already been received
*/
private boolean alreadyReceived(Message m) {
long msgIndex = ((MessageInfoPMLRB) (m.getMessageInfo())).sentSequenceNumber;
MutableLong index = (MutableLong) (this.latestReceivedIndex.get(m.getSourceBodyID()));
return (index != null) && (msgIndex <= index.getValue());
}
/**
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onSendReplyBefore(org.objectweb.proactive.core.body.reply.Reply)
*/
public synchronized int onSendReplyBefore(Reply reply) {
this.replyInfos.sentSequenceNumber = this.getNextSendNumber();
reply.setMessageInfo(this.replyInfos);
return 0;
}
/**
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onSendReplyAfter(org.objectweb.proactive.core.body.reply.Reply, int, org.objectweb.proactive.core.body.UniversalBody)
*/
public int onSendReplyAfter(Reply reply, int rdvValue,
UniversalBody destination) {
return 0;
}
/**
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onSendRequestBefore(org.objectweb.proactive.core.body.request.Request)
*/
public synchronized int onSendRequestBefore(Request request) {
this.requestInfos.sentSequenceNumber = this.getNextSendNumber();
request.setMessageInfo(this.requestInfos);
return 0;
}
/**
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onSendRequestAfter(org.objectweb.proactive.core.body.request.Request, int, org.objectweb.proactive.core.body.UniversalBody)
*/
public int onSendRequestAfter(Request request, int rdvValue,
UniversalBody destination) throws RenegotiateSessionException {
return 0;
}
/**
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onServeRequestBefore(org.objectweb.proactive.core.body.request.Request)
*/
public int onServeRequestBefore(Request request) {
if (this.haveToCheckpoint()) {
this.checkpoint(request);
}
return 0;
}
/**
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#onServeRequestAfter(org.objectweb.proactive.core.body.request.Request)
*/
public int onServeRequestAfter(Request request) {
return 0;
}
/**
* Message logs are contained in the checkpoint info structure.
*/
public int beforeRestartAfterRecovery(CheckpointInfo ci, int inc) {
// recovery mode: received message no longer logged
this.isRecovering = true;
//first must register incoming futures deserialized by the recovery thread
this.owner.registerIncomingFutures();
//get messages
List replies = ((CheckpointInfoPMLRB) ci).getReplyLog();
List request = ((CheckpointInfoPMLRB) ci).getRequestLog();
// add messages in the body context
// requests
Iterator itRequest = request.iterator();
BlockingRequestQueue queue = owner.getRequestQueue();
while (itRequest.hasNext()) {
queue.add((Request) (itRequest.next()));
}
// replies
Iterator itReplies = replies.iterator();
FuturePool fp = owner.getFuturePool();
try {
while (itReplies.hasNext()) {
Reply current = (Reply) (itReplies.next());
fp.receiveFutureValue(current.getSequenceNumber(),
current.getSourceBodyID(), current.getResult(), current);
}
} catch (IOException e) {
e.printStackTrace();
}
// add pending request to reuqestQueue
Request pendingRequest = ((CheckpointInfoPMLRB) ci).getPendingRequest();
// pending request could be null
if (pendingRequest != null) {
queue.addToFront(pendingRequest);
}
// normal mode
this.isRecovering = false;
// enable communication
this.owner.acceptCommunication();
try {
// update servers
this.location.updateLocation(ownerID, owner.getRemoteAdapter());
this.recovery.updateState(ownerID, RecoveryProcess.RUNNING);
} catch (RemoteException e) {
logger.error("Unable to connect with location server");
e.printStackTrace();
}
this.checkpointTimer = System.currentTimeMillis();
return 0;
}
/**
* @see org.objectweb.proactive.core.body.ft.protocols.FTManager#handleFTMessage(org.objectweb.proactive.core.body.ft.internalmsg.FTMessage)
*/
public Object handleFTMessage(FTMessage fte) {
return fte.handleFTMessage(this);
}
/////////////////////
// private methods //
/////////////////////
private boolean haveToCheckpoint() {
return ((this.checkpointTimer + this.ttc) < System.currentTimeMillis());
}
private void checkpoint(Request pending) {
//System.out.println("[PMLRB] Checkpointing...");
owner.blockCommunication();
// checkpoint the active object
try {
this.setCheckpointTag(true);
// create a checkpoint
Checkpoint c = new Checkpoint((Body) owner, this.additionalCodebase);
// create checkpoint info with the pending request
CheckpointInfoPMLRB ci = new CheckpointInfoPMLRB(pending);
// attach infos
c.setCheckpointInfo(ci);
// send it to server
this.storage.storeCheckpoint(c, FTManagerPMLRB.DEFAULT_TTC_VALUE); // SEE INC VALUE !
// reninit checkpoint values
this.checkpointTimer = System.currentTimeMillis();
this.setCheckpointTag(false);
} catch (RemoteException e) {
logger.error("[PMLRB] Unable to send checkpoint to the server");
e.printStackTrace();
}
owner.acceptCommunication();
}
private synchronized char getNextSendNumber() {
return ++sendNumber;
}
}
| Fix "potential duplicata of first incoming request after recovery" bug.
git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@2831 28e8926c-6b08-0410-baaa-805c5e19b8d6
| src/org/objectweb/proactive/core/body/ft/protocols/pmlrb/managers/FTManagerPMLRB.java | Fix "potential duplicata of first incoming request after recovery" bug. | <ide><path>rc/org/objectweb/proactive/core/body/ft/protocols/pmlrb/managers/FTManagerPMLRB.java
<ide> import org.apache.log4j.Logger;
<ide> import org.objectweb.proactive.Body;
<ide> import org.objectweb.proactive.core.ProActiveException;
<add>import org.objectweb.proactive.core.UniqueID;
<ide> import org.objectweb.proactive.core.body.AbstractBody;
<ide> import org.objectweb.proactive.core.body.UniversalBody;
<ide> import org.objectweb.proactive.core.body.ft.checkpointing.Checkpoint;
<ide>
<ide> //logger
<ide> protected static Logger logger = ProActiveLogger.getLogger(Loggers.FAULT_TOLERANCE_PML);
<del>
<add>
<ide> // index of the latest received messae per senderID
<ide> // UniqueID <-> MutableLong
<ide> private Hashtable latestReceivedIndex;
<ide> private char sendNumber;
<ide> private MessageInfoPMLRB replyInfos;
<ide> private MessageInfoPMLRB requestInfos;
<add>
<add> // After a recovery, the last message of the log could be resend by its sender:
<add> // if the failure has occured between the logging and the end of the RDV.
<add> // Identify possible duplicatas
<add> private transient UniqueID potentialDuplicataSender;
<add> private transient long potentialDuplicataSequence;
<ide>
<ide> /**
<ide> * FTManager initialization.
<ide> this.sendNumber = 0;
<ide> this.replyInfos = new MessageInfoPMLRB();
<ide> this.requestInfos = new MessageInfoPMLRB();
<add> this.potentialDuplicataSender = null;
<add> this.potentialDuplicataSequence = 0;
<ide> logger.info(" PML fault-tolerance is enabled for body " + this.ownerID);
<ide> return 0;
<ide> }
<ide> * Return true if this message has already been received
<ide> */
<ide> private boolean alreadyReceived(Message m) {
<del> long msgIndex = ((MessageInfoPMLRB) (m.getMessageInfo())).sentSequenceNumber;
<del> MutableLong index = (MutableLong) (this.latestReceivedIndex.get(m.getSourceBodyID()));
<del> return (index != null) && (msgIndex <= index.getValue());
<add> if ((this.potentialDuplicataSender != null) &&
<add> (m.getSourceBodyID().equals(this.potentialDuplicataSender)) &&
<add> (m.getSequenceNumber() == this.potentialDuplicataSequence)) {
<add> // this message has been already logged just before the failure of this.
<add> // no more such message can appear...
<add> this.potentialDuplicataSender = null;
<add> return true;
<add> } else {
<add> long msgIndex = ((MessageInfoPMLRB) (m.getMessageInfo())).sentSequenceNumber;
<add> MutableLong index = (MutableLong) (this.latestReceivedIndex.get(m.getSourceBodyID()));
<add> return (index != null) && (msgIndex <= index.getValue());
<add> }
<ide> }
<ide>
<ide> /**
<ide> List replies = ((CheckpointInfoPMLRB) ci).getReplyLog();
<ide> List request = ((CheckpointInfoPMLRB) ci).getRequestLog();
<ide>
<add> // deal with potential duplicata of request
<add> // duplicata of replies are not treated since they are automaticaly ignored.
<add> Request potentialDuplicata = (Request) (request.get(request.size() - 1));
<add> this.potentialDuplicataSender = potentialDuplicata.getSourceBodyID();
<add> this.potentialDuplicataSequence = potentialDuplicata.getSequenceNumber();
<add>
<ide> // add messages in the body context
<del> // requests
<ide> Iterator itRequest = request.iterator();
<ide> BlockingRequestQueue queue = owner.getRequestQueue();
<add>
<ide> while (itRequest.hasNext()) {
<ide> queue.add((Request) (itRequest.next()));
<ide> } |
|
Java | mit | 98aee7ec1aa22176799e41e217a896c77168d48a | 0 | ihongs/HongsCORE.new,ihongs/HongsCORE.new,ihongs/HongsCORE.new,ihongs/HongsCORE.new,ihongs/HongsCORE.new | package io.github.ihongs;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TimeZone;
import java.util.Locale;
import java.util.function.Supplier;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 核心类
*
* <p>
* Servlet 在众多实现中总是以单实例多线程的方式工作,
* 即对于单个请求有且仅有一个线程在为其服务;
* 此 Core 类为框架的对象代理, 对象在线程内唯一存在,
* 可在此管理的类需提供一个公共无参构造方法,
* getInstance 公共无参静态方法可自定构造和存储规则.
* 获取当前 Core 的唯一实例总是用 Core.getInstance()
* </p>
*
* <p>
* THREAD_CORE 被包装成了 ThreadLocal,
* 实例在单一线程内使用并没有什么问题,
* 如果跨线程使用则可能有线程安全问题;
* GLOBAL_CORE 用于存放全局对象和参数,
* 对读写等过程有加锁, 但仍需小心对待.
* Cleanable,Singleton 类别放入非全局.
* </p>
*
* <h3>静态属性:</h3>
* <pre>
* ENVIR 标识不同运行环境(0 cmd, 1 web)
* DEBUG 标识不同调试模式(0 无 , 1 输出, 2 日志, 4 禁止跟踪 8 禁止调试; 可使用位运算例如 3 表示既输出又记录)
* BASE_HREF 应用访问路径(Web应用中为ContextPath)
* BASE_PATH 应用目录路径(Web应用中为RealPath(/))
* CORE_PATH 应用目录路径(Web应用中为WEB-INF目录)
* CONF_PATH 配置目录路径(CORE_PATH/etc)
* DATA_PATH 数据目录路径(CORE_PATH/var)
* SERVER_ID 服务器ID (依附于 Core.newIdentity())
* 注: 以上属性需要在 Servlet/Filter/Cmdlet 等初始化时进行设置. 为保持简单, 整个容器是开放的 , 留意勿被恶意修改.
* </pre>
*
* <h3>错误代码:</h3>
* <pre>
* 0x24 实例名称不能为空
* 0x25 无法获取对应的类
* 0x26 禁止访问工厂方法
* 0x27 无法执行工厂方法
* 0x28 执行构造方法失败
* </pre>
*
* @author Hongs
*/
abstract public class Core
extends HashMap<String, Object>
implements AutoCloseable
{
/**
* 运行环境(0 Cmd , 1 Web )
*/
public static byte ENVIR;
/**
* 调试级别(0 静默, 1 输出, 2 日志, 4 禁止Trace, 8 禁止Debug)
* 注意: 错误总是会记录日志, 故生产环境中设为 0
*/
public static byte DEBUG;
/**
* 服务编号, 可用于分布式场景下防止产生重复的 ID
*/
public static String SERVER_ID = "0" ;
/**
* WEB基础域名, 注意: 不以斜杠结尾, 协议域名端口
*/
public static String SITE_HREF = null;
/**
* WEB基础链接, 注意: 不以斜杠结尾, 默认为空字串
*/
public static String BASE_HREF = null;
/**
* WEB顶级目录, 注意: 不以斜杠结尾, 其他同此规则
*/
public static String BASE_PATH = null;
/**
* 应用文件顶级目录
*/
public static String CORE_PATH = null;
/**
* 配置文件存放目录
*/
public static String CONF_PATH = null;
/**
* 数据文件存放目录
*/
public static String DATA_PATH = null;
/**
* 系统启动时间
*/
public static final long STARTS_TIME = System.currentTimeMillis();
/**
* 全局核心对象
*/
public static final Core GLOBAL_CORE = new Global();
/**
* 线程核心对象
*/
public static final ThreadLocal<Core> THREAD_CORE
= new ThreadLocal() {
@Override
protected Core initialValue() {
return new Simple ();
}
@Override
public void remove() {
try {
( (Core) get()).close();
} catch (Throwable ex) {
throw new Error(ex);
}
super.remove();
}
};
/**
* 动作开始时间
*/
public static final InheritableThreadLocal< Long > ACTION_TIME
= new InheritableThreadLocal();
/**
* 动作时区标识
*/
public static final InheritableThreadLocal<String> ACTION_ZONE
= new InheritableThreadLocal();
/**
* 动作语言标识
*/
public static final InheritableThreadLocal<String> ACTION_LANG
= new InheritableThreadLocal();
/**
* 动作路径标识
*/
public static final InheritableThreadLocal<String> ACTION_NAME
= new InheritableThreadLocal();
/**
* 客户地址标识
*/
public static final InheritableThreadLocal<String> CLIENT_ADDR
= new InheritableThreadLocal();
/**
* 获取核心对象
* @return 核心对象
*/
public static final Core getInstance()
{
return THREAD_CORE.get();
}
/**
* 按类获取单例
*
* @param <T>
* @param clas
* @return 类的对象
*/
public static final <T>T getInstance(Class<T> clas)
{
return getInstance().get(clas);
}
/**
* 类名获取单例
*
* @param name
* @return 类的对象
*/
public static final Object getInstance(String name)
{
return getInstance().get(name);
}
public static final <T>T newInstance(Class<T> clas)
{
try
{
// 获取工厂方法
java.lang.reflect.Method method;
method = clas.getMethod("getInstance", new Class [] {});
// 获取工厂对象
try
{
return ( T ) method.invoke( null , new Object[] {});
}
catch (IllegalAccessException ex)
{
throw new HongsError(0x27, "Can not build "+clas.getName(), ex);
}
catch (IllegalArgumentException ex)
{
throw new HongsError(0x27, "Can not build "+clas.getName(), ex);
}
catch (java.lang.reflect.InvocationTargetException ex )
{
Throwable ta = ex.getCause();
// 调用层级过多, 最好直接抛出
if (ta instanceof StackOverflowError)
{
throw ( StackOverflowError ) ta ;
}
throw new HongsError(0x27, "Can not build "+clas.getName(), ta);
}
}
catch (NoSuchMethodException ez)
{
// 获取标准对象
try
{
return clas.newInstance();
}
catch (IllegalAccessException ex)
{
throw new HongsError(0x28, "Can not build "+clas.getName(), ex);
}
catch (InstantiationException ex)
{
Throwable ta = ex.getCause();
// 调用层级过多, 最好直接抛出
if (ta instanceof StackOverflowError)
{
throw ( StackOverflowError ) ta ;
}
throw new HongsError(0x28, "Can not build "+clas.getName(), ex);
}
}
catch (SecurityException se)
{
throw new HongsError(0x26, "Can not build "+clas.getName(), se);
}
}
public static final Object newInstance(String name)
{
Class klass;
// 获取类
try
{
klass = Class.forName( name );
}
catch (ClassNotFoundException ex)
{
throw new HongsError(0x25, "Can not find class by name '" + name + "'.");
}
return newInstance(klass);
}
/**
* 新建唯一标识
*
* 36进制的16位字串(服务器ID占两位),
* 可以支持到"2101/01/18 02:32:27".
* 取值范围: 0~9A~Z
*
* @param svid 服务器ID
* @return 唯一标识
*/
public static final String newIdentity(String svid)
{
long time = (System.currentTimeMillis ()- 1314320040000L); // 2011/08/26, 溜溜生日
long trid = (Thread.currentThread/**/ (). getId ()%1296L); // 36^2
int rand = ThreadLocalRandom.current().nextInt(1679616); // 36^4
time = time % 2821109907456L; // 36^8
return String.format(
"%8s%4s%2s%2s",
Long.toString(time, 36),
Long.toString(rand, 36),
Long.toString(trid, 36),
svid
).replace(' ','0')
.toUpperCase( );
}
/**
* 新建唯一标识
*
* 采用当前服务器ID(Core.SERVER_ID)
*
* @return 唯一标识
*/
public static final String newIdentity()
{
return Core.newIdentity(Core.SERVER_ID);
}
/**
* 获取语言地区
* @return
*/
public static final Locale getLocality()
{
Core core = Core.getInstance();
String name = Locale.class.getName();
Locale inst = (Locale)core.got(name);
if (null != inst) {
return inst;
}
String[] lang = Core.ACTION_LANG.get().split("_",2);
if (2 <= lang.length) {
inst = new Locale(lang[0],lang[1]);
} else {
inst = new Locale(lang[0]);
}
core.put(name, inst);
return inst;
}
/**
* 获取当前时区
* @return
*/
public static final TimeZone getTimezone()
{
Core core = Core.getInstance();
String name = TimeZone.class.getName();
TimeZone inst = (TimeZone)core.got(name);
if (null != inst) {
return inst;
}
inst = TimeZone.getTimeZone(Core.ACTION_ZONE.get());
core.put(name, inst);
return inst;
}
//** 核心方法 **/
/**
* 获取名对应的唯一对象
*
* @param key [包路径.]类名
* @return 唯一对象
*/
abstract public Object get(String key);
/**
* 获取类对应的唯一对象
*
* @param <T> 返回类型同请求类型
* @param cls [包.]类.class
* @return 唯一对象
*/
abstract public <T>T get(Class<T> cls);
/**
* 获取实例, 无则构建
* @param <T>
* @param key
* @param fun
* @return 会执行 fun 进行构建, 当没有对象时
*/
abstract public <T>T get(String key, Supplier<T> fun);
/**
* 写入实例, 过程加锁
* @param <T>
* @param key
* @param fun
* @return 不同于 put 返回旧的, 这里返回新的
*/
abstract public <T>T set(String key, Supplier<T> fun);
/**
* 调用原始 get 方法
*
* @param name
* @return 唯一对象, 不存在则返回空
*/
public Object got(String name)
{
return super.get(name);
}
/**
* 弃用 get(Object), 请用 got(String),get(String|Class)
*
* @param name
* @return 抛出异常, 为避歧义禁用之
* @throws UnsupportedOperationException
* @deprecated
*/
@Override
public Object get(Object name)
{
throw new UnsupportedOperationException(
"May cause an error on 'get(Object)', use 'got(String)' or 'get(String|Class)'");
}
/**
* 可关闭清理
*/
public void clean()
{
if (this.isEmpty())
{
return;
}
Iterator i = this.entrySet().iterator();
while ( i.hasNext( ) )
{
Entry e = (Entry)i.next();
Object o = e . getValue();
try
{
if (o instanceof Cleanable)
{
Cleanable c = (Cleanable) o;
if (c.cleanable ())
{
if (o instanceof AutoCloseable )
{
((AutoCloseable) c ).close( );
}
i.remove();
}
}
}
catch ( Throwable x )
{
x.printStackTrace ( System.err );
}
}
}
/**
* 关闭后清空
*/
@Override
public void clear()
{
if (this.isEmpty())
{
return;
}
/**
* 为规避 ConcurrentModificationException,
* 只能采用遍历数组而非迭代循环的方式进行.
*/
Object[] a = this.values().toArray();
for (int i = 0; i < a.length; i ++ )
{
Object o = a [i];
try
{
if (o instanceof AutoCloseable )
{
((AutoCloseable) o ).close( );
}
}
catch ( Throwable x )
{
x.printStackTrace ( System.err );
}
}
super.clear();
}
@Override
public void close()
{
clear();
}
@Override
protected void finalize() throws Throwable
{
try {
close();
} finally {
super.finalize();
}
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
for(Map.Entry<String, Object> et : entrySet())
{
sb.append('[');
int ln = sb.length();
Object ob = et.getValue();
if (ob instanceof AutoCloseable)
{
sb.append('A');
}
if (ob instanceof Cleanable)
{
sb.append('C');
}
if (ob instanceof Singleton)
{
sb.append('S');
}
if (ln < sb.length() )
{
sb.append(']');
} else {
sb.setLength(ln - 1);
}
sb.append(et.getKey()).append(", ");
}
// 去掉尾巴上多的逗号
int sl = sb.length();
if (sl > 0 )
{
sb.setLength(sl-2);
}
return sb.toString();
}
/**
* 简单容器
* 非线程安全, 未对任何过程加锁, 作线程内共享对象
*/
private static final class Simple extends Core
{
@Override
public Object get(String name)
{
Core core = Core.GLOBAL_CORE;
if (this.containsKey(name))
{
return this.got(name);
}
if (core.containsKey(name))
{
return core.got(name);
}
Object inst = newInstance( name );
if (inst instanceof Soliloquy)
{
// Do not keep it-self.
} else
if (inst instanceof Singleton)
{
core.put( name, inst );
} else
{
this.put( name, inst );
}
return inst;
}
@Override
public <T>T get(Class<T> clas)
{
String name = clas.getName( );
Core core = Core.GLOBAL_CORE;
if (this.containsKey(name))
{
return (T)this.got(name);
}
if (core.containsKey(name))
{
return (T)core.got(name);
}
T inst = newInstance( clas );
if (inst instanceof Soliloquy)
{
// Do not keep it-self.
} else
if (inst instanceof Singleton)
{
core.put( name, inst );
} else
{
this.put( name, inst );
}
return inst;
}
@Override
public <T>T get(String key, Supplier<T> fun)
{
Object abj=super.got(key);
if (null != abj)
return (T) abj;
T obj = fun.get( );
super.put(key,obj);
return obj;
}
@Override
public <T>T set(String key, Supplier<T> fun)
{
T obj = fun.get( );
super.put(key,obj);
return obj;
}
}
/**
* 全局容器
* 带锁的容器, 内部采用了读写锁, 并对写过程可包裹
*/
private static final class Global extends Core
{
private final ReadWriteLock LOCK = new ReentrantReadWriteLock();
@Override
public Object got(String key)
{
LOCK.readLock( ).lock();
try {
return super.got(key);
} finally {
LOCK.readLock( ).unlock();
}
}
@Override
public Object get(String key)
{
LOCK.readLock( ).lock();
try {
if (super.containsKey(key)) {
return super.got(key);
}
} finally {
LOCK.readLock( ).unlock();
}
LOCK.writeLock().lock();
try {
Object obj = newInstance(key);
super.put( key, obj );
return obj;
} finally {
LOCK.writeLock().unlock();
}
}
@Override
public <T>T get(Class<T> cls)
{
String key = cls.getName( );
LOCK.readLock( ).lock();
try {
if (super.containsKey(key)) {
return (T) super.got(key);
}
} finally {
LOCK.readLock( ).unlock();
}
LOCK.writeLock().lock();
try {
T obj = newInstance(cls);
super.put( key, obj );
return obj;
} finally {
LOCK.writeLock().unlock();
}
}
@Override
public <T>T get(String key, Supplier<T> fun)
{
LOCK.readLock( ).lock();
try {
Object obj=super.got(key);
if (null != obj)
return (T) obj;
} finally {
LOCK.readLock( ).unlock();
}
LOCK.writeLock().lock();
try {
T obj = fun.get( );
super.put(key,obj);
return obj;
} finally {
LOCK.writeLock().unlock();
}
}
@Override
public <T>T set(String key, Supplier<T> fun)
{
LOCK.writeLock().lock();
try {
T obj = fun.get( );
super.put(key,obj);
return obj;
} finally {
LOCK.writeLock().unlock();
}
}
@Override
public Object put(String key, Object obj)
{
LOCK.writeLock().lock();
try {
return super.put(key,obj);
} finally {
LOCK.writeLock().unlock();
}
}
@Override
public void clear()
{
LOCK.writeLock().lock();
try {
super.clear();
} finally {
LOCK.writeLock().unlock();
}
}
@Override
public void clean()
{
LOCK.writeLock().lock();
try {
super.clean();
} finally {
LOCK.writeLock().unlock();
}
}
}
//** 核心接口 **/
/**
* 可关闭的
* 实现此接口, 会询问是否可清理, 许可则会被删除掉
*/
static public interface Cleanable
{
public boolean cleanable ();
}
/**
* 单例模式
* 实现此接口, 则在全局环境唯一, 常驻且仅构造一次
*/
static public interface Singleton {}
/**
* 自持模式
* 实现此接口, 则自行维护其实例, 不会主动进行存储
*/
static public interface Soliloquy {}
}
| hongs-core/src/main/java/io/github/ihongs/Core.java | package io.github.ihongs;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TimeZone;
import java.util.Locale;
import java.util.function.Supplier;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 核心类
*
* <p>
* Servlet 在众多实现中总是以单实例多线程的方式工作,
* 即对于单个请求有且仅有一个线程在为其服务;
* 此 Core 类为框架的对象代理, 对象在线程内唯一存在,
* 可在此管理的类需提供一个公共无参构造方法,
* getInstance 公共无参静态方法可自定构造和存储规则.
* 获取当前 Core 的唯一实例总是用 Core.getInstance()
* </p>
*
* <p>
* THREAD_CORE 被包装成了 ThreadLocal,
* 实例在单一线程内使用并没有什么问题,
* 如果跨线程使用则可能有线程安全问题;
* GLOBAL_CORE 用于存放全局对象和参数,
* 对读写等过程有加锁, 但仍需小心对待.
* Cleanable,Singleton 类别放入非全局.
* </p>
*
* <h3>静态属性:</h3>
* <pre>
* ENVIR 标识不同运行环境(0 cmd, 1 web)
* DEBUG 标识不同调试模式(0 无 , 1 输出, 2 日志, 4 禁止跟踪 8 禁止调试; 可使用位运算例如 3 表示既输出又记录)
* BASE_HREF 应用访问路径(WEB应用中为ContextPath)
* BASE_PATH 应用目录路径(WEB应用中为RealPath(/))
* CORE_PATH 应用目录路径(WEB应用中为WEB-INF目录)
* CONF_PATH 配置文件存放目录
* DATA_PATH 数据文件存放目录
* SERVER_ID 服务器ID (依附于 Core.getUniqueId())
* 注: 以上属性需要在 Servlet/Filter/Cmdlet 等初始化时进行设置. 为保持简单, 整个容器是开放的 , 留意勿被恶意修改.
* </pre>
*
* <h3>错误代码:</h3>
* <pre>
* 0x24 实例名称不能为空
* 0x25 无法获取对应的类
* 0x26 禁止访问工厂方法
* 0x27 无法执行工厂方法
* 0x28 执行构造方法失败
* </pre>
*
* @author Hongs
*/
abstract public class Core
extends HashMap<String, Object>
implements AutoCloseable
{
/**
* 运行环境(0 Cmd , 1 Web )
*/
public static byte ENVIR;
/**
* 调试级别(0 静默, 1 输出, 2 日志, 4 禁止Trace, 8 禁止Debug)
* 注意: 错误总是会记录日志, 故生产环境中设为 0
*/
public static byte DEBUG;
/**
* 服务编号, 可用于分布式场景下防止产生重复的 ID
*/
public static String SERVER_ID = "0" ;
/**
* WEB基础域名, 注意: 不以斜杠结尾, 协议域名端口
*/
public static String SITE_HREF = null;
/**
* WEB基础链接, 注意: 不以斜杠结尾, 默认为空字串
*/
public static String BASE_HREF = null;
/**
* WEB顶级目录, 注意: 不以斜杠结尾, 其他同此规则
*/
public static String BASE_PATH = null;
/**
* 应用文件顶级目录
*/
public static String CORE_PATH = null;
/**
* 配置文件存放目录
*/
public static String CONF_PATH = null;
/**
* 数据文件存放目录
*/
public static String DATA_PATH = null;
/**
* 系统启动时间
*/
public static final long STARTS_TIME = System.currentTimeMillis();
/**
* 全局核心对象
*/
public static final Core GLOBAL_CORE = new Global();
/**
* 线程核心对象
*/
public static final ThreadLocal<Core> THREAD_CORE
= new ThreadLocal() {
@Override
protected Core initialValue() {
return new Simple ();
}
@Override
public void remove() {
try {
( (Core) get()).close();
} catch (Throwable ex) {
throw new Error(ex);
}
super.remove();
}
};
/**
* 动作开始时间
*/
public static final InheritableThreadLocal< Long > ACTION_TIME
= new InheritableThreadLocal();
/**
* 动作时区标识
*/
public static final InheritableThreadLocal<String> ACTION_ZONE
= new InheritableThreadLocal();
/**
* 动作语言标识
*/
public static final InheritableThreadLocal<String> ACTION_LANG
= new InheritableThreadLocal();
/**
* 动作路径标识
*/
public static final InheritableThreadLocal<String> ACTION_NAME
= new InheritableThreadLocal();
/**
* 客户地址标识
*/
public static final InheritableThreadLocal<String> CLIENT_ADDR
= new InheritableThreadLocal();
/**
* 获取核心对象
* @return 核心对象
*/
public static final Core getInstance()
{
return THREAD_CORE.get();
}
/**
* 按类获取单例
*
* @param <T>
* @param clas
* @return 类的对象
*/
public static final <T>T getInstance(Class<T> clas)
{
return getInstance().get(clas);
}
/**
* 类名获取单例
*
* @param name
* @return 类的对象
*/
public static final Object getInstance(String name)
{
return getInstance().get(name);
}
public static final <T>T newInstance(Class<T> clas)
{
try
{
// 获取工厂方法
java.lang.reflect.Method method;
method = clas.getMethod("getInstance", new Class [] {});
// 获取工厂对象
try
{
return ( T ) method.invoke( null , new Object[] {});
}
catch (IllegalAccessException ex)
{
throw new HongsError(0x27, "Can not build "+clas.getName(), ex);
}
catch (IllegalArgumentException ex)
{
throw new HongsError(0x27, "Can not build "+clas.getName(), ex);
}
catch (java.lang.reflect.InvocationTargetException ex )
{
Throwable ta = ex.getCause();
// 调用层级过多, 最好直接抛出
if (ta instanceof StackOverflowError)
{
throw ( StackOverflowError ) ta ;
}
throw new HongsError(0x27, "Can not build "+clas.getName(), ta);
}
}
catch (NoSuchMethodException ez)
{
// 获取标准对象
try
{
return clas.newInstance();
}
catch (IllegalAccessException ex)
{
throw new HongsError(0x28, "Can not build "+clas.getName(), ex);
}
catch (InstantiationException ex)
{
Throwable ta = ex.getCause();
// 调用层级过多, 最好直接抛出
if (ta instanceof StackOverflowError)
{
throw ( StackOverflowError ) ta ;
}
throw new HongsError(0x28, "Can not build "+clas.getName(), ex);
}
}
catch (SecurityException se)
{
throw new HongsError(0x26, "Can not build "+clas.getName(), se);
}
}
public static final Object newInstance(String name)
{
Class klass;
// 获取类
try
{
klass = Class.forName( name );
}
catch (ClassNotFoundException ex)
{
throw new HongsError(0x25, "Can not find class by name '" + name + "'.");
}
return newInstance(klass);
}
/**
* 新建唯一标识
*
* 36进制的16位字串(服务器ID占两位),
* 可以支持到"2101/01/18 02:32:27".
* 取值范围: 0~9A~Z
*
* @param svid 服务器ID
* @return 唯一标识
*/
public static final String newIdentity(String svid)
{
long time = (System.currentTimeMillis ()- 1314320040000L); // 2011/08/26, 溜溜生日
long trid = (Thread.currentThread/**/ (). getId ()%1296L); // 36^2
int rand = ThreadLocalRandom.current().nextInt(1679616); // 36^4
time = time % 2821109907456L; // 36^8
return String.format(
"%8s%4s%2s%2s",
Long.toString(time, 36),
Long.toString(rand, 36),
Long.toString(trid, 36),
svid
).replace(' ','0')
.toUpperCase( );
}
/**
* 新建唯一标识
*
* 采用当前服务器ID(Core.SERVER_ID)
*
* @return 唯一标识
*/
public static final String newIdentity()
{
return Core.newIdentity(Core.SERVER_ID);
}
/**
* 获取语言地区
* @return
*/
public static final Locale getLocality()
{
Core core = Core.getInstance();
String name = Locale.class.getName();
Locale inst = (Locale)core.got(name);
if (null != inst) {
return inst;
}
String[] lang = Core.ACTION_LANG.get().split("_",2);
if (2 <= lang.length) {
inst = new Locale(lang[0],lang[1]);
} else {
inst = new Locale(lang[0]);
}
core.put(name, inst);
return inst;
}
/**
* 获取当前时区
* @return
*/
public static final TimeZone getTimezone()
{
Core core = Core.getInstance();
String name = TimeZone.class.getName();
TimeZone inst = (TimeZone)core.got(name);
if (null != inst) {
return inst;
}
inst = TimeZone.getTimeZone(Core.ACTION_ZONE.get());
core.put(name, inst);
return inst;
}
//** 核心方法 **/
/**
* 获取名对应的唯一对象
*
* @param key [包路径.]类名
* @return 唯一对象
*/
abstract public Object get(String key);
/**
* 获取类对应的唯一对象
*
* @param <T> 返回类型同请求类型
* @param cls [包.]类.class
* @return 唯一对象
*/
abstract public <T>T get(Class<T> cls);
/**
* 获取实例, 无则构建
* @param <T>
* @param key
* @param fun
* @return 会执行 fun 进行构建, 当没有对象时
*/
abstract public <T>T get(String key, Supplier<T> fun);
/**
* 写入实例, 过程加锁
* @param <T>
* @param key
* @param fun
* @return 不同于 put 返回旧的, 这里返回新的
*/
abstract public <T>T set(String key, Supplier<T> fun);
/**
* 调用原始 get 方法
*
* @param name
* @return 唯一对象, 不存在则返回空
*/
public Object got(String name)
{
return super.get(name);
}
/**
* 弃用 get(Object), 请用 got(String),get(String|Class)
*
* @param name
* @return 抛出异常, 为避歧义禁用之
* @throws UnsupportedOperationException
* @deprecated
*/
@Override
public Object get(Object name)
{
throw new UnsupportedOperationException(
"May cause an error on 'get(Object)', use 'got(String)' or 'get(String|Class)'");
}
/**
* 可关闭清理
*/
public void clean()
{
if (this.isEmpty())
{
return;
}
Iterator i = this.entrySet().iterator();
while ( i.hasNext( ) )
{
Entry e = (Entry)i.next();
Object o = e . getValue();
try
{
if (o instanceof Cleanable)
{
Cleanable c = (Cleanable) o;
if (c.cleanable ())
{
if (o instanceof AutoCloseable )
{
((AutoCloseable) c ).close( );
}
i.remove();
}
}
}
catch ( Throwable x )
{
x.printStackTrace ( System.err );
}
}
}
/**
* 关闭后清空
*/
@Override
public void clear()
{
if (this.isEmpty())
{
return;
}
/**
* 为规避 ConcurrentModificationException,
* 只能采用遍历数组而非迭代循环的方式进行.
*/
Object[] a = this.values().toArray();
for (int i = 0; i < a.length; i ++ )
{
Object o = a [i];
try
{
if (o instanceof AutoCloseable )
{
((AutoCloseable) o ).close( );
}
}
catch ( Throwable x )
{
x.printStackTrace ( System.err );
}
}
super.clear();
}
@Override
public void close()
{
clear();
}
@Override
protected void finalize() throws Throwable
{
try {
close();
} finally {
super.finalize();
}
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
for(Map.Entry<String, Object> et : entrySet())
{
sb.append('[');
int ln = sb.length();
Object ob = et.getValue();
if (ob instanceof AutoCloseable)
{
sb.append('A');
}
if (ob instanceof Cleanable)
{
sb.append('C');
}
if (ob instanceof Singleton)
{
sb.append('S');
}
if (ln < sb.length() )
{
sb.append(']');
} else {
sb.setLength(ln - 1);
}
sb.append(et.getKey()).append(", ");
}
// 去掉尾巴上多的逗号
int sl = sb.length();
if (sl > 0 )
{
sb.setLength(sl-2);
}
return sb.toString();
}
/**
* 简单容器
* 非线程安全, 未对任何过程加锁, 作线程内共享对象
*/
private static final class Simple extends Core
{
@Override
public Object get(String name)
{
Core core = Core.GLOBAL_CORE;
if (this.containsKey(name))
{
return this.got(name);
}
if (core.containsKey(name))
{
return core.got(name);
}
Object inst = newInstance( name );
if (inst instanceof Singleton)
{
core.put( name, inst );
} else
{
this.put( name, inst );
}
return inst;
}
@Override
public <T>T get(Class<T> clas)
{
String name = clas.getName( );
Core core = Core.GLOBAL_CORE;
if (this.containsKey(name))
{
return (T)this.got(name);
}
if (core.containsKey(name))
{
return (T)core.got(name);
}
T inst = newInstance( clas );
if (inst instanceof Singleton)
{
core.put( name, inst );
} else
{
this.put( name, inst );
}
return inst;
}
@Override
public <T>T get(String key, Supplier<T> fun)
{
Object abj=super.got(key);
if (null != abj)
return (T) abj;
T obj = fun.get( );
super.put(key,obj);
return obj;
}
@Override
public <T>T set(String key, Supplier<T> fun)
{
T obj = fun.get( );
super.put(key,obj);
return obj;
}
}
/**
* 全局容器
* 带锁的容器, 内部采用了读写锁, 并对写过程可包裹
*/
private static final class Global extends Core
{
private final ReadWriteLock LOCK = new ReentrantReadWriteLock();
@Override
public Object got(String key)
{
LOCK.readLock( ).lock();
try {
return super.got(key);
} finally {
LOCK.readLock( ).unlock();
}
}
@Override
public Object get(String key)
{
LOCK.readLock( ).lock();
try {
if (super.containsKey(key)) {
return super.got(key);
}
} finally {
LOCK.readLock( ).unlock();
}
LOCK.writeLock().lock();
try {
Object obj = newInstance(key);
super.put( key, obj );
return obj;
} finally {
LOCK.writeLock().unlock();
}
}
@Override
public <T>T get(Class<T> cls)
{
String key = cls.getName( );
LOCK.readLock( ).lock();
try {
if (super.containsKey(key)) {
return (T) super.got(key);
}
} finally {
LOCK.readLock( ).unlock();
}
LOCK.writeLock().lock();
try {
T obj = newInstance(cls);
super.put( key, obj );
return obj;
} finally {
LOCK.writeLock().unlock();
}
}
@Override
public <T>T get(String key, Supplier<T> fun)
{
LOCK.readLock( ).lock();
try {
Object obj=super.got(key);
if (null != obj)
return (T) obj;
} finally {
LOCK.readLock( ).unlock();
}
LOCK.writeLock().lock();
try {
T obj = fun.get( );
super.put(key,obj);
return obj;
} finally {
LOCK.writeLock().unlock();
}
}
@Override
public <T>T set(String key, Supplier<T> fun)
{
LOCK.writeLock().lock();
try {
T obj = fun.get( );
super.put(key,obj);
return obj;
} finally {
LOCK.writeLock().unlock();
}
}
@Override
public Object put(String key, Object obj)
{
LOCK.writeLock().lock();
try {
return super.put(key,obj);
} finally {
LOCK.writeLock().unlock();
}
}
@Override
public void clear()
{
LOCK.writeLock().lock();
try {
super.clear();
} finally {
LOCK.writeLock().unlock();
}
}
@Override
public void clean()
{
LOCK.writeLock().lock();
try {
super.clean();
} finally {
LOCK.writeLock().unlock();
}
}
}
//** 核心接口 **/
/**
* 可关闭的
* 实现此接口, 会询问是否可清理, 许可则会被删除掉
*/
static public interface Cleanable
{
public boolean cleanable ();
}
/**
* 单例模式
* 实现此接口, 则在全局环境唯一, 常驻且仅构造一次
*/
static public interface Singleton {}
}
| 增加自持模式接口, 在此接口下 Core 不主动存储其对象, 交由其自行处理. | hongs-core/src/main/java/io/github/ihongs/Core.java | 增加自持模式接口, 在此接口下 Core 不主动存储其对象, 交由其自行处理. | <ide><path>ongs-core/src/main/java/io/github/ihongs/Core.java
<ide> * <pre>
<ide> * ENVIR 标识不同运行环境(0 cmd, 1 web)
<ide> * DEBUG 标识不同调试模式(0 无 , 1 输出, 2 日志, 4 禁止跟踪 8 禁止调试; 可使用位运算例如 3 表示既输出又记录)
<del> * BASE_HREF 应用访问路径(WEB应用中为ContextPath)
<del> * BASE_PATH 应用目录路径(WEB应用中为RealPath(/))
<del> * CORE_PATH 应用目录路径(WEB应用中为WEB-INF目录)
<del> * CONF_PATH 配置文件存放目录
<del> * DATA_PATH 数据文件存放目录
<del> * SERVER_ID 服务器ID (依附于 Core.getUniqueId())
<add> * BASE_HREF 应用访问路径(Web应用中为ContextPath)
<add> * BASE_PATH 应用目录路径(Web应用中为RealPath(/))
<add> * CORE_PATH 应用目录路径(Web应用中为WEB-INF目录)
<add> * CONF_PATH 配置目录路径(CORE_PATH/etc)
<add> * DATA_PATH 数据目录路径(CORE_PATH/var)
<add> * SERVER_ID 服务器ID (依附于 Core.newIdentity())
<ide> * 注: 以上属性需要在 Servlet/Filter/Cmdlet 等初始化时进行设置. 为保持简单, 整个容器是开放的 , 留意勿被恶意修改.
<ide> * </pre>
<ide> *
<ide> }
<ide>
<ide> Object inst = newInstance( name );
<add> if (inst instanceof Soliloquy)
<add> {
<add> // Do not keep it-self.
<add> } else
<ide> if (inst instanceof Singleton)
<ide> {
<ide> core.put( name, inst );
<ide> }
<ide>
<ide> T inst = newInstance( clas );
<add> if (inst instanceof Soliloquy)
<add> {
<add> // Do not keep it-self.
<add> } else
<ide> if (inst instanceof Singleton)
<ide> {
<ide> core.put( name, inst );
<ide> */
<ide> static public interface Singleton {}
<ide>
<add> /**
<add> * 自持模式
<add> * 实现此接口, 则自行维护其实例, 不会主动进行存储
<add> */
<add> static public interface Soliloquy {}
<add>
<ide> } |
|
Java | epl-1.0 | bd2a34b08d84a767fd1e63397644d36f65352d78 | 0 | Fiser12/Sudoku-SPQ | package es.deusto.ingenieria.spq.sudoku.client.gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import java.awt.CardLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.Color;
import javax.swing.JList;
import javax.swing.JRadioButton;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.SystemColor;
import javax.swing.UIManager;
public class Dificultad extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel panelSeleccion;
private JLabel lblSeleccionarUnaOpcion;
private JPanel panelBotones;
private JPanel panelOpciones;
private JPanel panel_3;
private JRadioButton rdbtn_1F;
private JButton btnFacil;
private JRadioButton radioButton_M;
private JButton btnMedio;
private JRadioButton radioButtonD;
private JButton btnDificil;
private JRadioButton rdbtnE;
private JButton btnExtremo;
private JButton btnAtras;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Dificultad frame = new Dificultad();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private static Thread hilo = null;
/**
* Create the frame.
*/
public Dificultad() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Seleccionar dificultad");
setForeground(Color.WHITE);
setBounds(450, 100, 300, 450);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
// setDefaultCloseOperation(0); // No se cerrar pulsando X
panelSeleccion = new JPanel();
contentPane.add(panelSeleccion, BorderLayout.NORTH);
panelSeleccion.setLayout(new GridLayout(0, 1, 0, 0));
lblSeleccionarUnaOpcion = new JLabel("Seleccionar una dificultad para el sudoku");
panelSeleccion.add(lblSeleccionarUnaOpcion);
panelBotones = new JPanel();
contentPane.add(panelBotones, BorderLayout.CENTER);
panelBotones.setLayout(new GridLayout(0, 1, 0, 0));
panelOpciones = new JPanel();
panelBotones.add(panelOpciones);
panelOpciones.setLayout(new GridLayout(0, 1, 0, 0));
panel_3 = new JPanel();
panelOpciones.add(panel_3);
panel_3.setLayout(new BorderLayout(0, 0));
rdbtn_1F = new JRadioButton("");
rdbtn_1F.setEnabled(false);
panel_3.add(rdbtn_1F, BorderLayout.WEST);
btnFacil = new JButton("Facil");
btnFacil.setIcon(null);
btnFacil.setFont(new Font("Tahoma", Font.PLAIN, 15));
panel_3.add(btnFacil);
btnFacil.setForeground(Color.GREEN);
btnFacil.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
radioButtonD.setSelected(false);
rdbtnE.setSelected(false);
rdbtn_1F.setSelected(true);
radioButton_M.setSelected(false);
}
});
JPanel panel_4 = new JPanel();
panelOpciones.add(panel_4);
panel_4.setLayout(new BorderLayout(0, 0));
radioButton_M = new JRadioButton("");
radioButton_M.setEnabled(false);
panel_4.add(radioButton_M, BorderLayout.WEST);
btnMedio = new JButton("Medio");
btnMedio.setFont(new Font("Tahoma", Font.PLAIN, 15));
panel_4.add(btnMedio);
btnMedio.setForeground(Color.BLUE);
btnMedio.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
radioButtonD.setSelected(false);
rdbtnE.setSelected(false);
rdbtn_1F.setSelected(false);
radioButton_M.setSelected(true);
}
});
JPanel panel_5 = new JPanel();
panelOpciones.add(panel_5);
panel_5.setLayout(new BorderLayout(0, 0));
radioButtonD = new JRadioButton("");
radioButtonD.setEnabled(false);
panel_5.add(radioButtonD, BorderLayout.WEST);
btnDificil = new JButton("Difcil");
btnDificil.setFont(new Font("Tahoma", Font.PLAIN, 15));
panel_5.add(btnDificil);
btnDificil.setForeground(Color.RED);
btnDificil.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
radioButtonD.setSelected(true);
rdbtnE.setSelected(false);
rdbtn_1F.setSelected(false);
radioButton_M.setSelected(false);
}
});
JPanel panel_6 = new JPanel();
panelOpciones.add(panel_6);
panel_6.setLayout(new BorderLayout(0, 0));
rdbtnE = new JRadioButton("");
rdbtnE.setEnabled(false);
panel_6.add(rdbtnE, BorderLayout.WEST);
btnExtremo = new JButton("Extremo");
btnExtremo.setFont(new Font("Tahoma", Font.PLAIN, 15));
panel_6.add(btnExtremo, BorderLayout.CENTER);
btnExtremo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
radioButtonD.setSelected(false);
rdbtnE.setSelected(true);
rdbtn_1F.setSelected(false);
radioButton_M.setSelected(false);
//metodo de selecionar la dificulatad
}
});
JPanel panel_2 = new JPanel();
panelBotones.add(panel_2);
panel_2.setLayout(new GridLayout(0, 1, 0, 0));
btnAtras = new JButton("Atras");
btnAtras.setFont(new Font("Tahoma", Font.PLAIN, 15));
btnAtras.setHorizontalAlignment(SwingConstants.LEFT);
btnAtras.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
volver();
}
});
JPanel panel = new JPanel();
panel_2.add(panel);
panel_2.add(btnAtras);
JPanel panel_1 = new JPanel();
panel_2.add(panel_1);
}
public void volver()
{
hilo = new Thread()
{
public void run()
{
setVisible(false);
MenuJuego mj = new MenuJuego();
mj.setResizable(false);
mj.setVisible(true);
hilo = null;
}
};
hilo.start();
}
}
| src/es/deusto/ingenieria/spq/sudoku/client/gui/Dificultad.java | package es.deusto.ingenieria.spq.sudoku.client.gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import java.awt.CardLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.Color;
import javax.swing.JList;
import javax.swing.JRadioButton;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.SystemColor;
import javax.swing.UIManager;
public class Dificultad extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel panelSeleccion;
private JLabel lblSeleccionarUnaOpcion;
private JPanel panelBotones;
private JPanel panelOpciones;
private JPanel panel_3;
private JRadioButton rdbtn_1F;
private JButton btnFacil;
private JRadioButton radioButton_M;
private JButton btnMedio;
private JRadioButton radioButtonD;
private JButton btnDificil;
private JRadioButton rdbtnE;
private JButton btnExtremo;
private JButton btnAtras;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Dificultad frame = new Dificultad();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private static Thread hilo = null;
/**
* Create the frame.
*/
public Dificultad() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Seleccionar dificultad");
setForeground(Color.WHITE);
setBounds(450, 100, 300, 450);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
setDefaultCloseOperation(0); // No se cerrar pulsando X
panelSeleccion = new JPanel();
contentPane.add(panelSeleccion, BorderLayout.NORTH);
panelSeleccion.setLayout(new GridLayout(0, 1, 0, 0));
lblSeleccionarUnaOpcion = new JLabel("Seleccionar una dificultad para el sudoku");
panelSeleccion.add(lblSeleccionarUnaOpcion);
panelBotones = new JPanel();
contentPane.add(panelBotones, BorderLayout.CENTER);
panelBotones.setLayout(new GridLayout(0, 1, 0, 0));
panelOpciones = new JPanel();
panelBotones.add(panelOpciones);
panelOpciones.setLayout(new GridLayout(0, 1, 0, 0));
panel_3 = new JPanel();
panelOpciones.add(panel_3);
panel_3.setLayout(new BorderLayout(0, 0));
rdbtn_1F = new JRadioButton("");
rdbtn_1F.setEnabled(false);
panel_3.add(rdbtn_1F, BorderLayout.WEST);
btnFacil = new JButton("Facil");
btnFacil.setIcon(null);
btnFacil.setFont(new Font("Tahoma", Font.PLAIN, 15));
panel_3.add(btnFacil);
btnFacil.setForeground(Color.GREEN);
btnFacil.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
radioButtonD.setSelected(false);
rdbtnE.setSelected(false);
rdbtn_1F.setSelected(true);
radioButton_M.setSelected(false);
}
});
JPanel panel_4 = new JPanel();
panelOpciones.add(panel_4);
panel_4.setLayout(new BorderLayout(0, 0));
radioButton_M = new JRadioButton("");
radioButton_M.setEnabled(false);
panel_4.add(radioButton_M, BorderLayout.WEST);
btnMedio = new JButton("Medio");
btnMedio.setFont(new Font("Tahoma", Font.PLAIN, 15));
panel_4.add(btnMedio);
btnMedio.setForeground(Color.BLUE);
btnMedio.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
radioButtonD.setSelected(false);
rdbtnE.setSelected(false);
rdbtn_1F.setSelected(false);
radioButton_M.setSelected(true);
}
});
JPanel panel_5 = new JPanel();
panelOpciones.add(panel_5);
panel_5.setLayout(new BorderLayout(0, 0));
radioButtonD = new JRadioButton("");
radioButtonD.setEnabled(false);
panel_5.add(radioButtonD, BorderLayout.WEST);
btnDificil = new JButton("Difcil");
btnDificil.setBackground(Color.WHITE);
btnDificil.setFont(new Font("Tahoma", Font.PLAIN, 15));
panel_5.add(btnDificil);
btnDificil.setForeground(Color.RED);
btnDificil.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
radioButtonD.setSelected(true);
rdbtnE.setSelected(false);
rdbtn_1F.setSelected(false);
radioButton_M.setSelected(false);
}
});
JPanel panel_6 = new JPanel();
panelOpciones.add(panel_6);
panel_6.setLayout(new BorderLayout(0, 0));
rdbtnE = new JRadioButton("");
rdbtnE.setEnabled(false);
panel_6.add(rdbtnE, BorderLayout.WEST);
btnExtremo = new JButton("Extremo");
btnExtremo.setFont(new Font("Tahoma", Font.PLAIN, 15));
panel_6.add(btnExtremo, BorderLayout.CENTER);
btnExtremo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
radioButtonD.setSelected(false);
rdbtnE.setSelected(true);
rdbtn_1F.setSelected(false);
radioButton_M.setSelected(false);
//metodo de selecionar la dificulatad
}
});
JPanel panel_2 = new JPanel();
panelBotones.add(panel_2);
panel_2.setLayout(new GridLayout(0, 1, 0, 0));
btnAtras = new JButton("Atras");
btnAtras.setFont(new Font("Tahoma", Font.PLAIN, 15));
btnAtras.setHorizontalAlignment(SwingConstants.LEFT);
btnAtras.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
volver();
}
});
JPanel panel = new JPanel();
panel_2.add(panel);
panel_2.add(btnAtras);
JPanel panel_1 = new JPanel();
panel_2.add(panel_1);
}
public void volver()
{
hilo = new Thread()
{
public void run()
{
setVisible(false);
MenuJuego mj = new MenuJuego();
mj.setResizable(false);
mj.setVisible(true);
hilo = null;
}
};
hilo.start();
}
}
| Ventana difficultad echa
| src/es/deusto/ingenieria/spq/sudoku/client/gui/Dificultad.java | Ventana difficultad echa | <ide><path>rc/es/deusto/ingenieria/spq/sudoku/client/gui/Dificultad.java
<ide> contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
<ide> setContentPane(contentPane);
<ide> contentPane.setLayout(new BorderLayout(0, 0));
<del> setDefaultCloseOperation(0); // No se cerrar pulsando X
<add>// setDefaultCloseOperation(0); // No se cerrar pulsando X
<ide>
<ide> panelSeleccion = new JPanel();
<ide> contentPane.add(panelSeleccion, BorderLayout.NORTH);
<ide> panel_5.add(radioButtonD, BorderLayout.WEST);
<ide>
<ide> btnDificil = new JButton("Difcil");
<del> btnDificil.setBackground(Color.WHITE);
<ide> btnDificil.setFont(new Font("Tahoma", Font.PLAIN, 15));
<ide> panel_5.add(btnDificil);
<ide> btnDificil.setForeground(Color.RED); |
|
JavaScript | mit | d296e4c3094147c1d2e0966152c97bfb48ad9352 | 0 | kamaal-/itunes-app,kamaal-/itunes-app | /**
* Created by kamaal on 10/7/17.
*/
import {
SEARCH_TEXT_UPDATED,
ITUNES_FETCH_STARTED,
ITUNES_FETCH_SUCCESS,
FAVORITE_ALBUM_ADDED,
FAVORITE_ARTIST_FILTERED,
MOBILE_TAB_CHANGED
} from '../action-types'
import {uniqBy} from 'lodash'
import Album from '../../models/Album' // album model
import Suggestion from '../../models/Artist' // importing artist as suggestion
/*
* Add or remove favorite album from favorite collection by checking current favorite collection
* @param {array} _favorite collection of Album instances from current state
* @album {Album} album instance of Album from triggered album
* @returns {array} of Album instances
* */
const _togleFavorite = (_favorite, album) => {
let favorite = _favorite
if(favorite.find(_album => _album.id === album.id)){
return favorite.filter(_album => _album.id !== album.id)
}
favorite.push(album)
return favorite
}
/*
* Fetch albums using browsers default fetch api
* @param {string} artist name of the artist from search input
* @callback cb
*/
const _justFetch = (artist, cb) => {
const uri = `https://itunes.apple.com/search?term=${artist}&entity=album`
fetch(uri)
.then(response => response.json())
.then(res => {
if (res.resultCount > 0) {
cb(res.results.map(r => new Album(r)), res.results.map(r => new Suggestion(r)))
}
})
}
/*
* Redux action to call fetch artist
* @param {string} artist name of the artist from search input
* @returns {object} will return Promise from fetch api it will be composed to pure object from redux-thunk
*/
export const doSearch = (artist = 'michael') => {
return (dispatch, getState) => {
let { suggestions } = getState() // getting current suggestions
dispatch({type: ITUNES_FETCH_STARTED})
_justFetch(artist, (albums, _suggestions) => {
suggestions = suggestions.length < 200 ? suggestions.concat(_suggestions) : [] // combining old suggestions and new ones from each fetch, max limit only 200 items(for performance)
suggestions = uniqBy(suggestions, 'name') // then removing duplicate artist from suggestions.
dispatch({ type: ITUNES_FETCH_SUCCESS, albums, suggestions })
})
}
}
/*
* Redux action to call fetch artist
* @param {string} value name of the artist from search input
* @returns {object} will return Promise from fetch api it will be composed to pure object from redux-thunk
*/
export const searchTextUpdated = value => {
return dispatch => {
dispatch({type: SEARCH_TEXT_UPDATED, searchText: value})
if(value && value.length > 2) {
dispatch(doSearch(value))
}else{
dispatch({type: ITUNES_FETCH_STARTED, searchText: value})
}
}
}
/*
* Redux action call from album favorite click
* @album {Album} album instance of Album from triggered album
* @returns pure redux object
* */
export const addRemoveFavorite = album => {
return (dispatch, getState) => {
let { favoriteAlbums } = getState()
const _favorite = _togleFavorite(favoriteAlbums, album)
dispatch({type: FAVORITE_ALBUM_ADDED, favoriteAlbums: _favorite})
}
}
/*
* Redux action call from favorite artist filter
* @artist {array} of artists id from select component
* @returns pure redux object
* */
export const favoriteArtistFilter = artist => {
return (dispatch, getState) => {
dispatch({type: FAVORITE_ARTIST_FILTERED, favoriteArtists: artist})
}
}
/*
* Redux action call from mobile tab button
* @selectedTab {number} index of clicked button
* @returns pure redux object
* */
export const mobileTabClicked = selectedTab => {
return (dispatch, getState) => {
dispatch({type: MOBILE_TAB_CHANGED, selectedTab})
}
} | src/services/actions/index.js | /**
* Created by kamaal on 10/7/17.
*/
import {
SEARCH_TEXT_UPDATED,
ITUNES_FETCH_STARTED,
ITUNES_FETCH_SUCCESS,
FAVORITE_ALBUM_ADDED,
FAVORITE_ARTIST_FILTERED,
MOBILE_TAB_CHANGED
} from '../action-types'
import {uniqBy} from 'lodash'
import Album from '../../models/Album' // album model
import Suggestion from '../../models/Artist' // importing artist as suggestion
/*
* Add or remove favorite album from favorite collection by checking current favorite collection
* @param {array} _favorite collection of Album instances from current state
* @album {Album} album instance of Album from triggered album
* @returns {array} of Album instances
* */
const _togleFavorite = (_favorite, album) => {
let favorite = _favorite
if(favorite.find(_album => _album.id === album.id)){
return favorite.filter(_album => _album.id !== album.id)
}
favorite.push(album)
return favorite
}
/*
* Fetch albums using browsers default fetch api
* @param {string} artist name of the artist from search input
* @callback cb
*/
const _justFetch = (artist, cb) => {
const uri = `https://itunes.apple.com/search?term=${artist}&entity=album`
fetch(uri)
.then(response => response.json())
.then(res => {
if (res.resultCount > 0) {
cb(res.results.map(r => new Album(r)), res.results.map(r => new Suggestion(r)))
}
})
}
/*
* Redux action to call fetch artist
* @param {string} artist name of the artist from search input
* @returns {object} will return Promise from fetch api it will be composed to pure object from redux-thunk
*/
export const doSearch = (artist = 'michael') => {
return (dispatch, getState) => {
let { suggestions } = getState() // getting current suggestions
dispatch({type: ITUNES_FETCH_STARTED})
_justFetch(artist, (albums, _suggestions) => {
suggestions = suggestions.length < 200 ? suggestions.concat(_suggestions) : [] // combining old suggestions and new ones from each fetch, max limit only 200 items(for performance)
suggestions = uniqBy(suggestions, 'name') // then removing duplicate artist from suggestions.
dispatch({ type: ITUNES_FETCH_SUCCESS, albums, suggestions })
})
}
}
/*
* Redux action to call fetch artist
* @param {string} value name of the artist from search input
* @returns {object} will return Promise from fetch api it will be composed to pure object from redux-thunk
*/
export const searchTextUpdated = value => {
return dispatch => {
dispatch({type: SEARCH_TEXT_UPDATED, searchText: value})
if(value && value.length > 2) {
dispatch(doSearch(value))
}else{
dispatch({type: ITUNES_FETCH_STARTED, searchText: value})
}
}
}
/*
* Redux action call from album favorite click
* @album {Album} album instance of Album from triggered album
* @returns pure redux object
* */
export const addRemoveFavorite = album => {
return (dispatch, getState) => {
let { favoriteAlbums } = getState()
const _favorite = _togleFavorite(favoriteAlbums, album)
dispatch({type: FAVORITE_ALBUM_ADDED, favoriteAlbums: _favorite})
}
}
/*
* Redux action call from favorite artist filter
* @artist {array} of artists id from select component
* @returns pure redux object
* */
export const favoriteArtistFilter = artist => {
return (dispatch, getState) => {
dispatch({type: FAVORITE_ARTIST_FILTERED, favoriteArtists: artist})
}
}
/*
* Redux action call from mobile tab button
* @selectedTab {number} index of clicked button
* @returns pure redux object
* */
export const mobileTabClicked = selectedTab => {
return (dispatch, getState) => {
dispatch({type: MOBILE_TAB_CHANGED, selectedTab})
}
} | Responsiveness done.
| src/services/actions/index.js | Responsiveness done. | <ide><path>rc/services/actions/index.js
<ide> * @returns pure redux object
<ide> * */
<ide> export const mobileTabClicked = selectedTab => {
<del>
<ide> return (dispatch, getState) => {
<ide> dispatch({type: MOBILE_TAB_CHANGED, selectedTab})
<ide> } |
|
Java | apache-2.0 | 9bbcf24a1e4697be427326d5512c8d84c47b9752 | 0 | evanchooly/morphia,evanchooly/morphia | package com.google.code.morphia.query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.bson.BSONObject;
import org.bson.types.CodeWScope;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.DatastoreImpl;
import com.google.code.morphia.Key;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.logging.Logr;
import com.google.code.morphia.logging.MorphiaLoggerFactory;
import com.google.code.morphia.mapping.MappedClass;
import com.google.code.morphia.mapping.MappedField;
import com.google.code.morphia.mapping.Mapper;
import com.google.code.morphia.mapping.cache.EntityCache;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.Bytes;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.ReadPreference;
/**
* <p>Implementation of Query</p>
*
* @param <T> The type we will be querying for, and returning.
* @author Scott Hernandez
*/
public class QueryImpl<T> extends CriteriaContainerImpl implements Query<T> {
private static final Logr log = MorphiaLoggerFactory.get(QueryImpl.class);
private EntityCache cache;
private boolean validateName = true;
private boolean validateType = true;
private String[] fields;
private Boolean includeFields;
private BasicDBObject sort;
private final DatastoreImpl ds;
private final DBCollection dbColl;
private int offset;
private int limit = -1;
private int batchSize;
private String indexHint;
private final Class<T> clazz;
private BasicDBObject baseQuery;
private boolean snapshotted;
private boolean noTimeout;
private boolean tail;
private boolean tail_await_data;
private ReadPreference readPref;
public QueryImpl(final Class<T> clazz, final DBCollection coll, final Datastore ds) {
super(CriteriaJoin.AND);
query = this;
this.clazz = clazz;
this.ds = ((DatastoreImpl) ds);
dbColl = coll;
cache = this.ds.getMapper().createEntityCache();
final MappedClass mc = this.ds.getMapper().getMappedClass(clazz);
final Entity entAn = mc == null ? null : mc.getEntityAnnotation();
if (entAn != null) {
readPref = this.ds.getMapper().getMappedClass(clazz).getEntityAnnotation().queryNonPrimary() ? ReadPreference.secondary() : null;
}
}
public QueryImpl(final Class<T> clazz, final DBCollection coll, final Datastore ds, final int offset, final int limit) {
this(clazz, coll, ds);
this.offset = offset;
this.limit = limit;
}
public QueryImpl(final Class<T> clazz, final DBCollection coll, final DatastoreImpl ds, final DBObject baseQuery) {
this(clazz, coll, ds);
this.baseQuery = (BasicDBObject) baseQuery;
}
@Override
public QueryImpl<T> clone() {
final QueryImpl<T> n = new QueryImpl<T>(clazz, dbColl, ds);
n.batchSize = batchSize;
n.cache = ds.getMapper().createEntityCache(); // fresh cache
n.fields = fields == null ? null : copy();
n.includeFields = includeFields;
n.indexHint = indexHint;
n.limit = limit;
n.noTimeout = noTimeout;
n.query = n; // feels weird, correct?
n.offset = offset;
n.readPref = readPref;
n.snapshotted = snapshotted;
n.validateName = validateName;
n.validateType = validateType;
n.sort = (BasicDBObject) (sort == null ? null : sort.clone());
n.baseQuery = (BasicDBObject) (baseQuery == null ? null : baseQuery.clone());
// fields from superclass
n.attachedTo = attachedTo;
n.children = children == null ? null : new ArrayList<Criteria>(children);
n.tail = tail;
n.tail_await_data = tail_await_data;
return n;
}
private String[] copy() {
final String[] copy = new String[fields.length];
System.arraycopy(fields, 0, copy, 0, fields.length);
return copy;
}
public DBCollection getCollection() {
return dbColl;
}
public void setQueryObject(final DBObject query) {
baseQuery = (BasicDBObject) query;
}
public int getOffset() {
return offset;
}
public int getLimit() {
return limit;
}
public DBObject getQueryObject() {
final DBObject obj = new BasicDBObject();
if (baseQuery != null) {
obj.putAll((BSONObject) baseQuery);
}
addTo(obj);
return obj;
}
public DatastoreImpl getDatastore() {
return ds;
}
public DBObject getFieldsObject() {
if (fields == null || fields.length == 0) {
return null;
}
final Map<String, Integer> fieldsFilter = new HashMap<String, Integer>();
for (String field : fields) {
final StringBuffer sb = new StringBuffer(field); //validate might modify prop string to translate java field name to db field name
Mapper.validate(clazz, ds.getMapper(), sb, FilterOperator.EQUAL, null, validateName, false);
field = sb.toString();
fieldsFilter.put(field, (includeFields ? 1 : 0));
}
//Add className field just in case.
if (includeFields) {
fieldsFilter.put(Mapper.CLASS_NAME_FIELDNAME, 1);
}
return new BasicDBObject(fieldsFilter);
}
public DBObject getSortObject() {
return (sort == null) ? null : sort;
}
public boolean isValidatingNames() {
return validateName;
}
public boolean isValidatingTypes() {
return validateType;
}
public long countAll() {
final DBObject query = getQueryObject();
if (log.isTraceEnabled()) {
log.trace("Executing count(" + dbColl.getName() + ") for query: " + query);
}
return dbColl.getCount(query);
}
public DBCursor prepareCursor() {
final DBObject query = getQueryObject();
final DBObject fields = getFieldsObject();
if (log.isTraceEnabled()) {
log.trace("Running query(" + dbColl.getName() + ") : " + query + ", fields:" + fields + ",off:" + offset + ",limit:" + limit);
}
final DBCursor cursor = dbColl.find(query, fields);
cursor.setDecoderFactory(ds.getDecoderFact());
if (offset > 0) {
cursor.skip(offset);
}
if (limit > 0) {
cursor.limit(limit);
}
if (batchSize > 0) {
cursor.batchSize(batchSize);
}
if (snapshotted) {
cursor.snapshot();
}
if (sort != null) {
cursor.sort(sort);
}
if (indexHint != null) {
cursor.hint(indexHint);
}
if (null != readPref) {
cursor.setReadPreference(readPref);
}
if (noTimeout) {
cursor.addOption(Bytes.QUERYOPTION_NOTIMEOUT);
}
if (tail) {
cursor.addOption(Bytes.QUERYOPTION_TAILABLE);
if (tail_await_data) {
cursor.addOption(Bytes.QUERYOPTION_AWAITDATA);
}
}
//Check for bad options.
if (snapshotted && (sort != null || indexHint != null)) {
log.warning("Snapshotted query should not have hint/sort.");
}
if (tail && (sort != null)) {
// i don´t think that just warning is enough here, i´d favor a RTE, agree?
log.warning("Sorting on tail is not allowed.");
}
return cursor;
}
public Iterable<T> fetch() {
final DBCursor cursor = prepareCursor();
if (log.isTraceEnabled()) {
log.trace("Getting cursor(" + dbColl.getName() + ") for query:" + cursor.getQuery());
}
return new MorphiaIterator<T, T>(cursor, ds.getMapper(), clazz, dbColl.getName(), cache);
}
public Iterable<Key<T>> fetchKeys() {
final String[] oldFields = fields;
final Boolean oldInclude = includeFields;
fields = new String[] {Mapper.ID_KEY};
includeFields = true;
final DBCursor cursor = prepareCursor();
if (log.isTraceEnabled()) {
log.trace("Getting cursor(" + dbColl.getName() + ") for query:" + cursor.getQuery());
}
fields = oldFields;
includeFields = oldInclude;
return new MorphiaKeyIterator<T>(cursor, ds.getMapper(), clazz, dbColl.getName());
}
public List<T> asList() {
final List<T> results = new ArrayList<T>();
final MorphiaIterator<T, T> iter = (MorphiaIterator<T, T>) fetch().iterator();
for (final T ent : iter) {
results.add(ent);
}
if (log.isTraceEnabled()) {
log.trace(String.format("asList: %s \t %d entities, iterator time: driver %n ms, mapper %n ms \n\t cache: %s \n\t for %s",
dbColl.getName(), results.size(), iter.getDriverTime(), iter.getMapperTime(), cache.stats().toString(), getQueryObject()));
}
return results;
}
public List<Key<T>> asKeyList() {
final List<Key<T>> results = new ArrayList<Key<T>>();
for (final Key<T> key : fetchKeys()) {
results.add(key);
}
return results;
}
public Iterable<T> fetchEmptyEntities() {
final String[] oldFields = fields;
final Boolean oldInclude = includeFields;
fields = new String[] {Mapper.ID_KEY};
includeFields = true;
final Iterable<T> res = fetch();
fields = oldFields;
includeFields = oldInclude;
return res;
}
/**
* Converts the textual operator (">", "<=", etc) into a FilterOperator. Forgiving about the syntax; != and <> are NOT_EQUAL, = and == are
* EQUAL.
*/
protected FilterOperator translate(final String operator) {
final String trimmed = operator.trim();
if ("=".equals(trimmed) || "==".equals(trimmed)) {
return FilterOperator.EQUAL;
} else if (">".equals(trimmed)) {
return FilterOperator.GREATER_THAN;
} else if (">=".equals(trimmed)) {
return FilterOperator.GREATER_THAN_OR_EQUAL;
} else if ("<".equals(trimmed)) {
return FilterOperator.LESS_THAN;
} else if ("<=".equals(trimmed)) {
return FilterOperator.LESS_THAN_OR_EQUAL;
} else if ("!=".equals(trimmed) || "<>".equals(trimmed)) {
return FilterOperator.NOT_EQUAL;
} else if ("in".equals(trimmed.toLowerCase())) {
return FilterOperator.IN;
} else if ("nin".equals(trimmed.toLowerCase())) {
return FilterOperator.NOT_IN;
} else if ("all".equals(trimmed.toLowerCase())) {
return FilterOperator.ALL;
} else if ("exists".equals(trimmed.toLowerCase())) {
return FilterOperator.EXISTS;
} else if ("elem".equals(trimmed.toLowerCase())) {
return FilterOperator.ELEMENT_MATCH;
} else if ("size".equals(trimmed.toLowerCase())) {
return FilterOperator.SIZE;
} else if ("within".equals(trimmed.toLowerCase())) {
return FilterOperator.WITHIN;
} else if ("near".equals(trimmed.toLowerCase())) {
return FilterOperator.NEAR;
} else {
throw new IllegalArgumentException("Unknown operator '" + trimmed + "'");
}
}
public Query<T> filter(final String condition, final Object value) {
final String[] parts = condition.trim().split(" ");
if (parts.length < 1 || parts.length > 6) {
throw new IllegalArgumentException("'" + condition + "' is not a legal filter condition");
}
final String prop = parts[0].trim();
final FilterOperator op = (parts.length == 2) ? translate(parts[1]) : FilterOperator.EQUAL;
add(new FieldCriteria(this, prop, op, value, validateName, validateType));
return this;
}
public Query<T> where(final CodeWScope js) {
add(new WhereCriteria(js));
return this;
}
public Query<T> where(final String js) {
add(new WhereCriteria(js));
return this;
}
public Query<T> enableValidation() {
validateName = validateType = true;
return this;
}
public Query<T> disableValidation() {
validateName = validateType = false;
return this;
}
QueryImpl<T> validateNames() {
validateName = true;
return this;
}
QueryImpl<T> disableTypeValidation() {
validateType = false;
return this;
}
public T get() {
final int oldLimit = limit;
limit = 1;
final Iterator<T> it = fetch().iterator();
limit = oldLimit;
return (it.hasNext()) ? it.next() : null;
}
public Key<T> getKey() {
final int oldLimit = limit;
limit = 1;
final Iterator<Key<T>> it = fetchKeys().iterator();
limit = oldLimit;
return (it.hasNext()) ? it.next() : null;
}
public Query<T> limit(final int value) {
limit = value;
return this;
}
public Query<T> batchSize(final int value) {
batchSize = value;
return this;
}
public int getBatchSize() {
return batchSize;
}
public Query<T> skip(final int value) {
offset = value;
return this;
}
public Query<T> offset(final int value) {
offset = value;
return this;
}
public Query<T> order(final String condition) {
if (snapshotted) {
throw new QueryException("order cannot be used on a snapshotted query.");
}
//reset order
if (condition == null || condition.trim().length() == 0) {
sort = null;
}
sort = parseFieldsString(condition, clazz, ds.getMapper(), validateName);
return this;
}
/**
* parses the string and validates each part
*/
@SuppressWarnings("rawtypes")
public static BasicDBObject parseFieldsString(final String str, final Class clazz, final Mapper mapper, final boolean validate) {
BasicDBObjectBuilder ret = BasicDBObjectBuilder.start();
final String[] parts = str.split(",");
for (String s : parts) {
s = s.trim();
int dir = 1;
if (s.startsWith("-")) {
dir = -1;
s = s.substring(1).trim();
}
if (validate) {
final StringBuffer sb = new StringBuffer(s);
Mapper.validate(clazz, mapper, sb, FilterOperator.IN, "", true, false);
s = sb.toString();
}
ret = ret.add(s, dir);
}
return (BasicDBObject) ret.get();
}
public Iterator<T> iterator() {
return fetch().iterator();
}
public Iterator<T> tail() {
return tail(true);
}
public Iterator<T> tail(final boolean awaitData) {
//Create a new query for this, so the current one is not affected.
final QueryImpl<T> tailQ = clone();
tailQ.tail = true;
tailQ.tail_await_data = awaitData;
return tailQ.fetch().iterator();
}
public Class<T> getEntityClass() {
return clazz;
}
public String toString() {
return getQueryObject().toString();
}
public FieldEnd<? extends Query<T>> field(final String name) {
return field(name, validateName);
}
private FieldEnd<? extends Query<T>> field(final String field, final boolean validate) {
return new FieldEndImpl<QueryImpl<T>>(this, field, this, validate);
}
@Override
public FieldEnd<? extends CriteriaContainerImpl> criteria(final String field) {
return criteria(field, validateName);
}
private FieldEnd<? extends CriteriaContainerImpl> criteria(final String field, final boolean validate) {
final CriteriaContainerImpl container = new CriteriaContainerImpl(this, CriteriaJoin.AND);
add(container);
return new FieldEndImpl<CriteriaContainerImpl>(this, field, container, validate);
}
//TODO: test this.
public Query<T> hintIndex(final String idxName) {
indexHint = idxName;
return this;
}
public Query<T> retrievedFields(final boolean include, final String... fields) {
if (includeFields != null && include != includeFields) {
throw new IllegalStateException("You cannot mix include and excluded fields together!");
}
includeFields = include;
this.fields = fields;
return this;
}
public Query<T> retrieveKnownFields() {
final MappedClass mc = ds.getMapper().getMappedClass(clazz);
final ArrayList<String> fields = new ArrayList<String>(mc.getPersistenceFields().size() + 1);
for (final MappedField mf : mc.getPersistenceFields()) {
fields.add(mf.getNameToStore());
}
retrievedFields(true, (String[]) fields.toArray());
return this;
}
/**
* Enabled snapshotted mode where duplicate results (which may be updated during the lifetime of the cursor) will not be returned. Not
* compatible with order/sort and hint.
*/
public Query<T> enableSnapshotMode() {
snapshotted = true;
return this;
}
/**
* Disable snapshotted mode (default mode). This will be faster but changes made during the cursor may cause duplicates. *
*/
public Query<T> disableSnapshotMode() {
snapshotted = false;
return this;
}
public Query<T> useReadPreference(final ReadPreference readPref) {
this.readPref = readPref;
return this;
}
public Query<T> queryNonPrimary() {
readPref = ReadPreference.secondary();
return this;
}
public Query<T> queryPrimaryOnly() {
readPref = ReadPreference.primary();
return this;
}
/**
* Disables cursor timeout on server.
*/
public Query<T> disableCursorTimeout() {
noTimeout = true;
return this;
}
/**
* Enables cursor timeout on server.
*/
public Query<T> enableCursorTimeout() {
noTimeout = false;
return this;
}
@Override
public String getFieldName() {
return null;
}
}
| morphia/src/main/java/com/google/code/morphia/query/QueryImpl.java | package com.google.code.morphia.query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.bson.BSONObject;
import org.bson.types.CodeWScope;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.DatastoreImpl;
import com.google.code.morphia.Key;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.logging.Logr;
import com.google.code.morphia.logging.MorphiaLoggerFactory;
import com.google.code.morphia.mapping.MappedClass;
import com.google.code.morphia.mapping.MappedField;
import com.google.code.morphia.mapping.Mapper;
import com.google.code.morphia.mapping.cache.EntityCache;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.Bytes;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.ReadPreference;
/**
* <p>Implementation of Query</p>
*
* @param <T> The type we will be querying for, and returning.
* @author Scott Hernandez
*/
public class QueryImpl<T> extends CriteriaContainerImpl implements Query<T> {
private static final Logr log = MorphiaLoggerFactory.get(QueryImpl.class);
private EntityCache cache;
private boolean validateName = true;
private boolean validateType = true;
private String[] fields;
private Boolean includeFields;
private BasicDBObject sort;
private final DatastoreImpl ds;
private final DBCollection dbColl;
private int offset;
private int limit = -1;
private int batchSize;
private String indexHint;
private final Class<T> clazz;
private BasicDBObject baseQuery;
private boolean snapshotted;
private boolean noTimeout;
private boolean tail;
private boolean tail_await_data;
private ReadPreference readPref;
public QueryImpl(final Class<T> clazz, final DBCollection coll, final Datastore ds) {
super(CriteriaJoin.AND);
query = this;
this.clazz = clazz;
this.ds = ((DatastoreImpl) ds);
dbColl = coll;
cache = this.ds.getMapper().createEntityCache();
final MappedClass mc = this.ds.getMapper().getMappedClass(clazz);
final Entity entAn = mc == null ? null : mc.getEntityAnnotation();
if (entAn != null) {
readPref = this.ds.getMapper().getMappedClass(clazz).getEntityAnnotation().queryNonPrimary() ? ReadPreference.secondary() : null;
}
}
public QueryImpl(final Class<T> clazz, final DBCollection coll, final Datastore ds, final int offset, final int limit) {
this(clazz, coll, ds);
this.offset = offset;
this.limit = limit;
}
public QueryImpl(final Class<T> clazz, final DBCollection coll, final DatastoreImpl ds, final DBObject baseQuery) {
this(clazz, coll, ds);
this.baseQuery = (BasicDBObject) baseQuery;
}
@Override
public QueryImpl<T> clone() {
final QueryImpl<T> n = new QueryImpl<T>(clazz, dbColl, ds);
n.batchSize = batchSize;
n.cache = ds.getMapper().createEntityCache(); // fresh cache
n.fields = fields == null ? null : copy();
n.includeFields = includeFields;
n.indexHint = indexHint;
n.limit = limit;
n.noTimeout = noTimeout;
n.query = n; // feels weird, correct?
n.offset = offset;
n.readPref = readPref;
n.snapshotted = snapshotted;
n.validateName = validateName;
n.validateType = validateType;
n.sort = (BasicDBObject) (sort == null ? null : sort.clone());
n.baseQuery = (BasicDBObject) (baseQuery == null ? null : baseQuery.clone());
// fields from superclass
n.attachedTo = attachedTo;
n.children = children == null ? null : new ArrayList<Criteria>(children);
n.tail = tail;
n.tail_await_data = tail_await_data;
return n;
}
private String[] copy() {
final String[] copy = new String[fields.length];
System.arraycopy(fields, 0, copy, 0, fields.length);
return copy;
}
public DBCollection getCollection() {
return dbColl;
}
public void setQueryObject(final DBObject query) {
baseQuery = (BasicDBObject) query;
}
public int getOffset() {
return offset;
}
public int getLimit() {
return limit;
}
public DBObject getQueryObject() {
final DBObject obj = new BasicDBObject();
if (baseQuery != null) {
obj.putAll((BSONObject) baseQuery);
}
addTo(obj);
return obj;
}
public DatastoreImpl getDatastore() {
return ds;
}
public DBObject getFieldsObject() {
if (fields == null || fields.length == 0) {
return null;
}
final Map<String, Integer> fieldsFilter = new HashMap<String, Integer>();
for (String field : fields) {
final StringBuffer sb = new StringBuffer(field); //validate might modify prop string to translate java field name to db field name
Mapper.validate(clazz, ds.getMapper(), sb, FilterOperator.EQUAL, null, validateName, false);
field = sb.toString();
fieldsFilter.put(field, (includeFields ? 1 : 0));
}
//Add className field just in case.
if (includeFields) {
fieldsFilter.put(Mapper.CLASS_NAME_FIELDNAME, 1);
}
return new BasicDBObject(fieldsFilter);
}
public DBObject getSortObject() {
return (sort == null) ? null : sort;
}
public boolean isValidatingNames() {
return validateName;
}
public boolean isValidatingTypes() {
return validateType;
}
public long countAll() {
final DBObject query = getQueryObject();
if (log.isTraceEnabled()) {
log.trace("Executing count(" + dbColl.getName() + ") for query: " + query);
}
return dbColl.getCount(query);
}
public DBCursor prepareCursor() {
final DBObject query = getQueryObject();
final DBObject fields = getFieldsObject();
if (log.isTraceEnabled()) {
log.trace("Running query(" + dbColl.getName() + ") : " + query + ", fields:" + fields + ",off:" + offset + ",limit:" + limit);
}
final DBCursor cursor = dbColl.find(query, fields);
cursor.setDecoderFactory(ds.getDecoderFact());
if (offset > 0) {
cursor.skip(offset);
}
if (limit > 0) {
cursor.limit(limit);
}
if (batchSize > 0) {
cursor.batchSize(batchSize);
}
if (snapshotted) {
cursor.snapshot();
}
if (sort != null) {
cursor.sort(sort);
}
if (indexHint != null) {
cursor.hint(indexHint);
}
if (null != readPref) {
cursor.setReadPreference(readPref);
}
if (noTimeout) {
cursor.addOption(Bytes.QUERYOPTION_NOTIMEOUT);
}
if (tail) {
cursor.addOption(Bytes.QUERYOPTION_TAILABLE);
if (tail_await_data) {
cursor.addOption(Bytes.QUERYOPTION_AWAITDATA);
}
}
//Check for bad options.
if (snapshotted && (sort != null || indexHint != null)) {
log.warning("Snapshotted query should not have hint/sort.");
}
if (tail && (sort != null)) {
// i don´t think that just warning is enough here, i´d favor a RTE, agree?
log.warning("Sorting on tail is not allowed.");
}
return cursor;
}
public Iterable<T> fetch() {
final DBCursor cursor = prepareCursor();
if (log.isTraceEnabled()) {
log.trace("Getting cursor(" + dbColl.getName() + ") for query:" + cursor.getQuery());
}
return new MorphiaIterator<T, T>(cursor, ds.getMapper(), clazz, dbColl.getName(), cache);
}
public Iterable<Key<T>> fetchKeys() {
final String[] oldFields = fields;
final Boolean oldInclude = includeFields;
fields = new String[] {Mapper.ID_KEY};
includeFields = true;
final DBCursor cursor = prepareCursor();
if (log.isTraceEnabled()) {
log.trace("Getting cursor(" + dbColl.getName() + ") for query:" + cursor.getQuery());
}
fields = oldFields;
includeFields = oldInclude;
return new MorphiaKeyIterator<T>(cursor, ds.getMapper(), clazz, dbColl.getName());
}
public List<T> asList() {
final List<T> results = new ArrayList<T>();
final MorphiaIterator<T, T> iter = (MorphiaIterator<T, T>) fetch().iterator();
for (final T ent : iter) {
results.add(ent);
}
if (log.isTraceEnabled()) {
log.trace(String.format("\nasList: %s \t %d entities, iterator time: driver %n ms, mapper %n ms \n cache: %s \n for $s \n ",
dbColl.getName(), results.size(), iter.getDriverTime(), iter.getMapperTime(), cache.stats().toString(), getQueryObject()));
}
return results;
}
public List<Key<T>> asKeyList() {
final List<Key<T>> results = new ArrayList<Key<T>>();
for (final Key<T> key : fetchKeys()) {
results.add(key);
}
return results;
}
public Iterable<T> fetchEmptyEntities() {
final String[] oldFields = fields;
final Boolean oldInclude = includeFields;
fields = new String[] {Mapper.ID_KEY};
includeFields = true;
final Iterable<T> res = fetch();
fields = oldFields;
includeFields = oldInclude;
return res;
}
/**
* Converts the textual operator (">", "<=", etc) into a FilterOperator. Forgiving about the syntax; != and <> are NOT_EQUAL, = and == are
* EQUAL.
*/
protected FilterOperator translate(final String operator) {
final String trimmed = operator.trim();
if ("=".equals(trimmed) || "==".equals(trimmed)) {
return FilterOperator.EQUAL;
} else if (">".equals(trimmed)) {
return FilterOperator.GREATER_THAN;
} else if (">=".equals(trimmed)) {
return FilterOperator.GREATER_THAN_OR_EQUAL;
} else if ("<".equals(trimmed)) {
return FilterOperator.LESS_THAN;
} else if ("<=".equals(trimmed)) {
return FilterOperator.LESS_THAN_OR_EQUAL;
} else if ("!=".equals(trimmed) || "<>".equals(trimmed)) {
return FilterOperator.NOT_EQUAL;
} else if ("in".equals(trimmed.toLowerCase())) {
return FilterOperator.IN;
} else if ("nin".equals(trimmed.toLowerCase())) {
return FilterOperator.NOT_IN;
} else if ("all".equals(trimmed.toLowerCase())) {
return FilterOperator.ALL;
} else if ("exists".equals(trimmed.toLowerCase())) {
return FilterOperator.EXISTS;
} else if ("elem".equals(trimmed.toLowerCase())) {
return FilterOperator.ELEMENT_MATCH;
} else if ("size".equals(trimmed.toLowerCase())) {
return FilterOperator.SIZE;
} else if ("within".equals(trimmed.toLowerCase())) {
return FilterOperator.WITHIN;
} else if ("near".equals(trimmed.toLowerCase())) {
return FilterOperator.NEAR;
} else {
throw new IllegalArgumentException("Unknown operator '" + trimmed + "'");
}
}
public Query<T> filter(final String condition, final Object value) {
final String[] parts = condition.trim().split(" ");
if (parts.length < 1 || parts.length > 6) {
throw new IllegalArgumentException("'" + condition + "' is not a legal filter condition");
}
final String prop = parts[0].trim();
final FilterOperator op = (parts.length == 2) ? translate(parts[1]) : FilterOperator.EQUAL;
add(new FieldCriteria(this, prop, op, value, validateName, validateType));
return this;
}
public Query<T> where(final CodeWScope js) {
add(new WhereCriteria(js));
return this;
}
public Query<T> where(final String js) {
add(new WhereCriteria(js));
return this;
}
public Query<T> enableValidation() {
validateName = validateType = true;
return this;
}
public Query<T> disableValidation() {
validateName = validateType = false;
return this;
}
QueryImpl<T> validateNames() {
validateName = true;
return this;
}
QueryImpl<T> disableTypeValidation() {
validateType = false;
return this;
}
public T get() {
final int oldLimit = limit;
limit = 1;
final Iterator<T> it = fetch().iterator();
limit = oldLimit;
return (it.hasNext()) ? it.next() : null;
}
public Key<T> getKey() {
final int oldLimit = limit;
limit = 1;
final Iterator<Key<T>> it = fetchKeys().iterator();
limit = oldLimit;
return (it.hasNext()) ? it.next() : null;
}
public Query<T> limit(final int value) {
limit = value;
return this;
}
public Query<T> batchSize(final int value) {
batchSize = value;
return this;
}
public int getBatchSize() {
return batchSize;
}
public Query<T> skip(final int value) {
offset = value;
return this;
}
public Query<T> offset(final int value) {
offset = value;
return this;
}
public Query<T> order(final String condition) {
if (snapshotted) {
throw new QueryException("order cannot be used on a snapshotted query.");
}
//reset order
if (condition == null || condition.trim().length() == 0) {
sort = null;
}
sort = parseFieldsString(condition, clazz, ds.getMapper(), validateName);
return this;
}
/**
* parses the string and validates each part
*/
@SuppressWarnings("rawtypes")
public static BasicDBObject parseFieldsString(final String str, final Class clazz, final Mapper mapper, final boolean validate) {
BasicDBObjectBuilder ret = BasicDBObjectBuilder.start();
final String[] parts = str.split(",");
for (String s : parts) {
s = s.trim();
int dir = 1;
if (s.startsWith("-")) {
dir = -1;
s = s.substring(1).trim();
}
if (validate) {
final StringBuffer sb = new StringBuffer(s);
Mapper.validate(clazz, mapper, sb, FilterOperator.IN, "", true, false);
s = sb.toString();
}
ret = ret.add(s, dir);
}
return (BasicDBObject) ret.get();
}
public Iterator<T> iterator() {
return fetch().iterator();
}
public Iterator<T> tail() {
return tail(true);
}
public Iterator<T> tail(final boolean awaitData) {
//Create a new query for this, so the current one is not affected.
final QueryImpl<T> tailQ = clone();
tailQ.tail = true;
tailQ.tail_await_data = awaitData;
return tailQ.fetch().iterator();
}
public Class<T> getEntityClass() {
return clazz;
}
public String toString() {
return getQueryObject().toString();
}
public FieldEnd<? extends Query<T>> field(final String name) {
return field(name, validateName);
}
private FieldEnd<? extends Query<T>> field(final String field, final boolean validate) {
return new FieldEndImpl<QueryImpl<T>>(this, field, this, validate);
}
@Override
public FieldEnd<? extends CriteriaContainerImpl> criteria(final String field) {
return criteria(field, validateName);
}
private FieldEnd<? extends CriteriaContainerImpl> criteria(final String field, final boolean validate) {
final CriteriaContainerImpl container = new CriteriaContainerImpl(this, CriteriaJoin.AND);
add(container);
return new FieldEndImpl<CriteriaContainerImpl>(this, field, container, validate);
}
//TODO: test this.
public Query<T> hintIndex(final String idxName) {
indexHint = idxName;
return this;
}
public Query<T> retrievedFields(final boolean include, final String... fields) {
if (includeFields != null && include != includeFields) {
throw new IllegalStateException("You cannot mix include and excluded fields together!");
}
includeFields = include;
this.fields = fields;
return this;
}
public Query<T> retrieveKnownFields() {
final MappedClass mc = ds.getMapper().getMappedClass(clazz);
final ArrayList<String> fields = new ArrayList<String>(mc.getPersistenceFields().size() + 1);
for (final MappedField mf : mc.getPersistenceFields()) {
fields.add(mf.getNameToStore());
}
retrievedFields(true, (String[]) fields.toArray());
return this;
}
/**
* Enabled snapshotted mode where duplicate results (which may be updated during the lifetime of the cursor) will not be returned. Not
* compatible with order/sort and hint.
*/
public Query<T> enableSnapshotMode() {
snapshotted = true;
return this;
}
/**
* Disable snapshotted mode (default mode). This will be faster but changes made during the cursor may cause duplicates. *
*/
public Query<T> disableSnapshotMode() {
snapshotted = false;
return this;
}
public Query<T> useReadPreference(final ReadPreference readPref) {
this.readPref = readPref;
return this;
}
public Query<T> queryNonPrimary() {
readPref = ReadPreference.secondary();
return this;
}
public Query<T> queryPrimaryOnly() {
readPref = ReadPreference.primary();
return this;
}
/**
* Disables cursor timeout on server.
*/
public Query<T> disableCursorTimeout() {
noTimeout = true;
return this;
}
/**
* Enables cursor timeout on server.
*/
public Query<T> enableCursorTimeout() {
noTimeout = false;
return this;
}
@Override
public String getFieldName() {
return null;
}
}
| logging tweak. aesthetic updates.
| morphia/src/main/java/com/google/code/morphia/query/QueryImpl.java | logging tweak. aesthetic updates. | <ide><path>orphia/src/main/java/com/google/code/morphia/query/QueryImpl.java
<ide> }
<ide>
<ide> if (log.isTraceEnabled()) {
<del> log.trace(String.format("\nasList: %s \t %d entities, iterator time: driver %n ms, mapper %n ms \n cache: %s \n for $s \n ",
<add> log.trace(String.format("asList: %s \t %d entities, iterator time: driver %n ms, mapper %n ms \n\t cache: %s \n\t for %s",
<ide> dbColl.getName(), results.size(), iter.getDriverTime(), iter.getMapperTime(), cache.stats().toString(), getQueryObject()));
<ide> }
<ide> |
|
JavaScript | mit | 5b04db81ba7548060a215400f4fc0c257083a8e5 | 0 | Philantrope/starter,francishogue/starter,Philantrope/starter,francishogue/starter | /* jshint node:true */
'use strict';
var gulp = require('gulp'),
gutil = require('gulp-util'),
del = require('del'),
sass = require('gulp-sass'),
autoprefixer = require('gulp-autoprefixer'),
minifyCSS = require('gulp-minify-css'),
concat = require('gulp-concat'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
notify = require('gulp-notify'),
size = require('gulp-size'),
sourcemaps = require('gulp-sourcemaps'),
browserSync = require('browser-sync'),
imagemin = require('gulp-imagemin'),
changed = require('gulp-changed'),
reload = browserSync.reload;
// Options, project specifics
var options = {};
// browserSync options
// If you already have a server
// Comment out the 'server' option (below)
// Uncomment the 'proxy' option and update its value in 'gulp-config.json'
// You can easily create 'gulp-config.json' from 'gulp-config-sample.json'
// Uncomment 'var config' line below
// Custom browserSync config
// var config = require('./gulp-config.json');
options.browserSync = {
notify: false,
server: {
baseDir: './'
},
// proxy: config.browsersync.proxy,
// If you want to specify your IP adress (on more complex network), uncomment the 'host' option and update it
// host: config.browsersync.host,
// If you want to run as https, uncomment the 'https' option
// https: true
};
// Paths settings
options.distPath = 'assets/dist/'; // path to your assets distribution folder
options.srcPath = 'assets/src/'; // path to your assets source folder
options.paths = {
sass: options.srcPath + 'sass/',
js: options.srcPath + 'js/',
images: options.srcPath + 'images/',
fonts: options.srcPath + 'fonts/',
destCss: options.distPath + 'css/',
destJs: options.distPath + 'js/',
destImages: options.distPath + 'images/',
destFonts: options.distPath + 'fonts/'
};
// gulp-sass options
options.libsass = {
errLogToConsole: false,
sourceMap: true,
sourceComments: true,
precision: 10,
outputStyle: 'expanded',
imagePath: 'assets/src/images',
};
// gulp-autoprefixer
options.autoprefixer = {
support: [
'last 2 version',
'ie >= 8',
'safari >= 6',
'ios >= 6',
'android >= 4',
'bb >= 7'
]
};
// gulp-uglify
options.uglify = {
compress: {
pure_funcs: ['console.log']
}
};
// gulp-imagemin
options.imagemin = {
progressive: true,
interlaced: true,
optimizationLevel: 3
};
// Delete the dist directory
gulp.task('clean', function(cb) {
del([options.distPath], cb);
});
// browser-sync task for starting the server. (Use the built-in server or use your existing one by filling the proxy options)
gulp.task('browser-sync', function() {
browserSync(options.browserSync);
});
// Node Sass
gulp.task('sass', function() {
// List all .scss files that need to be processed
return gulp.src([
options.paths.sass + 'main.scss'
])
.pipe(sourcemaps.init())
.pipe(sass(options.libsass))
// Catch any SCSS errors and prevent them from crashing gulp
.on('error', function (error) {
gutil.log(gutil.colors.red(error.message));
this.emit('end');
})
// Hotfix while gulp-sass sourcemaps gets fixed
// https://github.com/dlmanning/gulp-sass/issues/106#issuecomment-60977513
.pipe(sourcemaps.write())
.pipe(sourcemaps.init({loadMaps: true}))
// Add vendor prefixes
.pipe(autoprefixer(options.autoprefixer.support))
.pipe(gutil.env.type === 'prod' ? minifyCSS() : gutil.noop())
// Write final .map file for Dev only
.pipe(gutil.env.type === 'prod' ? gutil.noop() : sourcemaps.write())
// Output the processed CSS
.pipe(gulp.dest(options.paths.destCss))
.pipe(notify('Sass compiled'))
.pipe(size({title: 'CSS'}))
.pipe(reload({stream:true}));
});
// JS
gulp.task('scripts', function() {
return gulp.src([
options.paths.js + 'libs/*.js',
options.paths.js + 'helpers.js',
options.paths.js + 'app.js',
'!' + options.paths.js + 'libs/modernizr.js'
])
.pipe(gutil.env.type !== 'prod' ? sourcemaps.init() : gutil.noop())
.pipe(concat('app.min.js'))
.pipe(gutil.env.type === 'prod' ? uglify(options.uglify) : gutil.noop())
.pipe(gutil.env.type !== 'prod' ? sourcemaps.write() : gutil.noop())
.pipe(gulp.dest(options.paths.destJs))
.pipe(notify('JS compiled'))
.pipe(reload({stream: true, once: true})
);
});
// Copy Modernizr
gulp.task('modernizr', function () {
return gulp.src([
options.paths.js + 'libs/modernizr.js'
])
.pipe(uglify())
.pipe(gulp.dest(options.paths.destJs)
);
});
// Images
gulp.task('images', function() {
return gulp.src(options.paths.images + '**/*')
.pipe(changed(options.paths.destImages)) // Ignore unchanged files
.pipe(imagemin(options.imagemin)) // Optimize
.pipe(gulp.dest(options.paths.destImages));
});
// Fonts
gulp.task('fonts', function() {
return gulp.src(options.paths.fonts + '**/*.{ttf,woff,woff2,eot,svg}')
.pipe(changed(options.paths.destFonts)) // Ignore unchanged files
.pipe(gulp.dest(options.paths.destFonts));
});
// JS hint task (WIP)
gulp.task('jshint', function() {
return gulp.src([
options.paths.js + '*.js',
'./gulpfile.js'
])
.pipe(jshint('.jshintrc'))
.pipe(jshint.reporter('jshint-stylish'));
});
// gulp serve -> build for dev
// gulp build -> build for prod
// gulp serve:dist -> build and serve the output from the dist build
gulp.task('serve', [
'sass',
'jshint',
'scripts',
'modernizr',
'images',
'fonts',
'browser-sync'
], function() {
// Watch Sass
gulp.watch(options.paths.sass + '**/*.scss', ['sass'])
.on('change', function(evt) {
// notify('[watcher] File ' + evt.path.replace(/.*(?=sass)/,'') + ' was ' + evt.type + ', compiling...');
console.log(
'[watcher] File ' + evt.path.replace(/.*(?=sass)/,'') + ' was ' + evt.type + ', compiling...'
);
});
// Watch JS
gulp.watch(options.paths.js + '**/*.js', ['jshint', 'scripts']);
// Watch images
gulp.watch(options.paths.images + '**/*', ['images']);
});
// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
browserSync(options.browserSync);
});
gulp.task('build', ['clean'], function () {
gutil.env.type = 'prod';
gulp.start('sass', 'scripts', 'modernizr', 'images', 'fonts');
return gulp.src(options.distPath + '**/*').pipe(size({title: 'build', gzip: false}));
});
gulp.task('default', function () {
gulp.start('build');
});
| gulpfile.js | /* jshint node:true */
'use strict';
var gulp = require('gulp'),
gutil = require('gulp-util'),
del = require('del'),
sass = require('gulp-sass'),
autoprefixer = require('gulp-autoprefixer'),
minifyCSS = require('gulp-minify-css'),
concat = require('gulp-concat'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
notify = require('gulp-notify'),
size = require('gulp-size'),
sourcemaps = require('gulp-sourcemaps'),
browserSync = require('browser-sync'),
imagemin = require('gulp-imagemin'),
changed = require('gulp-changed'),
reload = browserSync.reload;
// Options, project specifics
var options = {};
// browserSync options
// If you already have a server
// Comment out the 'server' option (below)
// Uncomment the 'proxy' option and update its value in 'gulp-config.json'
// You can easily create 'gulp-config.json' from 'gulp-config-sample.json'
// Uncomment 'var config' line below
// Custom browserSync config
// var config = require('./gulp-config.json');
options.browserSync = {
notify: false,
server: {
baseDir: './'
},
// proxy: config.browsersync.proxy,
// If you want to specify your IP adress (on more complex network), uncomment the 'host' option and update it
// host: config.browsersync.host,
// If you want to run as https, uncomment the 'https' option
// https: true
};
// Paths settings
options.distPath = 'assets/dist/'; // path to your assets distribution folder
options.srcPath = 'assets/src/'; // path to your assets source folder
options.paths = {
sass: options.srcPath + 'sass/',
js: options.srcPath + 'js/',
images: options.srcPath + 'images/',
fonts: options.srcPath + 'fonts/',
destCss: options.distPath + 'css/',
destJs: options.distPath + 'js/',
destImages: options.distPath + 'images/',
destFonts: options.distPath + 'fonts/'
};
// gulp-sass options
options.libsass = {
errLogToConsole: false,
sourceMap: true,
sourceComments: true,
precision: 10,
outputStyle: 'expanded',
imagePath: 'assets/src/images',
};
// gulp-autoprefixer
options.autoprefixer = {
support: [
'last 2 version',
'ie >= 8',
'safari >= 6',
'ios >= 6',
'android >= 4',
'bb >= 7'
]
};
// gulp-uglify
options.uglify = {
compress: {
pure_funcs: ['console.log']
}
};
// gulp-imagemin
options.imagemin = {
progressive: true,
interlaced: true,
optimizationLevel: 3
};
// Delete the dist directory
gulp.task('clean', function(cb) {
del([options.distPath], cb);
});
// browser-sync task for starting the server. (Use the built-in server or use your existing one by filling the proxy options)
gulp.task('browser-sync', function() {
browserSync(options.browserSync);
});
// Node Sass
gulp.task('sass', function() {
// List all .scss files that need to be processed
return gulp.src([
options.paths.sass + 'main.scss'
])
.pipe(sourcemaps.init())
.pipe(sass(options.libsass))
// Catch any SCSS errors and prevent them from crashing gulp
.on('error', function (error) {
gutil.log(gutil.colors.red(error.message));
this.emit('end');
})
// Hotfix while gulp-sass sourcemaps gets fixed
// https://github.com/dlmanning/gulp-sass/issues/106#issuecomment-60977513
.pipe(sourcemaps.write())
.pipe(sourcemaps.init({loadMaps: true}))
// Add vendor prefixes
.pipe(autoprefixer(options.autoprefixer.support))
.pipe(gutil.env.type === 'prod' ? minifyCSS() : gutil.noop())
// Write final .map file
.pipe(sourcemaps.write())
// Output the processed CSS
.pipe(gulp.dest(options.paths.destCss))
.pipe(notify('Sass compiled'))
.pipe(size({title: 'CSS'}))
.pipe(reload({stream:true}));
});
// JS
gulp.task('scripts', function() {
return gulp.src([
options.paths.js + 'libs/*.js',
options.paths.js + 'helpers.js',
options.paths.js + 'app.js',
'!' + options.paths.js + 'libs/modernizr.js'
])
.pipe(gutil.env.type !== 'prod' ? sourcemaps.init() : gutil.noop())
.pipe(concat('app.min.js'))
.pipe(gutil.env.type === 'prod' ? uglify(options.uglify) : gutil.noop())
.pipe(gutil.env.type !== 'prod' ? sourcemaps.write() : gutil.noop())
.pipe(gulp.dest(options.paths.destJs))
.pipe(notify('JS compiled'))
.pipe(reload({stream: true, once: true})
);
});
// Copy Modernizr
gulp.task('modernizr', function () {
return gulp.src([
options.paths.js + 'libs/modernizr.js'
])
.pipe(uglify())
.pipe(gulp.dest(options.paths.destJs)
);
});
// Images
gulp.task('images', function() {
return gulp.src(options.paths.images + '**/*')
.pipe(changed(options.paths.destImages)) // Ignore unchanged files
.pipe(imagemin(options.imagemin)) // Optimize
.pipe(gulp.dest(options.paths.destImages));
});
// Fonts
gulp.task('fonts', function() {
return gulp.src(options.paths.fonts + '**/*.{ttf,woff,woff2,eot,svg}')
.pipe(changed(options.paths.destFonts)) // Ignore unchanged files
.pipe(gulp.dest(options.paths.destFonts));
});
// JS hint task (WIP)
gulp.task('jshint', function() {
return gulp.src([
options.paths.js + '*.js',
'./gulpfile.js'
])
.pipe(jshint('.jshintrc'))
.pipe(jshint.reporter('jshint-stylish'));
});
// gulp serve -> build for dev
// gulp build -> build for prod
// gulp serve:dist -> build and serve the output from the dist build
gulp.task('serve', [
'sass',
'jshint',
'scripts',
'modernizr',
'images',
'fonts',
'browser-sync'
], function() {
// Watch Sass
gulp.watch(options.paths.sass + '**/*.scss', ['sass'])
.on('change', function(evt) {
// notify('[watcher] File ' + evt.path.replace(/.*(?=sass)/,'') + ' was ' + evt.type + ', compiling...');
console.log(
'[watcher] File ' + evt.path.replace(/.*(?=sass)/,'') + ' was ' + evt.type + ', compiling...'
);
});
// Watch JS
gulp.watch(options.paths.js + '**/*.js', ['jshint', 'scripts']);
// Watch images
gulp.watch(options.paths.images + '**/*', ['images']);
});
// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
browserSync(options.browserSync);
});
gulp.task('build', ['clean'], function () {
gutil.env.type = 'prod';
gulp.start('sass', 'scripts', 'modernizr', 'images', 'fonts');
return gulp.src(options.distPath + '**/*').pipe(size({title: 'build', gzip: false}));
});
gulp.task('default', function () {
gulp.start('build');
});
| Append CSS sourcemaps only for Dev (not for prod)
| gulpfile.js | Append CSS sourcemaps only for Dev (not for prod) | <ide><path>ulpfile.js
<ide>
<ide> .pipe(gutil.env.type === 'prod' ? minifyCSS() : gutil.noop())
<ide>
<del> // Write final .map file
<del> .pipe(sourcemaps.write())
<add> // Write final .map file for Dev only
<add> .pipe(gutil.env.type === 'prod' ? gutil.noop() : sourcemaps.write())
<ide>
<ide> // Output the processed CSS
<ide> .pipe(gulp.dest(options.paths.destCss)) |
|
JavaScript | bsd-3-clause | 16be1782936af6089d7ceb67e205a642315a218b | 0 | Tietoarkisto/metka,Tietoarkisto/metka,Tietoarkisto/metka,Tietoarkisto/metka | /**************************************************************************************
* Copyright (c) 2013-2015, Finnish Social Science Data Archive/University of Tampere *
* *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, *
* are permitted provided that the following conditions are met: *
* 1. Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* 2. Redistributions in binary form must reproduce the above copyright notice, *
* this list of conditions and the following disclaimer in the documentation *
* and/or other materials provided with the distribution. *
* 3. Neither the name of the copyright holder nor the names of its contributors *
* may be used to endorse or promote products derived from this software *
* without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND *
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. *
**************************************************************************************/
define(function (require) {
'use strict';
var resultParser = require('./resultParser');
return {
APPROVE: function (options) {
this
.click(require('./formAction')('approve')(options, function (response) {
if(resultParser(response.result).getResult() === 'NO_CHANGES') {
require('./assignUrl')('view', {no: ''});
} else {
$.extend(options.data, response.data);
// Fire an event so that metka doesn't ask for confirmation if moving from page
var evt = new CustomEvent('saved');
window.dispatchEvent(evt);
options.$events.trigger('refresh.metka');
}
}, [
'OPERATION_SUCCESSFUL',
'RESTRICTION_VALIDATION_FAILURE',
'NO_CHANGES'
], "approve"));
},
CANCEL: function (options) {
options.title = MetkaJS.L10N.get('general.buttons.cancel');
},
CLAIM: function (options) {
this
.click(function () {
$(".modal-footer").find("button").attr('disabled', 'disabled');
require('./server')('/revision/ajax/claim', {
data: JSON.stringify(options.data.key),
success: function (response) {
$(".modal-footer").find("button").removeAttr('disabled');
$.extend(options.data, response.data);
options.$events.trigger('refresh.metka');
location.reload();
},
error: function() {
$(".modal-footer").find("button").removeAttr('disabled');
}
});
});
},
BEGIN_EDIT: function (options) {
this
.click(function () {
$(".modal-footer").find("button").attr('disabled', 'disabled');
require('./server')('/revision/ajax/beginEdit', {
data: JSON.stringify(options.data.key),
success: function (response) {
$(".modal-footer").find("button").removeAttr('disabled');
if(resultParser(response.result).getResult() === 'REVISION_UPDATE_SUCCESSFUL') {
$.extend(options.data, response.data);
options.$events.trigger('refresh.metka');
location.reload();
} else {
require('./resultViewer')(response.result, 'beginEdit', function() {
require('./assignUrl')('view');
});
}
},
error: function() {
$(".modal-footer").find("button").removeAttr('disabled');
}
});
});
},
COMPARE: function (options) {
options.title = MetkaJS.L10N.get('general.revision.compare');
this.prop('disabled', true);
},
CUSTOM: function(options) {
},
DISMISS: function (options) {
options.title = MetkaJS.L10N.get('general.buttons.close');
},
EDIT: function (options) {
this.click(require('./formAction')('edit')(options, function (response) {
$(".modal-footer").find("button").removeAttr('disabled');
$.extend(options.data, response.data);
options.$events.trigger('refresh.metka');
history.replaceState(undefined, '', require('./url')('view'));
location.reload()
}, [
'REVISION_FOUND',
'REVISION_CREATED'
], "edit"));
},
HISTORY: function (options) {
$.extend(true, options, {
preventDismiss: true
});
this
.click(function () {
var o = options;
function checkRadioGroups() {
var beginVal = parseInt($('input[name="beginGrp"]:checked').val());
var endVal = parseInt($('input[name="endGrp"]:checked').val())
if (beginVal) {
$('input[name="endGrp"]').each(function () {
if (parseInt($(this).val()) <= beginVal) {
$(this).attr('disabled', true);
} else {
$(this).attr('disabled', false);
}
});
}
if (endVal) {
$('input[name="beginGrp"]').each(function () {
if (parseInt($(this).val()) >= endVal) {
$(this).attr('disabled', true);
} else {
$(this).attr('disabled', false);
}
});
}
if (typeof beginVal !== 'undefined' && typeof endVal !== 'undefined') {
if (beginVal >= endVal) {
$('#compareRevisions').prop('disabled', true);
} else {
$('#compareRevisions').prop('disabled', false);
}
}
}
var $table = $('<table class="table">')
.append($('<thead>')
.append($('<tr>')
.append((function () {
var arr = [
'general.revision',
'general.revision.publishDate',
'general.revision.compare.begin',
'general.revision.compare.end'
];
return arr.map(function (entry) {
return $('<th>')
.text(MetkaJS.L10N.get(entry));
});
})())));
require('./modal')($.extend(true, require('./optionsBase')(), {
title: MetkaJS.L10N.get('general.revision.revisions'),
body: $table,
large: true,
buttons: [{
type: 'COMPARE',
//preventDismiss: true,
create: function () {
this
.attr('id', 'compareRevisions')
.click(function () {
var $table = $('<table class="table">')
.append($('<thead>')
.append($('<tr>')
.append([
MetkaJS.L10N.get("dialog.history.path"),
///MetkaJS.L10N.get("dialog.history.language"),
MetkaJS.L10N.get("dialog.history.original"),
MetkaJS.L10N.get("dialog.history.current")
].map(function (entry) {
return $('<th style="width: 33%;">')
.text(entry);
}))));
require('./modal')($.extend(true, require('./optionsBase')(), {
title: MetkaJS.L10N.get('general.revision.revisions'),
body: $table,
large: true,
buttons: [{
type: 'DISMISS'
}]
}));
require('./server')('/revision/revisionCompare', {
data: JSON.stringify({
id: o.data.key.id,
begin: $('input[name="beginGrp"]:checked').val(),
end: $('input[name="endGrp"]:checked').val(),
type: o.data.configuration.type
}),
success: function (response) {
if (resultParser(response.result).getResult() === 'OPERATION_SUCCESSFUL') {
$table
.append($('<tbody>')
.append(response.rows.map(function (row) {
var parts = row.key.split('[');
return $('<tr>')
.append([
// TODO: get field title (titles are all over GUI conf, which is a problem)
//parts[0],
// TODO: get language from
//parts[1].substr(0, parts[1].length - 1),
row.key,
row.original,
row.current
].map(function (entry) {
return $('<td>')
.text(entry.supplant({
rowNumber: MetkaJS.L10N.get("dialog.history.compare.rowId"),
newRow: MetkaJS.L10N.get("dialog.history.compare.newRow"),
removedRow: MetkaJS.L10N.get("dialog.history.compare.removedRow"),
}));
}));
})));
}
}
});
});
}
}, {
type: 'DISMISS'
}]
}));
require('./server')('/revision/revisionHistory', {
data: JSON.stringify({
id: options.data.key.id
}),
success: function (response) {
$table
.append($('<tbody>')
.append(response.rows.map(function (row) {
return $('<tr>')
.append((function () {
var publishDate = new Date(row.publishDate);
if (publishDate.getFullYear() === 1970)
publishDate = null;
var items = [
$('<a>', {
href: require('./url')('view', row),
text: row.no
}),
publishDate !== null ? publishDate.getDate() + "." + parseInt(publishDate.getMonth()+1) + "." + publishDate.getFullYear() : "",
$('<input>', {
type: 'radio',
name: 'beginGrp',
value: row.no,
change: checkRadioGroups
}),
$('<input>', {
type: 'radio',
name: 'endGrp',
value: row.no,
change: checkRadioGroups
})
];
return items.map(function (entry) {
return $('<td>')
.append(entry);
});
})());
})));
checkRadioGroups();
$(".modal-footer").find("button").removeAttr('disabled');
},
error: function() {
$(".modal-footer").find("button").removeAttr('disabled');
}
});
});
},
NO: function (options) {
options.title = MetkaJS.L10N.get('general.buttons.no');
},
REMOVE: function (options) {
this.click(require('./remove')(options));
},
RELEASE: function (options) {
this
.click(function () {
$(".modal-footer").find("button").attr('disabled', 'disabled');
var $this = $(this);
require('./server')('/revision/ajax/release', {
data: JSON.stringify(options.data.key),
success: function (response) {
$(".modal-footer").find("button").removeAttr('disabled');
$.extend(options.data, response.data);
options.$events.trigger('refresh.metka');
location.reload();
},
error: function (){
$(".modal-footer").find("button").removeAttr('disabled');
}
});
});
},
RESTORE: function (options) {
this
.click(function () {
$(".modal-footer").find("button").attr('disabled', 'disabled');
var $this = $(this);
var request = $.extend({
data: JSON.stringify(options.data.key),
success: function (response) {
$(".modal-footer").find("button").removeAttr('disabled');
$.extend(options.data, response.data);
options.$events.trigger('refresh.metka');
},
error: function () {
$(".modal-footer").find("button").removeAttr('disabled');
}
}, options.request);
require('./server')('/revision/ajax/restore', request);
});
},
REVERTCONFIRM: function (options) {
options.title = MetkaJS.L10N.get('general.buttons.revert');
},
REVERT: function (options){
this
.click(function() {
var $this = $(this);
console.log(options);
var $table = $('<table class="table">')
.append($('<thead>')
.append($('<tr>')
.append((function () {
var arr = [
'general.revision',
'general.revision.publishDate',
''
];
return arr.map(function (entry) {
return $('<th>')
.text(MetkaJS.L10N.get(entry));
});
}))));
require('./modal')($.extend(true, require('./optionsBase')(), {
title: MetkaJS.L10N.get('general.revision.revert'),
body: $table,
//large: false,
buttons: [{
type: 'REVERTCONFIRM',
create: function() {
options.title = MetkaJS.L10N.get('general.buttons.revert');
this
.attr('id', 'revertRevision')
.click(function() {
$(".modal-footer").find("button").attr('disabled', 'disabled');
var request = {
data: JSON.stringify({
targetNo: parseInt($('input[name="revertRadio"]:checked').val()),
key: options.data.key
}),
success: function(response) {
$(".modal-footer").find("button").removeAttr('disabled');
options.$events.trigger('refresh.metka');
require('./assignUrl')('view', {
id: response.data.key.id,
no: response.data.key.no
});
}, error: function() {
$(".modal-footer").find("button").removeAttr('disabled');
}
};
require('./server')('/revision/ajax/revert', request);
// Ajax-kutsu
})
}
}, {
type: 'DISMISS'
}]
}));
require('./server')('/revision/revisionHistory', {
data: JSON.stringify({
id: options.data.key.id
}),
success: function(response){
$table
.append($('<tbody>')
.append(response.rows.map(function(row){
return $('<tr>')
.append((function(){
var publishDate = new Date(row.publishDate);
if (publishDate.getFullYear() === 1970)
publishDate = null;
var items = [
$('<a>', {
href: require('./url')('view', row),
text: row.no
}),
publishDate !== null ? publishDate.getDate() + "." + parseInt(publishDate.getMonth()+1) + "."+ publishDate.getFullYear() : "",
$('<input>', {
type: 'radio',
name: 'revertRadio',
value: row.no
})
];
return items.map(function(entry){
return $('<td>')
.append(entry)
});
}))
})));
}
})
})
},
SAVE: function (options) {
this
.click(require('./save')(options, function (response) {
$(".modal-footer").find("button").removeAttr('disabled');
$.extend(options.data, response.data);
// Fire an event so that metka doesn't ask for confirmation if moving from page
var evt = new CustomEvent('saved');
window.dispatchEvent(evt);
options.$events.trigger('refresh.metka');
}));
},
YES: function (options) {
options.title = MetkaJS.L10N.get('general.buttons.yes');
},
OK: function(options) {
options.title = MetkaJS.L10N.get('general.buttons.ok');
}
};
});
| metka/src/main/webapp/resources/js/modules/buttons.js | /**************************************************************************************
* Copyright (c) 2013-2015, Finnish Social Science Data Archive/University of Tampere *
* *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, *
* are permitted provided that the following conditions are met: *
* 1. Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* 2. Redistributions in binary form must reproduce the above copyright notice, *
* this list of conditions and the following disclaimer in the documentation *
* and/or other materials provided with the distribution. *
* 3. Neither the name of the copyright holder nor the names of its contributors *
* may be used to endorse or promote products derived from this software *
* without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND *
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. *
**************************************************************************************/
define(function (require) {
'use strict';
var resultParser = require('./resultParser');
return {
APPROVE: function (options) {
this
.click(require('./formAction')('approve')(options, function (response) {
if(resultParser(response.result).getResult() === 'NO_CHANGES') {
require('./assignUrl')('view', {no: ''});
} else {
$.extend(options.data, response.data);
options.$events.trigger('refresh.metka');
}
}, [
'OPERATION_SUCCESSFUL',
'RESTRICTION_VALIDATION_FAILURE',
'NO_CHANGES'
], "approve"));
},
CANCEL: function (options) {
options.title = MetkaJS.L10N.get('general.buttons.cancel');
},
CLAIM: function (options) {
this
.click(function () {
$(".modal-footer").find("button").attr('disabled', 'disabled');
require('./server')('/revision/ajax/claim', {
data: JSON.stringify(options.data.key),
success: function (response) {
$(".modal-footer").find("button").removeAttr('disabled');
$.extend(options.data, response.data);
options.$events.trigger('refresh.metka');
location.reload();
},
error: function() {
$(".modal-footer").find("button").removeAttr('disabled');
}
});
});
},
BEGIN_EDIT: function (options) {
this
.click(function () {
$(".modal-footer").find("button").attr('disabled', 'disabled');
require('./server')('/revision/ajax/beginEdit', {
data: JSON.stringify(options.data.key),
success: function (response) {
$(".modal-footer").find("button").removeAttr('disabled');
if(resultParser(response.result).getResult() === 'REVISION_UPDATE_SUCCESSFUL') {
$.extend(options.data, response.data);
options.$events.trigger('refresh.metka');
location.reload();
} else {
require('./resultViewer')(response.result, 'beginEdit', function() {
require('./assignUrl')('view');
});
}
},
error: function() {
$(".modal-footer").find("button").removeAttr('disabled');
}
});
});
},
COMPARE: function (options) {
options.title = MetkaJS.L10N.get('general.revision.compare');
this.prop('disabled', true);
},
CUSTOM: function(options) {
},
DISMISS: function (options) {
options.title = MetkaJS.L10N.get('general.buttons.close');
},
EDIT: function (options) {
this.click(require('./formAction')('edit')(options, function (response) {
$(".modal-footer").find("button").removeAttr('disabled');
$.extend(options.data, response.data);
options.$events.trigger('refresh.metka');
history.replaceState(undefined, '', require('./url')('view'));
location.reload()
}, [
'REVISION_FOUND',
'REVISION_CREATED'
], "edit"));
},
HISTORY: function (options) {
$.extend(true, options, {
preventDismiss: true
});
this
.click(function () {
var o = options;
function checkRadioGroups() {
var beginVal = parseInt($('input[name="beginGrp"]:checked').val());
var endVal = parseInt($('input[name="endGrp"]:checked').val())
if (beginVal) {
$('input[name="endGrp"]').each(function () {
if (parseInt($(this).val()) <= beginVal) {
$(this).attr('disabled', true);
} else {
$(this).attr('disabled', false);
}
});
}
if (endVal) {
$('input[name="beginGrp"]').each(function () {
if (parseInt($(this).val()) >= endVal) {
$(this).attr('disabled', true);
} else {
$(this).attr('disabled', false);
}
});
}
if (typeof beginVal !== 'undefined' && typeof endVal !== 'undefined') {
if (beginVal >= endVal) {
$('#compareRevisions').prop('disabled', true);
} else {
$('#compareRevisions').prop('disabled', false);
}
}
}
var $table = $('<table class="table">')
.append($('<thead>')
.append($('<tr>')
.append((function () {
var arr = [
'general.revision',
'general.revision.publishDate',
'general.revision.compare.begin',
'general.revision.compare.end'
];
return arr.map(function (entry) {
return $('<th>')
.text(MetkaJS.L10N.get(entry));
});
})())));
require('./modal')($.extend(true, require('./optionsBase')(), {
title: MetkaJS.L10N.get('general.revision.revisions'),
body: $table,
large: true,
buttons: [{
type: 'COMPARE',
//preventDismiss: true,
create: function () {
this
.attr('id', 'compareRevisions')
.click(function () {
var $table = $('<table class="table">')
.append($('<thead>')
.append($('<tr>')
.append([
MetkaJS.L10N.get("dialog.history.path"),
///MetkaJS.L10N.get("dialog.history.language"),
MetkaJS.L10N.get("dialog.history.original"),
MetkaJS.L10N.get("dialog.history.current")
].map(function (entry) {
return $('<th style="width: 33%;">')
.text(entry);
}))));
require('./modal')($.extend(true, require('./optionsBase')(), {
title: MetkaJS.L10N.get('general.revision.revisions'),
body: $table,
large: true,
buttons: [{
type: 'DISMISS'
}]
}));
require('./server')('/revision/revisionCompare', {
data: JSON.stringify({
id: o.data.key.id,
begin: $('input[name="beginGrp"]:checked').val(),
end: $('input[name="endGrp"]:checked').val(),
type: o.data.configuration.type
}),
success: function (response) {
if (resultParser(response.result).getResult() === 'OPERATION_SUCCESSFUL') {
$table
.append($('<tbody>')
.append(response.rows.map(function (row) {
var parts = row.key.split('[');
return $('<tr>')
.append([
// TODO: get field title (titles are all over GUI conf, which is a problem)
//parts[0],
// TODO: get language from
//parts[1].substr(0, parts[1].length - 1),
row.key,
row.original,
row.current
].map(function (entry) {
return $('<td>')
.text(entry.supplant({
rowNumber: MetkaJS.L10N.get("dialog.history.compare.rowId"),
newRow: MetkaJS.L10N.get("dialog.history.compare.newRow"),
removedRow: MetkaJS.L10N.get("dialog.history.compare.removedRow"),
}));
}));
})));
}
}
});
});
}
}, {
type: 'DISMISS'
}]
}));
require('./server')('/revision/revisionHistory', {
data: JSON.stringify({
id: options.data.key.id
}),
success: function (response) {
$table
.append($('<tbody>')
.append(response.rows.map(function (row) {
return $('<tr>')
.append((function () {
var publishDate = new Date(row.publishDate);
if (publishDate.getFullYear() === 1970)
publishDate = null;
var items = [
$('<a>', {
href: require('./url')('view', row),
text: row.no
}),
publishDate !== null ? publishDate.getDate() + "." + parseInt(publishDate.getMonth()+1) + "." + publishDate.getFullYear() : "",
$('<input>', {
type: 'radio',
name: 'beginGrp',
value: row.no,
change: checkRadioGroups
}),
$('<input>', {
type: 'radio',
name: 'endGrp',
value: row.no,
change: checkRadioGroups
})
];
return items.map(function (entry) {
return $('<td>')
.append(entry);
});
})());
})));
checkRadioGroups();
$(".modal-footer").find("button").removeAttr('disabled');
},
error: function() {
$(".modal-footer").find("button").removeAttr('disabled');
}
});
});
},
NO: function (options) {
options.title = MetkaJS.L10N.get('general.buttons.no');
},
REMOVE: function (options) {
this.click(require('./remove')(options));
},
RELEASE: function (options) {
this
.click(function () {
$(".modal-footer").find("button").attr('disabled', 'disabled');
var $this = $(this);
require('./server')('/revision/ajax/release', {
data: JSON.stringify(options.data.key),
success: function (response) {
$(".modal-footer").find("button").removeAttr('disabled');
$.extend(options.data, response.data);
options.$events.trigger('refresh.metka');
location.reload();
},
error: function (){
$(".modal-footer").find("button").removeAttr('disabled');
}
});
});
},
RESTORE: function (options) {
this
.click(function () {
$(".modal-footer").find("button").attr('disabled', 'disabled');
var $this = $(this);
var request = $.extend({
data: JSON.stringify(options.data.key),
success: function (response) {
$(".modal-footer").find("button").removeAttr('disabled');
$.extend(options.data, response.data);
options.$events.trigger('refresh.metka');
},
error: function () {
$(".modal-footer").find("button").removeAttr('disabled');
}
}, options.request);
require('./server')('/revision/ajax/restore', request);
});
},
REVERTCONFIRM: function (options) {
options.title = MetkaJS.L10N.get('general.buttons.revert');
},
REVERT: function (options){
this
.click(function() {
var $this = $(this);
console.log(options);
var $table = $('<table class="table">')
.append($('<thead>')
.append($('<tr>')
.append((function () {
var arr = [
'general.revision',
'general.revision.publishDate',
''
];
return arr.map(function (entry) {
return $('<th>')
.text(MetkaJS.L10N.get(entry));
});
}))));
require('./modal')($.extend(true, require('./optionsBase')(), {
title: MetkaJS.L10N.get('general.revision.revert'),
body: $table,
//large: false,
buttons: [{
type: 'REVERTCONFIRM',
create: function() {
options.title = MetkaJS.L10N.get('general.buttons.revert');
this
.attr('id', 'revertRevision')
.click(function() {
$(".modal-footer").find("button").attr('disabled', 'disabled');
var request = {
data: JSON.stringify({
targetNo: parseInt($('input[name="revertRadio"]:checked').val()),
key: options.data.key
}),
success: function(response) {
$(".modal-footer").find("button").removeAttr('disabled');
options.$events.trigger('refresh.metka');
require('./assignUrl')('view', {
id: response.data.key.id,
no: response.data.key.no
});
}, error: function() {
$(".modal-footer").find("button").removeAttr('disabled');
}
};
require('./server')('/revision/ajax/revert', request);
// Ajax-kutsu
})
}
}, {
type: 'DISMISS'
}]
}));
require('./server')('/revision/revisionHistory', {
data: JSON.stringify({
id: options.data.key.id
}),
success: function(response){
$table
.append($('<tbody>')
.append(response.rows.map(function(row){
return $('<tr>')
.append((function(){
var publishDate = new Date(row.publishDate);
if (publishDate.getFullYear() === 1970)
publishDate = null;
var items = [
$('<a>', {
href: require('./url')('view', row),
text: row.no
}),
publishDate !== null ? publishDate.getDate() + "." + parseInt(publishDate.getMonth()+1) + "."+ publishDate.getFullYear() : "",
$('<input>', {
type: 'radio',
name: 'revertRadio',
value: row.no
})
];
return items.map(function(entry){
return $('<td>')
.append(entry)
});
}))
})));
}
})
})
},
SAVE: function (options) {
this
.click(require('./save')(options, function (response) {
$(".modal-footer").find("button").removeAttr('disabled');
$.extend(options.data, response.data);
// Fire an event so that metka doesn't ask for confirmation if moving from page
var evt = new CustomEvent('saved');
window.dispatchEvent(evt);
options.$events.trigger('refresh.metka');
}));
},
YES: function (options) {
options.title = MetkaJS.L10N.get('general.buttons.yes');
},
OK: function(options) {
options.title = MetkaJS.L10N.get('general.buttons.ok');
}
};
});
| Metka ei varoita tallentamattomista muutoksista aineiston hyväksymisen jälkeen sivulta poistuttaessa
| metka/src/main/webapp/resources/js/modules/buttons.js | Metka ei varoita tallentamattomista muutoksista aineiston hyväksymisen jälkeen sivulta poistuttaessa | <ide><path>etka/src/main/webapp/resources/js/modules/buttons.js
<ide> require('./assignUrl')('view', {no: ''});
<ide> } else {
<ide> $.extend(options.data, response.data);
<add> // Fire an event so that metka doesn't ask for confirmation if moving from page
<add> var evt = new CustomEvent('saved');
<add> window.dispatchEvent(evt);
<ide> options.$events.trigger('refresh.metka');
<ide> }
<ide> }, [ |
|
Java | mit | feb06b715b6f01948a0a6bb69e38be1e9b6f57e0 | 0 | TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android | /*
HostDeviceOrientationProfile.java
Copyright (c) 2014 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
package org.deviceconnect.android.deviceplugin.host.profile;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import org.deviceconnect.android.deviceplugin.host.HostDeviceService;
import org.deviceconnect.android.event.Event;
import org.deviceconnect.android.event.EventError;
import org.deviceconnect.android.event.EventManager;
import org.deviceconnect.android.message.MessageUtils;
import org.deviceconnect.android.profile.DConnectProfile;
import org.deviceconnect.android.profile.DeviceOrientationProfile;
import org.deviceconnect.android.profile.api.DConnectApi;
import org.deviceconnect.android.profile.api.DeleteApi;
import org.deviceconnect.android.profile.api.GetApi;
import org.deviceconnect.android.profile.api.PutApi;
import org.deviceconnect.message.DConnectMessage;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* DeviceOrientation Profile.
* @author NTT DOCOMO, INC.
*/
public class HostDeviceOrientationProfile extends DeviceOrientationProfile implements SensorEventListener {
/** SensorManager. */
private SensorManager mSensorManager;
/** ServiceID. */
private String mServiceId;
/** X軸方向の重力付き加速度. (単位: m/s^2). */
private double mAccellX;
/** Y軸方向の重力付き加速度. (単位: m/s^2). */
private double mAccellY;
/** Z軸方向の重力付き加速度. (単位: m/s^2). */
private double mAccellZ;
/** 加速度データが準備できているかどうかのフラグ */
private AtomicBoolean mIsAccellReady = new AtomicBoolean(false);
/** X軸方向の重力加速度成分. (単位: m/s^2). */
private double mGravityX = 0;
/** Y軸方向の重力加速度成分. (単位: m/s^2). */
private double mGravityY = 0;
/** Z軸方向の重力加速度成分. (単位: m/s^2). */
private double mGravityZ = 0;
/** 重力加速度データが準備できているかどうかのフラグ */
private AtomicBoolean mIsGravityReady = new AtomicBoolean(false);
/** X軸周りの角速度. (単位: degree/s). */
private double mGyroX;
/** Y軸周りの角速度. (単位: degree/s). */
private double mGyroY;
/** Z軸周りの角速度. (単位: degree/s). */
private double mGyroZ;
/** 角速度データが準備できているかどうかのフラグ */
private AtomicBoolean mIsGyroReady = new AtomicBoolean(false);
/** 前回の加速度の計測時間を保持する. */
private long mAccelLastTime;
/** イベント送信間隔設定用. */
private long mEventSendInterval;
/** イベント送信間隔計測用. */
private long mLastEventSendTime;
/**
* Device Orientationのデフォルト送信間隔を定義.
*/
private static final long DEVICE_ORIENTATION_INTERVAL_TIME = 200;
/**
* Device Orientationのキャッシュを残す時間を定義する.
*/
private static final long DEVICE_ORIENTATION_CACHE_TIME = 100;
private final DConnectApi mGetOnDeviceOrientationApi = new GetApi() {
@Override
public String getAttribute() {
return ATTRIBUTE_ON_DEVICE_ORIENTATION;
}
@Override
public boolean onRequest(final Intent request, final Intent response) {
return getDeviceOrientationEvent(response);
}
};
private final DConnectApi mPutOnDeviceOrientationApi = new PutApi() {
@Override
public String getAttribute() {
return ATTRIBUTE_ON_DEVICE_ORIENTATION;
}
@Override
public boolean onRequest(final Intent request, final Intent response) {
String serviceId = getServiceID(request);
try {
String interval = request.getStringExtra(PARAM_INTERVAL);
mEventSendInterval = Long.parseLong(interval);
} catch (NumberFormatException e) {
mEventSendInterval = DEVICE_ORIENTATION_INTERVAL_TIME;
}
// イベントの登録
EventError error = EventManager.INSTANCE.addEvent(request);
if (error == EventError.NONE) {
registerDeviceOrientationEvent(response, serviceId);
} else {
MessageUtils.setUnknownError(response, "Can not register event.");
}
return true;
}
};
private final DConnectApi mDeleteOnDeviceOrientationApi = new DeleteApi() {
@Override
public String getAttribute() {
return ATTRIBUTE_ON_DEVICE_ORIENTATION;
}
@Override
public boolean onRequest(final Intent request, final Intent response) {
// イベントの解除
EventError error = EventManager.INSTANCE.removeEvent(request);
if (error == EventError.NONE) {
unregisterDeviceOrientationEvent(response);
} else {
MessageUtils.setUnknownError(response, "Can not unregister event.");
}
return true;
}
};
public HostDeviceOrientationProfile() {
addApi(mGetOnDeviceOrientationApi);
addApi(mPutOnDeviceOrientationApi);
addApi(mDeleteOnDeviceOrientationApi);
}
/**
* センサー管理クラスを取得する.
* @return センサー管理クラス
*/
private SensorManager getSensorManager() {
return (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
}
/**
* イベント登録が空か確認する.
* @return 空の場合はtrue、それ以外はfalse
*/
private boolean isEmptyEventList() {
List<Event> events = EventManager.INSTANCE.getEventList(mServiceId,
DeviceOrientationProfile.PROFILE_NAME, null,
DeviceOrientationProfile.ATTRIBUTE_ON_DEVICE_ORIENTATION);
return events == null || events.size() == 0;
}
/**
* Device Orientationのデータを取得する.
* @param response データを格納するレスポンス
* @return trueの場合には即座に値を返却する、falseの場合には返さない
*/
private boolean getDeviceOrientationEvent(final Intent response) {
long t = System.currentTimeMillis() - mAccelLastTime;
if (t > DEVICE_ORIENTATION_CACHE_TIME) {
List<Sensor> sensors;
final SensorEventListener l = new SensorEventListener() {
@Override
public void onSensorChanged(final SensorEvent event) {
processSensorData(event);
if (mIsAccellReady.get() && mIsGravityReady.get() && mIsGyroReady.get()) {
mAccelLastTime = System.currentTimeMillis();
Bundle orientation = createOrientation();
setResult(response, DConnectMessage.RESULT_OK);
setOrientation(response, orientation);
HostDeviceService service = (HostDeviceService) getContext();
service.sendResponse(response);
if (isEmptyEventList()) {
mSensorManager.unregisterListener(this);
}
}
}
@Override
public void onAccuracyChanged(final Sensor sensor, final int accuracy) {
// No operation
}
};
mSensorManager = getSensorManager();
sensors = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if (sensors.size() > 0) {
Sensor sensor = sensors.get(0);
mSensorManager.registerListener(l, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
} else {
MessageUtils.setNotSupportAttributeError(response);
return true;
}
sensors = mSensorManager
.getSensorList(Sensor.TYPE_GRAVITY);
if (sensors.size() > 0) {
Sensor sensor = sensors.get(0);
mSensorManager.registerListener(l, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
} else {
MessageUtils.setNotSupportAttributeError(response);
return true;
}
sensors = mSensorManager.getSensorList(Sensor.TYPE_GYROSCOPE);
if (sensors.size() > 0) {
Sensor sensor = sensors.get(0);
mSensorManager.registerListener(l, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
} else {
MessageUtils.setNotSupportAttributeError(response);
return true;
}
invalidateLatestData();
return false;
} else {
Bundle orientation = createOrientation();
setResult(response, DConnectMessage.RESULT_OK);
setOrientation(response, orientation);
return true;
}
}
/**
* Device Orientation Profile<br>
* イベントの登録.
*
* @param response
* レスポンス
* @param serviceId
* サービスID
*/
private void registerDeviceOrientationEvent(final Intent response, final String serviceId) {
mServiceId = serviceId;
mSensorManager = getSensorManager();
mAccelLastTime = System.currentTimeMillis();
List<Sensor> sensors;
sensors = mSensorManager
.getSensorList(Sensor.TYPE_ACCELEROMETER);
if (sensors.size() > 0) {
Sensor sensor = sensors.get(0);
mSensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
} else {
MessageUtils.setNotSupportAttributeError(response);
return;
}
sensors = mSensorManager
.getSensorList(Sensor.TYPE_GRAVITY);
if (sensors.size() > 0) {
Sensor sensor = sensors.get(0);
mSensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
} else {
MessageUtils.setNotSupportAttributeError(response);
return;
}
sensors = mSensorManager.getSensorList(Sensor.TYPE_GYROSCOPE);
if (sensors.size() > 0) {
Sensor sensor = sensors.get(0);
mSensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
} else {
MessageUtils.setNotSupportAttributeError(response);
return;
}
DConnectProfile.setResult(response, DConnectMessage.RESULT_OK);
response.putExtra(DConnectMessage.EXTRA_VALUE,
"Register OnDeviceOrientation event");
}
/**
* Device Orientation Profile イベントの解除.
* @param response レスポンス
*/
private void unregisterDeviceOrientationEvent(final Intent response) {
mSensorManager.unregisterListener(this);
response.putExtra(DConnectMessage.EXTRA_RESULT,
DConnectMessage.RESULT_OK);
response.putExtra(DConnectMessage.EXTRA_VALUE,
"Unregister OnDeviceOrientation event");
}
/**
* Orientationのデータを作成する.
* @return Orientationのデータ
*/
private Bundle createOrientation() {
long interval = System.currentTimeMillis() - mAccelLastTime;
Bundle orientation = new Bundle();
Bundle a1 = new Bundle();
DeviceOrientationProfile.setX(a1, mAccellX - mGravityX);
DeviceOrientationProfile.setY(a1, mAccellY - mGravityY);
DeviceOrientationProfile.setZ(a1, mAccellZ - mGravityZ);
Bundle a2 = new Bundle();
DeviceOrientationProfile.setX(a2, mAccellX);
DeviceOrientationProfile.setY(a2, mAccellY);
DeviceOrientationProfile.setZ(a2, mAccellZ);
Bundle r = new Bundle();
DeviceOrientationProfile.setAlpha(r, mGyroX);
DeviceOrientationProfile.setBeta(r, mGyroY);
DeviceOrientationProfile.setGamma(r, mGyroZ);
DeviceOrientationProfile.setAcceleration(orientation, a1);
DeviceOrientationProfile.setAccelerationIncludingGravity(orientation, a2);
DeviceOrientationProfile.setRotationRate(orientation, r);
DeviceOrientationProfile.setInterval(orientation, interval);
return orientation;
}
private void processSensorData(final SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mAccellX = sensorEvent.values[0];
mAccellY = sensorEvent.values[1];
mAccellZ = sensorEvent.values[2];
mIsAccellReady.compareAndSet(false, true);
} else if (sensorEvent.sensor.getType() == Sensor.TYPE_GRAVITY) {
mGravityX = sensorEvent.values[0];
mGravityY = sensorEvent.values[1];
mGravityZ = sensorEvent.values[2];
mIsGravityReady.compareAndSet(false, true);
} else if (sensorEvent.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
mGyroX = Math.toDegrees(sensorEvent.values[0]);
mGyroY = Math.toDegrees(sensorEvent.values[1]);
mGyroZ = Math.toDegrees(sensorEvent.values[2]);
mIsGyroReady.compareAndSet(false, true);
}
}
/**
* キャッシュされたセンサーデータを無効扱いにし、最新センサーデータが全て揃うまでデータ収集を行わせる。
*/
private void invalidateLatestData() {
mIsAccellReady.compareAndSet(true, false);
mIsGravityReady.compareAndSet(true, false);
mIsGyroReady.compareAndSet(true, false);
}
@Override
public void onSensorChanged(final SensorEvent sensorEvent) {
processSensorData(sensorEvent);
if (mIsAccellReady.get() && mIsGravityReady.get() && mIsGyroReady.get()) {
Bundle orientation = createOrientation();
mAccelLastTime = System.currentTimeMillis();
if (isEmptyEventList()) {
mSensorManager.unregisterListener(this);
return;
}
long interval = System.currentTimeMillis() - mLastEventSendTime;
if (interval > mEventSendInterval) {
List<Event> events = EventManager.INSTANCE.getEventList(mServiceId,
DeviceOrientationProfile.PROFILE_NAME, null,
DeviceOrientationProfile.ATTRIBUTE_ON_DEVICE_ORIENTATION);
for (int i = 0; i < events.size(); i++) {
Event event = events.get(i);
Intent intent = EventManager.createEventMessage(event);
intent.putExtra(DeviceOrientationProfile.PARAM_ORIENTATION, orientation);
sendEvent(intent, event.getAccessToken());
}
mLastEventSendTime = System.currentTimeMillis();
}
}
}
@Override
public void onAccuracyChanged(final Sensor sensor, final int accuracy) {
// No operation
}
}
| dConnectDevicePlugin/dConnectDeviceHost/app/src/main/java/org/deviceconnect/android/deviceplugin/host/profile/HostDeviceOrientationProfile.java | /*
HostDeviceOrientationProfile.java
Copyright (c) 2014 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
package org.deviceconnect.android.deviceplugin.host.profile;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import org.deviceconnect.android.deviceplugin.host.HostDeviceService;
import org.deviceconnect.android.event.Event;
import org.deviceconnect.android.event.EventError;
import org.deviceconnect.android.event.EventManager;
import org.deviceconnect.android.message.MessageUtils;
import org.deviceconnect.android.profile.DConnectProfile;
import org.deviceconnect.android.profile.DeviceOrientationProfile;
import org.deviceconnect.android.profile.api.DConnectApi;
import org.deviceconnect.android.profile.api.DeleteApi;
import org.deviceconnect.android.profile.api.GetApi;
import org.deviceconnect.android.profile.api.PutApi;
import org.deviceconnect.message.DConnectMessage;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* DeviceOrientation Profile.
* @author NTT DOCOMO, INC.
*/
public class HostDeviceOrientationProfile extends DeviceOrientationProfile implements SensorEventListener {
/** SensorManager. */
private SensorManager mSensorManager;
/** ServiceID. */
private String mServiceId;
/** X軸方向の重力付き加速度. (単位: m/s^2). */
private double mAccellX;
/** Y軸方向の重力付き加速度. (単位: m/s^2). */
private double mAccellY;
/** Z軸方向の重力付き加速度. (単位: m/s^2). */
private double mAccellZ;
/** 加速度データが準備できているかどうかのフラグ */
private AtomicBoolean mIsAccellReady = new AtomicBoolean(false);
/** X軸方向の重力加速度成分. (単位: m/s^2). */
private double mGravityX = 0;
/** Y軸方向の重力加速度成分. (単位: m/s^2). */
private double mGravityY = 0;
/** Z軸方向の重力加速度成分. (単位: m/s^2). */
private double mGravityZ = 0;
/** 重力加速度データが準備できているかどうかのフラグ */
private AtomicBoolean mIsGravityReady = new AtomicBoolean(false);
/** X軸周りの角速度. (単位: degree/s). */
private double mGyroX;
/** Y軸周りの角速度. (単位: degree/s). */
private double mGyroY;
/** Z軸周りの角速度. (単位: degree/s). */
private double mGyroZ;
/** 角速度データが準備できているかどうかのフラグ */
private AtomicBoolean mIsGyroReady = new AtomicBoolean(false);
/** 前回の加速度の計測時間を保持する. */
private long mAccelLastTime;
/**
* Device Orientationのキャッシュを残す時間を定義する.
*/
private static final long DEVICE_ORIENTATION_CACHE_TIME = 100;
private final DConnectApi mGetOnDeviceOrientationApi = new GetApi() {
@Override
public String getAttribute() {
return ATTRIBUTE_ON_DEVICE_ORIENTATION;
}
@Override
public boolean onRequest(final Intent request, final Intent response) {
return getDeviceOrientationEvent(response);
}
};
private final DConnectApi mPutOnDeviceOrientationApi = new PutApi() {
@Override
public String getAttribute() {
return ATTRIBUTE_ON_DEVICE_ORIENTATION;
}
@Override
public boolean onRequest(final Intent request, final Intent response) {
String serviceId = getServiceID(request);
// イベントの登録
EventError error = EventManager.INSTANCE.addEvent(request);
if (error == EventError.NONE) {
registerDeviceOrientationEvent(response, serviceId);
} else {
MessageUtils.setUnknownError(response, "Can not register event.");
}
return true;
}
};
private final DConnectApi mDeleteOnDeviceOrientationApi = new DeleteApi() {
@Override
public String getAttribute() {
return ATTRIBUTE_ON_DEVICE_ORIENTATION;
}
@Override
public boolean onRequest(final Intent request, final Intent response) {
// イベントの解除
EventError error = EventManager.INSTANCE.removeEvent(request);
if (error == EventError.NONE) {
unregisterDeviceOrientationEvent(response);
} else {
MessageUtils.setUnknownError(response, "Can not unregister event.");
}
return true;
}
};
public HostDeviceOrientationProfile() {
addApi(mGetOnDeviceOrientationApi);
addApi(mPutOnDeviceOrientationApi);
addApi(mDeleteOnDeviceOrientationApi);
}
/**
* センサー管理クラスを取得する.
* @return センサー管理クラス
*/
private SensorManager getSensorManager() {
return (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
}
/**
* イベント登録が空か確認する.
* @return 空の場合はtrue、それ以外はfalse
*/
private boolean isEmptyEventList() {
List<Event> events = EventManager.INSTANCE.getEventList(mServiceId,
DeviceOrientationProfile.PROFILE_NAME, null,
DeviceOrientationProfile.ATTRIBUTE_ON_DEVICE_ORIENTATION);
return events == null || events.size() == 0;
}
/**
* Device Orientationのデータを取得する.
* @param response データを格納するレスポンス
* @return trueの場合には即座に値を返却する、falseの場合には返さない
*/
private boolean getDeviceOrientationEvent(final Intent response) {
long t = System.currentTimeMillis() - mAccelLastTime;
if (t > DEVICE_ORIENTATION_CACHE_TIME) {
List<Sensor> sensors;
final SensorEventListener l = new SensorEventListener() {
@Override
public void onSensorChanged(final SensorEvent event) {
processSensorData(event);
if (mIsAccellReady.get() && mIsGravityReady.get() && mIsGyroReady.get()) {
mAccelLastTime = System.currentTimeMillis();
Bundle orientation = createOrientation();
setResult(response, DConnectMessage.RESULT_OK);
setOrientation(response, orientation);
HostDeviceService service = (HostDeviceService) getContext();
service.sendResponse(response);
if (isEmptyEventList()) {
mSensorManager.unregisterListener(this);
}
}
}
@Override
public void onAccuracyChanged(final Sensor sensor, final int accuracy) {
// No operation
}
};
mSensorManager = getSensorManager();
sensors = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if (sensors.size() > 0) {
Sensor sensor = sensors.get(0);
mSensorManager.registerListener(l, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
} else {
MessageUtils.setNotSupportAttributeError(response);
return true;
}
sensors = mSensorManager
.getSensorList(Sensor.TYPE_GRAVITY);
if (sensors.size() > 0) {
Sensor sensor = sensors.get(0);
mSensorManager.registerListener(l, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
} else {
MessageUtils.setNotSupportAttributeError(response);
return true;
}
sensors = mSensorManager.getSensorList(Sensor.TYPE_GYROSCOPE);
if (sensors.size() > 0) {
Sensor sensor = sensors.get(0);
mSensorManager.registerListener(l, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
} else {
MessageUtils.setNotSupportAttributeError(response);
return true;
}
invalidateLatestData();
return false;
} else {
Bundle orientation = createOrientation();
setResult(response, DConnectMessage.RESULT_OK);
setOrientation(response, orientation);
return true;
}
}
/**
* Device Orientation Profile<br>
* イベントの登録.
*
* @param response
* レスポンス
* @param serviceId
* サービスID
*/
private void registerDeviceOrientationEvent(final Intent response, final String serviceId) {
mServiceId = serviceId;
mSensorManager = getSensorManager();
mAccelLastTime = System.currentTimeMillis();
List<Sensor> sensors;
sensors = mSensorManager
.getSensorList(Sensor.TYPE_ACCELEROMETER);
if (sensors.size() > 0) {
Sensor sensor = sensors.get(0);
mSensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
} else {
MessageUtils.setNotSupportAttributeError(response);
return;
}
sensors = mSensorManager
.getSensorList(Sensor.TYPE_GRAVITY);
if (sensors.size() > 0) {
Sensor sensor = sensors.get(0);
mSensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
} else {
MessageUtils.setNotSupportAttributeError(response);
return;
}
sensors = mSensorManager.getSensorList(Sensor.TYPE_GYROSCOPE);
if (sensors.size() > 0) {
Sensor sensor = sensors.get(0);
mSensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
} else {
MessageUtils.setNotSupportAttributeError(response);
return;
}
DConnectProfile.setResult(response, DConnectMessage.RESULT_OK);
response.putExtra(DConnectMessage.EXTRA_VALUE,
"Register OnDeviceOrientation event");
}
/**
* Device Orientation Profile イベントの解除.
* @param response レスポンス
*/
private void unregisterDeviceOrientationEvent(final Intent response) {
mSensorManager.unregisterListener(this);
response.putExtra(DConnectMessage.EXTRA_RESULT,
DConnectMessage.RESULT_OK);
response.putExtra(DConnectMessage.EXTRA_VALUE,
"Unregister OnDeviceOrientation event");
}
/**
* Orientationのデータを作成する.
* @return Orientationのデータ
*/
private Bundle createOrientation() {
long interval = System.currentTimeMillis() - mAccelLastTime;
Bundle orientation = new Bundle();
Bundle a1 = new Bundle();
DeviceOrientationProfile.setX(a1, mAccellX - mGravityX);
DeviceOrientationProfile.setY(a1, mAccellY - mGravityY);
DeviceOrientationProfile.setZ(a1, mAccellZ - mGravityZ);
Bundle a2 = new Bundle();
DeviceOrientationProfile.setX(a2, mAccellX);
DeviceOrientationProfile.setY(a2, mAccellY);
DeviceOrientationProfile.setZ(a2, mAccellZ);
Bundle r = new Bundle();
DeviceOrientationProfile.setAlpha(r, mGyroX);
DeviceOrientationProfile.setBeta(r, mGyroY);
DeviceOrientationProfile.setGamma(r, mGyroZ);
DeviceOrientationProfile.setAcceleration(orientation, a1);
DeviceOrientationProfile.setAccelerationIncludingGravity(orientation, a2);
DeviceOrientationProfile.setRotationRate(orientation, r);
DeviceOrientationProfile.setInterval(orientation, interval);
return orientation;
}
private void processSensorData(final SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mAccellX = sensorEvent.values[0];
mAccellY = sensorEvent.values[1];
mAccellZ = sensorEvent.values[2];
mIsAccellReady.compareAndSet(false, true);
} else if (sensorEvent.sensor.getType() == Sensor.TYPE_GRAVITY) {
mGravityX = sensorEvent.values[0];
mGravityY = sensorEvent.values[1];
mGravityZ = sensorEvent.values[2];
mIsGravityReady.compareAndSet(false, true);
} else if (sensorEvent.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
mGyroX = Math.toDegrees(sensorEvent.values[0]);
mGyroY = Math.toDegrees(sensorEvent.values[1]);
mGyroZ = Math.toDegrees(sensorEvent.values[2]);
mIsGyroReady.compareAndSet(false, true);
}
}
/**
* キャッシュされたセンサーデータを無効扱いにし、最新センサーデータが全て揃うまでデータ収集を行わせる。
*/
private void invalidateLatestData() {
mIsAccellReady.compareAndSet(true, false);
mIsGravityReady.compareAndSet(true, false);
mIsGyroReady.compareAndSet(true, false);
}
@Override
public void onSensorChanged(final SensorEvent sensorEvent) {
processSensorData(sensorEvent);
if (mIsAccellReady.get() && mIsGravityReady.get() && mIsGyroReady.get()) {
Bundle orientation = createOrientation();
mAccelLastTime = System.currentTimeMillis();
if (isEmptyEventList()) {
mSensorManager.unregisterListener(this);
return;
}
List<Event> events = EventManager.INSTANCE.getEventList(mServiceId,
DeviceOrientationProfile.PROFILE_NAME, null,
DeviceOrientationProfile.ATTRIBUTE_ON_DEVICE_ORIENTATION);
for (int i = 0; i < events.size(); i++) {
Event event = events.get(i);
Intent intent = EventManager.createEventMessage(event);
intent.putExtra(DeviceOrientationProfile.PARAM_ORIENTATION, orientation);
sendEvent(intent, event.getAccessToken());
}
}
}
@Override
public void onAccuracyChanged(final Sensor sensor, final int accuracy) {
// No operation
}
}
| イベント設定時のintervalパラメータ実装。
| dConnectDevicePlugin/dConnectDeviceHost/app/src/main/java/org/deviceconnect/android/deviceplugin/host/profile/HostDeviceOrientationProfile.java | イベント設定時のintervalパラメータ実装。 | <ide><path>ConnectDevicePlugin/dConnectDeviceHost/app/src/main/java/org/deviceconnect/android/deviceplugin/host/profile/HostDeviceOrientationProfile.java
<ide> /** 前回の加速度の計測時間を保持する. */
<ide> private long mAccelLastTime;
<ide>
<add> /** イベント送信間隔設定用. */
<add> private long mEventSendInterval;
<add>
<add> /** イベント送信間隔計測用. */
<add> private long mLastEventSendTime;
<add>
<add> /**
<add> * Device Orientationのデフォルト送信間隔を定義.
<add> */
<add> private static final long DEVICE_ORIENTATION_INTERVAL_TIME = 200;
<add>
<ide> /**
<ide> * Device Orientationのキャッシュを残す時間を定義する.
<ide> */
<ide> @Override
<ide> public boolean onRequest(final Intent request, final Intent response) {
<ide> String serviceId = getServiceID(request);
<add>
<add> try {
<add> String interval = request.getStringExtra(PARAM_INTERVAL);
<add> mEventSendInterval = Long.parseLong(interval);
<add> } catch (NumberFormatException e) {
<add> mEventSendInterval = DEVICE_ORIENTATION_INTERVAL_TIME;
<add> }
<add>
<ide> // イベントの登録
<ide> EventError error = EventManager.INSTANCE.addEvent(request);
<ide> if (error == EventError.NONE) {
<ide> return;
<ide> }
<ide>
<del> List<Event> events = EventManager.INSTANCE.getEventList(mServiceId,
<del> DeviceOrientationProfile.PROFILE_NAME, null,
<del> DeviceOrientationProfile.ATTRIBUTE_ON_DEVICE_ORIENTATION);
<del>
<del> for (int i = 0; i < events.size(); i++) {
<del> Event event = events.get(i);
<del> Intent intent = EventManager.createEventMessage(event);
<del> intent.putExtra(DeviceOrientationProfile.PARAM_ORIENTATION, orientation);
<del> sendEvent(intent, event.getAccessToken());
<add> long interval = System.currentTimeMillis() - mLastEventSendTime;
<add> if (interval > mEventSendInterval) {
<add> List<Event> events = EventManager.INSTANCE.getEventList(mServiceId,
<add> DeviceOrientationProfile.PROFILE_NAME, null,
<add> DeviceOrientationProfile.ATTRIBUTE_ON_DEVICE_ORIENTATION);
<add>
<add> for (int i = 0; i < events.size(); i++) {
<add> Event event = events.get(i);
<add> Intent intent = EventManager.createEventMessage(event);
<add> intent.putExtra(DeviceOrientationProfile.PARAM_ORIENTATION, orientation);
<add> sendEvent(intent, event.getAccessToken());
<add> }
<add> mLastEventSendTime = System.currentTimeMillis();
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | f6ffa90f3530da8c6022d53c33ee8a4ec9639ab5 | 0 | rabbitcount/incubator-groovy,dpolivaev/groovy,paulk-asert/groovy,paulk-asert/incubator-groovy,upadhyayap/incubator-groovy,apache/groovy,alien11689/groovy-core,fpavageau/groovy,eginez/incubator-groovy,kenzanmedia/incubator-groovy,taoguan/incubator-groovy,genqiang/incubator-groovy,armsargis/groovy,upadhyayap/incubator-groovy,paplorinc/incubator-groovy,yukangguo/incubator-groovy,traneHead/groovy-core,guangying945/incubator-groovy,EPadronU/incubator-groovy,groovy/groovy-core,taoguan/incubator-groovy,jwagenleitner/incubator-groovy,adjohnson916/groovy-core,ebourg/incubator-groovy,shils/incubator-groovy,shils/incubator-groovy,eginez/incubator-groovy,sagarsane/incubator-groovy,dpolivaev/groovy,antoaravinth/incubator-groovy,sagarsane/groovy-core,adjohnson916/incubator-groovy,russel/groovy,russel/incubator-groovy,alien11689/groovy-core,fpavageau/groovy,taoguan/incubator-groovy,groovy/groovy-core,guangying945/incubator-groovy,rlovtangen/groovy-core,pledbrook/incubator-groovy,shils/incubator-groovy,i55ac/incubator-groovy,groovy/groovy-core,bsideup/groovy-core,paulk-asert/groovy,graemerocher/incubator-groovy,tkruse/incubator-groovy,EPadronU/incubator-groovy,apache/incubator-groovy,genqiang/incubator-groovy,yukangguo/incubator-groovy,christoph-frick/groovy-core,alien11689/groovy-core,christoph-frick/groovy-core,rlovtangen/groovy-core,alien11689/incubator-groovy,ChanJLee/incubator-groovy,jwagenleitner/groovy,apache/incubator-groovy,avafanasiev/groovy,adjohnson916/incubator-groovy,fpavageau/groovy,gillius/incubator-groovy,alien11689/incubator-groovy,paulk-asert/incubator-groovy,eginez/incubator-groovy,samanalysis/incubator-groovy,russel/groovy,sagarsane/groovy-core,antoaravinth/incubator-groovy,samanalysis/incubator-groovy,rlovtangen/groovy-core,armsargis/groovy,jwagenleitner/incubator-groovy,i55ac/incubator-groovy,ChanJLee/incubator-groovy,paplorinc/incubator-groovy,kenzanmedia/incubator-groovy,kidaa/incubator-groovy,graemerocher/incubator-groovy,ChanJLee/incubator-groovy,shils/incubator-groovy,russel/incubator-groovy,aim-for-better/incubator-groovy,russel/incubator-groovy,adjohnson916/incubator-groovy,bsideup/groovy-core,ebourg/incubator-groovy,genqiang/incubator-groovy,fpavageau/groovy,sagarsane/groovy-core,bsideup/incubator-groovy,avafanasiev/groovy,christoph-frick/groovy-core,kidaa/incubator-groovy,sagarsane/incubator-groovy,sagarsane/groovy-core,gillius/incubator-groovy,traneHead/groovy-core,alien11689/incubator-groovy,adjohnson916/groovy-core,nobeans/incubator-groovy,pledbrook/incubator-groovy,gillius/incubator-groovy,nkhuyu/incubator-groovy,apache/incubator-groovy,tkruse/incubator-groovy,sagarsane/incubator-groovy,gillius/incubator-groovy,EPadronU/incubator-groovy,eginez/incubator-groovy,sagarsane/incubator-groovy,ebourg/incubator-groovy,bsideup/groovy-core,mariogarcia/groovy-core,bsideup/groovy-core,yukangguo/incubator-groovy,armsargis/groovy,PascalSchumacher/incubator-groovy,rlovtangen/groovy-core,PascalSchumacher/incubator-groovy,apache/groovy,aim-for-better/incubator-groovy,apache/incubator-groovy,dpolivaev/groovy,taoguan/incubator-groovy,ebourg/groovy-core,russel/incubator-groovy,pickypg/incubator-groovy,paulk-asert/incubator-groovy,kenzanmedia/incubator-groovy,EPadronU/incubator-groovy,rlovtangen/groovy-core,jwagenleitner/incubator-groovy,shils/groovy,pickypg/incubator-groovy,paplorinc/incubator-groovy,alien11689/incubator-groovy,ebourg/groovy-core,adjohnson916/groovy-core,jwagenleitner/groovy,shils/groovy,paulk-asert/incubator-groovy,aaronzirbes/incubator-groovy,bsideup/incubator-groovy,aaronzirbes/incubator-groovy,tkruse/incubator-groovy,paulk-asert/incubator-groovy,aim-for-better/incubator-groovy,jwagenleitner/groovy,ebourg/groovy-core,pledbrook/incubator-groovy,groovy/groovy-core,ChanJLee/incubator-groovy,yukangguo/incubator-groovy,kenzanmedia/incubator-groovy,dpolivaev/groovy,russel/groovy,christoph-frick/groovy-core,nkhuyu/incubator-groovy,PascalSchumacher/incubator-groovy,upadhyayap/incubator-groovy,i55ac/incubator-groovy,shils/groovy,paulk-asert/groovy,shils/groovy,avafanasiev/groovy,bsideup/incubator-groovy,christoph-frick/groovy-core,apache/groovy,kidaa/incubator-groovy,graemerocher/incubator-groovy,traneHead/groovy-core,rabbitcount/incubator-groovy,antoaravinth/incubator-groovy,bsideup/incubator-groovy,mariogarcia/groovy-core,rabbitcount/incubator-groovy,PascalSchumacher/incubator-groovy,adjohnson916/incubator-groovy,sagarsane/groovy-core,PascalSchumacher/incubator-groovy,samanalysis/incubator-groovy,aaronzirbes/incubator-groovy,alien11689/groovy-core,aaronzirbes/incubator-groovy,armsargis/groovy,ebourg/incubator-groovy,genqiang/incubator-groovy,guangying945/incubator-groovy,mariogarcia/groovy-core,mariogarcia/groovy-core,nobeans/incubator-groovy,antoaravinth/incubator-groovy,kidaa/incubator-groovy,ebourg/groovy-core,rabbitcount/incubator-groovy,alien11689/groovy-core,aim-for-better/incubator-groovy,avafanasiev/groovy,traneHead/groovy-core,pickypg/incubator-groovy,adjohnson916/groovy-core,samanalysis/incubator-groovy,groovy/groovy-core,i55ac/incubator-groovy,paplorinc/incubator-groovy,jwagenleitner/incubator-groovy,guangying945/incubator-groovy,pledbrook/incubator-groovy,nkhuyu/incubator-groovy,paulk-asert/groovy,nobeans/incubator-groovy,apache/groovy,nobeans/incubator-groovy,pickypg/incubator-groovy,russel/groovy,graemerocher/incubator-groovy,nkhuyu/incubator-groovy,jwagenleitner/groovy,ebourg/groovy-core,tkruse/incubator-groovy,adjohnson916/groovy-core,mariogarcia/groovy-core,upadhyayap/incubator-groovy | /*
* Copyright 2003-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.vmplugin.v7;
import groovy.lang.AdaptingMetaClass;
import groovy.lang.GString;
import groovy.lang.GroovyObject;
import groovy.lang.GroovyRuntimeException;
import groovy.lang.GroovySystem;
import groovy.lang.MetaClass;
import groovy.lang.MetaClassImpl;
import groovy.lang.MetaMethod;
import groovy.lang.MetaObjectProtocol;
import groovy.lang.MissingMethodException;
import java.lang.invoke.*;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigInteger;
import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.reflection.CachedMethod;
import org.codehaus.groovy.runtime.NullObject;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.metaclass.DefaultMetaClassInfo;
import org.codehaus.groovy.runtime.metaclass.MissingMethodExecutionFailed;
import org.codehaus.groovy.runtime.metaclass.NewInstanceMetaMethod;
import org.codehaus.groovy.runtime.metaclass.ReflectionMetaMethod;
import org.codehaus.groovy.runtime.metaclass.DefaultMetaClassInfo.ConstantMetaClassVersioning;
import org.codehaus.groovy.runtime.wrappers.Wrapper;
/**
* Bytecode level interface for bootstrap methods used by invokedynamic.
*
* @author <a href="mailto:[email protected]">Jochen "blackdrag" Theodorou</a>
*/
public class IndyInterface {
/*
* notes:
* MethodHandles#dropArguments:
* invocation with (a,b,c), drop first 2 results in invocation
* with (a) only.
* MethodHandles#insertArguments:
* invocation with (a,b,c), insert (x,y) results in error.
* first need to add with addParameters (X,Y), then bind them with
* insert
*/
private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
private static final MethodHandle SELECT_METHOD;
static {
MethodType mt = MethodType.methodType(Object.class, MutableCallSite.class, Class.class, String.class, Boolean.class, Boolean.class, Object.class, Object[].class);
try {
SELECT_METHOD = LOOKUP.findStatic(IndyInterface.class, "selectMethod", mt);
} catch (Exception e) {
throw new GroovyBugError(e);
}
}
private static final MethodType GENERAL_INVOKER_SIGNATURE = MethodType.methodType(Object.class, Object.class, Object[].class);
private static final MethodType INVOKE_METHOD_SIGNATURE = MethodType.methodType(Object.class, Class.class, Object.class, String.class, Object[].class, boolean.class, boolean.class);
private static final MethodType O2O = MethodType.methodType(Object.class, Object.class);
private static final MethodHandle
UNWRAP_METHOD, TO_STRING, TO_BYTE,
TO_BIGINT, SAME_MC, IS_NULL,
IS_NOT_NULL, UNWRAP_EXCEPTION, SAME_CLASS,
META_METHOD_INVOKER, GROOVY_OBJECT_INVOKER;
static {
try {
UNWRAP_METHOD = LOOKUP.findStatic(IndyInterface.class, "unwrap", O2O);
TO_STRING = LOOKUP.findStatic(IndyInterface.class, "coerceToString", MethodType.methodType(String.class, Object.class));
TO_BYTE = LOOKUP.findStatic(IndyInterface.class, "coerceToByte", O2O);
TO_BIGINT = LOOKUP.findStatic(IndyInterface.class, "coerceToBigInt", O2O);
SAME_MC = LOOKUP.findStatic(IndyInterface.class, "isSameMetaClass", MethodType.methodType(boolean.class, MetaClass.class, Object.class));
IS_NULL = LOOKUP.findStatic(IndyInterface.class, "isNull", MethodType.methodType(boolean.class, Object.class));
IS_NOT_NULL = LOOKUP.findStatic(IndyInterface.class, "isNotNull", MethodType.methodType(boolean.class, Object.class));
UNWRAP_EXCEPTION = LOOKUP.findStatic(IndyInterface.class, "unwrap", MethodType.methodType(Object.class, GroovyRuntimeException.class));
SAME_CLASS = LOOKUP.findStatic(IndyInterface.class, "sameClass", MethodType.methodType(boolean.class, Class.class, Object.class));
META_METHOD_INVOKER = LOOKUP.findVirtual(MetaMethod.class, "invoke", GENERAL_INVOKER_SIGNATURE);
GROOVY_OBJECT_INVOKER = LOOKUP.findStatic(IndyInterface.class, "invokeGroovyObjectInvoker", MethodType.methodType(Object.class, MissingMethodException.class, Object.class, String.class, Object[].class));
} catch (Exception e) {
throw new GroovyBugError(e);
}
}
private static final MethodHandle NULL_REF = MethodHandles.constant(Object.class, null);
private static final MethodHandle VALID_MC_VERSION;
static {
try {
VALID_MC_VERSION = LOOKUP.findVirtual(ConstantMetaClassVersioning.class, "isValid", MethodType.methodType(boolean.class));
} catch (Exception e) {
throw new GroovyBugError(e);
}
}
// the 4 entry points from bytecode
public static CallSite bootstrapCurrent(Lookup caller, String name, MethodType type) {
return realBootstrap(caller, name, type, false, true);
}
public static CallSite bootstrapCurrentSafe(Lookup caller, String name, MethodType type) {
return realBootstrap(caller, name, type, true, true);
}
public static CallSite bootstrap(Lookup caller, String name, MethodType type) {
return realBootstrap(caller, name, type, false, false);
}
public static CallSite bootstrapSafe(Lookup caller, String name, MethodType type) {
return realBootstrap(caller, name, type, true, false);
}
private static CallSite realBootstrap(Lookup caller, String name, MethodType type, boolean safe, boolean thisCall) {
// since indy does not give us the runtime types
// we produce first a dummy call site, which then changes the target to one,
// that does the method selection including the the direct call to the
// real method.
MutableCallSite mc = new MutableCallSite(type);
MethodHandle mh = makeFallBack(mc,caller.lookupClass(),name,type,safe,thisCall);
mc.setTarget(mh);
return mc;
}
private static MethodHandle makeFallBack(MutableCallSite mc, Class<?> sender, String name, MethodType type, boolean safeNavigation, boolean thisCall) {
MethodHandle mh = MethodHandles.insertArguments(SELECT_METHOD, 0, mc, sender, name, safeNavigation, thisCall, /*dummy receiver:*/ 1);
mh = mh.asCollector(Object[].class, type.parameterCount()).
asType(type);
return mh;
}
private static Class getClass(Object x) {
if (x instanceof Class) return (Class) x;
return x.getClass();
}
private static MetaClass getMetaClass(Object receiver) {
if (receiver == null) {
return NullObject.getNullObject().getMetaClass();
} else if (receiver instanceof GroovyObject) {
return ((GroovyObject) receiver).getMetaClass();
} else {
return GroovySystem.getMetaClassRegistry().getMetaClass(getClass(receiver));
}
}
private static class CallInfo {
public Object[] args;
public MetaMethod method;
public MethodType targetType;
public String methodName;
public MethodHandle handle;
public boolean useMetaClass = false;
public MutableCallSite callSite;
public Class sender;
public boolean isVargs;
public boolean safeNavigation;
public boolean thisCall;
public Class methodSelectionBase;
}
private static boolean isStatic(Method m) {
int mods = m.getModifiers();
return (mods & Modifier.STATIC) != 0;
}
private static void setHandleForMetaMethod(CallInfo info) {
MetaMethod metaMethod = info.method;
boolean isCategoryTypeMethod = metaMethod instanceof NewInstanceMetaMethod;
if (metaMethod instanceof ReflectionMetaMethod) {
ReflectionMetaMethod rmm = (ReflectionMetaMethod) metaMethod;
metaMethod = rmm.getCachedMethod();
}
if (metaMethod instanceof CachedMethod) {
CachedMethod cm = (CachedMethod) metaMethod;
info.isVargs = cm.isVargsMethod();
try {
Method m = cm.getCachedMethod();
info.handle = LOOKUP.unreflect(m);
if (!isCategoryTypeMethod && isStatic(m)) {
info.handle = MethodHandles.dropArguments(info.handle, 0, Class.class);
}
} catch (IllegalAccessException e) {
throw new GroovyBugError(e);
}
} else if (info.method != null) {
// dgm method helper path
info.handle = META_METHOD_INVOKER;
info.handle = info.handle.bindTo(info.method);
if (info.method.getNativeParameterTypes().length==1 &&
info.args.length==1)
{
// the method expects a parameter but we don't provide an
// argument for that. So we give in a Object[], containing
// a null value
// since MethodHandles.insertArguments is a vargs method giving
// only the array would be like just giving a null value, so
// we need to wrap the array that represents our argument in
// another one for the vargs call
info.handle = MethodHandles.insertArguments(info.handle, 1, new Object[]{new Object[]{null}});
} else if (info.method.isVargsMethod()) {
// the method expects the arguments as Object[] in a Object[]
info.handle = info.handle.asCollector(Object[].class, 1);
info.handle = info.handle.asCollector(Object[].class, info.targetType.parameterCount()-1);
} else {
info.handle = info.handle.asCollector(Object[].class, info.targetType.parameterCount()-1);
}
}
}
private static void chooseMethod(MetaClass mc, CallInfo ci) {
if (!(mc instanceof MetaClassImpl) || mc instanceof AdaptingMetaClass) {return;}
MetaClassImpl mci = (MetaClassImpl) mc;
Object receiver = ci.args[0];
if (receiver==null) {
receiver = NullObject.getNullObject();
}
if (receiver instanceof Class) {
ci.method = mci.retrieveStaticMethod(ci.methodName, removeRealReceiver(ci.args));
} else {
ci.method = mci.getMethodWithCaching(ci.methodSelectionBase, ci.methodName, removeRealReceiver(ci.args), false);
}
}
private static void setMetaClassCallHandleIfNedded(MetaClass mc, CallInfo ci) {
if (ci.handle!=null) return;
try {
ci.useMetaClass = true;
Object receiver = ci.args[0];
if (receiver instanceof Class) {
ci.handle = LOOKUP.findVirtual(mc.getClass(), "invokeStaticMethod", MethodType.methodType(Object.class, Object.class, String.class, Object[].class));
ci.handle = ci.handle.bindTo(mc);
} else {
boolean useShortForm = mc instanceof AdaptingMetaClass;
if (useShortForm) {
ci.handle = LOOKUP.findVirtual(MetaObjectProtocol.class, "invokeMethod", MethodType.methodType(Object.class, Object.class, String.class, Object[].class));
} else {
ci.handle = LOOKUP.findVirtual(MetaClass.class, "invokeMethod", INVOKE_METHOD_SIGNATURE);
ci.handle = MethodHandles.insertArguments(ci.handle, ci.handle.type().parameterCount()-2, false, true);
}
ci.handle = ci.handle.bindTo(mc);
if (!useShortForm) {
ci.handle = ci.handle.bindTo(ci.methodSelectionBase);
}
if (receiver instanceof GroovyObject) {
// if the meta class call fails we may still want to fall back to call
// GroovyObject#invokeMethod if the receiver is a GroovyObject
ci.handle = MethodHandles.catchException(ci.handle, MissingMethodException.class, GROOVY_OBJECT_INVOKER);
}
}
ci.handle = MethodHandles.insertArguments(ci.handle, 1, ci.methodName);
ci.handle = ci.handle.asCollector(Object[].class, ci.targetType.parameterCount()-1);
} catch (Exception e) {
throw new GroovyBugError(e);
}
}
/**
* called by handle
*/
public static Object invokeGroovyObjectInvoker(MissingMethodException e, Object receiver, String name, Object[] args) {
if (e instanceof MissingMethodExecutionFailed) {
throw (MissingMethodException)e.getCause();
} else if (receiver.getClass() == e.getType() && e.getMethod().equals(name)) {
//TODO: we should consider calling this one directly for MetaClassImpl,
// then we save the new method selection
// in case there's nothing else, invoke the object's own invokeMethod()
return ((GroovyObject)receiver).invokeMethod(name, args);
} else {
throw e;
}
}
/**
* called by handle
*/
public static Object unwrap(GroovyRuntimeException gre) throws Throwable {
throw ScriptBytecodeAdapter.unwrap(gre);
}
/**
* called by handle
*/
public static boolean isSameMetaClass(MetaClass mc, Object receiver) {
//TODO: remove this method if possible by switchpoint usage
return receiver instanceof GroovyObject && mc==((GroovyObject)receiver).getMetaClass();
}
/**
* called by handle
*/
public static Object unwrap(Object o) {
Wrapper w = (Wrapper) o;
return w.unwrap();
}
/**
* called by handle
*/
public static String coerceToString(Object o) {
return o.toString();
}
/**
* called by handle
*/
public static Object coerceToByte(Object o) {
return new Byte(((Number) o).byteValue());
}
/**
* called by handle
*/
public static Object coerceToBigInt(Object o) {
return new BigInteger(String.valueOf((Number) o));
}
/**
* check for null - called by handle
*/
public static boolean isNull(Object o) {
return o == null;
}
/**
* check for != null - called by handle
*/
public static boolean isNotNull(Object o) {
return o != null;
}
/**
* called by handle
*/
public static boolean sameClass(Class c, Object o) {
if (o==null) return false;
return o.getClass() == c;
}
private static void correctWrapping(CallInfo ci) {
if (ci.useMetaClass) return;
Class[] pt = ci.handle.type().parameterArray();
for (int i=1; i<ci.args.length; i++) {
if (ci.args[i] instanceof Wrapper) {
Class type = pt[i];
MethodType mt = MethodType.methodType(type, Object.class);
ci.handle = MethodHandles.filterArguments(ci.handle, i, UNWRAP_METHOD.asType(mt));
}
}
}
private static void correctCoerce(CallInfo ci) {
if (ci.useMetaClass) return;
Class[] parameters = ci.handle.type().parameterArray();
if (ci.args.length != parameters.length) {
throw new GroovyBugError("at this point argument array length and parameter array length should be the same");
}
for (int i=1; i<ci.args.length; i++) {
Object arg = ci.args[i];
if (arg==null) continue;
Class got = arg.getClass();
if (arg instanceof GString && parameters[i] == String.class) {
ci.handle = MethodHandles.filterArguments(ci.handle, i, TO_STRING);
} else if (parameters[i] == Byte.class && got != Byte.class) {
ci.handle = MethodHandles.filterArguments(ci.handle, i, TO_BYTE);
} else if (parameters[i] == BigInteger.class && got != BigInteger.class) {
ci.handle = MethodHandles.filterArguments(ci.handle, i, TO_BIGINT);
}
}
}
private static void correctNullReceiver(CallInfo ci){
if (ci.args[0]!=null) return;
ci.handle = ci.handle.bindTo(NullObject.getNullObject());
ci.handle = MethodHandles.dropArguments(ci.handle, 0, ci.targetType.parameterType(0));
}
private static void setGuards(CallInfo ci, Object receiver) {
if (ci.handle==null) return;
MethodHandle fallback = makeFallBack(ci.callSite, ci.sender, ci.methodName, ci.targetType, ci.safeNavigation, ci.thisCall);
// special guards for receiver
MethodHandle test=null;
if (receiver instanceof GroovyObject) {
GroovyObject go = (GroovyObject) receiver;
MetaClass mc = (MetaClass) go.getMetaClass();
test = SAME_MC.bindTo(mc);
// drop dummy receiver
test = test.asType(MethodType.methodType(boolean.class,ci.targetType.parameterType(0)));
} else if (receiver != null) {
// handle constant meta class
ConstantMetaClassVersioning mcv = DefaultMetaClassInfo.getCurrentConstantMetaClassVersioning();
test = VALID_MC_VERSION.bindTo(mcv);
ci.handle = MethodHandles.guardWithTest(test, ci.handle, fallback);
// check for not being null
test = IS_NOT_NULL.asType(MethodType.methodType(boolean.class,ci.targetType.parameterType(0)));
}
if (test!=null) {
ci.handle = MethodHandles.guardWithTest(test, ci.handle, fallback);
}
// guards for receiver and parameter
Class[] pt = ci.handle.type().parameterArray();
for (int i=0; i<ci.args.length; i++) {
Object arg = ci.args[i];
if (arg==null) {
test = IS_NULL.asType(MethodType.methodType(boolean.class, pt[i]));
} else {
Class argClass = arg.getClass();
test = SAME_CLASS.
bindTo(argClass).
asType(MethodType.methodType(boolean.class, pt[i]));
}
Class[] drops = new Class[i];
for (int j=0; j<drops.length; j++) drops[j] = pt[j];
test = MethodHandles.dropArguments(test, 0, drops);
ci.handle = MethodHandles.guardWithTest(test, ci.handle, fallback);
}
}
private static void correctParameterLenth(CallInfo info) {
Class[] params = info.handle.type().parameterArray();
if (info.handle==null) return;
if (!info.isVargs) {
if (params.length != info.args.length) {
//TODO: add null argument
}
return;
}
Class lastParam = params[params.length-1];
Object lastArg = info.args[info.args.length-1];
if (params.length == info.args.length) {
// may need rewrap
if (lastParam == lastArg || lastArg == null) return;
if (lastParam.isInstance(lastArg)) return;
// arg is not null and not assignment compatible
// so we really need to rewrap
info.handle = info.handle.asCollector(lastParam, 1);
} else if (params.length > info.args.length) {
// we depend on the method selection having done a good
// job before already, so the only case for this here is, that
// we have no argument for the array, meaning params.length is
// args.length+1. In that case we have to fill in an empty array
info.handle = MethodHandles.insertArguments(info.handle, params.length-1, Array.newInstance(lastParam.getComponentType(), 0));
} else { //params.length < args.length
// we depend on the method selection having done a good
// job before already, so the only case for this here is, that
// all trailing arguments belong into the vargs array
info.handle = info.handle.asCollector(
lastParam,
info.args.length - params.length + 1);
}
}
private static void addExceptionHandler(CallInfo info) {
if (info.handle==null) return;
MethodType returnType = MethodType.methodType(info.handle.type().returnType(), GroovyRuntimeException.class);
info.handle = MethodHandles.catchException(info.handle, GroovyRuntimeException.class, UNWRAP_EXCEPTION.asType(returnType));
}
private static boolean setNullForSafeNavigation(CallInfo info) {
if (!info.safeNavigation) return false;
info.handle = MethodHandles.dropArguments(NULL_REF,0,info.targetType.parameterArray());
return true;
}
private static void setMethodSelectionBase(CallInfo ci, MetaClass mc) {
if (ci.thisCall) {
ci.methodSelectionBase = ci.sender;
} else if (ci.args[0]==null) {
ci.methodSelectionBase = NullObject.class;
} else {
ci.methodSelectionBase = mc.getTheClass();
}
}
public static Object selectMethod(MutableCallSite callSite, Class sender, String methodName, Boolean safeNavigation, Boolean thisCall, Object dummyReceiver, Object[] arguments) throws Throwable {
//TODO: handle GroovyInterceptable
CallInfo callInfo = new CallInfo();
callInfo.targetType = callSite.type();
callInfo.methodName = methodName;
callInfo.args = arguments;
callInfo.callSite = callSite;
callInfo.sender = sender;
callInfo.safeNavigation = safeNavigation && arguments[0]==null;
callInfo.thisCall = thisCall;
if (!setNullForSafeNavigation(callInfo)) {
// setInterceptableHandle(callInfo);
MetaClass mc = getMetaClass(callInfo.args[0]);
setMethodSelectionBase(callInfo, mc);
chooseMethod(mc, callInfo);
setHandleForMetaMethod(callInfo);
setMetaClassCallHandleIfNedded(mc, callInfo);
correctWrapping(callInfo);
correctParameterLenth(callInfo);
correctCoerce(callInfo);
correctNullReceiver(callInfo);
try {
callInfo.handle = callInfo.handle.asType(callInfo.targetType);
} catch (Exception e) {
System.err.println("ERROR while processing "+methodName);
throw e;
}
addExceptionHandler(callInfo);
}
setGuards(callInfo, callInfo.args[0]);
callSite.setTarget(callInfo.handle);
return callInfo.handle.invokeWithArguments(callInfo.args);
}
private static Object[] removeRealReceiver(Object[] args) {
Object[] ar = new Object[args.length-1];
for (int i=1; i<args.length; i++) {
ar[i-1] = args[i];
}
return ar;
}
}
| src/main/org/codehaus/groovy/vmplugin/v7/IndyInterface.java | /*
* Copyright 2003-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.vmplugin.v7;
import groovy.lang.AdaptingMetaClass;
import groovy.lang.GString;
import groovy.lang.GroovyObject;
import groovy.lang.GroovyRuntimeException;
import groovy.lang.GroovySystem;
import groovy.lang.MetaClass;
import groovy.lang.MetaClassImpl;
import groovy.lang.MetaMethod;
import groovy.lang.MetaObjectProtocol;
import groovy.lang.MissingMethodException;
import java.lang.invoke.*;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigInteger;
import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.reflection.CachedMethod;
import org.codehaus.groovy.runtime.NullObject;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.metaclass.DefaultMetaClassInfo;
import org.codehaus.groovy.runtime.metaclass.MissingMethodExecutionFailed;
import org.codehaus.groovy.runtime.metaclass.NewInstanceMetaMethod;
import org.codehaus.groovy.runtime.metaclass.ReflectionMetaMethod;
import org.codehaus.groovy.runtime.metaclass.DefaultMetaClassInfo.ConstantMetaClassVersioning;
import org.codehaus.groovy.runtime.wrappers.Wrapper;
/**
* Bytecode level interface for bootstrap methods used by invokedynamic.
*
* @author <a href="mailto:[email protected]">Jochen "blackdrag" Theodorou</a>
*/
public class IndyInterface {
/*
* notes:
* MethodHandles#dropArguments:
* invocation with (a,b,c), drop first 2 results in invocation
* with (a) only.
* MethodHandles#insertArguments:
* invocation with (a,b,c), insert (x,y) results in error.
* first need to add with addParameters (X,Y), then bind them with
* insert
*/
private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
private static final MethodHandle SELECT_METHOD;
static {
MethodType mt = MethodType.methodType(Object.class, MutableCallSite.class, Class.class, String.class, Boolean.class, Boolean.class, Object.class, Object[].class);
try {
SELECT_METHOD = LOOKUP.findStatic(IndyInterface.class, "selectMethod", mt);
} catch (Exception e) {
throw new GroovyBugError(e);
}
}
private static final MethodType GENERAL_INVOKER_SIGNATURE = MethodType.methodType(Object.class, Object.class, Object[].class);
private static final MethodType INVOKE_METHOD_SIGNATURE = MethodType.methodType(Object.class, Class.class, Object.class, String.class, Object[].class, boolean.class, boolean.class);
private static final MethodType O2O = MethodType.methodType(Object.class, Object.class);
private static final MethodHandle
UNWRAP_METHOD, TO_STRING, TO_BYTE,
TO_BIGINT, SAME_MC, IS_NULL,
IS_NOT_NULL, UNWRAP_EXCEPTION, SAME_CLASS,
META_METHOD_INVOKER, GROOVY_OBJECT_INVOKER;
static {
try {
UNWRAP_METHOD = LOOKUP.findStatic(IndyInterface.class, "unwrap", O2O);
TO_STRING = LOOKUP.findStatic(IndyInterface.class, "coerceToString", MethodType.methodType(String.class, Object.class));
TO_BYTE = LOOKUP.findStatic(IndyInterface.class, "coerceToByte", O2O);
TO_BIGINT = LOOKUP.findStatic(IndyInterface.class, "coerceToBigInt", O2O);
SAME_MC = LOOKUP.findStatic(IndyInterface.class, "isSameMetaClass", MethodType.methodType(boolean.class, MetaClass.class, Object.class));
IS_NULL = LOOKUP.findStatic(IndyInterface.class, "isNull", MethodType.methodType(boolean.class, Object.class));
IS_NOT_NULL = LOOKUP.findStatic(IndyInterface.class, "isNotNull", MethodType.methodType(boolean.class, Object.class));
UNWRAP_EXCEPTION = LOOKUP.findStatic(IndyInterface.class, "unwrap", MethodType.methodType(Object.class, GroovyRuntimeException.class));
SAME_CLASS = LOOKUP.findStatic(IndyInterface.class, "sameClass", MethodType.methodType(boolean.class, Class.class, Object.class));
META_METHOD_INVOKER = LOOKUP.findVirtual(MetaMethod.class, "invoke", GENERAL_INVOKER_SIGNATURE);
GROOVY_OBJECT_INVOKER = LOOKUP.findStatic(IndyInterface.class, "invokeGroovyObjectInvoker", MethodType.methodType(Object.class, MissingMethodException.class, Object.class, String.class, Object[].class));
} catch (Exception e) {
throw new GroovyBugError(e);
}
}
private static final MethodHandle NULL_REF = MethodHandles.constant(Object.class, null);
private static final MethodHandle VALID_MC_VERSION;
static {
try {
VALID_MC_VERSION = LOOKUP.findVirtual(ConstantMetaClassVersioning.class, "isValid", MethodType.methodType(boolean.class));
} catch (Exception e) {
throw new GroovyBugError(e);
}
}
// the 4 entry points from bytecode
public static CallSite bootstrapCurrent(Lookup caller, String name, MethodType type) {
return realBootstrap(caller, name, type, false, true);
}
public static CallSite bootstrapCurrentSafe(Lookup caller, String name, MethodType type) {
return realBootstrap(caller, name, type, true, true);
}
public static CallSite bootstrap(Lookup caller, String name, MethodType type) {
return realBootstrap(caller, name, type, false, false);
}
public static CallSite bootstrapSafe(Lookup caller, String name, MethodType type) {
return realBootstrap(caller, name, type, true, false);
}
private static CallSite realBootstrap(Lookup caller, String name, MethodType type, boolean safe, boolean thisCall) {
// since indy does not give us the runtime types
// we produce first a dummy call site, which then changes the target to one,
// that does the method selection including the the direct call to the
// real method.
MutableCallSite mc = new MutableCallSite(type);
MethodHandle mh = makeFallBack(mc,caller.lookupClass(),name,type,safe,thisCall);
mc.setTarget(mh);
return mc;
}
private static MethodHandle makeFallBack(MutableCallSite mc, Class<?> sender, String name, MethodType type, boolean safeNavigation, boolean thisCall) {
MethodHandle mh = MethodHandles.insertArguments(SELECT_METHOD, 0, mc, sender, name, safeNavigation, thisCall, /*dummy receiver:*/ 1);
mh = mh.asCollector(Object[].class, type.parameterCount()).
asType(type);
return mh;
}
private static Class getClass(Object x) {
if (x instanceof Class) return (Class) x;
return x.getClass();
}
private static MetaClass getMetaClass(Object receiver) {
if (receiver == null) {
return NullObject.getNullObject().getMetaClass();
} else if (receiver instanceof GroovyObject) {
return ((GroovyObject) receiver).getMetaClass();
} else {
return GroovySystem.getMetaClassRegistry().getMetaClass(getClass(receiver));
}
}
private static class CallInfo {
public Object[] args;
public MetaMethod method;
public MethodType targetType;
public String methodName;
public MethodHandle handle;
public boolean useMetaClass = false;
public MutableCallSite callSite;
public Class sender;
public boolean isVargs;
public boolean safeNavigation;
public boolean thisCall;
public Class methodSelectionBase;
}
private static boolean isStatic(Method m) {
int mods = m.getModifiers();
return (mods & Modifier.STATIC) != 0;
}
private static void setHandleForMetaMethod(CallInfo info) {
MetaMethod metaMethod = info.method;
boolean isCategoryTypeMethod = metaMethod instanceof NewInstanceMetaMethod;
if (metaMethod instanceof ReflectionMetaMethod) {
ReflectionMetaMethod rmm = (ReflectionMetaMethod) metaMethod;
metaMethod = rmm.getCachedMethod();
}
if (metaMethod instanceof CachedMethod) {
CachedMethod cm = (CachedMethod) metaMethod;
info.isVargs = cm.isVargsMethod();
try {
Method m = cm.getCachedMethod();
info.handle = LOOKUP.unreflect(m);
if (!isCategoryTypeMethod && isStatic(m)) {
info.handle = MethodHandles.dropArguments(info.handle, 0, Class.class);
}
} catch (IllegalAccessException e) {
throw new GroovyBugError(e);
}
} else if (info.method != null) {
// dgm method helper path
info.handle = META_METHOD_INVOKER;
info.handle = info.handle.bindTo(info.method);
if (info.method.getNativeParameterTypes().length==1 &&
info.args.length==1)
{
// the method expects a parameter but we don't provide an
// argument for that. So we give in a Object[], containing
// a null value
// since MethodHandles.insertArguments is a vargs method giving
// only the array would be like just giving a null value, so
// we need to wrap the array that represents our argument in
// another one for the vargs call
info.handle = MethodHandles.insertArguments(info.handle, 1, new Object[]{new Object[]{null}});
} else if (info.method.isVargsMethod()) {
// the method expects the arguments as Object[] in a Object[]
info.handle = info.handle.asCollector(Object[].class, 1);
info.handle = info.handle.asCollector(Object[].class, info.targetType.parameterCount()-1);
} else {
info.handle = info.handle.asCollector(Object[].class, info.targetType.parameterCount()-1);
}
}
}
private static void chooseMethod(MetaClass mc, CallInfo ci) {
if (!(mc instanceof MetaClassImpl) || mc instanceof AdaptingMetaClass) {return;}
MetaClassImpl mci = (MetaClassImpl) mc;
Object receiver = ci.args[0];
if (receiver==null) {
receiver = NullObject.getNullObject();
}
if (receiver instanceof Class) {
ci.method = mci.retrieveStaticMethod(ci.methodName, removeRealReceiver(ci.args));
} else {
ci.method = mci.getMethodWithCaching(ci.methodSelectionBase, ci.methodName, removeRealReceiver(ci.args), false);
}
}
private static void setMetaClassCallHandleIfNedded(MetaClass mc, CallInfo ci) {
if (ci.handle!=null) return;
try {
ci.useMetaClass = true;
Object receiver = ci.args[0];
if (receiver instanceof Class) {
ci.handle = LOOKUP.findVirtual(mc.getClass(), "invokeStaticMethod", MethodType.methodType(Object.class, Object.class, String.class, Object[].class));
ci.handle = ci.handle.bindTo(mc);
} else {
boolean useShortForm = mc instanceof AdaptingMetaClass;
if (useShortForm) {
ci.handle = LOOKUP.findVirtual(MetaObjectProtocol.class, "invokeMethod", MethodType.methodType(Object.class, Object.class, String.class, Object[].class));
} else {
ci.handle = LOOKUP.findVirtual(MetaClass.class, "invokeMethod", INVOKE_METHOD_SIGNATURE);
ci.handle = MethodHandles.insertArguments(ci.handle, ci.handle.type().parameterCount()-2, false, true);
}
ci.handle = ci.handle.bindTo(mc);
if (!useShortForm) {
ci.handle = ci.handle.bindTo(ci.methodSelectionBase);
}
if (receiver instanceof GroovyObject) {
// if the meta class call fails we may still want to fall back to call
// GroovyObject#invokeMethod if the receiver is a GroovyObject
ci.handle = MethodHandles.catchException(ci.handle, MissingMethodException.class, GROOVY_OBJECT_INVOKER);
}
}
ci.handle = MethodHandles.insertArguments(ci.handle, 1, ci.methodName);
ci.handle = ci.handle.asCollector(Object[].class, ci.targetType.parameterCount()-1);
} catch (Exception e) {
throw new GroovyBugError(e);
}
}
/**
* called by handle
*/
public static Object invokeGroovyObjectInvoker(MissingMethodException e, Object receiver, String name, Object[] args) {
if (e instanceof MissingMethodExecutionFailed) {
throw (MissingMethodException)e.getCause();
} else if (receiver.getClass() == e.getType() && e.getMethod().equals(name)) {
//TODO: we should consider calling this one directly for MetaClassImpl,
// then we save the new method selection
// in case there's nothing else, invoke the object's own invokeMethod()
return ((GroovyObject)receiver).invokeMethod(name, args);
} else {
throw e;
}
}
/**
* called by handle
*/
public static Object unwrap(GroovyRuntimeException gre) throws Throwable {
throw ScriptBytecodeAdapter.unwrap(gre);
}
/**
* called by handle
*/
public static boolean isSameMetaClass(MetaClass mc, Object receiver) {
//TODO: remove this method if possible by switchpoint usage
return receiver instanceof GroovyObject && mc==((GroovyObject)receiver).getMetaClass();
}
/**
* called by handle
*/
public static Object unwrap(Object o) {
Wrapper w = (Wrapper) o;
return w.unwrap();
}
/**
* called by handle
*/
public static String coerceToString(Object o) {
return o.toString();
}
/**
* called by handle
*/
public static Object coerceToByte(Object o) {
return new Byte(((Number) o).byteValue());
}
/**
* called by handle
*/
public static Object coerceToBigInt(Object o) {
return new BigInteger(String.valueOf((Number) o));
}
/**
* check for null - called by handle
*/
public static boolean isNull(Object o) {
return o == null;
}
/**
* check for != null - called by handle
*/
public static boolean isNotNull(Object o) {
return o != null;
}
/**
* called by handle
*/
public static boolean sameClass(Class c, Object o) {
if (o==null) return false;
return o.getClass() == c;
}
private static void correctWrapping(CallInfo ci) {
if (ci.useMetaClass) return;
Class[] pt = ci.handle.type().parameterArray();
for (int i=1; i<ci.args.length; i++) {
if (ci.args[i] instanceof Wrapper) {
Class type = pt[i];
MethodType mt = MethodType.methodType(type, Object.class);
ci.handle = MethodHandles.filterArguments(ci.handle, i, UNWRAP_METHOD.asType(mt));
}
}
}
private static void correctCoerce(CallInfo ci) {
if (ci.useMetaClass) return;
Class[] parameters = ci.handle.type().parameterArray();
if (ci.args.length != parameters.length) {
throw new GroovyBugError("at this point argument array length and parameter array length should be the same");
}
for (int i=1; i<ci.args.length; i++) {
Object arg = ci.args[i];
if (arg==null) continue;
Class got = arg.getClass();
if (arg instanceof GString && parameters[i] == String.class) {
ci.handle = MethodHandles.filterArguments(ci.handle, i, TO_STRING);
} else if (parameters[i] == Byte.class && got != Byte.class) {
ci.handle = MethodHandles.filterArguments(ci.handle, i, TO_BYTE);
} else if (parameters[i] == BigInteger.class && got != BigInteger.class) {
ci.handle = MethodHandles.filterArguments(ci.handle, i, TO_BIGINT);
}
}
}
private static void correctNullReceiver(CallInfo ci){
if (ci.args[0]!=null) return;
ci.handle = ci.handle.bindTo(NullObject.getNullObject());
ci.handle = MethodHandles.dropArguments(ci.handle, 0, ci.targetType.parameterType(0));
}
private static void dropDummyReceiver(CallInfo ci) {
ci.handle = MethodHandles.dropArguments(ci.handle, 0, Integer.class);
ci.handle = MethodHandles.insertArguments(ci.handle, 0, 1);
}
private static void setGuards(CallInfo ci, Object receiver) {
if (ci.handle==null) return;
MethodHandle fallback = makeFallBack(ci.callSite, ci.sender, ci.methodName, ci.targetType, ci.safeNavigation, ci.thisCall);
// special guards for receiver
MethodHandle test=null;
if (receiver instanceof GroovyObject) {
GroovyObject go = (GroovyObject) receiver;
MetaClass mc = (MetaClass) go.getMetaClass();
test = SAME_MC.bindTo(mc);
// drop dummy receiver
test = test.asType(MethodType.methodType(boolean.class,ci.targetType.parameterType(0)));
} else if (receiver != null) {
// handle constant meta class
ConstantMetaClassVersioning mcv = DefaultMetaClassInfo.getCurrentConstantMetaClassVersioning();
test = VALID_MC_VERSION.bindTo(mcv);
ci.handle = MethodHandles.guardWithTest(test, ci.handle, fallback);
// check for not being null
test = IS_NOT_NULL.asType(MethodType.methodType(boolean.class,ci.targetType.parameterType(0)));
}
if (test!=null) {
ci.handle = MethodHandles.guardWithTest(test, ci.handle, fallback);
}
// guards for receiver and parameter
Class[] pt = ci.handle.type().parameterArray();
for (int i=0; i<ci.args.length; i++) {
Object arg = ci.args[i];
if (arg==null) {
test = IS_NULL.asType(MethodType.methodType(boolean.class, pt[i]));
} else {
Class argClass = arg.getClass();
test = SAME_CLASS.
bindTo(argClass).
asType(MethodType.methodType(boolean.class, pt[i]));
}
Class[] drops = new Class[i];
for (int j=0; j<drops.length; j++) drops[j] = pt[j];
test = MethodHandles.dropArguments(test, 0, drops);
ci.handle = MethodHandles.guardWithTest(test, ci.handle, fallback);
}
}
private static void correctParameterLenth(CallInfo info) {
Class[] params = info.handle.type().parameterArray();
if (info.handle==null) return;
if (!info.isVargs) {
if (params.length != info.args.length) {
//TODO: add null argument
}
return;
}
Class lastParam = params[params.length-1];
Object lastArg = info.args[info.args.length-1];
if (params.length == info.args.length) {
// may need rewrap
if (lastParam == lastArg || lastArg == null) return;
if (lastParam.isInstance(lastArg)) return;
// arg is not null and not assignment compatible
// so we really need to rewrap
info.handle = info.handle.asCollector(lastParam, 1);
} else if (params.length > info.args.length) {
// we depend on the method selection having done a good
// job before already, so the only case for this here is, that
// we have no argument for the array, meaning params.length is
// args.length+1. In that case we have to fill in an empty array
info.handle = MethodHandles.insertArguments(info.handle, params.length-1, Array.newInstance(lastParam.getComponentType(), 0));
} else { //params.length < args.length
// we depend on the method selection having done a good
// job before already, so the only case for this here is, that
// all trailing arguments belong into the vargs array
info.handle = info.handle.asCollector(
lastParam,
info.args.length - params.length + 1);
}
}
private static void addExceptionHandler(CallInfo info) {
if (info.handle==null) return;
MethodType returnType = MethodType.methodType(info.handle.type().returnType(), GroovyRuntimeException.class);
info.handle = MethodHandles.catchException(info.handle, GroovyRuntimeException.class, UNWRAP_EXCEPTION.asType(returnType));
}
private static boolean setNullForSafeNavigation(CallInfo info) {
if (!info.safeNavigation) return false;
info.handle = MethodHandles.dropArguments(NULL_REF,0,info.targetType.parameterArray());
return true;
}
private static void setMethodSelectionBase(CallInfo ci, MetaClass mc) {
if (ci.thisCall) {
ci.methodSelectionBase = ci.sender;
} else if (ci.args[0]==null) {
ci.methodSelectionBase = NullObject.class;
} else {
ci.methodSelectionBase = mc.getTheClass();
}
}
public static Object selectMethod(MutableCallSite callSite, Class sender, String methodName, Boolean safeNavigation, Boolean thisCall, Object dummyReceiver, Object[] arguments) throws Throwable {
//TODO: handle GroovyInterceptable
CallInfo callInfo = new CallInfo();
callInfo.targetType = callSite.type();
callInfo.methodName = methodName;
callInfo.args = arguments;
callInfo.callSite = callSite;
callInfo.sender = sender;
callInfo.safeNavigation = safeNavigation && arguments[0]==null;
callInfo.thisCall = thisCall;
if (!setNullForSafeNavigation(callInfo)) {
// setInterceptableHandle(callInfo);
MetaClass mc = getMetaClass(callInfo.args[0]);
setMethodSelectionBase(callInfo, mc);
chooseMethod(mc, callInfo);
setHandleForMetaMethod(callInfo);
setMetaClassCallHandleIfNedded(mc, callInfo);
correctWrapping(callInfo);
correctParameterLenth(callInfo);
correctCoerce(callInfo);
correctNullReceiver(callInfo);
dropDummyReceiver(callInfo);
try {
callInfo.handle = callInfo.handle.asType(callInfo.targetType);
} catch (Exception e) {
System.err.println("ERROR while processing "+methodName);
throw e;
}
addExceptionHandler(callInfo);
}
setGuards(callInfo, callInfo.args[0]);
callSite.setTarget(callInfo.handle);
return callInfo.handle.invokeWithArguments(callInfo.args);
}
private static Object[] removeRealReceiver(Object[] args) {
Object[] ar = new Object[args.length-1];
for (int i=1; i<args.length; i++) {
ar[i-1] = args[i];
}
return ar;
}
}
| remove dropDummy method, because it is no longer needed
| src/main/org/codehaus/groovy/vmplugin/v7/IndyInterface.java | remove dropDummy method, because it is no longer needed | <ide><path>rc/main/org/codehaus/groovy/vmplugin/v7/IndyInterface.java
<ide> ci.handle = MethodHandles.dropArguments(ci.handle, 0, ci.targetType.parameterType(0));
<ide> }
<ide>
<del> private static void dropDummyReceiver(CallInfo ci) {
<del> ci.handle = MethodHandles.dropArguments(ci.handle, 0, Integer.class);
<del> ci.handle = MethodHandles.insertArguments(ci.handle, 0, 1);
<del> }
<del>
<ide> private static void setGuards(CallInfo ci, Object receiver) {
<ide> if (ci.handle==null) return;
<ide>
<ide> correctParameterLenth(callInfo);
<ide> correctCoerce(callInfo);
<ide> correctNullReceiver(callInfo);
<del> dropDummyReceiver(callInfo);
<ide>
<ide> try {
<ide> callInfo.handle = callInfo.handle.asType(callInfo.targetType); |
|
Java | apache-2.0 | 683d459cc55ef1a6cd75cf28e921d81a53313e80 | 0 | TWtablero/tablero,giovaneliberato/tablero,giovaneliberato/tablero,TWtablero/tablero,giovaneliberato/tablero,giovaneliberato/tablero,TWtablero/tablero,TWtablero/tablero | package rocketboard;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.openqa.selenium.support.PageFactory;
import rocketboardPages.GitHub;
import rocketboardPages.GitHub.AuthorizePage;
public class ChangeAccessLevelTests extends AbstractRocketboardTests {
@Test
public void changeAccessLevel() throws Exception {
assertTrue(whenChangesAccessToOnlyPublic().isAuthorizePage());
}
private AuthorizePage whenChangesAccessToOnlyPublic()
throws InterruptedException {
rocketboardPage.openChangeAccess();
rocketboardPage.selectAccessToPublicReposOnly();
return PageFactory.initElements(driver, GitHub.AuthorizePage.class);
}
}
| test/spec/functionalTest/rocketboard/src/test/java/rocketboard/ChangeAccessLevelTests.java | package rocketboard;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.openqa.selenium.support.PageFactory;
import rocketboardPages.GitHub;
import rocketboardPages.GitHub.AuthorizePage;
public class ChangeAccessLevelTests extends AbstractRocketboardTests {
@Test
public void changeAccessLevel() throws Exception {
givenTableroAccessToPrivateRepositories();
assertTrue(whenChangesAccessToOnlyPublic().isAuthorizePage());
}
private AuthorizePage whenChangesAccessToOnlyPublic()
throws InterruptedException {
rocketboardPage.openChangeAccess();
rocketboardPage.selectAccessToPublicReposOnly();
return PageFactory.initElements(driver, GitHub.AuthorizePage.class);
}
private void givenTableroAccessToPrivateRepositories()
throws Exception {
rocketboardPage.waitingLoading();
}
}
| Remove unnecessary method on ChangeAccessLevelTests.
| test/spec/functionalTest/rocketboard/src/test/java/rocketboard/ChangeAccessLevelTests.java | Remove unnecessary method on ChangeAccessLevelTests. | <ide><path>est/spec/functionalTest/rocketboard/src/test/java/rocketboard/ChangeAccessLevelTests.java
<ide> import rocketboardPages.GitHub.AuthorizePage;
<ide>
<ide> public class ChangeAccessLevelTests extends AbstractRocketboardTests {
<add>
<ide> @Test
<ide> public void changeAccessLevel() throws Exception {
<del> givenTableroAccessToPrivateRepositories();
<del>
<ide> assertTrue(whenChangesAccessToOnlyPublic().isAuthorizePage());
<ide> }
<ide>
<ide>
<ide> return PageFactory.initElements(driver, GitHub.AuthorizePage.class);
<ide> }
<del>
<del> private void givenTableroAccessToPrivateRepositories()
<del> throws Exception {
<del> rocketboardPage.waitingLoading();
<del> }
<ide> } |
|
Java | apache-2.0 | 05992a91091d529ef547670341a5b3c04afabf8f | 0 | mathemage/h2o-3,h2oai/h2o-3,brightchen/h2o-3,nilbody/h2o-3,YzPaul3/h2o-3,michalkurka/h2o-3,tarasane/h2o-3,pchmieli/h2o-3,michalkurka/h2o-3,spennihana/h2o-3,mrgloom/h2o-3,h2oai/h2o-3,datachand/h2o-3,YzPaul3/h2o-3,h2oai/h2o-dev,bikash/h2o-dev,mathemage/h2o-3,kyoren/https-github.com-h2oai-h2o-3,weaver-viii/h2o-3,jangorecki/h2o-3,jangorecki/h2o-3,madmax983/h2o-3,ChristosChristofidis/h2o-3,madmax983/h2o-3,kyoren/https-github.com-h2oai-h2o-3,weaver-viii/h2o-3,printedheart/h2o-3,nilbody/h2o-3,spennihana/h2o-3,brightchen/h2o-3,weaver-viii/h2o-3,printedheart/h2o-3,ChristosChristofidis/h2o-3,brightchen/h2o-3,junwucs/h2o-3,tarasane/h2o-3,nilbody/h2o-3,h2oai/h2o-3,spennihana/h2o-3,datachand/h2o-3,weaver-viii/h2o-3,h2oai/h2o-dev,madmax983/h2o-3,mrgloom/h2o-3,madmax983/h2o-3,printedheart/h2o-3,ChristosChristofidis/h2o-3,bospetersen/h2o-3,spennihana/h2o-3,mathemage/h2o-3,YzPaul3/h2o-3,kyoren/https-github.com-h2oai-h2o-3,junwucs/h2o-3,madmax983/h2o-3,mrgloom/h2o-3,jangorecki/h2o-3,mathemage/h2o-3,PawarPawan/h2o-v3,michalkurka/h2o-3,brightchen/h2o-3,brightchen/h2o-3,brightchen/h2o-3,YzPaul3/h2o-3,spennihana/h2o-3,datachand/h2o-3,printedheart/h2o-3,spennihana/h2o-3,printedheart/h2o-3,junwucs/h2o-3,spennihana/h2o-3,ChristosChristofidis/h2o-3,weaver-viii/h2o-3,PawarPawan/h2o-v3,kyoren/https-github.com-h2oai-h2o-3,michalkurka/h2o-3,mathemage/h2o-3,h2oai/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,junwucs/h2o-3,bikash/h2o-dev,mathemage/h2o-3,nilbody/h2o-3,mrgloom/h2o-3,weaver-viii/h2o-3,tarasane/h2o-3,tarasane/h2o-3,jangorecki/h2o-3,bikash/h2o-dev,h2oai/h2o-3,bikash/h2o-dev,h2oai/h2o-dev,tarasane/h2o-3,bospetersen/h2o-3,junwucs/h2o-3,h2oai/h2o-3,kyoren/https-github.com-h2oai-h2o-3,PawarPawan/h2o-v3,mathemage/h2o-3,datachand/h2o-3,datachand/h2o-3,madmax983/h2o-3,weaver-viii/h2o-3,ChristosChristofidis/h2o-3,kyoren/https-github.com-h2oai-h2o-3,mrgloom/h2o-3,bikash/h2o-dev,madmax983/h2o-3,bospetersen/h2o-3,michalkurka/h2o-3,bospetersen/h2o-3,h2oai/h2o-3,pchmieli/h2o-3,PawarPawan/h2o-v3,mrgloom/h2o-3,jangorecki/h2o-3,nilbody/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,YzPaul3/h2o-3,nilbody/h2o-3,bikash/h2o-dev,datachand/h2o-3,michalkurka/h2o-3,printedheart/h2o-3,h2oai/h2o-3,YzPaul3/h2o-3,h2oai/h2o-dev,bospetersen/h2o-3,pchmieli/h2o-3,datachand/h2o-3,ChristosChristofidis/h2o-3,bospetersen/h2o-3,printedheart/h2o-3,pchmieli/h2o-3,tarasane/h2o-3,brightchen/h2o-3,ChristosChristofidis/h2o-3,pchmieli/h2o-3,pchmieli/h2o-3,PawarPawan/h2o-v3,michalkurka/h2o-3,junwucs/h2o-3,h2oai/h2o-dev,kyoren/https-github.com-h2oai-h2o-3,junwucs/h2o-3,pchmieli/h2o-3,PawarPawan/h2o-v3,YzPaul3/h2o-3,mrgloom/h2o-3,nilbody/h2o-3,bospetersen/h2o-3,tarasane/h2o-3,PawarPawan/h2o-v3 | package hex.deeplearning;
import hex.*;
import hex.quantile.Quantile;
import hex.quantile.QuantileModel;
import hex.schemas.DeepLearningModelV2;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import water.*;
import water.api.ModelSchema;
import water.exceptions.H2OIllegalArgumentException;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.Vec;
import water.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import static hex.ModelMetrics.calcVarImp;
import static java.lang.Double.isNaN;
/**
* The Deep Learning model
* It contains a DeepLearningModelInfo with the most up-to-date model,
* a scoring history, as well as some helpers to indicate the progress
*/
public class DeepLearningModel extends SupervisedModel<DeepLearningModel,DeepLearningModel.DeepLearningParameters,DeepLearningModel.DeepLearningModelOutput> implements Model.DeepFeatures {
public static class DeepLearningParameters extends SupervisedModel.SupervisedParameters {
public int _n_folds;
public boolean _keep_cross_validation_splits;
/**
* A model key associated with a previously trained Deep Learning
* model. This option allows users to build a new model as a
* continuation of a previously generated model (e.g., by a grid search).
*/
public Key _checkpoint;
/**
* If enabled, store the best model under the destination key of this model at the end of training.
* Only applicable if training is not cancelled.
*/
public boolean _override_with_best_model = true;
/**
* Unlock expert mode parameters than can affect model building speed,
* predictive accuracy and scoring. Leaving expert mode parameters at default
* values is fine for many problems, but best results on complex datasets are often
* only attainable via expert mode options.
*/
public boolean _expert_mode = false;
public boolean _autoencoder = false;
public boolean _use_all_factor_levels = true;
/*Neural Net Topology*/
/**
* The activation function (non-linearity) to be used the neurons in the hidden layers.
* Tanh: Hyperbolic tangent function (same as scaled and shifted sigmoid).
* Rectifier: Chooses the maximum of (0, x) where x is the input value.
* Maxout: Choose the maximum coordinate of the input vector.
* With Dropout: Zero out a random user-given fraction of the
* incoming weights to each hidden layer during training, for each
* training row. This effectively trains exponentially many models at
* once, and can improve generalization.
*/
public Activation _activation = Activation.Rectifier;
/**
* The number and size of each hidden layer in the model.
* For example, if a user specifies "100,200,100" a model with 3 hidden
* layers will be produced, and the middle hidden layer will have 200
* neurons.To specify a grid search, add parentheses around each
* model's specification: "(100,100), (50,50,50), (20,20,20,20)".
*/
public int[] _hidden = new int[] { 200, 200 };
/**
* The number of passes over the training dataset to be carried out.
* It is recommended to start with lower values for initial grid searches.
* This value can be modified during checkpoint restarts and allows continuation
* of selected models.
*/
public double _epochs = 10;
/**
* The number of training data rows to be processed per iteration. Note that
* independent of this parameter, each row is used immediately to update the model
* with (online) stochastic gradient descent. This parameter controls the
* synchronization period between nodes in a distributed environment and the
* frequency at which scoring and model cancellation can happen. For example, if
* it is set to 10,000 on H2O running on 4 nodes, then each node will
* process 2,500 rows per iteration, sampling randomly from their local data.
* Then, model averaging between the nodes takes place, and scoring can happen
* (dependent on scoring interval and duty factor). Special values are 0 for
* one epoch per iteration, -1 for processing the maximum amount of data
* per iteration (if **replicate training data** is enabled, N epochs
* will be trained per iteration on N nodes, otherwise one epoch). Special value
* of -2 turns on automatic mode (auto-tuning).
*/
public long _train_samples_per_iteration = -2;
public double _target_ratio_comm_to_comp = 0.02;
/**
* The random seed controls sampling and initialization. Reproducible
* results are only expected with single-threaded operation (i.e.,
* when running on one node, turning off load balancing and providing
* a small dataset that fits in one chunk). In general, the
* multi-threaded asynchronous updates to the model parameters will
* result in (intentional) race conditions and non-reproducible
* results. Note that deterministic sampling and initialization might
* still lead to some weak sense of determinism in the model.
*/
public long _seed = new Random().nextLong();
/*Adaptive Learning Rate*/
/**
* The implemented adaptive learning rate algorithm (ADADELTA) automatically
* combines the benefits of learning rate annealing and momentum
* training to avoid slow convergence. Specification of only two
* parameters (rho and epsilon) simplifies hyper parameter search.
* In some cases, manually controlled (non-adaptive) learning rate and
* momentum specifications can lead to better results, but require the
* specification (and hyper parameter search) of up to 7 parameters.
* If the model is built on a topology with many local minima or
* long plateaus, it is possible for a constant learning rate to produce
* sub-optimal results. Learning rate annealing allows digging deeper into
* local minima, while rate decay allows specification of different
* learning rates per layer. When the gradient is being estimated in
* a long valley in the optimization landscape, a large learning rate
* can cause the gradient to oscillate and move in the wrong
* direction. When the gradient is computed on a relatively flat
* surface with small learning rates, the model can converge far
* slower than necessary.
*/
public boolean _adaptive_rate = true;
/**
* The first of two hyper parameters for adaptive learning rate (ADADELTA).
* It is similar to momentum and relates to the memory to prior weight updates.
* Typical values are between 0.9 and 0.999.
* This parameter is only active if adaptive learning rate is enabled.
*/
public double _rho = 0.99;
/**
* The second of two hyper parameters for adaptive learning rate (ADADELTA).
* It is similar to learning rate annealing during initial training
* and momentum at later stages where it allows forward progress.
* Typical values are between 1e-10 and 1e-4.
* This parameter is only active if adaptive learning rate is enabled.
*/
public double _epsilon = 1e-8;
/*Learning Rate*/
/**
* When adaptive learning rate is disabled, the magnitude of the weight
* updates are determined by the user specified learning rate
* (potentially annealed), and are a function of the difference
* between the predicted value and the target value. That difference,
* generally called delta, is only available at the output layer. To
* correct the output at each hidden layer, back propagation is
* used. Momentum modifies back propagation by allowing prior
* iterations to influence the current update. Using the momentum
* parameter can aid in avoiding local minima and the associated
* instability. Too much momentum can lead to instabilities, that's
* why the momentum is best ramped up slowly.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _rate = .005;
/**
* Learning rate annealing reduces the learning rate to "freeze" into
* local minima in the optimization landscape. The annealing rate is the
* inverse of the number of training samples it takes to cut the learning rate in half
* (e.g., 1e-6 means that it takes 1e6 training samples to halve the learning rate).
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _rate_annealing = 1e-6;
/**
* The learning rate decay parameter controls the change of learning rate across layers.
* For example, assume the rate parameter is set to 0.01, and the rate_decay parameter is set to 0.5.
* Then the learning rate for the weights connecting the input and first hidden layer will be 0.01,
* the learning rate for the weights connecting the first and the second hidden layer will be 0.005,
* and the learning rate for the weights connecting the second and third hidden layer will be 0.0025, etc.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _rate_decay = 1.0;
/*Momentum*/
/**
* The momentum_start parameter controls the amount of momentum at the beginning of training.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _momentum_start = 0;
/**
* The momentum_ramp parameter controls the amount of learning for which momentum increases
* (assuming momentum_stable is larger than momentum_start). The ramp is measured in the number
* of training samples.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _momentum_ramp = 1e6;
/**
* The momentum_stable parameter controls the final momentum value reached after momentum_ramp training samples.
* The momentum used for training will remain the same for training beyond reaching that point.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _momentum_stable = 0;
/**
* The Nesterov accelerated gradient descent method is a modification to
* traditional gradient descent for convex functions. The method relies on
* gradient information at various points to build a polynomial approximation that
* minimizes the residuals in fewer iterations of the descent.
* This parameter is only active if adaptive learning rate is disabled.
*/
public boolean _nesterov_accelerated_gradient = true;
/*Regularization*/
/**
* A fraction of the features for each training row to be omitted from training in order
* to improve generalization (dimension sampling).
*/
public double _input_dropout_ratio = 0.0;
/**
* A fraction of the inputs for each hidden layer to be omitted from training in order
* to improve generalization. Defaults to 0.5 for each hidden layer if omitted.
*/
public double[] _hidden_dropout_ratios;
/**
* A regularization method that constrains the absolute value of the weights and
* has the net effect of dropping some weights (setting them to zero) from a model
* to reduce complexity and avoid overfitting.
*/
public double _l1 = 0.0;
/**
* A regularization method that constrdains the sum of the squared
* weights. This method introduces bias into parameter estimates, but
* frequently produces substantial gains in modeling as estimate variance is
* reduced.
*/
public double _l2 = 0.0;
/**
* A maximum on the sum of the squared incoming weights into
* any one neuron. This tuning parameter is especially useful for unbound
* activation functions such as Maxout or Rectifier.
*/
public float _max_w2 = Float.POSITIVE_INFINITY;
/*Initialization*/
/**
* The distribution from which initial weights are to be drawn. The default
* option is an optimized initialization that considers the size of the network.
* The "uniform" option uses a uniform distribution with a mean of 0 and a given
* interval. The "normal" option draws weights from the standard normal
* distribution with a mean of 0 and given standard deviation.
*/
public InitialWeightDistribution _initial_weight_distribution = InitialWeightDistribution.UniformAdaptive;
/**
* The scale of the distribution function for Uniform or Normal distributions.
* For Uniform, the values are drawn uniformly from -initial_weight_scale...initial_weight_scale.
* For Normal, the values are drawn from a Normal distribution with a standard deviation of initial_weight_scale.
*/
public double _initial_weight_scale = 1.0;
/**
* The loss (error) function to be minimized by the model.
* Cross Entropy loss is used when the model output consists of independent
* hypotheses, and the outputs can be interpreted as the probability that each
* hypothesis is true. Cross entropy is the recommended loss function when the
* target values are class labels, and especially for imbalanced data.
* It strongly penalizes error in the prediction of the actual class label.
* Mean Square loss is used when the model output are continuous real values, but can
* be used for classification as well (where it emphasizes the error on all
* output classes, not just for the actual class).
*/
public Loss _loss = null;
/*Scoring*/
/**
* The minimum time (in seconds) to elapse between model scoring. The actual
* interval is determined by the number of training samples per iteration and the scoring duty cycle.
*/
public double _score_interval = 5;
/**
* The number of training dataset points to be used for scoring. Will be
* randomly sampled. Use 0 for selecting the entire training dataset.
*/
public long _score_training_samples = 10000l;
/**
* The number of validation dataset points to be used for scoring. Can be
* randomly sampled or stratified (if "balance classes" is set and "score
* validation sampling" is set to stratify). Use 0 for selecting the entire
* training dataset.
*/
public long _score_validation_samples = 0l;
/**
* Maximum fraction of wall clock time spent on model scoring on training and validation samples,
* and on diagnostics such as computation of feature importances (i.e., not on training).
*/
public double _score_duty_cycle = 0.1;
/**
* The stopping criteria in terms of classification error (1-accuracy) on the
* training data scoring dataset. When the error is at or below this threshold,
* training stops.
*/
public double _classification_stop = 0;
/**
* The stopping criteria in terms of regression error (MSE) on the training
* data scoring dataset. When the error is at or below this threshold, training
* stops.
*/
public double _regression_stop = 1e-6;
/**
* Enable quiet mode for less output to standard output.
*/
public boolean _quiet_mode = false;
/**
* Method used to sample the validation dataset for scoring, see Score Validation Samples above.
*/
public ClassSamplingMethod _score_validation_sampling = ClassSamplingMethod.Uniform;
/*Misc*/
/**
* Gather diagnostics for hidden layers, such as mean and RMS values of learning
* rate, momentum, weights and biases.
*/
public boolean _diagnostics = true;
/**
* Whether to compute variable importances for input features.
* The implemented method (by Gedeon) considers the weights connecting the
* input features to the first two hidden layers.
*/
public boolean _variable_importances = false;
/**
* Enable fast mode (minor approximation in back-propagation), should not affect results significantly.
*/
public boolean _fast_mode = true;
/**
* Ignore constant training columns (no information can be gained anyway).
*/
public boolean _ignore_const_cols = true;
/**
* Increase training speed on small datasets by splitting it into many chunks
* to allow utilization of all cores.
*/
public boolean _force_load_balance = true;
/**
* Replicate the entire training dataset onto every node for faster training on small datasets.
*/
public boolean _replicate_training_data = true;
/**
* Run on a single node for fine-tuning of model parameters. Can be useful for
* checkpoint resumes after training on multiple nodes for fast initial
* convergence.
*/
public boolean _single_node_mode = false;
/**
* Enable shuffling of training data (on each node). This option is
* recommended if training data is replicated on N nodes, and the number of training samples per iteration
* is close to N times the dataset size, where all nodes train will (almost) all
* the data. It is automatically enabled if the number of training samples per iteration is set to -1 (or to N
* times the dataset size or larger).
*/
public boolean _shuffle_training_data = false;
public MissingValuesHandling _missing_values_handling = MissingValuesHandling.MeanImputation;
public boolean _sparse = false;
public boolean _col_major = false;
public double _average_activation = 0;
public double _sparsity_beta = 0;
/**
* Max. number of categorical features, enforced via hashing (Experimental)
*/
public int _max_categorical_features = Integer.MAX_VALUE;
/**
* Force reproducibility on small data (will be slow - only uses 1 thread)
*/
public boolean _reproducible = false;
public enum MissingValuesHandling {
Skip, MeanImputation
}
public enum ClassSamplingMethod {
Uniform, Stratified
}
public enum InitialWeightDistribution {
UniformAdaptive, Uniform, Normal
}
/**
* Activation functions
*/
public enum Activation {
Tanh, TanhWithDropout, Rectifier, RectifierWithDropout, Maxout, MaxoutWithDropout
}
/**
* Loss functions
* CrossEntropy is recommended for classification, MeanSquare for regression (or classification)
*/
public enum Loss {
MeanSquare, CrossEntropy, MeanSquareClassification
}
void validate( DeepLearning dl, boolean expensive ) {
boolean classification = expensive || dl._nclass != 0 ? dl.isClassifier() : (_loss == Loss.CrossEntropy || _loss == Loss.MeanSquareClassification);
if (_hidden == null || _hidden.length == 0) dl.error("_hidden", "There must be at least one hidden layer.");
for( int h : _hidden ) if( h==0 ) dl.error("_hidden", "Hidden layer size must be >0.");
if (!_autoencoder) {
if (_valid == null)
dl.hide("_score_validation_samples", "score_validation_samples requires a validation frame.");
if (classification) {
dl.hide("_regression_stop", "regression_stop is used only with regression.");
} else {
dl.hide("_classification_stop", "classification_stop is used only with classification.");
dl.hide("_max_confusion_matrix_size", "max_confusion_matrix_size is used only with classification.");
dl.hide("_max_hit_ratio_k", "max_hit_ratio_k is used only with classification.");
dl.hide("_balance_classes", "balance_classes is used only with classification.");
}
if( !classification || !_balance_classes )
dl.hide("_class_sampling_factors", "class_sampling_factors requires both classification and balance_classes.");
if (!classification && _valid != null || _valid == null)
dl.hide("_score_validation_sampling", "score_validation_sampling requires regression and a validation frame OR no validation frame.");
}
// Auto-fill defaults
if (_activation != Activation.TanhWithDropout && _activation != Activation.MaxoutWithDropout && _activation != Activation.RectifierWithDropout)
dl.hide("_hidden_dropout_ratios", "hidden_dropout_ratios requires a dropout activation function.");
if (_hidden_dropout_ratios == null) {
if (_activation == Activation.TanhWithDropout || _activation == Activation.MaxoutWithDropout || _activation == Activation.RectifierWithDropout) {
if (expensive) {
_hidden_dropout_ratios = new double[_hidden.length];
if (!_quiet_mode)
dl.info("_hidden_dropout_ratios", "Automatically setting all hidden dropout ratios to 0.5.");
Arrays.fill(_hidden_dropout_ratios, 0.5);
}
}
}
else if (_hidden_dropout_ratios.length != _hidden.length) {
dl.error("_hidden_dropout_ratios", "Must have " + _hidden.length + " hidden layer dropout ratios.");
}
else if (_activation != Activation.TanhWithDropout && _activation != Activation.MaxoutWithDropout && _activation != Activation.RectifierWithDropout) {
if (!_quiet_mode) dl.hide("_hidden_dropout_ratios", "Ignoring hidden_dropout_ratios because a non-dropout activation function was specified.");
}
if (_input_dropout_ratio < 0 || _input_dropout_ratio >= 1)
dl.error("_input_dropout_ratio", "Input dropout must be in [0,1).");
if (H2O.CLOUD.size() == 1 && _replicate_training_data) {
dl.hide("_replicate_training_data", "replicate_training_data is only valid with cloud size greater than 1.");
if (expensive) {
dl.info("_replicate_training_data", "Disabling replicate_training_data on 1 node.");
_replicate_training_data = false;
}
}
if (_single_node_mode && (H2O.CLOUD.size() == 1 || !_replicate_training_data)) {
dl.hide("_single_node_mode", "single_node_mode is only used with multi-node operation with replicated training data.");
if (expensive) {
dl.info("_single_node_mode", "Disabling single_node_mode (only for multi-node operation with replicated training data).");
_single_node_mode = false;
}
}
if (_autoencoder) {
dl.hide("_use_all_factor_levels", "use_all_factor_levels is unsupported in combination with autoencoder.");
}
if (!_use_all_factor_levels && _autoencoder ) {
if (expensive) {
dl.warn("_use_all_factor_levels", "Enabling all_factor_levels for auto-encoders.");
_use_all_factor_levels = true;
}
}
if (_n_folds != 0)
dl.hide("_override_with_best_model", "override_with_best_model is unsupported in combination with n-fold cross-validation.");
if(_override_with_best_model && _n_folds != 0) {
if (expensive) {
dl.warn("_override_with_best_model", "Disabling override_with_best_model in combination with n-fold cross-validation.");
_override_with_best_model = false;
}
}
if (_adaptive_rate) {
dl.hide("_rate", "rate is not used with adaptive_rate.");
dl.hide("_rate_annealing", "rate_annealing is not used with adaptive_rate.");
dl.hide("_rate_decay", "rate_decay is not used with adaptive_rate.");
dl.hide("_momentum_start", "momentum_start is not used with adaptive_rate.");
dl.hide("_momentum_ramp", "momentum_ramp is not used with adaptive_rate.");
dl.hide("_momentum_stable", "momentum_stable is not used with adaptive_rate.");
dl.hide("_nesterov_accelerated_gradient", "nesterov_accelerated_gradient is not used with adaptive_rate.");
} else {
// ! adaptive_rate
dl.hide("_rho", "rho is only used with adaptive_rate.");
dl.hide("_epsilon", "epsilon is only used with adaptive_rate.");
}
if (!_quiet_mode) {
if (_adaptive_rate) {
if (expensive) {
dl.info("_adaptive_rate", "Using automatic learning rate. Ignoring the following input parameters: "
+ "rate, rate_decay, rate_annealing, momentum_start, momentum_ramp, momentum_stable, nesterov_accelerated_gradient.");
_momentum_start = 0;
_momentum_stable = 0;
}
} else {
if (expensive) {
dl.info("_adaptive_rate", "Using manual learning rate. Ignoring the following input parameters: "
+ "rho, epsilon.");
_rho = 0;
_epsilon = 0;
}
}
if (_initial_weight_distribution == InitialWeightDistribution.UniformAdaptive) {
dl.hide("_initial_weight_scale", "initial_weight_scale is not used if initial_weight_distribution == UniformAdaptive.");
}
if (_n_folds != 0) {
if (expensive) {
if (_override_with_best_model) {
dl.warn("_override_with_best_model", "Automatically disabling override_with_best_model, since the final model is the only scored model with n-fold cross-validation.");
_override_with_best_model = false;
}
}
}
}
if (_loss == null) {
if (expensive || dl._nclass != 0) {
dl.error("_loss", "Loss function must be specified. For classification (categorical response), use CrossEntropy or MeanSquareClassification. For regression (numerical response), use MeanSquare. For auto-encoders, use MeanSquare.");
}
//otherwise, we might not know whether classification=true or false (from R, for example, the training data isn't known when init(false) is called).
} else {
if (_autoencoder && _loss != Loss.MeanSquare)
dl.error("_loss", "Must use MeanSquare loss function for auto-encoder.");
if (!classification && _loss == Loss.CrossEntropy)
dl.error("_loss", "For CrossEntropy loss, the response must be categorical. Either select MeanSquare loss for regression, or convert the response to a categorical (if applicable).");
else if (!classification && _loss == Loss.MeanSquareClassification)
dl.error("_loss", "For MeanSquareClassification loss, the response must be categorical. Either select MeanSquare loss for regression, or convert the response to a categorical (if applicable).");
else if (classification && _loss == Loss.MeanSquare)
dl.error("_loss", "For MeanSquare loss, the response must be numerical. Either select CrossEntropy or MeanSquareClassification loss for classification, or convert the response to numerical (if applicable).");
}
if (_score_training_samples < 0) {
dl.error("_score_training_samples", "Number of training samples for scoring must be >= 0 (0 for all).");
}
if (_score_validation_samples < 0) {
dl.error("_score_validation_samples", "Number of training samples for scoring must be >= 0 (0 for all).");
}
if(_autoencoder && _sparsity_beta > 0) {
if (_activation == Activation.Tanh || _activation == Activation.TanhWithDropout) {
if (_average_activation >= 1 || _average_activation <= -1)
dl.error("_average_activation", "Tanh average activation must be in (-1,1).");
}
else if (_activation == Activation.Rectifier || _activation == Activation.RectifierWithDropout) {
if (_average_activation <= 0)
dl.error("_average_activation", "Rectifier average activation must be positive.");
}
}
if (!_autoencoder && _sparsity_beta != 0) dl.info("_sparsity_beta", "Sparsity beta can only be used for autoencoder.");
// reason for the error message below is that validation might not have the same horizontalized features as the training data (or different order)
if (_autoencoder && _valid != null) dl.error("_validation_frame", "Cannot specify a validation dataset for auto-encoder.");
if (_autoencoder && _activation == Activation.Maxout) dl.error("_activation", "Maxout activation is not supported for auto-encoder.");
if (_max_categorical_features < 1) dl.error("_max_categorical_features", "max_categorical_features must be at least 1.");
if (!_sparse && _col_major) {
if (!_quiet_mode) dl.error("_col_major", "Cannot use column major storage for non-sparse data handling.");
}
if (expensive) {
if (!classification && _balance_classes) {
dl.error("_balance_classes", "balance_classes requires classification to be enabled.");
}
if (_class_sampling_factors != null && !_balance_classes) {
dl.error("_class_sampling_factors", "class_sampling_factors requires balance_classes to be enabled.");
}
}
if (_reproducible) {
if (expensive) {
if (!_quiet_mode)
Log.info("Automatically enabling force_load_balancing, disabling single_node_mode and replicate_training_data\nand setting train_samples_per_iteration to -1 to enforce reproducibility.");
_force_load_balance = true;
_single_node_mode = false;
_train_samples_per_iteration = -1;
_replicate_training_data = false; //there's no benefit from having multiple nodes compute the exact same thing, and then average it back to the same
// replicate_training_data = true; //doesn't hurt, but does replicated identical work
}
}
}
}
public static class DeepLearningModelOutput extends SupervisedModel.SupervisedOutput {
public DeepLearningModelOutput() { super(); }
public DeepLearningModelOutput(DeepLearning b) { super(b); }
boolean autoencoder;
Key[] weights;
Key[] biases;
DeepLearningScoring errors;
TwoDimTable model_summary;
TwoDimTable scoring_history;
TwoDimTable variable_importances;
ModelMetrics train_metrics;
ModelMetrics valid_metrics;
double run_time;
@Override public ModelCategory getModelCategory() {
return autoencoder ? ModelCategory.AutoEncoder : super.getModelCategory();
}
@Override public boolean isSupervised() { return !autoencoder; }
}
// Default publicly visible Schema is V2
public ModelSchema schema() { return new DeepLearningModelV2(); }
private volatile DeepLearningModelInfo model_info;
void set_model_info(DeepLearningModelInfo mi) { model_info = mi; }
final public DeepLearningModelInfo model_info() { return model_info; }
public long run_time;
private long start_time;
public long actual_train_samples_per_iteration;
public double time_for_communication_us; //helper for auto-tuning: time in microseconds for collective bcast/reduce of the model
public double epoch_counter;
public long training_rows;
public long validation_rows;
private DeepLearningScoring[] errors;
public DeepLearningScoring[] scoring_history() { return errors; }
// Keep the best model so far, based on a single criterion (overall class. error or MSE)
private float _bestError = Float.POSITIVE_INFINITY;
public Key actual_best_model_key;
// return the most up-to-date model metrics
DeepLearningScoring last_scored() { return errors == null ? null : errors[errors.length-1]; }
// @Override
public final DeepLearningParameters get_params() { return _parms; }
// @Override public final Request2 job() { return get_params(); }
// double missingColumnsType() { return get_params()._sparse ? 0 : Double.NaN; }
public float error() { return (float) (_output.isClassifier() ? cm().err() : mse()); }
@Override public ModelMetrics.MetricBuilder makeMetricBuilder(String[] domain) {
switch(_output.getModelCategory()) {
case Binomial: return new ModelMetricsBinomial.MetricBuilderBinomial(domain, ModelUtils.DEFAULT_THRESHOLDS);
case Multinomial: return new ModelMetricsMultinomial.MetricBuilderMultinomial(_output.nclasses(),domain);
case Regression: return new ModelMetricsRegression.MetricBuilderRegression();
case AutoEncoder: return new ModelMetricsAutoEncoder.MetricBuilderAutoEncoder(_output.nfeatures());
default: throw H2O.unimpl();
}
}
public int compareTo(DeepLearningModel o) {
if (o._output.isClassifier() != _output.isClassifier()) throw new UnsupportedOperationException("Cannot compare classifier against regressor.");
if (o._output.nclasses() != _output.nclasses()) throw new UnsupportedOperationException("Cannot compare models with different number of classes.");
return (error() < o.error() ? -1 : error() > o.error() ? 1 : 0);
}
public static class DeepLearningScoring extends Iced {
// static final int API_WEAVER = 1;
// static public DocGen.FieldDoc[] DOC_FIELDS;
public double epoch_counter;
public long training_samples;
public long training_time_ms;
//training/validation sets
boolean validation;
int num_folds;
public long score_training_samples;
public long score_validation_samples;
public boolean classification;
VarImp variable_importances;
// classification
public ConfusionMatrix train_confusion_matrix;
public ConfusionMatrix valid_confusion_matrix;
public double train_err = 1;
public double valid_err = 1;
public AUCData trainAUC;
public AUCData validAUC;
public float[] train_hitratio; // "Hit ratio on training data"
public float[] valid_hitratio; // "Hit ratio on validation data"
// regression
public double train_mse = Double.NaN;
public double valid_mse = Double.NaN;
public double train_r2 = Double.NaN;
public double valid_r2 = Double.NaN;
public long scoring_time;
DeepLearningScoring deep_clone() {
AutoBuffer ab = new AutoBuffer();
this.write(ab);
ab.flipForReading();
return (DeepLearningScoring) new DeepLearningScoring().read(ab);
}
@Override public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Training MSE: " + train_mse + "\n");
if (classification) {
sb.append("Training R^2: " + train_r2 + "\n");
sb.append("Training " + train_confusion_matrix.table.toString(1));
sb.append("Training Misclassification"
+ (trainAUC != null ? " [using threshold for " + trainAUC.threshold_criterion.toString().replace("_", " ") + "]: " : ": ")
+ String.format("%.2f", 100 * train_err) + "%");
if (trainAUC != null) sb.append(", AUC: " + String.format("%.4f", 100 * trainAUC.AUC) + "%");
}
if (validation || num_folds>0) {
if (num_folds > 0) {
sb.append("\nDoing " + num_folds + "-fold cross-validation:");
}
sb.append("\nValidation MSE: " + valid_mse + "\n");
sb.append("Validation R^2: " + valid_r2 + "\n");
if (classification) {
sb.append("Validation " + valid_confusion_matrix.table.toString(1));
sb.append("Validation Misclassification"
+ (validAUC != null ? " [using threshold for " + validAUC.threshold_criterion.toString().replace("_", " ") + "]: " : ": ")
+ String.format("%.2f", (100 * valid_err)) + "%");
if (validAUC != null) sb.append(", AUC: " + String.format("%.4f", 100 * validAUC.AUC) + "%");
}
}
sb.append("\n");
return sb.toString();
}
}
final private static class ConfMat extends ConfusionMatrix {
final private double _err;
final private double _f1;
public ConfMat(double err, double f1) {
super(null, null);
_err=err;
_f1=f1;
}
@Override public double err() { return _err; }
@Override public double F1() { return _f1; }
@Override public double[] classErr() { return null; }
}
/** for grid search error reporting */
// @Override
public ConfusionMatrix cm() {
final DeepLearningScoring lasterror = last_scored();
if (lasterror == null) return null;
ConfusionMatrix cm = lasterror.validation || lasterror.num_folds > 0 ?
lasterror.valid_confusion_matrix :
lasterror.train_confusion_matrix;
if (cm == null ) {
if (lasterror.validation || lasterror.num_folds > 0) {
return new ConfMat(lasterror.valid_err, lasterror.validAUC != null ? lasterror.validAUC.F1() : 0);
} else {
return new ConfMat(lasterror.train_err, lasterror.trainAUC != null ? lasterror.trainAUC.F1() : 0);
}
}
return cm;
}
// @Override
public double mse() {
if (errors == null) return Double.NaN;
return last_scored().validation || last_scored().num_folds > 0 ? last_scored().valid_mse : last_scored().train_mse;
}
// @Override
public VarImp varimp() {
if (errors == null) return null;
return last_scored().variable_importances;
}
private TwoDimTable createScoringHistoryTable(DeepLearningScoring[] errors) {
return createScoringHistoryTable(errors, 20);
}
private TwoDimTable createScoringHistoryTable(DeepLearningScoring[] errors, final int size_limit) {
assert (size_limit >= 10);
List<String> colHeaders = new ArrayList<>();
List<String> colTypes = new ArrayList<>();
List<String> colFormat = new ArrayList<>();
colHeaders.add("Timestamp"); colTypes.add("string"); colFormat.add("%s");
colHeaders.add("Training Duration"); colTypes.add("string"); colFormat.add("%s");
colHeaders.add("Training Speed"); colTypes.add("string"); colFormat.add("%s");
colHeaders.add("Training Epochs"); colTypes.add("double"); colFormat.add("%.5f");
colHeaders.add("Training Samples"); colTypes.add("long"); colFormat.add("%d");
colHeaders.add("Training MSE"); colTypes.add("double"); colFormat.add("%.5f");
if (!_output.autoencoder) {
colHeaders.add("Training R^2");
colTypes.add("double");
colFormat.add("%.5f");
}
if (_output.getModelCategory() == ModelCategory.Binomial) {
colHeaders.add("Training AUC");
colTypes.add("double");
colFormat.add("%.5f");
}
if (_output.getModelCategory() == ModelCategory.Binomial || _output.getModelCategory() == ModelCategory.Multinomial) {
colHeaders.add("Training Classification Error");
colTypes.add("double");
colFormat.add("%.5f");
}
if (get_params()._valid != null) {
colHeaders.add("Validation MSE"); colTypes.add("double"); colFormat.add("%.5f");
if (!_output.autoencoder) {
colHeaders.add("Validation R^2");
colTypes.add("double");
colFormat.add("%.5f");
}
if (_output.getModelCategory() == ModelCategory.Binomial) {
colHeaders.add("Validation AUC");
colTypes.add("double");
colFormat.add("%.5f");
}
if (_output.isClassifier()) {
colHeaders.add("Validation Classification Error");
colTypes.add("double");
colFormat.add("%.5f");
}
} else if (get_params()._n_folds > 0) {
colHeaders.add("Cross-Validation MSE"); colTypes.add("double"); colFormat.add("%.5f");
// colHeaders.add("Validation R^2"); colTypes.add("double"); colFormat.add("%g");
if (_output.getModelCategory() == ModelCategory.Binomial) {
colHeaders.add("Cross-Validation AUC");
colTypes.add("double");
colFormat.add("%.5f");
}
if (_output.isClassifier()) {
colHeaders.add("Cross-Validation Classification Error");
colTypes.add("double");
colFormat.add("%.5f");
}
}
List<Integer> which = new ArrayList<>();
if (errors.length > size_limit) {
// always show first few
which.add(0);
// which.add(1);
// which.add(2);
// which.add(3);
// which.add(4);
// always show last few
// which.add(errors.length-5);
// which.add(errors.length-4);
// which.add(errors.length-3);
// which.add(errors.length-2);
which.add(errors.length-1);
// pick the remaining scoring points from the middle section
final float step = (float)(errors.length-which.size())/(size_limit-which.size());
for (float i=5; i<errors.length-5; i+=step) {
if (which.size() < size_limit) which.add((int)i);
}
}
final int rows = Math.min(size_limit, errors.length);
TwoDimTable table = new TwoDimTable(
"Scoring History",
new String[rows],
colHeaders.toArray(new String[0]),
colTypes.toArray(new String[0]),
colFormat.toArray(new String[0]),
"");
int row = 0;
for( int i = 0; i<errors.length ; i++ ) {
if (errors.length > size_limit && !which.contains(new Integer(i))) continue;
final DeepLearningScoring e = errors[i];
int col = 0;
assert(row < table.getRowDim());
assert(col < table.getColDim());
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
table.set(row, col++, fmt.print(start_time + e.training_time_ms));
table.set(row, col++, PrettyPrint.msecs(e.training_time_ms, true));
table.set(row, col++, e.training_time_ms == 0 ? null : (String.format("%.3f", e.training_samples/(e.training_time_ms/1e3)) + " rows/sec"));
table.set(row, col++, e.epoch_counter);
table.set(row, col++, e.training_samples);
table.set(row, col++, e.train_mse);
if (!_output.autoencoder) {
table.set(row, col++, e.train_r2);
}
if (_output.getModelCategory() == ModelCategory.Binomial) {
table.set(row, col++, e.trainAUC != null ? e.trainAUC.AUC() : Double.NaN);
}
if (_output.isClassifier()) {
table.set(row, col++, e.train_err);
}
if (get_params()._valid != null) {
table.set(row, col++, e.valid_mse);
if (!_output.autoencoder) {
table.set(row, col++, e.valid_r2);
}
if (_output.getModelCategory() == ModelCategory.Binomial) {
table.set(row, col++, e.validAUC != null ? e.validAUC.AUC() : Double.NaN);
}
if (_output.isClassifier()) {
table.set(row, col++, e.valid_err);
}
}
else if(get_params()._n_folds > 0) {
throw H2O.unimpl();
}
row++;
}
return table;
}
// This describes the model, together with the parameters
// This will be shared: one per node
public static class DeepLearningModelInfo extends Iced {
public TwoDimTable summaryTable;
private DataInfo data_info;
public DataInfo data_info() { return data_info; }
// model is described by parameters and the following arrays
private Neurons.DenseRowMatrix[] dense_row_weights; //one 2D weight matrix per layer (stored as a 1D array each)
private Neurons.DenseColMatrix[] dense_col_weights; //one 2D weight matrix per layer (stored as a 1D array each)
private Neurons.DenseVector[] biases; //one 1D bias array per layer
private Neurons.DenseVector[] avg_activations; //one 1D array per hidden layer
// helpers for storing previous step deltas
// Note: These two arrays *could* be made transient and then initialized freshly in makeNeurons() and in DeepLearningTask.initLocal()
// But then, after each reduction, the weights would be lost and would have to restart afresh -> not *exactly* right, but close...
private Neurons.DenseRowMatrix[] dense_row_weights_momenta;
private Neurons.DenseColMatrix[] dense_col_weights_momenta;
private Neurons.DenseVector[] biases_momenta;
// helpers for AdaDelta
private Neurons.DenseRowMatrix[] dense_row_ada_dx_g;
private Neurons.DenseColMatrix[] dense_col_ada_dx_g;
private Neurons.DenseVector[] biases_ada_dx_g;
// compute model size (number of model parameters required for making predictions)
// momenta are not counted here, but they are needed for model building
public long size() {
long siz = 0;
for (Neurons.Matrix w : dense_row_weights) if (w != null) siz += w.size();
for (Neurons.Matrix w : dense_col_weights) if (w != null) siz += w.size();
for (Neurons.Vector b : biases) siz += b.size();
return siz;
}
// accessors to (shared) weights and biases - those will be updated racily (c.f. Hogwild!)
boolean has_momenta() { return get_params()._momentum_start != 0 || get_params()._momentum_stable != 0; }
boolean adaDelta() { return get_params()._adaptive_rate; }
public final Neurons.Matrix get_weights(int i) { return dense_row_weights[i] == null ? dense_col_weights[i] : dense_row_weights[i]; }
public final Neurons.DenseVector get_biases(int i) { return biases[i]; }
public final Neurons.Matrix get_weights_momenta(int i) { return dense_row_weights_momenta[i] == null ? dense_col_weights_momenta[i] : dense_row_weights_momenta[i]; }
public final Neurons.DenseVector get_biases_momenta(int i) { return biases_momenta[i]; }
public final Neurons.Matrix get_ada_dx_g(int i) { return dense_row_ada_dx_g[i] == null ? dense_col_ada_dx_g[i] : dense_row_ada_dx_g[i]; }
public final Neurons.DenseVector get_biases_ada_dx_g(int i) { return biases_ada_dx_g[i]; }
//accessor to shared parameter defining avg activations
public final Neurons.DenseVector get_avg_activations(int i) { return avg_activations[i]; }
private DeepLearningParameters parameters;
public final DeepLearningParameters get_params() { return parameters; }
private float[] mean_rate;
private float[] rms_rate;
private float[] mean_bias;
private float[] rms_bias;
private float[] mean_weight;
public float[] rms_weight;
public float[] mean_a;
private volatile boolean unstable = false;
public boolean unstable() { return unstable; }
public void set_unstable() { if (!unstable) computeStats(); unstable = true; }
private long processed_global;
public synchronized long get_processed_global() { return processed_global; }
public synchronized void set_processed_global(long p) { processed_global = p; }
public synchronized void add_processed_global(long p) { processed_global += p; }
private long processed_local;
public synchronized long get_processed_local() { return processed_local; }
public synchronized void set_processed_local(long p) { processed_local = p; }
public synchronized void add_processed_local(long p) { processed_local += p; }
public synchronized long get_processed_total() { return processed_global + processed_local; }
// package local helpers
int[] units; //number of neurons per layer, extracted from parameters and from datainfo
final boolean _classification; // Classification cache (nclasses>1)
final Frame _train; // Prepared training frame
final Frame _valid; // Prepared validation frame
public DeepLearningModelInfo() {
_classification = false;
_train = _valid = null;
}
public DeepLearningModelInfo(final DeepLearningParameters params, final DataInfo dinfo, boolean classification, Frame train, Frame valid) {
_classification = classification;
_train = train;
_valid = valid;
data_info = dinfo;
parameters = params;
final int num_input = dinfo.fullN();
final int num_output = get_params()._autoencoder ? num_input : (_classification ? train.lastVec().cardinality() : 1);
assert(num_input > 0);
assert(num_output > 0);
if (has_momenta() && adaDelta()) throw new IllegalArgumentException("Cannot have non-zero momentum and adaptive rate at the same time.");
final int layers=get_params()._hidden.length;
// units (# neurons for each layer)
units = new int[layers+2];
if (get_params()._max_categorical_features <= Integer.MAX_VALUE - dinfo._nums)
units[0] = Math.min(dinfo._nums + get_params()._max_categorical_features, num_input);
else
units[0] = num_input;
System.arraycopy(get_params()._hidden, 0, units, 1, layers);
units[layers+1] = num_output;
if ((long)units[0] > 100000L) {
final String[][] domains = dinfo._adaptedFrame.domains();
int[] levels = new int[domains.length];
for (int i=0; i<levels.length; ++i) {
levels[i] = domains[i] != null ? domains[i].length : 0;
}
Arrays.sort(levels);
Log.warn("===================================================================================================================================");
Log.warn(num_input + " input features" + (dinfo._cats > 0 ? " (after categorical one-hot encoding)" : "") + ". Can be slow and require a lot of memory.");
if (levels[levels.length-1] > 0) {
int levelcutoff = levels[levels.length-1-Math.min(10, levels.length)];
int count = 0;
for (int i=0; i<dinfo._adaptedFrame.numCols() - (get_params()._autoencoder ? 0 : 1) && count < 10; ++i) {
if (dinfo._adaptedFrame.domains()[i] != null && dinfo._adaptedFrame.domains()[i].length >= levelcutoff) {
Log.warn("Categorical feature '" + dinfo._adaptedFrame._names[i] + "' has cardinality " + dinfo._adaptedFrame.domains()[i].length + ".");
}
count++;
}
}
Log.warn("Suggestions:");
Log.warn(" *) Limit the size of the first hidden layer");
if (dinfo._cats > 0) {
Log.warn(" *) Limit the total number of one-hot encoded features with the parameter 'max_categorical_features'");
Log.warn(" *) Run h2o.interaction(...,pairwise=F) on high-cardinality categorical columns to limit the factor count, see http://learn.h2o.ai");
}
Log.warn("===================================================================================================================================");
}
// weights (to connect layers)
dense_row_weights = new Neurons.DenseRowMatrix[layers+1];
dense_col_weights = new Neurons.DenseColMatrix[layers+1];
// decide format of weight matrices row-major or col-major
if (get_params()._col_major) dense_col_weights[0] = new Neurons.DenseColMatrix(units[1], units[0]);
else dense_row_weights[0] = new Neurons.DenseRowMatrix(units[1], units[0]);
for (int i = 1; i <= layers; ++i)
dense_row_weights[i] = new Neurons.DenseRowMatrix(units[i + 1] /*rows*/, units[i] /*cols*/);
// biases (only for hidden layers and output layer)
biases = new Neurons.DenseVector[layers+1];
for (int i=0; i<=layers; ++i) biases[i] = new Neurons.DenseVector(units[i+1]);
// average activation (only for hidden layers)
if (get_params()._autoencoder && get_params()._sparsity_beta > 0) {
avg_activations = new Neurons.DenseVector[layers];
mean_a = new float[layers];
for (int i = 0; i < layers; ++i) avg_activations[i] = new Neurons.DenseVector(units[i + 1]);
}
fillHelpers();
// for diagnostics
mean_rate = new float[units.length];
rms_rate = new float[units.length];
mean_bias = new float[units.length];
rms_bias = new float[units.length];
mean_weight = new float[units.length];
rms_weight = new float[units.length];
}
// deep clone all weights/biases
DeepLearningModelInfo deep_clone() {
AutoBuffer ab = new AutoBuffer();
this.write(ab);
ab.flipForReading();
return (DeepLearningModelInfo) new DeepLearningModelInfo().read(ab);
}
void fillHelpers() {
if (has_momenta()) {
dense_row_weights_momenta = new Neurons.DenseRowMatrix[dense_row_weights.length];
dense_col_weights_momenta = new Neurons.DenseColMatrix[dense_col_weights.length];
if (dense_row_weights[0] != null)
dense_row_weights_momenta[0] = new Neurons.DenseRowMatrix(units[1], units[0]);
else
dense_col_weights_momenta[0] = new Neurons.DenseColMatrix(units[1], units[0]);
for (int i=1; i<dense_row_weights_momenta.length; ++i) dense_row_weights_momenta[i] = new Neurons.DenseRowMatrix(units[i+1], units[i]);
biases_momenta = new Neurons.DenseVector[biases.length];
for (int i=0; i<biases_momenta.length; ++i) biases_momenta[i] = new Neurons.DenseVector(units[i+1]);
}
else if (adaDelta()) {
dense_row_ada_dx_g = new Neurons.DenseRowMatrix[dense_row_weights.length];
dense_col_ada_dx_g = new Neurons.DenseColMatrix[dense_col_weights.length];
//AdaGrad
if (dense_row_weights[0] != null) {
dense_row_ada_dx_g[0] = new Neurons.DenseRowMatrix(units[1], 2*units[0]);
} else {
dense_col_ada_dx_g[0] = new Neurons.DenseColMatrix(2*units[1], units[0]);
}
for (int i=1; i<dense_row_ada_dx_g.length; ++i) {
dense_row_ada_dx_g[i] = new Neurons.DenseRowMatrix(units[i+1], 2*units[i]);
}
biases_ada_dx_g = new Neurons.DenseVector[biases.length];
for (int i=0; i<biases_ada_dx_g.length; ++i) {
biases_ada_dx_g[i] = new Neurons.DenseVector(2*units[i+1]);
}
}
}
public TwoDimTable createSummaryTable() {
Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(this);
TwoDimTable table = new TwoDimTable(
"Status of Neuron Layers",
new String[neurons.length],
new String[]{"#", "Units", "Type", "Dropout", "L1", "L2",
(get_params()._adaptive_rate ? "Rate (Mean,RMS)" : "Rate"),
(get_params()._adaptive_rate ? "" : "Momentum"),
"Weight (Mean,RMS)",
"Bias (Mean,RMS)"
},
new String[]{"integer", "integer", "string", "double", "double", "double",
"string", "string", "string", "string"},
new String[]{"%d", "%d", "%s", "%2.2f %%", "%5f", "%5f", "%s", "%s", "%s", "%s"},
"");
final String format = "%7g";
for (int i = 0; i < neurons.length; ++i) {
table.set(i, 0, i + 1);
table.set(i, 1, neurons[i].units);
table.set(i, 2, neurons[i].getClass().getSimpleName());
if (i == 0) {
table.set(i, 3, neurons[i].params._input_dropout_ratio);
continue;
} else if (i < neurons.length - 1) {
if (neurons[i].params._hidden_dropout_ratios == null) {
table.set(i, 3, 0);
} else {
table.set(i, 3, neurons[i].params._hidden_dropout_ratios[i - 1]);
}
}
table.set(i, 4, neurons[i].params._l1);
table.set(i, 5, neurons[i].params._l2);
table.set(i, 6, (get_params()._adaptive_rate ? (" (" + String.format(format, mean_rate[i]) + ", " + String.format(format, rms_rate[i]) + ")")
: (String.format("%10g", neurons[i].rate(get_processed_total())))));
table.set(i, 7, get_params()._adaptive_rate ? "" : String.format("%5f", neurons[i].momentum(get_processed_total())));
table.set(i, 8, " (" + String.format(format, mean_weight[i])
+ ", " + String.format(format, rms_weight[i]) + ")");
table.set(i, 9, " (" + String.format(format, mean_bias[i])
+ ", " + String.format(format, rms_bias[i]) + ")");
}
summaryTable = table;
return summaryTable;
}
@Override public String toString() {
StringBuilder sb = new StringBuilder();
if (get_params()._diagnostics && !get_params()._quiet_mode) {
if (get_params()._sparsity_beta > 0) {
for (int k = 0; k < get_params()._hidden.length; k++) {
sb.append("Average activation in hidden layer ").append(k).append(" is ").append(mean_a[k]).append(" \n");
}
}
createSummaryTable();
sb.append(summaryTable.toString(1));
}
return sb.toString();
}
// DEBUGGING
public String toStringAll() {
StringBuilder sb = new StringBuilder();
sb.append(toString());
for (int i=0; i<units.length-1; ++i)
sb.append("\nweights[").append(i).append("][]=").append(Arrays.toString(get_weights(i).raw()));
for (int i=0; i<units.length-1; ++i) {
sb.append("\nbiases[").append(i).append("][]=").append(Arrays.toString(get_biases(i).raw()));
}
if (has_momenta()) {
for (int i=0; i<units.length-1; ++i)
sb.append("\nweights_momenta[").append(i).append("][]=").append(Arrays.toString(get_weights_momenta(i).raw()));
}
if (biases_momenta != null) {
for (int i=0; i<units.length-1; ++i) {
sb.append("\nbiases_momenta[").append(i).append("][]=").append(Arrays.toString(biases_momenta[i].raw()));
}
}
sb.append("\nunits[]=").append(Arrays.toString(units));
sb.append("\nprocessed global: ").append(get_processed_global());
sb.append("\nprocessed local: ").append(get_processed_local());
sb.append("\nprocessed total: ").append(get_processed_total());
sb.append("\n");
return sb.toString();
}
void initializeMembers() {
randomizeWeights();
//TODO: determine good/optimal/best initialization scheme for biases
// hidden layers
for (int i=0; i<get_params()._hidden.length; ++i) {
if (get_params()._activation == DeepLearningParameters.Activation.Rectifier
|| get_params()._activation == DeepLearningParameters.Activation.RectifierWithDropout
|| get_params()._activation == DeepLearningParameters.Activation.Maxout
|| get_params()._activation == DeepLearningParameters.Activation.MaxoutWithDropout
) {
// Arrays.fill(biases[i], 1.); //old behavior
Arrays.fill(biases[i].raw(), i == 0 ? 0.5f : 1f); //new behavior, might be slightly better
}
else if (get_params()._activation == DeepLearningParameters.Activation.Tanh || get_params()._activation == DeepLearningParameters.Activation.TanhWithDropout) {
Arrays.fill(biases[i].raw(), 0f);
}
}
Arrays.fill(biases[biases.length-1].raw(), 0f); //output layer
}
public void add(DeepLearningModelInfo other) {
for (int i=0;i<dense_row_weights.length;++i)
ArrayUtils.add(get_weights(i).raw(), other.get_weights(i).raw());
for (int i=0;i<biases.length;++i) ArrayUtils.add(biases[i].raw(), other.biases[i].raw());
if (avg_activations != null)
for (int i=0;i<avg_activations.length;++i)
ArrayUtils.add(avg_activations[i].raw(), other.biases[i].raw());
if (has_momenta()) {
assert(other.has_momenta());
for (int i=0;i<dense_row_weights_momenta.length;++i)
ArrayUtils.add(get_weights_momenta(i).raw(), other.get_weights_momenta(i).raw());
for (int i=0;i<biases_momenta.length;++i)
ArrayUtils.add(biases_momenta[i].raw(), other.biases_momenta[i].raw());
}
if (adaDelta()) {
assert(other.adaDelta());
for (int i=0;i<dense_row_ada_dx_g.length;++i) {
ArrayUtils.add(get_ada_dx_g(i).raw(), other.get_ada_dx_g(i).raw());
}
}
add_processed_local(other.get_processed_local());
}
protected void div(float N) {
for (int i=0; i<dense_row_weights.length; ++i)
ArrayUtils.div(get_weights(i).raw(), N);
for (Neurons.Vector bias : biases) ArrayUtils.div(bias.raw(), N);
if (avg_activations != null)
for (Neurons.Vector avgac : avg_activations)
ArrayUtils.div(avgac.raw(), N);
if (has_momenta()) {
for (int i=0; i<dense_row_weights_momenta.length; ++i)
ArrayUtils.div(get_weights_momenta(i).raw(), N);
for (Neurons.Vector bias_momenta : biases_momenta) ArrayUtils.div(bias_momenta.raw(), N);
}
if (adaDelta()) {
for (int i=0;i<dense_row_ada_dx_g.length;++i) {
ArrayUtils.div(get_ada_dx_g(i).raw(), N);
}
}
}
double uniformDist(Random rand, double min, double max) {
return min + rand.nextFloat() * (max - min);
}
void randomizeWeights() {
for (int w=0; w<dense_row_weights.length; ++w) {
final Random rng = water.util.RandomUtils.getDeterRNG(get_params()._seed + 0xBAD5EED + w+1); //to match NeuralNet behavior
final double range = Math.sqrt(6. / (units[w] + units[w+1]));
for( int i = 0; i < get_weights(w).rows(); i++ ) {
for( int j = 0; j < get_weights(w).cols(); j++ ) {
if (get_params()._initial_weight_distribution == DeepLearningParameters.InitialWeightDistribution.UniformAdaptive) {
// cf. http://machinelearning.wustl.edu/mlpapers/paper_files/AISTATS2010_GlorotB10.pdf
if (w==dense_row_weights.length-1 && _classification)
get_weights(w).set(i,j, (float)(4.*uniformDist(rng, -range, range))); //Softmax might need an extra factor 4, since it's like a sigmoid
else
get_weights(w).set(i,j, (float)uniformDist(rng, -range, range));
}
else if (get_params()._initial_weight_distribution == DeepLearningParameters.InitialWeightDistribution.Uniform) {
get_weights(w).set(i,j, (float)uniformDist(rng, -get_params()._initial_weight_scale, get_params()._initial_weight_scale));
}
else if (get_params()._initial_weight_distribution == DeepLearningParameters.InitialWeightDistribution.Normal) {
get_weights(w).set(i,j, (float)(rng.nextGaussian() * get_params()._initial_weight_scale));
}
}
}
}
}
// TODO: Add "subset randomize" function
// int count = Math.min(15, _previous.units);
// double min = -.1f, max = +.1f;
// //double min = -1f, max = +1f;
// for( int o = 0; o < units; o++ ) {
// for( int n = 0; n < count; n++ ) {
// int i = rand.nextInt(_previous.units);
// int w = o * _previous.units + i;
// _w[w] = uniformDist(rand, min, max);
// }
// }
/**
* Compute Variable Importance, based on
* GEDEON: DATA MINING OF INPUTS: ANALYSING MAGNITUDE AND FUNCTIONAL MEASURES
* @return variable importances for input features
*/
public float[] computeVariableImportances() {
float[] vi = new float[units[0]];
Arrays.fill(vi, 0f);
float[][] Qik = new float[units[0]][units[2]]; //importance of input i on output k
float[] sum_wj = new float[units[1]]; //sum of incoming weights into first hidden layer
float[] sum_wk = new float[units[2]]; //sum of incoming weights into output layer (or second hidden layer)
for (float[] Qi : Qik) Arrays.fill(Qi, 0f);
Arrays.fill(sum_wj, 0f);
Arrays.fill(sum_wk, 0f);
// compute sum of absolute incoming weights
for( int j = 0; j < units[1]; j++ ) {
for( int i = 0; i < units[0]; i++ ) {
float wij = get_weights(0).get(j, i);
sum_wj[j] += Math.abs(wij);
}
}
for( int k = 0; k < units[2]; k++ ) {
for( int j = 0; j < units[1]; j++ ) {
float wjk = get_weights(1).get(k,j);
sum_wk[k] += Math.abs(wjk);
}
}
// compute importance of input i on output k as product of connecting weights going through j
for( int i = 0; i < units[0]; i++ ) {
for( int k = 0; k < units[2]; k++ ) {
for( int j = 0; j < units[1]; j++ ) {
float wij = get_weights(0).get(j,i);
float wjk = get_weights(1).get(k,j);
//Qik[i][k] += Math.abs(wij)/sum_wj[j] * wjk; //Wong,Gedeon,Taggart '95
Qik[i][k] += Math.abs(wij)/sum_wj[j] * Math.abs(wjk)/sum_wk[k]; //Gedeon '97
}
}
}
// normalize Qik over all outputs k
for( int k = 0; k < units[2]; k++ ) {
float sumQk = 0;
for( int i = 0; i < units[0]; i++ ) sumQk += Qik[i][k];
for( int i = 0; i < units[0]; i++ ) Qik[i][k] /= sumQk;
}
// importance for feature i is the sum over k of i->k importances
for( int i = 0; i < units[0]; i++ ) vi[i] = ArrayUtils.sum(Qik[i]);
//normalize importances such that max(vi) = 1
ArrayUtils.div(vi, ArrayUtils.maxValue(vi));
return vi;
}
// compute stats on all nodes
public void computeStats() {
float[][] rate = get_params()._adaptive_rate ? new float[units.length-1][] : null;
if (get_params()._autoencoder && get_params()._sparsity_beta > 0) {
for (int k = 0; k < get_params()._hidden.length; k++) {
mean_a[k] = 0;
for (int j = 0; j < avg_activations[k].size(); j++)
mean_a[k] += avg_activations[k].get(j);
mean_a[k] /= avg_activations[k].size();
}
}
for( int y = 1; y < units.length; y++ ) {
mean_rate[y] = rms_rate[y] = 0;
mean_bias[y] = rms_bias[y] = 0;
mean_weight[y] = rms_weight[y] = 0;
for(int u = 0; u < biases[y-1].size(); u++) {
mean_bias[y] += biases[y-1].get(u);
}
if (rate != null) rate[y-1] = new float[get_weights(y-1).raw().length];
for(int u = 0; u < get_weights(y-1).raw().length; u++) {
mean_weight[y] += get_weights(y-1).raw()[u];
if (rate != null) {
// final float RMS_dx = (float)Math.sqrt(ada[y-1][2*u]+(float)get_params().epsilon);
// final float invRMS_g = (float)(1/Math.sqrt(ada[y-1][2*u+1]+(float)get_params().epsilon));
final float RMS_dx = MathUtils.approxSqrt(get_ada_dx_g(y-1).raw()[2*u]+(float)get_params()._epsilon);
final float invRMS_g = MathUtils.approxInvSqrt(get_ada_dx_g(y-1).raw()[2*u+1]+(float)get_params()._epsilon);
rate[y-1][u] = RMS_dx*invRMS_g; //not exactly right, RMS_dx should be from the previous time step -> but close enough for diagnostics.
mean_rate[y] += rate[y-1][u];
}
}
mean_bias[y] /= biases[y-1].size();
mean_weight[y] /= get_weights(y-1).size();
if (rate != null) mean_rate[y] /= rate[y-1].length;
for(int u = 0; u < biases[y-1].size(); u++) {
final double db = biases[y-1].get(u) - mean_bias[y];
rms_bias[y] += db * db;
}
for(int u = 0; u < get_weights(y-1).size(); u++) {
final double dw = get_weights(y-1).raw()[u] - mean_weight[y];
rms_weight[y] += dw * dw;
if (rate != null) {
final double drate = rate[y-1][u] - mean_rate[y];
rms_rate[y] += drate * drate;
}
}
rms_bias[y] = MathUtils.approxSqrt(rms_bias[y]/biases[y-1].size());
rms_weight[y] = MathUtils.approxSqrt(rms_weight[y] / get_weights(y - 1).size());
if (rate != null) rms_rate[y] = MathUtils.approxSqrt(rms_rate[y]/rate[y-1].length);
// rms_bias[y] = (float)Math.sqrt(rms_bias[y]/biases[y-1].length);
// rms_weight[y] = (float)Math.sqrt(rms_weight[y]/weights[y-1].length);
// if (rate != null) rms_rate[y] = (float)Math.sqrt(rms_rate[y]/rate[y-1].length);
// Abort the run if weights or biases are unreasonably large (Note that all input values are normalized upfront)
// This can happen with Rectifier units when L1/L2/max_w2 are all set to 0, especially when using more than 1 hidden layer.
final double thresh = 1e10;
unstable |= mean_bias[y] > thresh || isNaN(mean_bias[y])
|| rms_bias[y] > thresh || isNaN(rms_bias[y])
|| mean_weight[y] > thresh || isNaN(mean_weight[y])
|| rms_weight[y] > thresh || isNaN(rms_weight[y]);
}
}
}
/**
* Helper to allocate keys for output frames for weights and biases
* @param destKey
*/
private void makeWeightsBiases(Key destKey) {
_output.weights = new Key[model_info.get_params()._hidden.length + 1];
for (int i = 0; i < _output.weights.length; ++i) {
_output.weights[i] = Key.makeUserHidden(Key.make(destKey + ".weights." + i));
}
_output.biases = new Key[model_info.get_params()._hidden.length + 1];
for (int i = 0; i < _output.biases.length; ++i) {
_output.biases[i] = Key.makeUserHidden(Key.make(destKey + ".biases." + i));
}
}
/** Constructor to restart from a checkpointed model
* @param destKey New destination key for the model
* @param cp Checkpoint to restart from
* @param store_best_model Store only the best model instead of the latest one */
public DeepLearningModel(final Key destKey, final DeepLearningModel cp, final boolean store_best_model, final DataInfo dataInfo) {
super(destKey, (DeepLearningParameters)cp._parms.clone(), (DeepLearningModelOutput)cp._output.clone());
if (store_best_model) {
model_info = cp.model_info.deep_clone(); //don't want to interfere with model being built, just make a deep copy and store that
model_info.data_info = dataInfo.deep_clone(); //replace previous data_info with updated version that's passed in (contains enum for classification)
} else {
model_info = (DeepLearningModelInfo) cp.model_info.clone(); //shallow clone is ok (won't modify the Checkpoint in K-V store during checkpoint restart)
model_info.data_info = dataInfo; //shallow clone is ok
// Ok to modify (the normally immutable read-only) parameters, because
// this is a private copy just cloned above in the super() call.
_parms._checkpoint = cp._key; //it's only a "real" checkpoint if job != null, otherwise a best model copy
}
actual_best_model_key = cp.actual_best_model_key;
start_time = cp.start_time;
run_time = cp.run_time;
training_rows = cp.training_rows; //copy the value to display the right number on the model page before training has started
validation_rows = cp.validation_rows; //copy the value to display the right number on the model page before training has started
_bestError = cp._bestError;
// deep clone scoring history
errors = cp.errors.clone();
for (int i=0; i<errors.length;++i)
errors[i] = cp.errors[i].deep_clone();
_output.errors = last_scored();
makeWeightsBiases(destKey);
_output.scoring_history = createScoringHistoryTable(errors);
_output.variable_importances = calcVarImp(last_scored().variable_importances);
// set proper timing
_timeLastScoreEnter = System.currentTimeMillis();
_timeLastScoreStart = 0;
_timeLastScoreEnd = 0;
_timeLastPrintStart = 0;
assert(Arrays.equals(_key._kb, destKey._kb));
}
public DeepLearningModel(final Key destKey, final DeepLearningParameters parms, final DeepLearningModelOutput output, Frame train, Frame valid) {
super(destKey, parms, output);
boolean classification = train.lastVec().isEnum();
final DataInfo dinfo = new DataInfo(Key.make(), train, valid, parms._autoencoder ? 0 : 1, parms._autoencoder || parms._use_all_factor_levels, //use all FactorLevels for auto-encoder
parms._autoencoder ? DataInfo.TransformType.NORMALIZE : DataInfo.TransformType.STANDARDIZE, //transform predictors
classification ? DataInfo.TransformType.NONE : DataInfo.TransformType.STANDARDIZE, _parms._missing_values_handling == DeepLearningModel.DeepLearningParameters.MissingValuesHandling.Skip);
output._names = train._names ; // Since changed by DataInfo, need to be reflected in the Model output as well
output._domains= train.domains();
DKV.put(dinfo._key,dinfo);
model_info = new DeepLearningModelInfo(parms, dinfo, classification, train, valid);
actual_best_model_key = Key.makeUserHidden(Key.make());
if (parms._n_folds != 0) actual_best_model_key = null;
if (!parms._autoencoder) {
errors = new DeepLearningScoring[1];
errors[0] = new DeepLearningScoring();
errors[0].validation = (parms._valid != null);
errors[0].num_folds = parms._n_folds;
_output.errors = last_scored();
_output.scoring_history = createScoringHistoryTable(errors);
_output.variable_importances = calcVarImp(last_scored().variable_importances);
}
makeWeightsBiases(destKey);
run_time = 0;
start_time = System.currentTimeMillis();
_timeLastScoreEnter = start_time;
assert _key.equals(destKey);
}
public long _timeLastScoreEnter; //not transient: needed for HTML display page
transient private long _timeLastScoreStart;
transient private long _timeLastScoreEnd;
transient private long _timeLastPrintStart;
/**
*
* @param ftrain potentially downsampled training data for scoring
* @param ftest potentially downsampled validation data for scoring
* @param job_key key of the owning job
* @param progressKey key of the progress
* @return true if model building is ongoing
*/
boolean doScoring(Frame ftrain, Frame ftest, Key job_key, Key progressKey) {
boolean keep_running;
try {
final long now = System.currentTimeMillis();
epoch_counter = (float)model_info().get_processed_total()/training_rows;
final double time_last_iter_millis = Math.max(5,now-_timeLastScoreEnter);
// Auto-tuning
// if multi-node and auto-tuning and at least 10 ms for communication (to avoid doing thins on multi-JVM on same node),
// then adjust the auto-tuning parameter 'actual_train_samples_per_iteration' such that the targeted ratio of comm to comp is achieved
// Note: actual communication time is estimated by the NetworkTest's collective test.
if (H2O.CLOUD.size() > 1 && get_params()._train_samples_per_iteration == -2 && time_for_communication_us > 1e4) {
// Log.info("Time taken for communication: " + PrettyPrint.usecs((long)time_for_communication_us));
// Log.info("Time taken for Map/Reduce iteration: " + PrettyPrint.msecs((long)time_last_iter_millis, true));
final double comm_to_work_ratio = (time_for_communication_us *1e-3) / time_last_iter_millis;
// Log.info("Ratio of network communication to computation: " + String.format("%.3f", comm_to_work_ratio));
// Log.info("target_comm_to_work: " + get_params().target_ratio_comm_to_comp);
final double correction = get_params()._target_ratio_comm_to_comp / comm_to_work_ratio;
// Log.warn("Suggested value for train_samples_per_iteration: " + get_params().actual_train_samples_per_iteration/correction);
actual_train_samples_per_iteration /= correction;
actual_train_samples_per_iteration = Math.max(1, actual_train_samples_per_iteration);
}
run_time += time_last_iter_millis;
_timeLastScoreEnter = now;
keep_running = (epoch_counter < get_params()._epochs);
final long sinceLastScore = now -_timeLastScoreStart;
final long sinceLastPrint = now -_timeLastPrintStart;
if (!keep_running || sinceLastPrint > get_params()._score_interval * 1000) { //print this after every score_interval, not considering duty cycle
_timeLastPrintStart = now;
if (!get_params()._quiet_mode) {
Log.info("Training time: " + PrettyPrint.msecs(run_time, true)
+ ". Processed " + String.format("%,d", model_info().get_processed_total()) + " samples" + " (" + String.format("%.3f", epoch_counter) + " epochs)."
+ " Speed: " + String.format("%.3f", 1000. * model_info().get_processed_total() / run_time) + " samples/sec.\n");
}
}
// this is potentially slow - only do every so often
if( !keep_running ||
(sinceLastScore > get_params()._score_interval *1000 //don't score too often
&&(double)(_timeLastScoreEnd-_timeLastScoreStart)/sinceLastScore < get_params()._score_duty_cycle) ) { //duty cycle
if (progressKey != null) {
new Job.ProgressUpdate("Scoring on " + ftrain.numRows() + " training samples" +
(ftest != null ? (", " + ftest.numRows() + " validation samples)") : ")")
).fork(progressKey);
}
final boolean printme = !get_params()._quiet_mode;
_timeLastScoreStart = now;
if (get_params()._diagnostics) model_info().computeStats();
DeepLearningScoring err = new DeepLearningScoring();
err.training_time_ms = run_time;
err.epoch_counter = epoch_counter;
err.training_samples = model_info().get_processed_total();
err.validation = ftest != null;
err.score_training_samples = ftrain.numRows();
err.classification = _output.isClassifier();
if (get_params()._autoencoder) {
if (printme) Log.info("Scoring the auto-encoder.");
// training
{
final Frame mse_frame = scoreAutoEncoder(ftrain, Key.make());
final Vec l2 = mse_frame.anyVec();
Log.info("Mean reconstruction error on training data: " + l2.mean() + "\n");
err.train_mse = l2.mean();
mse_frame.delete();
}
} else {
if (printme) Log.info("Scoring the model.");
// compute errors
final String m = model_info().toString();
if (m.length() > 0) Log.info(m);
final Frame trainPredict = score(ftrain);
trainPredict.delete();
hex.ModelMetricsSupervised mm1 = (ModelMetricsSupervised)ModelMetrics.getFromDKV(this,ftrain);
if (mm1 instanceof ModelMetricsBinomial) {
ModelMetricsBinomial mm = (ModelMetricsBinomial)(mm1);
err.trainAUC = mm._aucdata;
err.train_confusion_matrix = mm._cm;
err.train_err = mm._cm.err();
}
else if (mm1 instanceof ModelMetricsMultinomial) {
ModelMetricsMultinomial mm = (ModelMetricsMultinomial)(mm1);
err.train_confusion_matrix = mm._cm;
err.train_err = mm._cm.err();
err.train_hitratio = mm._hit_ratios;
}
err.train_mse = mm1._mse;
err.train_r2 = mm1.r2();
_output.train_metrics = mm1;
_output.run_time = run_time;
if (ftest != null) {
Frame validPred = score(ftest);
validPred.delete();
hex.ModelMetricsSupervised mm2 = (ModelMetricsSupervised)hex.ModelMetrics.getFromDKV(this, ftest);
if (mm2 != null) {
if (mm2 instanceof ModelMetricsBinomial) {
ModelMetricsBinomial mm = (ModelMetricsBinomial) (mm2);
err.validAUC = mm._aucdata;
err.valid_confusion_matrix = mm._cm;
err.valid_err = mm._cm.err();
} else if (mm2 instanceof ModelMetricsMultinomial) {
ModelMetricsMultinomial mm = (ModelMetricsMultinomial) (mm2);
err.valid_confusion_matrix = mm._cm;
err.valid_err = mm._cm.err();
err.valid_hitratio = mm._hit_ratios;
}
err.valid_mse = mm2._mse;
err.valid_r2 = mm2.r2();
_output.valid_metrics = mm2;
}
}
}
if (get_params()._variable_importances) {
if (!get_params()._quiet_mode) Log.info("Computing variable importances.");
final float[] vi = model_info().computeVariableImportances();
err.variable_importances = new VarImp(vi, Arrays.copyOfRange(model_info().data_info().coefNames(), 0, vi.length));
}
_timeLastScoreEnd = System.currentTimeMillis();
err.scoring_time = System.currentTimeMillis() - now;
// enlarge the error array by one, push latest score back
if (errors == null) {
errors = new DeepLearningScoring[]{err};
} else {
DeepLearningScoring[] err2 = new DeepLearningScoring[errors.length + 1];
System.arraycopy(errors, 0, err2, 0, errors.length);
err2[err2.length - 1] = err;
errors = err2;
}
_output.errors = last_scored();
water.util.Timer t = new Timer();
// store weights and matrices to Frames
for (int i=0; i<_output.weights.length; ++i) {
model_info.get_weights(i).toFrame(_output.weights[i]);
}
for (int i=0; i<_output.biases.length; ++i) {
model_info.get_biases(i).toFrame(_output.biases[i]);
}
Log.info("Writing weights and biases to Frames took " + t.time()/1000. + " seconds.");
_output.scoring_history = createScoringHistoryTable(errors);
_output.variable_importances = calcVarImp(last_scored().variable_importances);
_output.model_summary = model_info.createSummaryTable();
if (!get_params()._autoencoder) {
// always keep a copy of the best model so far (based on the following criterion)
if (actual_best_model_key != null && get_params()._override_with_best_model && (
// if we have a best_model in DKV, then compare against its error() (unless it's a different model as judged by the network size)
(DKV.get(actual_best_model_key) != null && (error() < DKV.get(actual_best_model_key).<DeepLearningModel>get().error() || !Arrays.equals(model_info().units, DKV.get(actual_best_model_key).<DeepLearningModel>get().model_info().units)))
||
// otherwise, compare against our own _bestError
(DKV.get(actual_best_model_key) == null && error() < _bestError)
) ) {
if (!get_params()._quiet_mode)
Log.info("Error reduced from " + _bestError + " to " + error() + ".");
_bestError = error();
putMeAsBestModel(actual_best_model_key);
// debugging check
//if (false) {
// DeepLearningModel bestModel = DKV.get(actual_best_model_key).get();
// final Frame fr = ftest != null ? ftest : ftrain;
// final Frame bestPredict = bestModel.score(fr);
// final Frame hitRatio_bestPredict = new Frame(bestPredict);
// final double err3 = calcError(fr, fr.lastVec(), bestPredict, hitRatio_bestPredict, "cross-check",
// printme, get_params()._max_confusion_matrix_size, new hex.ConfusionMatrix2(), _output.isClassifier() && _output.nclasses() == 2 ? new AUC(null,null) : null, null);
// if (_output.isClassifier())
// assert (ftest != null ? Math.abs(err.valid_err - err3) < 1e-5 : Math.abs(err.train_err - err3) < 1e-5);
// else
// assert (ftest != null ? Math.abs(err.valid_mse - err3) < 1e-5 : Math.abs(err.train_mse - err3) < 1e-5);
// bestPredict.delete();
//}
}
// else {
// // keep output JSON small
// if (errors.length > 1) {
// if (last_scored().trainAUC != null) last_scored().trainAUC.clear();
// if (last_scored().validAUC != null) last_scored().validAUC.clear();
// last_scored().variable_importances = null;
// }
// }
// print the freshly scored model to ASCII
if (keep_running)
for (String s : toString().split("\n")) Log.info(s);
if (printme) Log.info("Time taken for scoring and diagnostics: " + PrettyPrint.msecs(err.scoring_time, true));
}
}
if (model_info().unstable()) {
Log.warn(unstable_msg);
keep_running = false;
} else if ( (_output.isClassifier() && last_scored().train_err <= get_params()._classification_stop)
|| (!_output.isClassifier() && last_scored().train_mse <= get_params()._regression_stop) ) {
Log.info("Achieved requested predictive accuracy on the training data. Model building completed.");
keep_running = false;
}
update(job_key);
}
catch (Exception ex) {
//ex.printStackTrace();
throw new RuntimeException(ex);
// return false;
}
return keep_running;
}
// @Override protected void setCrossValidationError(Parameters job, double cv_error, ConfusionMatrix cm, AUCData auc, HitRatio hr) {
// _have_cv_results = true;
// if (!get_params().classification)
// last_scored().valid_mse = cv_error;
// else
// last_scored().valid_err = cv_error;
// last_scored().score_validation_samples = last_scored().score_training_samples / get_params().n_folds;
// last_scored().num_folds = get_params().n_folds;
// last_scored().valid_confusion_matrix = cm;
// last_scored().validAUC = auc;
// last_scored().valid_hitratio = hr;
// DKV.put(this._key, this); //overwrite this model
// }
@Override public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(model_info.toString());
//sb.append(last_scored().toString());
sb.append(_output.scoring_history.toString());
if (_output.variable_importances != null) {
for (String s : Arrays.asList(_output.variable_importances.toString().split("\n")).subList(0, 12))
sb.append(s).append("\n");
}
return sb.toString();
}
/** Make either a prediction or a reconstruction.
* @param orig Test dataset
* @param adaptedFr Test dataset, adapted to the model
* @return A frame containing the prediction or reconstruction
*/
@Override protected Frame scoreImpl(Frame orig, Frame adaptedFr, String destination_key) {
if (!get_params()._autoencoder) {
return super.scoreImpl(orig,adaptedFr,destination_key);
} else {
// Reconstruction
final int len = model_info().data_info().fullN();
String prefix = "reconstr_";
assert(model_info().data_info()._responses == 0);
String[] coefnames = model_info().data_info().coefNames();
assert(len == coefnames.length);
Frame adaptFrm = new Frame(adaptedFr);
for( int c=0; c<len; c++ )
adaptFrm.add(prefix+coefnames[c],adaptFrm.anyVec().makeZero());
new MRTask() {
@Override public void map( Chunk chks[] ) {
double tmp [] = new double[_output._names.length];
float preds[] = new float [len];
final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info);
for( int row=0; row<chks[0]._len; row++ ) {
float p[] = score_autoencoder(chks, row, tmp, preds, neurons);
for( int c=0; c<preds.length; c++ )
chks[_output._names.length+c].set(row,p[c]);
}
}
}.doAll(adaptFrm);
// Return the predicted columns
int x=_output._names.length, y=adaptFrm.numCols();
Frame f = adaptFrm.extractFrame(x, y); //this will call vec_impl() and we cannot call the delete() below just yet
if (destination_key != null) {
Key k = Key.make(destination_key);
f = new Frame(k, f.names(), f.vecs());
DKV.put(k, f);
}
makeMetricBuilder(null).makeModelMetrics(this, orig, Double.NaN);
return f;
}
}
/**
* Predict from raw double values representing the data
* @param data raw array containing categorical values (horizontalized to 1,0,0,1,0,0 etc.) and numerical values (0.35,1.24,5.3234,etc), both can contain NaNs
* @param preds predicted label and per-class probabilities (for classification), predicted target (regression), can contain NaNs
* @return preds, can contain NaNs
*/
@Override public float[] score0(double[] data, float[] preds) {
if (model_info().unstable()) {
Log.warn(unstable_msg);
throw new UnsupportedOperationException("Trying to predict with an unstable model.");
}
Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info);
((Neurons.Input)neurons[0]).setInput(-1, data);
DeepLearningTask.step(-1, neurons, model_info, false, null);
float[] out = neurons[neurons.length - 1]._a.raw();
if (_output.isClassifier()) {
assert (preds.length == out.length + 1);
for (int i = 0; i < preds.length - 1; ++i) {
preds[i + 1] = out[i];
if (Float.isNaN(preds[i + 1])) throw new RuntimeException("Predicted class probability NaN!");
}
preds[0] = hex.genmodel.GenModel.getPrediction(preds, data);
} else {
if (model_info().data_info()._normRespMul != null)
preds[0] = (float) (out[0] / model_info().data_info()._normRespMul[0] + model_info().data_info()._normRespSub[0]);
else
preds[0] = out[0];
if (Float.isNaN(preds[0])) throw new RuntimeException("Predicted regression target NaN!");
}
return preds;
}
/**
* Score auto-encoded reconstruction (on-the-fly, without allocating the reconstruction as done in Frame score(Frame fr))
* @param frame Original data (can contain response, will be ignored)
* @return Frame containing one Vec with reconstruction error (MSE) of each reconstructed row, caller is responsible for deletion
*/
public Frame scoreAutoEncoder(Frame frame, Key destination_key) {
if (!get_params()._autoencoder)
throw new H2OIllegalArgumentException("Only for AutoEncoder Deep Learning model.", "");
final int len = _output._names.length;
Frame adaptFrm = new Frame(frame);
Vec v0 = adaptFrm.anyVec().makeZero();
Scope.enter();
adaptTestForTrain(adaptFrm,true);
adaptFrm.add("Reconstruction.MSE", v0);
new MRTask() {
@Override public void map( Chunk chks[] ) {
double tmp [] = new double[len];
final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info);
for( int row=0; row<chks[0]._len; row++ ) {
for( int i=0; i<len; i++ )
tmp[i] = chks[i].atd(row);
//store the per-row reconstruction error (MSE) in the last column
chks[len].set(row, score_autoencoder(tmp, null, neurons));
}
}
}.doAll(adaptFrm);
Scope.exit();
Frame res = adaptFrm.extractFrame(len, adaptFrm.numCols());
res = new Frame(destination_key, res.names(), res.vecs());
DKV.put(res);
makeMetricBuilder(null).makeModelMetrics(this, frame, res.vecs()[0].mean());
return res;
}
@Override public Frame score(Frame fr, String destination_key) {
if (!_parms._autoencoder)
return super.score(fr, destination_key);
else {
Frame adaptFr = new Frame(fr);
adaptTestForTrain(adaptFr, true); // Adapt
Frame output = scoreImpl(fr, adaptFr, destination_key); // Score
Vec[] vecs = adaptFr.vecs();
for (int i = 0; i < vecs.length; i++)
if (fr.find(vecs[i]) != -1) // Exists in the original frame?
vecs[i] = null; // Do not delete it
adaptFr.delete();
return output;
}
}
/**
* Score auto-encoded reconstruction (on-the-fly, and materialize the deep features of given layer
* @param frame Original data (can contain response, will be ignored)
* @param layer index of the hidden layer for which to extract the features
* @return Frame containing the deep features (#cols = hidden[layer])
*/
public Frame scoreDeepFeatures(Frame frame, final int layer) {
if (layer < 0 || layer >= model_info().get_params()._hidden.length)
throw new H2OIllegalArgumentException("hidden layer (index) to extract must be between " + 0 + " and " + (model_info().get_params()._hidden.length-1),"");
final int len = _output.nfeatures();
Vec resp = null;
if (isSupervised()) {
int ridx = frame.find(_output.responseName());
if (ridx != -1) { // drop the response for scoring!
frame = new Frame(frame);
resp = frame.vecs()[ridx];
frame.remove(ridx);
}
}
Frame adaptFrm = new Frame(frame);
//create new features, will be dense
final int features = model_info().get_params()._hidden[layer];
Vec[] vecs = adaptFrm.anyVec().makeZeros(features);
Scope.enter();
adaptTestForTrain(adaptFrm,true);
for (int j=0; j<features; ++j) {
adaptFrm.add("DF.C" + (j+1), vecs[j]);
}
new MRTask() {
@Override public void map( Chunk chks[] ) {
double tmp [] = new double[len];
final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info);
for( int row=0; row<chks[0]._len; row++ ) {
for( int i=0; i<len; i++ )
tmp[i] = chks[i].atd(row);
((Neurons.Input)neurons[0]).setInput(-1, tmp);
DeepLearningTask.step(-1, neurons, model_info, false, null);
float[] out = neurons[layer+1]._a.raw(); //extract the layer-th hidden feature
for( int c=0; c<features; c++ )
chks[_output._names.length+c].set(row,out[c]);
}
}
}.doAll(adaptFrm);
// Return just the output columns
int x=_output._names.length, y=adaptFrm.numCols();
Frame ret = adaptFrm.extractFrame(x, y);
if (resp != null) ret.prepend(_output.responseName(), resp);
Scope.exit();
return ret;
}
// Make (potentially expanded) reconstruction
private float[] score_autoencoder(Chunk[] chks, int row_in_chunk, double[] tmp, float[] preds, Neurons[] neurons) {
assert(get_params()._autoencoder);
assert(tmp.length == _output._names.length);
for( int i=0; i<tmp.length; i++ )
tmp[i] = chks[i].atd(row_in_chunk);
score_autoencoder(tmp, preds, neurons); // this fills preds, returns MSE error (ignored here)
return preds;
}
/**
* Helper to reconstruct original data into preds array and compute the reconstruction error (MSE)
* @param data Original data (unexpanded)
* @param preds Reconstruction (potentially expanded)
* @return reconstruction error
*/
private double score_autoencoder(double[] data, float[] preds, Neurons[] neurons) {
assert(model_info().get_params()._autoencoder);
if (model_info().unstable()) {
Log.warn(unstable_msg);
throw new UnsupportedOperationException("Trying to predict with an unstable model.");
}
((Neurons.Input)neurons[0]).setInput(-1, data); // expands categoricals inside
DeepLearningTask.step(-1, neurons, model_info, false, null); // reconstructs data in expanded space
float[] in = neurons[0]._a.raw(); //input (expanded)
float[] out = neurons[neurons.length - 1]._a.raw(); //output (expanded)
assert(in.length == out.length);
// First normalize categorical reconstructions to be probabilities
// (such that they can be better compared to the input where one factor was 1 and the rest was 0)
// model_info().data_info().softMaxCategoricals(out,out); //only modifies the categoricals
// Compute MSE of reconstruction in expanded space (with categorical probabilities)
double l2 = 0;
for (int i = 0; i < in.length; ++i)
l2 += Math.pow((out[i] - in[i]), 2);
l2 /= in.length;
if (preds!=null) {
// Now scale back numerical columns to original data space (scale + shift)
model_info().data_info().unScaleNumericals(out, out); //only modifies the numericals
System.arraycopy(out, 0, preds, 0, out.length); //copy reconstruction into preds
}
return l2;
}
/**
* Compute quantile-based threshold (in reconstruction error) to find outliers
* @param mse Vector containing reconstruction errors
* @param quantile Quantile for cut-off
* @return Threshold in MSE value for a point to be above the quantile
*/
public double calcOutlierThreshold(Vec mse, double quantile) {
Frame mse_frame = new Frame(Key.make(), new String[]{"Reconstruction.MSE"}, new Vec[]{mse});
DKV.put(mse_frame._key, mse_frame);
QuantileModel.QuantileParameters parms = new QuantileModel.QuantileParameters();
parms._train = mse_frame._key;
parms._probs = new double[]{quantile};
Quantile job = new Quantile(parms).trainModel();
QuantileModel kmm = job.get();
job.remove();
double q = kmm._output._quantiles[0][0];
kmm.delete();
DKV.remove(mse_frame._key);
return q;
}
// helper to push this model to another key (for keeping good models)
private void putMeAsBestModel(Key bestModelKey) {
DeepLearningModel bestModel = new DeepLearningModel(bestModelKey, this, true, model_info().data_info());
DKV.put(bestModel._key, bestModel);
assert (DKV.get(bestModelKey) != null);
assert (bestModel.compareTo(this) <= 0);
}
@Override public void delete() {
for (Key k : _output.weights) {
if (DKV.getGet(k) != null) ((Frame)DKV.getGet(k)).delete();
}
for (Key k : _output.biases) {
if (DKV.getGet(k) != null) ((Frame)DKV.getGet(k)).delete();
}
super.delete();
}
void delete_xval_models( ) {
// if (get_params().xval_models != null) {
// for (Key k : get_params().xval_models) {
// DKV.get(k).<DeepLearningModel>get().delete_best_model();
// DKV.get(k).<DeepLearningModel>get().delete();
// }
// }
}
transient private final String unstable_msg = "Job was aborted due to observed numerical instability (exponential growth)."
+ "\nTry a different initial distribution, a bounded activation function or adding"
+ "\nregularization with L1, L2 or max_w2 and/or use a smaller learning rate or faster annealing.";
}
| h2o-algos/src/main/java/hex/deeplearning/DeepLearningModel.java | package hex.deeplearning;
import hex.*;
import hex.quantile.Quantile;
import hex.quantile.QuantileModel;
import hex.schemas.DeepLearningModelV2;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import water.*;
import water.api.ModelSchema;
import water.exceptions.H2OIllegalArgumentException;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.Vec;
import water.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import static hex.ModelMetrics.calcVarImp;
import static java.lang.Double.isNaN;
/**
* The Deep Learning model
* It contains a DeepLearningModelInfo with the most up-to-date model,
* a scoring history, as well as some helpers to indicate the progress
*/
public class DeepLearningModel extends SupervisedModel<DeepLearningModel,DeepLearningModel.DeepLearningParameters,DeepLearningModel.DeepLearningModelOutput> implements Model.DeepFeatures {
public static class DeepLearningParameters extends SupervisedModel.SupervisedParameters {
public int _n_folds;
public boolean _keep_cross_validation_splits;
/**
* A model key associated with a previously trained Deep Learning
* model. This option allows users to build a new model as a
* continuation of a previously generated model (e.g., by a grid search).
*/
public Key _checkpoint;
/**
* If enabled, store the best model under the destination key of this model at the end of training.
* Only applicable if training is not cancelled.
*/
public boolean _override_with_best_model = true;
/**
* Unlock expert mode parameters than can affect model building speed,
* predictive accuracy and scoring. Leaving expert mode parameters at default
* values is fine for many problems, but best results on complex datasets are often
* only attainable via expert mode options.
*/
public boolean _expert_mode = false;
public boolean _autoencoder = false;
public boolean _use_all_factor_levels = true;
/*Neural Net Topology*/
/**
* The activation function (non-linearity) to be used the neurons in the hidden layers.
* Tanh: Hyperbolic tangent function (same as scaled and shifted sigmoid).
* Rectifier: Chooses the maximum of (0, x) where x is the input value.
* Maxout: Choose the maximum coordinate of the input vector.
* With Dropout: Zero out a random user-given fraction of the
* incoming weights to each hidden layer during training, for each
* training row. This effectively trains exponentially many models at
* once, and can improve generalization.
*/
public Activation _activation = Activation.Rectifier;
/**
* The number and size of each hidden layer in the model.
* For example, if a user specifies "100,200,100" a model with 3 hidden
* layers will be produced, and the middle hidden layer will have 200
* neurons.To specify a grid search, add parentheses around each
* model's specification: "(100,100), (50,50,50), (20,20,20,20)".
*/
public int[] _hidden = new int[] { 200, 200 };
/**
* The number of passes over the training dataset to be carried out.
* It is recommended to start with lower values for initial grid searches.
* This value can be modified during checkpoint restarts and allows continuation
* of selected models.
*/
public double _epochs = 10;
/**
* The number of training data rows to be processed per iteration. Note that
* independent of this parameter, each row is used immediately to update the model
* with (online) stochastic gradient descent. This parameter controls the
* synchronization period between nodes in a distributed environment and the
* frequency at which scoring and model cancellation can happen. For example, if
* it is set to 10,000 on H2O running on 4 nodes, then each node will
* process 2,500 rows per iteration, sampling randomly from their local data.
* Then, model averaging between the nodes takes place, and scoring can happen
* (dependent on scoring interval and duty factor). Special values are 0 for
* one epoch per iteration, -1 for processing the maximum amount of data
* per iteration (if **replicate training data** is enabled, N epochs
* will be trained per iteration on N nodes, otherwise one epoch). Special value
* of -2 turns on automatic mode (auto-tuning).
*/
public long _train_samples_per_iteration = -2;
public double _target_ratio_comm_to_comp = 0.02;
/**
* The random seed controls sampling and initialization. Reproducible
* results are only expected with single-threaded operation (i.e.,
* when running on one node, turning off load balancing and providing
* a small dataset that fits in one chunk). In general, the
* multi-threaded asynchronous updates to the model parameters will
* result in (intentional) race conditions and non-reproducible
* results. Note that deterministic sampling and initialization might
* still lead to some weak sense of determinism in the model.
*/
public long _seed = new Random().nextLong();
/*Adaptive Learning Rate*/
/**
* The implemented adaptive learning rate algorithm (ADADELTA) automatically
* combines the benefits of learning rate annealing and momentum
* training to avoid slow convergence. Specification of only two
* parameters (rho and epsilon) simplifies hyper parameter search.
* In some cases, manually controlled (non-adaptive) learning rate and
* momentum specifications can lead to better results, but require the
* specification (and hyper parameter search) of up to 7 parameters.
* If the model is built on a topology with many local minima or
* long plateaus, it is possible for a constant learning rate to produce
* sub-optimal results. Learning rate annealing allows digging deeper into
* local minima, while rate decay allows specification of different
* learning rates per layer. When the gradient is being estimated in
* a long valley in the optimization landscape, a large learning rate
* can cause the gradient to oscillate and move in the wrong
* direction. When the gradient is computed on a relatively flat
* surface with small learning rates, the model can converge far
* slower than necessary.
*/
public boolean _adaptive_rate = true;
/**
* The first of two hyper parameters for adaptive learning rate (ADADELTA).
* It is similar to momentum and relates to the memory to prior weight updates.
* Typical values are between 0.9 and 0.999.
* This parameter is only active if adaptive learning rate is enabled.
*/
public double _rho = 0.99;
/**
* The second of two hyper parameters for adaptive learning rate (ADADELTA).
* It is similar to learning rate annealing during initial training
* and momentum at later stages where it allows forward progress.
* Typical values are between 1e-10 and 1e-4.
* This parameter is only active if adaptive learning rate is enabled.
*/
public double _epsilon = 1e-8;
/*Learning Rate*/
/**
* When adaptive learning rate is disabled, the magnitude of the weight
* updates are determined by the user specified learning rate
* (potentially annealed), and are a function of the difference
* between the predicted value and the target value. That difference,
* generally called delta, is only available at the output layer. To
* correct the output at each hidden layer, back propagation is
* used. Momentum modifies back propagation by allowing prior
* iterations to influence the current update. Using the momentum
* parameter can aid in avoiding local minima and the associated
* instability. Too much momentum can lead to instabilities, that's
* why the momentum is best ramped up slowly.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _rate = .005;
/**
* Learning rate annealing reduces the learning rate to "freeze" into
* local minima in the optimization landscape. The annealing rate is the
* inverse of the number of training samples it takes to cut the learning rate in half
* (e.g., 1e-6 means that it takes 1e6 training samples to halve the learning rate).
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _rate_annealing = 1e-6;
/**
* The learning rate decay parameter controls the change of learning rate across layers.
* For example, assume the rate parameter is set to 0.01, and the rate_decay parameter is set to 0.5.
* Then the learning rate for the weights connecting the input and first hidden layer will be 0.01,
* the learning rate for the weights connecting the first and the second hidden layer will be 0.005,
* and the learning rate for the weights connecting the second and third hidden layer will be 0.0025, etc.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _rate_decay = 1.0;
/*Momentum*/
/**
* The momentum_start parameter controls the amount of momentum at the beginning of training.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _momentum_start = 0;
/**
* The momentum_ramp parameter controls the amount of learning for which momentum increases
* (assuming momentum_stable is larger than momentum_start). The ramp is measured in the number
* of training samples.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _momentum_ramp = 1e6;
/**
* The momentum_stable parameter controls the final momentum value reached after momentum_ramp training samples.
* The momentum used for training will remain the same for training beyond reaching that point.
* This parameter is only active if adaptive learning rate is disabled.
*/
public double _momentum_stable = 0;
/**
* The Nesterov accelerated gradient descent method is a modification to
* traditional gradient descent for convex functions. The method relies on
* gradient information at various points to build a polynomial approximation that
* minimizes the residuals in fewer iterations of the descent.
* This parameter is only active if adaptive learning rate is disabled.
*/
public boolean _nesterov_accelerated_gradient = true;
/*Regularization*/
/**
* A fraction of the features for each training row to be omitted from training in order
* to improve generalization (dimension sampling).
*/
public double _input_dropout_ratio = 0.0;
/**
* A fraction of the inputs for each hidden layer to be omitted from training in order
* to improve generalization. Defaults to 0.5 for each hidden layer if omitted.
*/
public double[] _hidden_dropout_ratios;
/**
* A regularization method that constrains the absolute value of the weights and
* has the net effect of dropping some weights (setting them to zero) from a model
* to reduce complexity and avoid overfitting.
*/
public double _l1 = 0.0;
/**
* A regularization method that constrdains the sum of the squared
* weights. This method introduces bias into parameter estimates, but
* frequently produces substantial gains in modeling as estimate variance is
* reduced.
*/
public double _l2 = 0.0;
/**
* A maximum on the sum of the squared incoming weights into
* any one neuron. This tuning parameter is especially useful for unbound
* activation functions such as Maxout or Rectifier.
*/
public float _max_w2 = Float.POSITIVE_INFINITY;
/*Initialization*/
/**
* The distribution from which initial weights are to be drawn. The default
* option is an optimized initialization that considers the size of the network.
* The "uniform" option uses a uniform distribution with a mean of 0 and a given
* interval. The "normal" option draws weights from the standard normal
* distribution with a mean of 0 and given standard deviation.
*/
public InitialWeightDistribution _initial_weight_distribution = InitialWeightDistribution.UniformAdaptive;
/**
* The scale of the distribution function for Uniform or Normal distributions.
* For Uniform, the values are drawn uniformly from -initial_weight_scale...initial_weight_scale.
* For Normal, the values are drawn from a Normal distribution with a standard deviation of initial_weight_scale.
*/
public double _initial_weight_scale = 1.0;
/**
* The loss (error) function to be minimized by the model.
* Cross Entropy loss is used when the model output consists of independent
* hypotheses, and the outputs can be interpreted as the probability that each
* hypothesis is true. Cross entropy is the recommended loss function when the
* target values are class labels, and especially for imbalanced data.
* It strongly penalizes error in the prediction of the actual class label.
* Mean Square loss is used when the model output are continuous real values, but can
* be used for classification as well (where it emphasizes the error on all
* output classes, not just for the actual class).
*/
public Loss _loss = null;
/*Scoring*/
/**
* The minimum time (in seconds) to elapse between model scoring. The actual
* interval is determined by the number of training samples per iteration and the scoring duty cycle.
*/
public double _score_interval = 5;
/**
* The number of training dataset points to be used for scoring. Will be
* randomly sampled. Use 0 for selecting the entire training dataset.
*/
public long _score_training_samples = 10000l;
/**
* The number of validation dataset points to be used for scoring. Can be
* randomly sampled or stratified (if "balance classes" is set and "score
* validation sampling" is set to stratify). Use 0 for selecting the entire
* training dataset.
*/
public long _score_validation_samples = 0l;
/**
* Maximum fraction of wall clock time spent on model scoring on training and validation samples,
* and on diagnostics such as computation of feature importances (i.e., not on training).
*/
public double _score_duty_cycle = 0.1;
/**
* The stopping criteria in terms of classification error (1-accuracy) on the
* training data scoring dataset. When the error is at or below this threshold,
* training stops.
*/
public double _classification_stop = 0;
/**
* The stopping criteria in terms of regression error (MSE) on the training
* data scoring dataset. When the error is at or below this threshold, training
* stops.
*/
public double _regression_stop = 1e-6;
/**
* Enable quiet mode for less output to standard output.
*/
public boolean _quiet_mode = false;
/**
* Method used to sample the validation dataset for scoring, see Score Validation Samples above.
*/
public ClassSamplingMethod _score_validation_sampling = ClassSamplingMethod.Uniform;
/*Misc*/
/**
* Gather diagnostics for hidden layers, such as mean and RMS values of learning
* rate, momentum, weights and biases.
*/
public boolean _diagnostics = true;
/**
* Whether to compute variable importances for input features.
* The implemented method (by Gedeon) considers the weights connecting the
* input features to the first two hidden layers.
*/
public boolean _variable_importances = false;
/**
* Enable fast mode (minor approximation in back-propagation), should not affect results significantly.
*/
public boolean _fast_mode = true;
/**
* Ignore constant training columns (no information can be gained anyway).
*/
public boolean _ignore_const_cols = true;
/**
* Increase training speed on small datasets by splitting it into many chunks
* to allow utilization of all cores.
*/
public boolean _force_load_balance = true;
/**
* Replicate the entire training dataset onto every node for faster training on small datasets.
*/
public boolean _replicate_training_data = true;
/**
* Run on a single node for fine-tuning of model parameters. Can be useful for
* checkpoint resumes after training on multiple nodes for fast initial
* convergence.
*/
public boolean _single_node_mode = false;
/**
* Enable shuffling of training data (on each node). This option is
* recommended if training data is replicated on N nodes, and the number of training samples per iteration
* is close to N times the dataset size, where all nodes train will (almost) all
* the data. It is automatically enabled if the number of training samples per iteration is set to -1 (or to N
* times the dataset size or larger).
*/
public boolean _shuffle_training_data = false;
public MissingValuesHandling _missing_values_handling = MissingValuesHandling.MeanImputation;
public boolean _sparse = false;
public boolean _col_major = false;
public double _average_activation = 0;
public double _sparsity_beta = 0;
/**
* Max. number of categorical features, enforced via hashing (Experimental)
*/
public int _max_categorical_features = Integer.MAX_VALUE;
/**
* Force reproducibility on small data (will be slow - only uses 1 thread)
*/
public boolean _reproducible = false;
public enum MissingValuesHandling {
Skip, MeanImputation
}
public enum ClassSamplingMethod {
Uniform, Stratified
}
public enum InitialWeightDistribution {
UniformAdaptive, Uniform, Normal
}
/**
* Activation functions
*/
public enum Activation {
Tanh, TanhWithDropout, Rectifier, RectifierWithDropout, Maxout, MaxoutWithDropout
}
/**
* Loss functions
* CrossEntropy is recommended for classification, MeanSquare for regression (or classification)
*/
public enum Loss {
MeanSquare, CrossEntropy, MeanSquareClassification
}
void validate( DeepLearning dl, boolean expensive ) {
boolean classification = expensive ? dl.isClassifier() : (_loss == Loss.CrossEntropy || _loss == Loss.MeanSquareClassification);
if (_hidden == null || _hidden.length == 0) dl.error("_hidden", "There must be at least one hidden layer.");
for( int h : _hidden ) if( h==0 ) dl.error("_hidden", "Hidden layer size must be >0.");
if (!_autoencoder) {
if (_valid == null)
dl.hide("_score_validation_samples", "score_validation_samples requires a validation frame.");
if (classification) {
dl.hide("_regression_stop", "regression_stop is used only with regression.");
} else {
dl.hide("_classification_stop", "classification_stop is used only with classification.");
dl.hide("_max_confusion_matrix_size", "max_confusion_matrix_size is used only with classification.");
dl.hide("_max_hit_ratio_k", "max_hit_ratio_k is used only with classification.");
dl.hide("_balance_classes", "balance_classes is used only with classification.");
}
if( !classification || !_balance_classes )
dl.hide("_class_sampling_factors", "class_sampling_factors requires both classification and balance_classes.");
if (!classification && _valid != null || _valid == null)
dl.hide("_score_validation_sampling", "score_validation_sampling requires regression and a validation frame OR no validation frame.");
}
// Auto-fill defaults
if (_activation != Activation.TanhWithDropout && _activation != Activation.MaxoutWithDropout && _activation != Activation.RectifierWithDropout)
dl.hide("_hidden_dropout_ratios", "hidden_dropout_ratios requires a dropout activation function.");
if (_hidden_dropout_ratios == null) {
if (_activation == Activation.TanhWithDropout || _activation == Activation.MaxoutWithDropout || _activation == Activation.RectifierWithDropout) {
if (expensive) {
_hidden_dropout_ratios = new double[_hidden.length];
if (!_quiet_mode)
dl.info("_hidden_dropout_ratios", "Automatically setting all hidden dropout ratios to 0.5.");
Arrays.fill(_hidden_dropout_ratios, 0.5);
}
}
}
else if (_hidden_dropout_ratios.length != _hidden.length) {
dl.error("_hidden_dropout_ratios", "Must have " + _hidden.length + " hidden layer dropout ratios.");
}
else if (_activation != Activation.TanhWithDropout && _activation != Activation.MaxoutWithDropout && _activation != Activation.RectifierWithDropout) {
if (!_quiet_mode) dl.hide("_hidden_dropout_ratios", "Ignoring hidden_dropout_ratios because a non-dropout activation function was specified.");
}
if (_input_dropout_ratio < 0 || _input_dropout_ratio >= 1)
dl.error("_input_dropout_ratio", "Input dropout must be in [0,1).");
if (H2O.CLOUD.size() == 1 && _replicate_training_data) {
dl.hide("_replicate_training_data", "replicate_training_data is only valid with cloud size greater than 1.");
if (expensive) {
dl.info("_replicate_training_data", "Disabling replicate_training_data on 1 node.");
_replicate_training_data = false;
}
}
if (_single_node_mode && (H2O.CLOUD.size() == 1 || !_replicate_training_data)) {
dl.hide("_single_node_mode", "single_node_mode is only used with multi-node operation with replicated training data.");
if (expensive) {
dl.info("_single_node_mode", "Disabling single_node_mode (only for multi-node operation with replicated training data).");
_single_node_mode = false;
}
}
if (_autoencoder) {
dl.hide("_use_all_factor_levels", "use_all_factor_levels is unsupported in combination with autoencoder.");
}
if (!_use_all_factor_levels && _autoencoder ) {
if (expensive) {
dl.warn("_use_all_factor_levels", "Enabling all_factor_levels for auto-encoders.");
_use_all_factor_levels = true;
}
}
if (_n_folds != 0)
dl.hide("_override_with_best_model", "override_with_best_model is unsupported in combination with n-fold cross-validation.");
if(_override_with_best_model && _n_folds != 0) {
if (expensive) {
dl.warn("_override_with_best_model", "Disabling override_with_best_model in combination with n-fold cross-validation.");
_override_with_best_model = false;
}
}
if (_adaptive_rate) {
dl.hide("_rate", "rate is not used with adaptive_rate.");
dl.hide("_rate_annealing", "rate_annealing is not used with adaptive_rate.");
dl.hide("_rate_decay", "rate_decay is not used with adaptive_rate.");
dl.hide("_momentum_start", "momentum_start is not used with adaptive_rate.");
dl.hide("_momentum_ramp", "momentum_ramp is not used with adaptive_rate.");
dl.hide("_momentum_stable", "momentum_stable is not used with adaptive_rate.");
dl.hide("_nesterov_accelerated_gradient", "nesterov_accelerated_gradient is not used with adaptive_rate.");
} else {
// ! adaptive_rate
dl.hide("_rho", "rho is only used with adaptive_rate.");
dl.hide("_epsilon", "epsilon is only used with adaptive_rate.");
}
if (!_quiet_mode) {
if (_adaptive_rate) {
if (expensive) {
dl.info("_adaptive_rate", "Using automatic learning rate. Ignoring the following input parameters: "
+ "rate, rate_decay, rate_annealing, momentum_start, momentum_ramp, momentum_stable, nesterov_accelerated_gradient.");
_momentum_start = 0;
_momentum_stable = 0;
}
} else {
if (expensive) {
dl.info("_adaptive_rate", "Using manual learning rate. Ignoring the following input parameters: "
+ "rho, epsilon.");
_rho = 0;
_epsilon = 0;
}
}
if (_initial_weight_distribution == InitialWeightDistribution.UniformAdaptive) {
dl.hide("_initial_weight_scale", "initial_weight_scale is not used if initial_weight_distribution == UniformAdaptive.");
}
if (_n_folds != 0) {
if (expensive) {
if (_override_with_best_model) {
dl.warn("_override_with_best_model", "Automatically disabling override_with_best_model, since the final model is the only scored model with n-fold cross-validation.");
_override_with_best_model = false;
}
}
}
}
if (expensive) { //otherwise, we might not know whether classification=true or false (from R, for example, the training data isn't known when init(false) is called).
if (_loss == null)
dl.error("_loss", "Loss function must be specified. For classification, use CrossEntropy or MeanSquareClassification. For regression, use MeanSquare.");
else if (_autoencoder && _loss != Loss.MeanSquare)
dl.error("_loss", "Must use MeanSquare loss function for auto-encoder.");
else if (!classification && _loss == Loss.CrossEntropy)
dl.error("_loss", "Cannot use CrossEntropy loss function for regression (numerical response).");
else if (!classification && _loss == Loss.MeanSquareClassification)
dl.error("_loss", "Cannot use MeanSquareClassification loss function for regression (numerical response).");
else if (classification && _loss == Loss.MeanSquare)
dl.error("_loss", "Cannot use MeanSquare loss function for classification (categorical response).");
}
if (_score_training_samples < 0) {
dl.error("_score_training_samples", "Number of training samples for scoring must be >= 0 (0 for all).");
}
if (_score_validation_samples < 0) {
dl.error("_score_validation_samples", "Number of training samples for scoring must be >= 0 (0 for all).");
}
if(_autoencoder && _sparsity_beta > 0) {
if (_activation == Activation.Tanh || _activation == Activation.TanhWithDropout) {
if (_average_activation >= 1 || _average_activation <= -1)
dl.error("_average_activation", "Tanh average activation must be in (-1,1).");
}
else if (_activation == Activation.Rectifier || _activation == Activation.RectifierWithDropout) {
if (_average_activation <= 0)
dl.error("_average_activation", "Rectifier average activation must be positive.");
}
}
if (!_autoencoder && _sparsity_beta != 0) dl.info("_sparsity_beta", "Sparsity beta can only be used for autoencoder.");
// reason for the error message below is that validation might not have the same horizontalized features as the training data (or different order)
if (_autoencoder && _valid != null) dl.error("_validation_frame", "Cannot specify a validation dataset for auto-encoder.");
if (_autoencoder && _activation == Activation.Maxout) dl.error("_activation", "Maxout activation is not supported for auto-encoder.");
if (_max_categorical_features < 1) dl.error("_max_categorical_features", "max_categorical_features must be at least 1.");
if (!_sparse && _col_major) {
if (!_quiet_mode) dl.error("_col_major", "Cannot use column major storage for non-sparse data handling.");
}
if (expensive) {
if (!classification && _balance_classes) {
dl.error("_balance_classes", "balance_classes requires classification to be enabled.");
}
if (_class_sampling_factors != null && !_balance_classes) {
dl.error("_class_sampling_factors", "class_sampling_factors requires balance_classes to be enabled.");
}
}
if (_reproducible) {
if (expensive) {
if (!_quiet_mode)
Log.info("Automatically enabling force_load_balancing, disabling single_node_mode and replicate_training_data\nand setting train_samples_per_iteration to -1 to enforce reproducibility.");
_force_load_balance = true;
_single_node_mode = false;
_train_samples_per_iteration = -1;
_replicate_training_data = false; //there's no benefit from having multiple nodes compute the exact same thing, and then average it back to the same
// replicate_training_data = true; //doesn't hurt, but does replicated identical work
}
}
}
}
public static class DeepLearningModelOutput extends SupervisedModel.SupervisedOutput {
public DeepLearningModelOutput() { super(); }
public DeepLearningModelOutput(DeepLearning b) { super(b); }
boolean autoencoder;
Key[] weights;
Key[] biases;
DeepLearningScoring errors;
TwoDimTable model_summary;
TwoDimTable scoring_history;
TwoDimTable variable_importances;
ModelMetrics train_metrics;
ModelMetrics valid_metrics;
double run_time;
@Override public ModelCategory getModelCategory() {
return autoencoder ? ModelCategory.AutoEncoder : super.getModelCategory();
}
@Override public boolean isSupervised() { return !autoencoder; }
}
// Default publicly visible Schema is V2
public ModelSchema schema() { return new DeepLearningModelV2(); }
private volatile DeepLearningModelInfo model_info;
void set_model_info(DeepLearningModelInfo mi) { model_info = mi; }
final public DeepLearningModelInfo model_info() { return model_info; }
public long run_time;
private long start_time;
public long actual_train_samples_per_iteration;
public double time_for_communication_us; //helper for auto-tuning: time in microseconds for collective bcast/reduce of the model
public double epoch_counter;
public long training_rows;
public long validation_rows;
private DeepLearningScoring[] errors;
public DeepLearningScoring[] scoring_history() { return errors; }
// Keep the best model so far, based on a single criterion (overall class. error or MSE)
private float _bestError = Float.POSITIVE_INFINITY;
public Key actual_best_model_key;
// return the most up-to-date model metrics
DeepLearningScoring last_scored() { return errors == null ? null : errors[errors.length-1]; }
// @Override
public final DeepLearningParameters get_params() { return _parms; }
// @Override public final Request2 job() { return get_params(); }
// double missingColumnsType() { return get_params()._sparse ? 0 : Double.NaN; }
public float error() { return (float) (_output.isClassifier() ? cm().err() : mse()); }
@Override public ModelMetrics.MetricBuilder makeMetricBuilder(String[] domain) {
switch(_output.getModelCategory()) {
case Binomial: return new ModelMetricsBinomial.MetricBuilderBinomial(domain, ModelUtils.DEFAULT_THRESHOLDS);
case Multinomial: return new ModelMetricsMultinomial.MetricBuilderMultinomial(_output.nclasses(),domain);
case Regression: return new ModelMetricsRegression.MetricBuilderRegression();
case AutoEncoder: return new ModelMetricsAutoEncoder.MetricBuilderAutoEncoder(_output.nfeatures());
default: throw H2O.unimpl();
}
}
public int compareTo(DeepLearningModel o) {
if (o._output.isClassifier() != _output.isClassifier()) throw new UnsupportedOperationException("Cannot compare classifier against regressor.");
if (o._output.nclasses() != _output.nclasses()) throw new UnsupportedOperationException("Cannot compare models with different number of classes.");
return (error() < o.error() ? -1 : error() > o.error() ? 1 : 0);
}
public static class DeepLearningScoring extends Iced {
// static final int API_WEAVER = 1;
// static public DocGen.FieldDoc[] DOC_FIELDS;
public double epoch_counter;
public long training_samples;
public long training_time_ms;
//training/validation sets
boolean validation;
int num_folds;
public long score_training_samples;
public long score_validation_samples;
public boolean classification;
VarImp variable_importances;
// classification
public ConfusionMatrix train_confusion_matrix;
public ConfusionMatrix valid_confusion_matrix;
public double train_err = 1;
public double valid_err = 1;
public AUCData trainAUC;
public AUCData validAUC;
public float[] train_hitratio; // "Hit ratio on training data"
public float[] valid_hitratio; // "Hit ratio on validation data"
// regression
public double train_mse = Double.NaN;
public double valid_mse = Double.NaN;
public double train_r2 = Double.NaN;
public double valid_r2 = Double.NaN;
public long scoring_time;
DeepLearningScoring deep_clone() {
AutoBuffer ab = new AutoBuffer();
this.write(ab);
ab.flipForReading();
return (DeepLearningScoring) new DeepLearningScoring().read(ab);
}
@Override public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Training MSE: " + train_mse + "\n");
if (classification) {
sb.append("Training R^2: " + train_r2 + "\n");
sb.append("Training " + train_confusion_matrix.table.toString(1));
sb.append("Training Misclassification"
+ (trainAUC != null ? " [using threshold for " + trainAUC.threshold_criterion.toString().replace("_", " ") + "]: " : ": ")
+ String.format("%.2f", 100 * train_err) + "%");
if (trainAUC != null) sb.append(", AUC: " + String.format("%.4f", 100 * trainAUC.AUC) + "%");
}
if (validation || num_folds>0) {
if (num_folds > 0) {
sb.append("\nDoing " + num_folds + "-fold cross-validation:");
}
sb.append("\nValidation MSE: " + valid_mse + "\n");
sb.append("Validation R^2: " + valid_r2 + "\n");
if (classification) {
sb.append("Validation " + valid_confusion_matrix.table.toString(1));
sb.append("Validation Misclassification"
+ (validAUC != null ? " [using threshold for " + validAUC.threshold_criterion.toString().replace("_", " ") + "]: " : ": ")
+ String.format("%.2f", (100 * valid_err)) + "%");
if (validAUC != null) sb.append(", AUC: " + String.format("%.4f", 100 * validAUC.AUC) + "%");
}
}
sb.append("\n");
return sb.toString();
}
}
final private static class ConfMat extends ConfusionMatrix {
final private double _err;
final private double _f1;
public ConfMat(double err, double f1) {
super(null, null);
_err=err;
_f1=f1;
}
@Override public double err() { return _err; }
@Override public double F1() { return _f1; }
@Override public double[] classErr() { return null; }
}
/** for grid search error reporting */
// @Override
public ConfusionMatrix cm() {
final DeepLearningScoring lasterror = last_scored();
if (lasterror == null) return null;
ConfusionMatrix cm = lasterror.validation || lasterror.num_folds > 0 ?
lasterror.valid_confusion_matrix :
lasterror.train_confusion_matrix;
if (cm == null ) {
if (lasterror.validation || lasterror.num_folds > 0) {
return new ConfMat(lasterror.valid_err, lasterror.validAUC != null ? lasterror.validAUC.F1() : 0);
} else {
return new ConfMat(lasterror.train_err, lasterror.trainAUC != null ? lasterror.trainAUC.F1() : 0);
}
}
return cm;
}
// @Override
public double mse() {
if (errors == null) return Double.NaN;
return last_scored().validation || last_scored().num_folds > 0 ? last_scored().valid_mse : last_scored().train_mse;
}
// @Override
public VarImp varimp() {
if (errors == null) return null;
return last_scored().variable_importances;
}
private TwoDimTable createScoringHistoryTable(DeepLearningScoring[] errors) {
return createScoringHistoryTable(errors, 20);
}
private TwoDimTable createScoringHistoryTable(DeepLearningScoring[] errors, final int size_limit) {
assert (size_limit >= 10);
List<String> colHeaders = new ArrayList<>();
List<String> colTypes = new ArrayList<>();
List<String> colFormat = new ArrayList<>();
colHeaders.add("Timestamp"); colTypes.add("string"); colFormat.add("%s");
colHeaders.add("Training Duration"); colTypes.add("string"); colFormat.add("%s");
colHeaders.add("Training Speed"); colTypes.add("string"); colFormat.add("%s");
colHeaders.add("Training Epochs"); colTypes.add("double"); colFormat.add("%.5f");
colHeaders.add("Training Samples"); colTypes.add("long"); colFormat.add("%d");
colHeaders.add("Training MSE"); colTypes.add("double"); colFormat.add("%.5f");
if (!_output.autoencoder) {
colHeaders.add("Training R^2");
colTypes.add("double");
colFormat.add("%.5f");
}
if (_output.getModelCategory() == ModelCategory.Binomial) {
colHeaders.add("Training AUC");
colTypes.add("double");
colFormat.add("%.5f");
}
if (_output.getModelCategory() == ModelCategory.Binomial || _output.getModelCategory() == ModelCategory.Multinomial) {
colHeaders.add("Training Classification Error");
colTypes.add("double");
colFormat.add("%.5f");
}
if (get_params()._valid != null) {
colHeaders.add("Validation MSE"); colTypes.add("double"); colFormat.add("%.5f");
if (!_output.autoencoder) {
colHeaders.add("Validation R^2");
colTypes.add("double");
colFormat.add("%.5f");
}
if (_output.getModelCategory() == ModelCategory.Binomial) {
colHeaders.add("Validation AUC");
colTypes.add("double");
colFormat.add("%.5f");
}
if (_output.isClassifier()) {
colHeaders.add("Validation Classification Error");
colTypes.add("double");
colFormat.add("%.5f");
}
} else if (get_params()._n_folds > 0) {
colHeaders.add("Cross-Validation MSE"); colTypes.add("double"); colFormat.add("%.5f");
// colHeaders.add("Validation R^2"); colTypes.add("double"); colFormat.add("%g");
if (_output.getModelCategory() == ModelCategory.Binomial) {
colHeaders.add("Cross-Validation AUC");
colTypes.add("double");
colFormat.add("%.5f");
}
if (_output.isClassifier()) {
colHeaders.add("Cross-Validation Classification Error");
colTypes.add("double");
colFormat.add("%.5f");
}
}
List<Integer> which = new ArrayList<>();
if (errors.length > size_limit) {
// always show first few
which.add(0);
// which.add(1);
// which.add(2);
// which.add(3);
// which.add(4);
// always show last few
// which.add(errors.length-5);
// which.add(errors.length-4);
// which.add(errors.length-3);
// which.add(errors.length-2);
which.add(errors.length-1);
// pick the remaining scoring points from the middle section
final float step = (float)(errors.length-which.size())/(size_limit-which.size());
for (float i=5; i<errors.length-5; i+=step) {
if (which.size() < size_limit) which.add((int)i);
}
}
final int rows = Math.min(size_limit, errors.length);
TwoDimTable table = new TwoDimTable(
"Scoring History",
new String[rows],
colHeaders.toArray(new String[0]),
colTypes.toArray(new String[0]),
colFormat.toArray(new String[0]),
"");
int row = 0;
for( int i = 0; i<errors.length ; i++ ) {
if (errors.length > size_limit && !which.contains(new Integer(i))) continue;
final DeepLearningScoring e = errors[i];
int col = 0;
assert(row < table.getRowDim());
assert(col < table.getColDim());
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
table.set(row, col++, fmt.print(start_time + e.training_time_ms));
table.set(row, col++, PrettyPrint.msecs(e.training_time_ms, true));
table.set(row, col++, e.training_time_ms == 0 ? null : (String.format("%.3f", e.training_samples/(e.training_time_ms/1e3)) + " rows/sec"));
table.set(row, col++, e.epoch_counter);
table.set(row, col++, e.training_samples);
table.set(row, col++, e.train_mse);
if (!_output.autoencoder) {
table.set(row, col++, e.train_r2);
}
if (_output.getModelCategory() == ModelCategory.Binomial) {
table.set(row, col++, e.trainAUC != null ? e.trainAUC.AUC() : Double.NaN);
}
if (_output.isClassifier()) {
table.set(row, col++, e.train_err);
}
if (get_params()._valid != null) {
table.set(row, col++, e.valid_mse);
if (!_output.autoencoder) {
table.set(row, col++, e.valid_r2);
}
if (_output.getModelCategory() == ModelCategory.Binomial) {
table.set(row, col++, e.validAUC != null ? e.validAUC.AUC() : Double.NaN);
}
if (_output.isClassifier()) {
table.set(row, col++, e.valid_err);
}
}
else if(get_params()._n_folds > 0) {
throw H2O.unimpl();
}
row++;
}
return table;
}
// This describes the model, together with the parameters
// This will be shared: one per node
public static class DeepLearningModelInfo extends Iced {
public TwoDimTable summaryTable;
private DataInfo data_info;
public DataInfo data_info() { return data_info; }
// model is described by parameters and the following arrays
private Neurons.DenseRowMatrix[] dense_row_weights; //one 2D weight matrix per layer (stored as a 1D array each)
private Neurons.DenseColMatrix[] dense_col_weights; //one 2D weight matrix per layer (stored as a 1D array each)
private Neurons.DenseVector[] biases; //one 1D bias array per layer
private Neurons.DenseVector[] avg_activations; //one 1D array per hidden layer
// helpers for storing previous step deltas
// Note: These two arrays *could* be made transient and then initialized freshly in makeNeurons() and in DeepLearningTask.initLocal()
// But then, after each reduction, the weights would be lost and would have to restart afresh -> not *exactly* right, but close...
private Neurons.DenseRowMatrix[] dense_row_weights_momenta;
private Neurons.DenseColMatrix[] dense_col_weights_momenta;
private Neurons.DenseVector[] biases_momenta;
// helpers for AdaDelta
private Neurons.DenseRowMatrix[] dense_row_ada_dx_g;
private Neurons.DenseColMatrix[] dense_col_ada_dx_g;
private Neurons.DenseVector[] biases_ada_dx_g;
// compute model size (number of model parameters required for making predictions)
// momenta are not counted here, but they are needed for model building
public long size() {
long siz = 0;
for (Neurons.Matrix w : dense_row_weights) if (w != null) siz += w.size();
for (Neurons.Matrix w : dense_col_weights) if (w != null) siz += w.size();
for (Neurons.Vector b : biases) siz += b.size();
return siz;
}
// accessors to (shared) weights and biases - those will be updated racily (c.f. Hogwild!)
boolean has_momenta() { return get_params()._momentum_start != 0 || get_params()._momentum_stable != 0; }
boolean adaDelta() { return get_params()._adaptive_rate; }
public final Neurons.Matrix get_weights(int i) { return dense_row_weights[i] == null ? dense_col_weights[i] : dense_row_weights[i]; }
public final Neurons.DenseVector get_biases(int i) { return biases[i]; }
public final Neurons.Matrix get_weights_momenta(int i) { return dense_row_weights_momenta[i] == null ? dense_col_weights_momenta[i] : dense_row_weights_momenta[i]; }
public final Neurons.DenseVector get_biases_momenta(int i) { return biases_momenta[i]; }
public final Neurons.Matrix get_ada_dx_g(int i) { return dense_row_ada_dx_g[i] == null ? dense_col_ada_dx_g[i] : dense_row_ada_dx_g[i]; }
public final Neurons.DenseVector get_biases_ada_dx_g(int i) { return biases_ada_dx_g[i]; }
//accessor to shared parameter defining avg activations
public final Neurons.DenseVector get_avg_activations(int i) { return avg_activations[i]; }
private DeepLearningParameters parameters;
public final DeepLearningParameters get_params() { return parameters; }
private float[] mean_rate;
private float[] rms_rate;
private float[] mean_bias;
private float[] rms_bias;
private float[] mean_weight;
public float[] rms_weight;
public float[] mean_a;
private volatile boolean unstable = false;
public boolean unstable() { return unstable; }
public void set_unstable() { if (!unstable) computeStats(); unstable = true; }
private long processed_global;
public synchronized long get_processed_global() { return processed_global; }
public synchronized void set_processed_global(long p) { processed_global = p; }
public synchronized void add_processed_global(long p) { processed_global += p; }
private long processed_local;
public synchronized long get_processed_local() { return processed_local; }
public synchronized void set_processed_local(long p) { processed_local = p; }
public synchronized void add_processed_local(long p) { processed_local += p; }
public synchronized long get_processed_total() { return processed_global + processed_local; }
// package local helpers
int[] units; //number of neurons per layer, extracted from parameters and from datainfo
final boolean _classification; // Classification cache (nclasses>1)
final Frame _train; // Prepared training frame
final Frame _valid; // Prepared validation frame
public DeepLearningModelInfo() {
_classification = false;
_train = _valid = null;
}
public DeepLearningModelInfo(final DeepLearningParameters params, final DataInfo dinfo, boolean classification, Frame train, Frame valid) {
_classification = classification;
_train = train;
_valid = valid;
data_info = dinfo;
parameters = params;
final int num_input = dinfo.fullN();
final int num_output = get_params()._autoencoder ? num_input : (_classification ? train.lastVec().cardinality() : 1);
assert(num_input > 0);
assert(num_output > 0);
if (has_momenta() && adaDelta()) throw new IllegalArgumentException("Cannot have non-zero momentum and adaptive rate at the same time.");
final int layers=get_params()._hidden.length;
// units (# neurons for each layer)
units = new int[layers+2];
if (get_params()._max_categorical_features <= Integer.MAX_VALUE - dinfo._nums)
units[0] = Math.min(dinfo._nums + get_params()._max_categorical_features, num_input);
else
units[0] = num_input;
System.arraycopy(get_params()._hidden, 0, units, 1, layers);
units[layers+1] = num_output;
if ((long)units[0] > 100000L) {
final String[][] domains = dinfo._adaptedFrame.domains();
int[] levels = new int[domains.length];
for (int i=0; i<levels.length; ++i) {
levels[i] = domains[i] != null ? domains[i].length : 0;
}
Arrays.sort(levels);
Log.warn("===================================================================================================================================");
Log.warn(num_input + " input features" + (dinfo._cats > 0 ? " (after categorical one-hot encoding)" : "") + ". Can be slow and require a lot of memory.");
if (levels[levels.length-1] > 0) {
int levelcutoff = levels[levels.length-1-Math.min(10, levels.length)];
int count = 0;
for (int i=0; i<dinfo._adaptedFrame.numCols() - (get_params()._autoencoder ? 0 : 1) && count < 10; ++i) {
if (dinfo._adaptedFrame.domains()[i] != null && dinfo._adaptedFrame.domains()[i].length >= levelcutoff) {
Log.warn("Categorical feature '" + dinfo._adaptedFrame._names[i] + "' has cardinality " + dinfo._adaptedFrame.domains()[i].length + ".");
}
count++;
}
}
Log.warn("Suggestions:");
Log.warn(" *) Limit the size of the first hidden layer");
if (dinfo._cats > 0) {
Log.warn(" *) Limit the total number of one-hot encoded features with the parameter 'max_categorical_features'");
Log.warn(" *) Run h2o.interaction(...,pairwise=F) on high-cardinality categorical columns to limit the factor count, see http://learn.h2o.ai");
}
Log.warn("===================================================================================================================================");
}
// weights (to connect layers)
dense_row_weights = new Neurons.DenseRowMatrix[layers+1];
dense_col_weights = new Neurons.DenseColMatrix[layers+1];
// decide format of weight matrices row-major or col-major
if (get_params()._col_major) dense_col_weights[0] = new Neurons.DenseColMatrix(units[1], units[0]);
else dense_row_weights[0] = new Neurons.DenseRowMatrix(units[1], units[0]);
for (int i = 1; i <= layers; ++i)
dense_row_weights[i] = new Neurons.DenseRowMatrix(units[i + 1] /*rows*/, units[i] /*cols*/);
// biases (only for hidden layers and output layer)
biases = new Neurons.DenseVector[layers+1];
for (int i=0; i<=layers; ++i) biases[i] = new Neurons.DenseVector(units[i+1]);
// average activation (only for hidden layers)
if (get_params()._autoencoder && get_params()._sparsity_beta > 0) {
avg_activations = new Neurons.DenseVector[layers];
mean_a = new float[layers];
for (int i = 0; i < layers; ++i) avg_activations[i] = new Neurons.DenseVector(units[i + 1]);
}
fillHelpers();
// for diagnostics
mean_rate = new float[units.length];
rms_rate = new float[units.length];
mean_bias = new float[units.length];
rms_bias = new float[units.length];
mean_weight = new float[units.length];
rms_weight = new float[units.length];
}
// deep clone all weights/biases
DeepLearningModelInfo deep_clone() {
AutoBuffer ab = new AutoBuffer();
this.write(ab);
ab.flipForReading();
return (DeepLearningModelInfo) new DeepLearningModelInfo().read(ab);
}
void fillHelpers() {
if (has_momenta()) {
dense_row_weights_momenta = new Neurons.DenseRowMatrix[dense_row_weights.length];
dense_col_weights_momenta = new Neurons.DenseColMatrix[dense_col_weights.length];
if (dense_row_weights[0] != null)
dense_row_weights_momenta[0] = new Neurons.DenseRowMatrix(units[1], units[0]);
else
dense_col_weights_momenta[0] = new Neurons.DenseColMatrix(units[1], units[0]);
for (int i=1; i<dense_row_weights_momenta.length; ++i) dense_row_weights_momenta[i] = new Neurons.DenseRowMatrix(units[i+1], units[i]);
biases_momenta = new Neurons.DenseVector[biases.length];
for (int i=0; i<biases_momenta.length; ++i) biases_momenta[i] = new Neurons.DenseVector(units[i+1]);
}
else if (adaDelta()) {
dense_row_ada_dx_g = new Neurons.DenseRowMatrix[dense_row_weights.length];
dense_col_ada_dx_g = new Neurons.DenseColMatrix[dense_col_weights.length];
//AdaGrad
if (dense_row_weights[0] != null) {
dense_row_ada_dx_g[0] = new Neurons.DenseRowMatrix(units[1], 2*units[0]);
} else {
dense_col_ada_dx_g[0] = new Neurons.DenseColMatrix(2*units[1], units[0]);
}
for (int i=1; i<dense_row_ada_dx_g.length; ++i) {
dense_row_ada_dx_g[i] = new Neurons.DenseRowMatrix(units[i+1], 2*units[i]);
}
biases_ada_dx_g = new Neurons.DenseVector[biases.length];
for (int i=0; i<biases_ada_dx_g.length; ++i) {
biases_ada_dx_g[i] = new Neurons.DenseVector(2*units[i+1]);
}
}
}
public TwoDimTable createSummaryTable() {
Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(this);
TwoDimTable table = new TwoDimTable(
"Status of Neuron Layers",
new String[neurons.length],
new String[]{"#", "Units", "Type", "Dropout", "L1", "L2",
(get_params()._adaptive_rate ? "Rate (Mean,RMS)" : "Rate"),
(get_params()._adaptive_rate ? "" : "Momentum"),
"Weight (Mean,RMS)",
"Bias (Mean,RMS)"
},
new String[]{"integer", "integer", "string", "double", "double", "double",
"string", "string", "string", "string"},
new String[]{"%d", "%d", "%s", "%2.2f %%", "%5f", "%5f", "%s", "%s", "%s", "%s"},
"");
final String format = "%7g";
for (int i = 0; i < neurons.length; ++i) {
table.set(i, 0, i + 1);
table.set(i, 1, neurons[i].units);
table.set(i, 2, neurons[i].getClass().getSimpleName());
if (i == 0) {
table.set(i, 3, neurons[i].params._input_dropout_ratio);
continue;
} else if (i < neurons.length - 1) {
if (neurons[i].params._hidden_dropout_ratios == null) {
table.set(i, 3, 0);
} else {
table.set(i, 3, neurons[i].params._hidden_dropout_ratios[i - 1]);
}
}
table.set(i, 4, neurons[i].params._l1);
table.set(i, 5, neurons[i].params._l2);
table.set(i, 6, (get_params()._adaptive_rate ? (" (" + String.format(format, mean_rate[i]) + ", " + String.format(format, rms_rate[i]) + ")")
: (String.format("%10g", neurons[i].rate(get_processed_total())))));
table.set(i, 7, get_params()._adaptive_rate ? "" : String.format("%5f", neurons[i].momentum(get_processed_total())));
table.set(i, 8, " (" + String.format(format, mean_weight[i])
+ ", " + String.format(format, rms_weight[i]) + ")");
table.set(i, 9, " (" + String.format(format, mean_bias[i])
+ ", " + String.format(format, rms_bias[i]) + ")");
}
summaryTable = table;
return summaryTable;
}
@Override public String toString() {
StringBuilder sb = new StringBuilder();
if (get_params()._diagnostics && !get_params()._quiet_mode) {
if (get_params()._sparsity_beta > 0) {
for (int k = 0; k < get_params()._hidden.length; k++) {
sb.append("Average activation in hidden layer ").append(k).append(" is ").append(mean_a[k]).append(" \n");
}
}
createSummaryTable();
sb.append(summaryTable.toString(1));
}
return sb.toString();
}
// DEBUGGING
public String toStringAll() {
StringBuilder sb = new StringBuilder();
sb.append(toString());
for (int i=0; i<units.length-1; ++i)
sb.append("\nweights[").append(i).append("][]=").append(Arrays.toString(get_weights(i).raw()));
for (int i=0; i<units.length-1; ++i) {
sb.append("\nbiases[").append(i).append("][]=").append(Arrays.toString(get_biases(i).raw()));
}
if (has_momenta()) {
for (int i=0; i<units.length-1; ++i)
sb.append("\nweights_momenta[").append(i).append("][]=").append(Arrays.toString(get_weights_momenta(i).raw()));
}
if (biases_momenta != null) {
for (int i=0; i<units.length-1; ++i) {
sb.append("\nbiases_momenta[").append(i).append("][]=").append(Arrays.toString(biases_momenta[i].raw()));
}
}
sb.append("\nunits[]=").append(Arrays.toString(units));
sb.append("\nprocessed global: ").append(get_processed_global());
sb.append("\nprocessed local: ").append(get_processed_local());
sb.append("\nprocessed total: ").append(get_processed_total());
sb.append("\n");
return sb.toString();
}
void initializeMembers() {
randomizeWeights();
//TODO: determine good/optimal/best initialization scheme for biases
// hidden layers
for (int i=0; i<get_params()._hidden.length; ++i) {
if (get_params()._activation == DeepLearningParameters.Activation.Rectifier
|| get_params()._activation == DeepLearningParameters.Activation.RectifierWithDropout
|| get_params()._activation == DeepLearningParameters.Activation.Maxout
|| get_params()._activation == DeepLearningParameters.Activation.MaxoutWithDropout
) {
// Arrays.fill(biases[i], 1.); //old behavior
Arrays.fill(biases[i].raw(), i == 0 ? 0.5f : 1f); //new behavior, might be slightly better
}
else if (get_params()._activation == DeepLearningParameters.Activation.Tanh || get_params()._activation == DeepLearningParameters.Activation.TanhWithDropout) {
Arrays.fill(biases[i].raw(), 0f);
}
}
Arrays.fill(biases[biases.length-1].raw(), 0f); //output layer
}
public void add(DeepLearningModelInfo other) {
for (int i=0;i<dense_row_weights.length;++i)
ArrayUtils.add(get_weights(i).raw(), other.get_weights(i).raw());
for (int i=0;i<biases.length;++i) ArrayUtils.add(biases[i].raw(), other.biases[i].raw());
if (avg_activations != null)
for (int i=0;i<avg_activations.length;++i)
ArrayUtils.add(avg_activations[i].raw(), other.biases[i].raw());
if (has_momenta()) {
assert(other.has_momenta());
for (int i=0;i<dense_row_weights_momenta.length;++i)
ArrayUtils.add(get_weights_momenta(i).raw(), other.get_weights_momenta(i).raw());
for (int i=0;i<biases_momenta.length;++i)
ArrayUtils.add(biases_momenta[i].raw(), other.biases_momenta[i].raw());
}
if (adaDelta()) {
assert(other.adaDelta());
for (int i=0;i<dense_row_ada_dx_g.length;++i) {
ArrayUtils.add(get_ada_dx_g(i).raw(), other.get_ada_dx_g(i).raw());
}
}
add_processed_local(other.get_processed_local());
}
protected void div(float N) {
for (int i=0; i<dense_row_weights.length; ++i)
ArrayUtils.div(get_weights(i).raw(), N);
for (Neurons.Vector bias : biases) ArrayUtils.div(bias.raw(), N);
if (avg_activations != null)
for (Neurons.Vector avgac : avg_activations)
ArrayUtils.div(avgac.raw(), N);
if (has_momenta()) {
for (int i=0; i<dense_row_weights_momenta.length; ++i)
ArrayUtils.div(get_weights_momenta(i).raw(), N);
for (Neurons.Vector bias_momenta : biases_momenta) ArrayUtils.div(bias_momenta.raw(), N);
}
if (adaDelta()) {
for (int i=0;i<dense_row_ada_dx_g.length;++i) {
ArrayUtils.div(get_ada_dx_g(i).raw(), N);
}
}
}
double uniformDist(Random rand, double min, double max) {
return min + rand.nextFloat() * (max - min);
}
void randomizeWeights() {
for (int w=0; w<dense_row_weights.length; ++w) {
final Random rng = water.util.RandomUtils.getDeterRNG(get_params()._seed + 0xBAD5EED + w+1); //to match NeuralNet behavior
final double range = Math.sqrt(6. / (units[w] + units[w+1]));
for( int i = 0; i < get_weights(w).rows(); i++ ) {
for( int j = 0; j < get_weights(w).cols(); j++ ) {
if (get_params()._initial_weight_distribution == DeepLearningParameters.InitialWeightDistribution.UniformAdaptive) {
// cf. http://machinelearning.wustl.edu/mlpapers/paper_files/AISTATS2010_GlorotB10.pdf
if (w==dense_row_weights.length-1 && _classification)
get_weights(w).set(i,j, (float)(4.*uniformDist(rng, -range, range))); //Softmax might need an extra factor 4, since it's like a sigmoid
else
get_weights(w).set(i,j, (float)uniformDist(rng, -range, range));
}
else if (get_params()._initial_weight_distribution == DeepLearningParameters.InitialWeightDistribution.Uniform) {
get_weights(w).set(i,j, (float)uniformDist(rng, -get_params()._initial_weight_scale, get_params()._initial_weight_scale));
}
else if (get_params()._initial_weight_distribution == DeepLearningParameters.InitialWeightDistribution.Normal) {
get_weights(w).set(i,j, (float)(rng.nextGaussian() * get_params()._initial_weight_scale));
}
}
}
}
}
// TODO: Add "subset randomize" function
// int count = Math.min(15, _previous.units);
// double min = -.1f, max = +.1f;
// //double min = -1f, max = +1f;
// for( int o = 0; o < units; o++ ) {
// for( int n = 0; n < count; n++ ) {
// int i = rand.nextInt(_previous.units);
// int w = o * _previous.units + i;
// _w[w] = uniformDist(rand, min, max);
// }
// }
/**
* Compute Variable Importance, based on
* GEDEON: DATA MINING OF INPUTS: ANALYSING MAGNITUDE AND FUNCTIONAL MEASURES
* @return variable importances for input features
*/
public float[] computeVariableImportances() {
float[] vi = new float[units[0]];
Arrays.fill(vi, 0f);
float[][] Qik = new float[units[0]][units[2]]; //importance of input i on output k
float[] sum_wj = new float[units[1]]; //sum of incoming weights into first hidden layer
float[] sum_wk = new float[units[2]]; //sum of incoming weights into output layer (or second hidden layer)
for (float[] Qi : Qik) Arrays.fill(Qi, 0f);
Arrays.fill(sum_wj, 0f);
Arrays.fill(sum_wk, 0f);
// compute sum of absolute incoming weights
for( int j = 0; j < units[1]; j++ ) {
for( int i = 0; i < units[0]; i++ ) {
float wij = get_weights(0).get(j, i);
sum_wj[j] += Math.abs(wij);
}
}
for( int k = 0; k < units[2]; k++ ) {
for( int j = 0; j < units[1]; j++ ) {
float wjk = get_weights(1).get(k,j);
sum_wk[k] += Math.abs(wjk);
}
}
// compute importance of input i on output k as product of connecting weights going through j
for( int i = 0; i < units[0]; i++ ) {
for( int k = 0; k < units[2]; k++ ) {
for( int j = 0; j < units[1]; j++ ) {
float wij = get_weights(0).get(j,i);
float wjk = get_weights(1).get(k,j);
//Qik[i][k] += Math.abs(wij)/sum_wj[j] * wjk; //Wong,Gedeon,Taggart '95
Qik[i][k] += Math.abs(wij)/sum_wj[j] * Math.abs(wjk)/sum_wk[k]; //Gedeon '97
}
}
}
// normalize Qik over all outputs k
for( int k = 0; k < units[2]; k++ ) {
float sumQk = 0;
for( int i = 0; i < units[0]; i++ ) sumQk += Qik[i][k];
for( int i = 0; i < units[0]; i++ ) Qik[i][k] /= sumQk;
}
// importance for feature i is the sum over k of i->k importances
for( int i = 0; i < units[0]; i++ ) vi[i] = ArrayUtils.sum(Qik[i]);
//normalize importances such that max(vi) = 1
ArrayUtils.div(vi, ArrayUtils.maxValue(vi));
return vi;
}
// compute stats on all nodes
public void computeStats() {
float[][] rate = get_params()._adaptive_rate ? new float[units.length-1][] : null;
if (get_params()._autoencoder && get_params()._sparsity_beta > 0) {
for (int k = 0; k < get_params()._hidden.length; k++) {
mean_a[k] = 0;
for (int j = 0; j < avg_activations[k].size(); j++)
mean_a[k] += avg_activations[k].get(j);
mean_a[k] /= avg_activations[k].size();
}
}
for( int y = 1; y < units.length; y++ ) {
mean_rate[y] = rms_rate[y] = 0;
mean_bias[y] = rms_bias[y] = 0;
mean_weight[y] = rms_weight[y] = 0;
for(int u = 0; u < biases[y-1].size(); u++) {
mean_bias[y] += biases[y-1].get(u);
}
if (rate != null) rate[y-1] = new float[get_weights(y-1).raw().length];
for(int u = 0; u < get_weights(y-1).raw().length; u++) {
mean_weight[y] += get_weights(y-1).raw()[u];
if (rate != null) {
// final float RMS_dx = (float)Math.sqrt(ada[y-1][2*u]+(float)get_params().epsilon);
// final float invRMS_g = (float)(1/Math.sqrt(ada[y-1][2*u+1]+(float)get_params().epsilon));
final float RMS_dx = MathUtils.approxSqrt(get_ada_dx_g(y-1).raw()[2*u]+(float)get_params()._epsilon);
final float invRMS_g = MathUtils.approxInvSqrt(get_ada_dx_g(y-1).raw()[2*u+1]+(float)get_params()._epsilon);
rate[y-1][u] = RMS_dx*invRMS_g; //not exactly right, RMS_dx should be from the previous time step -> but close enough for diagnostics.
mean_rate[y] += rate[y-1][u];
}
}
mean_bias[y] /= biases[y-1].size();
mean_weight[y] /= get_weights(y-1).size();
if (rate != null) mean_rate[y] /= rate[y-1].length;
for(int u = 0; u < biases[y-1].size(); u++) {
final double db = biases[y-1].get(u) - mean_bias[y];
rms_bias[y] += db * db;
}
for(int u = 0; u < get_weights(y-1).size(); u++) {
final double dw = get_weights(y-1).raw()[u] - mean_weight[y];
rms_weight[y] += dw * dw;
if (rate != null) {
final double drate = rate[y-1][u] - mean_rate[y];
rms_rate[y] += drate * drate;
}
}
rms_bias[y] = MathUtils.approxSqrt(rms_bias[y]/biases[y-1].size());
rms_weight[y] = MathUtils.approxSqrt(rms_weight[y] / get_weights(y - 1).size());
if (rate != null) rms_rate[y] = MathUtils.approxSqrt(rms_rate[y]/rate[y-1].length);
// rms_bias[y] = (float)Math.sqrt(rms_bias[y]/biases[y-1].length);
// rms_weight[y] = (float)Math.sqrt(rms_weight[y]/weights[y-1].length);
// if (rate != null) rms_rate[y] = (float)Math.sqrt(rms_rate[y]/rate[y-1].length);
// Abort the run if weights or biases are unreasonably large (Note that all input values are normalized upfront)
// This can happen with Rectifier units when L1/L2/max_w2 are all set to 0, especially when using more than 1 hidden layer.
final double thresh = 1e10;
unstable |= mean_bias[y] > thresh || isNaN(mean_bias[y])
|| rms_bias[y] > thresh || isNaN(rms_bias[y])
|| mean_weight[y] > thresh || isNaN(mean_weight[y])
|| rms_weight[y] > thresh || isNaN(rms_weight[y]);
}
}
}
/**
* Helper to allocate keys for output frames for weights and biases
* @param destKey
*/
private void makeWeightsBiases(Key destKey) {
_output.weights = new Key[model_info.get_params()._hidden.length + 1];
for (int i = 0; i < _output.weights.length; ++i) {
_output.weights[i] = Key.makeUserHidden(Key.make(destKey + ".weights." + i));
}
_output.biases = new Key[model_info.get_params()._hidden.length + 1];
for (int i = 0; i < _output.biases.length; ++i) {
_output.biases[i] = Key.makeUserHidden(Key.make(destKey + ".biases." + i));
}
}
/** Constructor to restart from a checkpointed model
* @param destKey New destination key for the model
* @param cp Checkpoint to restart from
* @param store_best_model Store only the best model instead of the latest one */
public DeepLearningModel(final Key destKey, final DeepLearningModel cp, final boolean store_best_model, final DataInfo dataInfo) {
super(destKey, (DeepLearningParameters)cp._parms.clone(), (DeepLearningModelOutput)cp._output.clone());
if (store_best_model) {
model_info = cp.model_info.deep_clone(); //don't want to interfere with model being built, just make a deep copy and store that
model_info.data_info = dataInfo.deep_clone(); //replace previous data_info with updated version that's passed in (contains enum for classification)
} else {
model_info = (DeepLearningModelInfo) cp.model_info.clone(); //shallow clone is ok (won't modify the Checkpoint in K-V store during checkpoint restart)
model_info.data_info = dataInfo; //shallow clone is ok
// Ok to modify (the normally immutable read-only) parameters, because
// this is a private copy just cloned above in the super() call.
_parms._checkpoint = cp._key; //it's only a "real" checkpoint if job != null, otherwise a best model copy
}
actual_best_model_key = cp.actual_best_model_key;
start_time = cp.start_time;
run_time = cp.run_time;
training_rows = cp.training_rows; //copy the value to display the right number on the model page before training has started
validation_rows = cp.validation_rows; //copy the value to display the right number on the model page before training has started
_bestError = cp._bestError;
// deep clone scoring history
errors = cp.errors.clone();
for (int i=0; i<errors.length;++i)
errors[i] = cp.errors[i].deep_clone();
_output.errors = last_scored();
makeWeightsBiases(destKey);
_output.scoring_history = createScoringHistoryTable(errors);
_output.variable_importances = calcVarImp(last_scored().variable_importances);
// set proper timing
_timeLastScoreEnter = System.currentTimeMillis();
_timeLastScoreStart = 0;
_timeLastScoreEnd = 0;
_timeLastPrintStart = 0;
assert(Arrays.equals(_key._kb, destKey._kb));
}
public DeepLearningModel(final Key destKey, final DeepLearningParameters parms, final DeepLearningModelOutput output, Frame train, Frame valid) {
super(destKey, parms, output);
boolean classification = train.lastVec().isEnum();
final DataInfo dinfo = new DataInfo(Key.make(), train, valid, parms._autoencoder ? 0 : 1, parms._autoencoder || parms._use_all_factor_levels, //use all FactorLevels for auto-encoder
parms._autoencoder ? DataInfo.TransformType.NORMALIZE : DataInfo.TransformType.STANDARDIZE, //transform predictors
classification ? DataInfo.TransformType.NONE : DataInfo.TransformType.STANDARDIZE, _parms._missing_values_handling == DeepLearningModel.DeepLearningParameters.MissingValuesHandling.Skip);
output._names = train._names ; // Since changed by DataInfo, need to be reflected in the Model output as well
output._domains= train.domains();
DKV.put(dinfo._key,dinfo);
model_info = new DeepLearningModelInfo(parms, dinfo, classification, train, valid);
actual_best_model_key = Key.makeUserHidden(Key.make());
if (parms._n_folds != 0) actual_best_model_key = null;
if (!parms._autoencoder) {
errors = new DeepLearningScoring[1];
errors[0] = new DeepLearningScoring();
errors[0].validation = (parms._valid != null);
errors[0].num_folds = parms._n_folds;
_output.errors = last_scored();
_output.scoring_history = createScoringHistoryTable(errors);
_output.variable_importances = calcVarImp(last_scored().variable_importances);
}
makeWeightsBiases(destKey);
run_time = 0;
start_time = System.currentTimeMillis();
_timeLastScoreEnter = start_time;
assert _key.equals(destKey);
}
public long _timeLastScoreEnter; //not transient: needed for HTML display page
transient private long _timeLastScoreStart;
transient private long _timeLastScoreEnd;
transient private long _timeLastPrintStart;
/**
*
* @param ftrain potentially downsampled training data for scoring
* @param ftest potentially downsampled validation data for scoring
* @param job_key key of the owning job
* @param progressKey key of the progress
* @return true if model building is ongoing
*/
boolean doScoring(Frame ftrain, Frame ftest, Key job_key, Key progressKey) {
boolean keep_running;
try {
final long now = System.currentTimeMillis();
epoch_counter = (float)model_info().get_processed_total()/training_rows;
final double time_last_iter_millis = Math.max(5,now-_timeLastScoreEnter);
// Auto-tuning
// if multi-node and auto-tuning and at least 10 ms for communication (to avoid doing thins on multi-JVM on same node),
// then adjust the auto-tuning parameter 'actual_train_samples_per_iteration' such that the targeted ratio of comm to comp is achieved
// Note: actual communication time is estimated by the NetworkTest's collective test.
if (H2O.CLOUD.size() > 1 && get_params()._train_samples_per_iteration == -2 && time_for_communication_us > 1e4) {
// Log.info("Time taken for communication: " + PrettyPrint.usecs((long)time_for_communication_us));
// Log.info("Time taken for Map/Reduce iteration: " + PrettyPrint.msecs((long)time_last_iter_millis, true));
final double comm_to_work_ratio = (time_for_communication_us *1e-3) / time_last_iter_millis;
// Log.info("Ratio of network communication to computation: " + String.format("%.3f", comm_to_work_ratio));
// Log.info("target_comm_to_work: " + get_params().target_ratio_comm_to_comp);
final double correction = get_params()._target_ratio_comm_to_comp / comm_to_work_ratio;
// Log.warn("Suggested value for train_samples_per_iteration: " + get_params().actual_train_samples_per_iteration/correction);
actual_train_samples_per_iteration /= correction;
actual_train_samples_per_iteration = Math.max(1, actual_train_samples_per_iteration);
}
run_time += time_last_iter_millis;
_timeLastScoreEnter = now;
keep_running = (epoch_counter < get_params()._epochs);
final long sinceLastScore = now -_timeLastScoreStart;
final long sinceLastPrint = now -_timeLastPrintStart;
if (!keep_running || sinceLastPrint > get_params()._score_interval * 1000) { //print this after every score_interval, not considering duty cycle
_timeLastPrintStart = now;
if (!get_params()._quiet_mode) {
Log.info("Training time: " + PrettyPrint.msecs(run_time, true)
+ ". Processed " + String.format("%,d", model_info().get_processed_total()) + " samples" + " (" + String.format("%.3f", epoch_counter) + " epochs)."
+ " Speed: " + String.format("%.3f", 1000. * model_info().get_processed_total() / run_time) + " samples/sec.\n");
}
}
// this is potentially slow - only do every so often
if( !keep_running ||
(sinceLastScore > get_params()._score_interval *1000 //don't score too often
&&(double)(_timeLastScoreEnd-_timeLastScoreStart)/sinceLastScore < get_params()._score_duty_cycle) ) { //duty cycle
if (progressKey != null) {
new Job.ProgressUpdate("Scoring on " + ftrain.numRows() + " training samples" +
(ftest != null ? (", " + ftest.numRows() + " validation samples)") : ")")
).fork(progressKey);
}
final boolean printme = !get_params()._quiet_mode;
_timeLastScoreStart = now;
if (get_params()._diagnostics) model_info().computeStats();
DeepLearningScoring err = new DeepLearningScoring();
err.training_time_ms = run_time;
err.epoch_counter = epoch_counter;
err.training_samples = model_info().get_processed_total();
err.validation = ftest != null;
err.score_training_samples = ftrain.numRows();
err.classification = _output.isClassifier();
if (get_params()._autoencoder) {
if (printme) Log.info("Scoring the auto-encoder.");
// training
{
final Frame mse_frame = scoreAutoEncoder(ftrain, Key.make());
final Vec l2 = mse_frame.anyVec();
Log.info("Mean reconstruction error on training data: " + l2.mean() + "\n");
err.train_mse = l2.mean();
mse_frame.delete();
}
} else {
if (printme) Log.info("Scoring the model.");
// compute errors
final String m = model_info().toString();
if (m.length() > 0) Log.info(m);
final Frame trainPredict = score(ftrain);
trainPredict.delete();
hex.ModelMetricsSupervised mm1 = (ModelMetricsSupervised)ModelMetrics.getFromDKV(this,ftrain);
if (mm1 instanceof ModelMetricsBinomial) {
ModelMetricsBinomial mm = (ModelMetricsBinomial)(mm1);
err.trainAUC = mm._aucdata;
err.train_confusion_matrix = mm._cm;
err.train_err = mm._cm.err();
}
else if (mm1 instanceof ModelMetricsMultinomial) {
ModelMetricsMultinomial mm = (ModelMetricsMultinomial)(mm1);
err.train_confusion_matrix = mm._cm;
err.train_err = mm._cm.err();
err.train_hitratio = mm._hit_ratios;
}
err.train_mse = mm1._mse;
err.train_r2 = mm1.r2();
_output.train_metrics = mm1;
_output.run_time = run_time;
if (ftest != null) {
Frame validPred = score(ftest);
validPred.delete();
hex.ModelMetricsSupervised mm2 = (ModelMetricsSupervised)hex.ModelMetrics.getFromDKV(this, ftest);
if (mm2 != null) {
if (mm2 instanceof ModelMetricsBinomial) {
ModelMetricsBinomial mm = (ModelMetricsBinomial) (mm2);
err.validAUC = mm._aucdata;
err.valid_confusion_matrix = mm._cm;
err.valid_err = mm._cm.err();
} else if (mm2 instanceof ModelMetricsMultinomial) {
ModelMetricsMultinomial mm = (ModelMetricsMultinomial) (mm2);
err.valid_confusion_matrix = mm._cm;
err.valid_err = mm._cm.err();
err.valid_hitratio = mm._hit_ratios;
}
err.valid_mse = mm2._mse;
err.valid_r2 = mm2.r2();
_output.valid_metrics = mm2;
}
}
}
if (get_params()._variable_importances) {
if (!get_params()._quiet_mode) Log.info("Computing variable importances.");
final float[] vi = model_info().computeVariableImportances();
err.variable_importances = new VarImp(vi, Arrays.copyOfRange(model_info().data_info().coefNames(), 0, vi.length));
}
_timeLastScoreEnd = System.currentTimeMillis();
err.scoring_time = System.currentTimeMillis() - now;
// enlarge the error array by one, push latest score back
if (errors == null) {
errors = new DeepLearningScoring[]{err};
} else {
DeepLearningScoring[] err2 = new DeepLearningScoring[errors.length + 1];
System.arraycopy(errors, 0, err2, 0, errors.length);
err2[err2.length - 1] = err;
errors = err2;
}
_output.errors = last_scored();
water.util.Timer t = new Timer();
// store weights and matrices to Frames
for (int i=0; i<_output.weights.length; ++i) {
model_info.get_weights(i).toFrame(_output.weights[i]);
}
for (int i=0; i<_output.biases.length; ++i) {
model_info.get_biases(i).toFrame(_output.biases[i]);
}
Log.info("Writing weights and biases to Frames took " + t.time()/1000. + " seconds.");
_output.scoring_history = createScoringHistoryTable(errors);
_output.variable_importances = calcVarImp(last_scored().variable_importances);
_output.model_summary = model_info.createSummaryTable();
if (!get_params()._autoencoder) {
// always keep a copy of the best model so far (based on the following criterion)
if (actual_best_model_key != null && get_params()._override_with_best_model && (
// if we have a best_model in DKV, then compare against its error() (unless it's a different model as judged by the network size)
(DKV.get(actual_best_model_key) != null && (error() < DKV.get(actual_best_model_key).<DeepLearningModel>get().error() || !Arrays.equals(model_info().units, DKV.get(actual_best_model_key).<DeepLearningModel>get().model_info().units)))
||
// otherwise, compare against our own _bestError
(DKV.get(actual_best_model_key) == null && error() < _bestError)
) ) {
if (!get_params()._quiet_mode)
Log.info("Error reduced from " + _bestError + " to " + error() + ".");
_bestError = error();
putMeAsBestModel(actual_best_model_key);
// debugging check
//if (false) {
// DeepLearningModel bestModel = DKV.get(actual_best_model_key).get();
// final Frame fr = ftest != null ? ftest : ftrain;
// final Frame bestPredict = bestModel.score(fr);
// final Frame hitRatio_bestPredict = new Frame(bestPredict);
// final double err3 = calcError(fr, fr.lastVec(), bestPredict, hitRatio_bestPredict, "cross-check",
// printme, get_params()._max_confusion_matrix_size, new hex.ConfusionMatrix2(), _output.isClassifier() && _output.nclasses() == 2 ? new AUC(null,null) : null, null);
// if (_output.isClassifier())
// assert (ftest != null ? Math.abs(err.valid_err - err3) < 1e-5 : Math.abs(err.train_err - err3) < 1e-5);
// else
// assert (ftest != null ? Math.abs(err.valid_mse - err3) < 1e-5 : Math.abs(err.train_mse - err3) < 1e-5);
// bestPredict.delete();
//}
}
// else {
// // keep output JSON small
// if (errors.length > 1) {
// if (last_scored().trainAUC != null) last_scored().trainAUC.clear();
// if (last_scored().validAUC != null) last_scored().validAUC.clear();
// last_scored().variable_importances = null;
// }
// }
// print the freshly scored model to ASCII
if (keep_running)
for (String s : toString().split("\n")) Log.info(s);
if (printme) Log.info("Time taken for scoring and diagnostics: " + PrettyPrint.msecs(err.scoring_time, true));
}
}
if (model_info().unstable()) {
Log.warn(unstable_msg);
keep_running = false;
} else if ( (_output.isClassifier() && last_scored().train_err <= get_params()._classification_stop)
|| (!_output.isClassifier() && last_scored().train_mse <= get_params()._regression_stop) ) {
Log.info("Achieved requested predictive accuracy on the training data. Model building completed.");
keep_running = false;
}
update(job_key);
}
catch (Exception ex) {
//ex.printStackTrace();
throw new RuntimeException(ex);
// return false;
}
return keep_running;
}
// @Override protected void setCrossValidationError(Parameters job, double cv_error, ConfusionMatrix cm, AUCData auc, HitRatio hr) {
// _have_cv_results = true;
// if (!get_params().classification)
// last_scored().valid_mse = cv_error;
// else
// last_scored().valid_err = cv_error;
// last_scored().score_validation_samples = last_scored().score_training_samples / get_params().n_folds;
// last_scored().num_folds = get_params().n_folds;
// last_scored().valid_confusion_matrix = cm;
// last_scored().validAUC = auc;
// last_scored().valid_hitratio = hr;
// DKV.put(this._key, this); //overwrite this model
// }
@Override public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(model_info.toString());
//sb.append(last_scored().toString());
sb.append(_output.scoring_history.toString());
if (_output.variable_importances != null) {
for (String s : Arrays.asList(_output.variable_importances.toString().split("\n")).subList(0, 12))
sb.append(s).append("\n");
}
return sb.toString();
}
/** Make either a prediction or a reconstruction.
* @param orig Test dataset
* @param adaptedFr Test dataset, adapted to the model
* @return A frame containing the prediction or reconstruction
*/
@Override protected Frame scoreImpl(Frame orig, Frame adaptedFr, String destination_key) {
if (!get_params()._autoencoder) {
return super.scoreImpl(orig,adaptedFr,destination_key);
} else {
// Reconstruction
final int len = model_info().data_info().fullN();
String prefix = "reconstr_";
assert(model_info().data_info()._responses == 0);
String[] coefnames = model_info().data_info().coefNames();
assert(len == coefnames.length);
Frame adaptFrm = new Frame(adaptedFr);
for( int c=0; c<len; c++ )
adaptFrm.add(prefix+coefnames[c],adaptFrm.anyVec().makeZero());
new MRTask() {
@Override public void map( Chunk chks[] ) {
double tmp [] = new double[_output._names.length];
float preds[] = new float [len];
final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info);
for( int row=0; row<chks[0]._len; row++ ) {
float p[] = score_autoencoder(chks, row, tmp, preds, neurons);
for( int c=0; c<preds.length; c++ )
chks[_output._names.length+c].set(row,p[c]);
}
}
}.doAll(adaptFrm);
// Return the predicted columns
int x=_output._names.length, y=adaptFrm.numCols();
Frame f = adaptFrm.extractFrame(x, y); //this will call vec_impl() and we cannot call the delete() below just yet
if (destination_key != null) {
Key k = Key.make(destination_key);
f = new Frame(k, f.names(), f.vecs());
DKV.put(k, f);
}
makeMetricBuilder(null).makeModelMetrics(this, orig, Double.NaN);
return f;
}
}
/**
* Predict from raw double values representing the data
* @param data raw array containing categorical values (horizontalized to 1,0,0,1,0,0 etc.) and numerical values (0.35,1.24,5.3234,etc), both can contain NaNs
* @param preds predicted label and per-class probabilities (for classification), predicted target (regression), can contain NaNs
* @return preds, can contain NaNs
*/
@Override public float[] score0(double[] data, float[] preds) {
if (model_info().unstable()) {
Log.warn(unstable_msg);
throw new UnsupportedOperationException("Trying to predict with an unstable model.");
}
Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info);
((Neurons.Input)neurons[0]).setInput(-1, data);
DeepLearningTask.step(-1, neurons, model_info, false, null);
float[] out = neurons[neurons.length - 1]._a.raw();
if (_output.isClassifier()) {
assert (preds.length == out.length + 1);
for (int i = 0; i < preds.length - 1; ++i) {
preds[i + 1] = out[i];
if (Float.isNaN(preds[i + 1])) throw new RuntimeException("Predicted class probability NaN!");
}
preds[0] = hex.genmodel.GenModel.getPrediction(preds, data);
} else {
if (model_info().data_info()._normRespMul != null)
preds[0] = (float) (out[0] / model_info().data_info()._normRespMul[0] + model_info().data_info()._normRespSub[0]);
else
preds[0] = out[0];
if (Float.isNaN(preds[0])) throw new RuntimeException("Predicted regression target NaN!");
}
return preds;
}
/**
* Score auto-encoded reconstruction (on-the-fly, without allocating the reconstruction as done in Frame score(Frame fr))
* @param frame Original data (can contain response, will be ignored)
* @return Frame containing one Vec with reconstruction error (MSE) of each reconstructed row, caller is responsible for deletion
*/
public Frame scoreAutoEncoder(Frame frame, Key destination_key) {
if (!get_params()._autoencoder)
throw new H2OIllegalArgumentException("Only for AutoEncoder Deep Learning model.", "");
final int len = _output._names.length;
Frame adaptFrm = new Frame(frame);
Vec v0 = adaptFrm.anyVec().makeZero();
Scope.enter();
adaptTestForTrain(adaptFrm,true);
adaptFrm.add("Reconstruction.MSE", v0);
new MRTask() {
@Override public void map( Chunk chks[] ) {
double tmp [] = new double[len];
final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info);
for( int row=0; row<chks[0]._len; row++ ) {
for( int i=0; i<len; i++ )
tmp[i] = chks[i].atd(row);
//store the per-row reconstruction error (MSE) in the last column
chks[len].set(row, score_autoencoder(tmp, null, neurons));
}
}
}.doAll(adaptFrm);
Scope.exit();
Frame res = adaptFrm.extractFrame(len, adaptFrm.numCols());
res = new Frame(destination_key, res.names(), res.vecs());
DKV.put(res);
makeMetricBuilder(null).makeModelMetrics(this, frame, res.vecs()[0].mean());
return res;
}
@Override public Frame score(Frame fr, String destination_key) {
if (!_parms._autoencoder)
return super.score(fr, destination_key);
else {
Frame adaptFr = new Frame(fr);
adaptTestForTrain(adaptFr, true); // Adapt
Frame output = scoreImpl(fr, adaptFr, destination_key); // Score
Vec[] vecs = adaptFr.vecs();
for (int i = 0; i < vecs.length; i++)
if (fr.find(vecs[i]) != -1) // Exists in the original frame?
vecs[i] = null; // Do not delete it
adaptFr.delete();
return output;
}
}
/**
* Score auto-encoded reconstruction (on-the-fly, and materialize the deep features of given layer
* @param frame Original data (can contain response, will be ignored)
* @param layer index of the hidden layer for which to extract the features
* @return Frame containing the deep features (#cols = hidden[layer])
*/
public Frame scoreDeepFeatures(Frame frame, final int layer) {
if (layer < 0 || layer >= model_info().get_params()._hidden.length)
throw new H2OIllegalArgumentException("hidden layer (index) to extract must be between " + 0 + " and " + (model_info().get_params()._hidden.length-1),"");
final int len = _output.nfeatures();
Vec resp = null;
if (isSupervised()) {
int ridx = frame.find(_output.responseName());
if (ridx != -1) { // drop the response for scoring!
frame = new Frame(frame);
resp = frame.vecs()[ridx];
frame.remove(ridx);
}
}
Frame adaptFrm = new Frame(frame);
//create new features, will be dense
final int features = model_info().get_params()._hidden[layer];
Vec[] vecs = adaptFrm.anyVec().makeZeros(features);
Scope.enter();
adaptTestForTrain(adaptFrm,true);
for (int j=0; j<features; ++j) {
adaptFrm.add("DF.C" + (j+1), vecs[j]);
}
new MRTask() {
@Override public void map( Chunk chks[] ) {
double tmp [] = new double[len];
final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info);
for( int row=0; row<chks[0]._len; row++ ) {
for( int i=0; i<len; i++ )
tmp[i] = chks[i].atd(row);
((Neurons.Input)neurons[0]).setInput(-1, tmp);
DeepLearningTask.step(-1, neurons, model_info, false, null);
float[] out = neurons[layer+1]._a.raw(); //extract the layer-th hidden feature
for( int c=0; c<features; c++ )
chks[_output._names.length+c].set(row,out[c]);
}
}
}.doAll(adaptFrm);
// Return just the output columns
int x=_output._names.length, y=adaptFrm.numCols();
Frame ret = adaptFrm.extractFrame(x, y);
if (resp != null) ret.prepend(_output.responseName(), resp);
Scope.exit();
return ret;
}
// Make (potentially expanded) reconstruction
private float[] score_autoencoder(Chunk[] chks, int row_in_chunk, double[] tmp, float[] preds, Neurons[] neurons) {
assert(get_params()._autoencoder);
assert(tmp.length == _output._names.length);
for( int i=0; i<tmp.length; i++ )
tmp[i] = chks[i].atd(row_in_chunk);
score_autoencoder(tmp, preds, neurons); // this fills preds, returns MSE error (ignored here)
return preds;
}
/**
* Helper to reconstruct original data into preds array and compute the reconstruction error (MSE)
* @param data Original data (unexpanded)
* @param preds Reconstruction (potentially expanded)
* @return reconstruction error
*/
private double score_autoencoder(double[] data, float[] preds, Neurons[] neurons) {
assert(model_info().get_params()._autoencoder);
if (model_info().unstable()) {
Log.warn(unstable_msg);
throw new UnsupportedOperationException("Trying to predict with an unstable model.");
}
((Neurons.Input)neurons[0]).setInput(-1, data); // expands categoricals inside
DeepLearningTask.step(-1, neurons, model_info, false, null); // reconstructs data in expanded space
float[] in = neurons[0]._a.raw(); //input (expanded)
float[] out = neurons[neurons.length - 1]._a.raw(); //output (expanded)
assert(in.length == out.length);
// First normalize categorical reconstructions to be probabilities
// (such that they can be better compared to the input where one factor was 1 and the rest was 0)
// model_info().data_info().softMaxCategoricals(out,out); //only modifies the categoricals
// Compute MSE of reconstruction in expanded space (with categorical probabilities)
double l2 = 0;
for (int i = 0; i < in.length; ++i)
l2 += Math.pow((out[i] - in[i]), 2);
l2 /= in.length;
if (preds!=null) {
// Now scale back numerical columns to original data space (scale + shift)
model_info().data_info().unScaleNumericals(out, out); //only modifies the numericals
System.arraycopy(out, 0, preds, 0, out.length); //copy reconstruction into preds
}
return l2;
}
/**
* Compute quantile-based threshold (in reconstruction error) to find outliers
* @param mse Vector containing reconstruction errors
* @param quantile Quantile for cut-off
* @return Threshold in MSE value for a point to be above the quantile
*/
public double calcOutlierThreshold(Vec mse, double quantile) {
Frame mse_frame = new Frame(Key.make(), new String[]{"Reconstruction.MSE"}, new Vec[]{mse});
DKV.put(mse_frame._key, mse_frame);
QuantileModel.QuantileParameters parms = new QuantileModel.QuantileParameters();
parms._train = mse_frame._key;
parms._probs = new double[]{quantile};
Quantile job = new Quantile(parms).trainModel();
QuantileModel kmm = job.get();
job.remove();
double q = kmm._output._quantiles[0][0];
kmm.delete();
DKV.remove(mse_frame._key);
return q;
}
// helper to push this model to another key (for keeping good models)
private void putMeAsBestModel(Key bestModelKey) {
DeepLearningModel bestModel = new DeepLearningModel(bestModelKey, this, true, model_info().data_info());
DKV.put(bestModel._key, bestModel);
assert (DKV.get(bestModelKey) != null);
assert (bestModel.compareTo(this) <= 0);
}
@Override public void delete() {
for (Key k : _output.weights) {
if (DKV.getGet(k) != null) ((Frame)DKV.getGet(k)).delete();
}
for (Key k : _output.biases) {
if (DKV.getGet(k) != null) ((Frame)DKV.getGet(k)).delete();
}
super.delete();
}
void delete_xval_models( ) {
// if (get_params().xval_models != null) {
// for (Key k : get_params().xval_models) {
// DKV.get(k).<DeepLearningModel>get().delete_best_model();
// DKV.get(k).<DeepLearningModel>get().delete();
// }
// }
}
transient private final String unstable_msg = "Job was aborted due to observed numerical instability (exponential growth)."
+ "\nTry a different initial distribution, a bounded activation function or adding"
+ "\nregularization with L1, L2 or max_w2 and/or use a smaller learning rate or faster annealing.";
}
| Improve error handling logic for loss function in DL. Allows Flow to mark fields red.
| h2o-algos/src/main/java/hex/deeplearning/DeepLearningModel.java | Improve error handling logic for loss function in DL. Allows Flow to mark fields red. | <ide><path>2o-algos/src/main/java/hex/deeplearning/DeepLearningModel.java
<ide> }
<ide>
<ide> void validate( DeepLearning dl, boolean expensive ) {
<del> boolean classification = expensive ? dl.isClassifier() : (_loss == Loss.CrossEntropy || _loss == Loss.MeanSquareClassification);
<add> boolean classification = expensive || dl._nclass != 0 ? dl.isClassifier() : (_loss == Loss.CrossEntropy || _loss == Loss.MeanSquareClassification);
<ide> if (_hidden == null || _hidden.length == 0) dl.error("_hidden", "There must be at least one hidden layer.");
<ide>
<ide> for( int h : _hidden ) if( h==0 ) dl.error("_hidden", "Hidden layer size must be >0.");
<ide> }
<ide> }
<ide>
<del> if (expensive) { //otherwise, we might not know whether classification=true or false (from R, for example, the training data isn't known when init(false) is called).
<del> if (_loss == null)
<del> dl.error("_loss", "Loss function must be specified. For classification, use CrossEntropy or MeanSquareClassification. For regression, use MeanSquare.");
<del> else if (_autoencoder && _loss != Loss.MeanSquare)
<add>
<add> if (_loss == null) {
<add> if (expensive || dl._nclass != 0) {
<add> dl.error("_loss", "Loss function must be specified. For classification (categorical response), use CrossEntropy or MeanSquareClassification. For regression (numerical response), use MeanSquare. For auto-encoders, use MeanSquare.");
<add> }
<add> //otherwise, we might not know whether classification=true or false (from R, for example, the training data isn't known when init(false) is called).
<add> } else {
<add> if (_autoencoder && _loss != Loss.MeanSquare)
<ide> dl.error("_loss", "Must use MeanSquare loss function for auto-encoder.");
<del> else if (!classification && _loss == Loss.CrossEntropy)
<del> dl.error("_loss", "Cannot use CrossEntropy loss function for regression (numerical response).");
<add>
<add> if (!classification && _loss == Loss.CrossEntropy)
<add> dl.error("_loss", "For CrossEntropy loss, the response must be categorical. Either select MeanSquare loss for regression, or convert the response to a categorical (if applicable).");
<ide> else if (!classification && _loss == Loss.MeanSquareClassification)
<del> dl.error("_loss", "Cannot use MeanSquareClassification loss function for regression (numerical response).");
<add> dl.error("_loss", "For MeanSquareClassification loss, the response must be categorical. Either select MeanSquare loss for regression, or convert the response to a categorical (if applicable).");
<ide> else if (classification && _loss == Loss.MeanSquare)
<del> dl.error("_loss", "Cannot use MeanSquare loss function for classification (categorical response).");
<add> dl.error("_loss", "For MeanSquare loss, the response must be numerical. Either select CrossEntropy or MeanSquareClassification loss for classification, or convert the response to numerical (if applicable).");
<ide> }
<ide>
<ide> if (_score_training_samples < 0) { |
|
Java | bsd-3-clause | d3cd17665a9c1f0bdf40b1680ade9fc65a635a54 | 0 | knopflerfish/knopflerfish.org,knopflerfish/knopflerfish.org,knopflerfish/knopflerfish.org | /*
* Copyright (c) 2003, KNOPFLERFISH project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the KNOPFLERFISH project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.knopflerfish.bundle.desktop.swing;
import org.osgi.framework.*;
import org.osgi.util.tracker.*;
import javax.swing.table.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.net.URL;
import java.io.*;
import java.lang.reflect.*;
/**
* Utiliy swing component which display bundle info as
* HTML.
*
*<p>
* Intended to be used as base class. Subclasses should override
* the <tt>valueChanged</tt> method and retur an HTML string.
*</p>
*
* <p>
* If the <tt>Util.bundleLink</tt> method is used to create
* text for bundles, these will become selection links for
* the bundle.
* </p>
*/
public abstract class JHTMLBundle extends JPanel {
JPanel panel;
JTextPane html;
JScrollPane scroll;
DefaultSwingBundleDisplayer displayer;
ArrayList historyBack = new ArrayList();
ArrayList historyFwd = new ArrayList();
JButton backButton = null;
JButton fwdButton = null;
private long currentBid = -1;
JHTMLBundle(DefaultSwingBundleDisplayer _displayer) {
setLayout(new BorderLayout());
this.displayer = _displayer;
html = new JTextPane();
html.setText(Strings.get("bundleinfo_startup"));
html.setContentType("text/html");
html.setEditable(false);
html.addHyperlinkListener(new HyperlinkListener()
{
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
URL url = e.getURL();
if(Util.isBundleLink(url)) {
long bid = Util.bidFromURL(url);
if(getCurrentBID() != -1) {
historyBack.add(new Long(getCurrentBID()));
backButton.setEnabled(!historyBack.isEmpty());
}
displayer.getBundleSelectionModel().clearSelection();
displayer.getBundleSelectionModel().setSelected(bid, true);
} else if(Util.isServiceLink(url)) {
long sid = Util.sidFromURL(url);
if(getCurrentBID() != -1) {
historyBack.add(new Long(getCurrentBID()));
backButton.setEnabled(!historyBack.isEmpty());
}
setServiceHTML(sid);
}
}
}
}
);
scroll =
new JScrollPane(html,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
html.setPreferredSize(new Dimension(300, 300));
JToolBar cmds = new JToolBar() {
{
add(backButton = new JButton(Activator.desktop.prevIcon) {
{
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
if(!historyBack.isEmpty()) {
Long bid = (Long)historyBack.get(historyBack.size()-1);
historyBack.remove(historyBack.size()-1);
if(getCurrentBID() != -1) {
historyFwd.add(new Long(getCurrentBID()));
}
// System.out.println("back to " + bid);
gotoBid(bid.longValue());
}
backButton.setEnabled(historyBack.size() > 0);
fwdButton.setEnabled(historyFwd.size() > 0);
}
});
setToolTipText(Strings.get("tt_html_back"));
}
});
add(fwdButton = new JButton(Activator.desktop.nextIcon) {
{
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
if(historyFwd.size() > 0) {
Long bid = (Long)historyFwd.get(historyFwd.size()-1);
historyFwd.remove(historyFwd.size()-1);
if(getCurrentBID() != -1) {
historyBack.add(new Long(getCurrentBID()));
}
// System.out.println("fwd to " + bid);
gotoBid(bid.longValue());
}
backButton.setEnabled(historyBack.size() > 0);
fwdButton.setEnabled(historyFwd.size() > 0);
}
});
setToolTipText(Strings.get("tt_html_back"));
}
});
backButton.setEnabled(historyBack.size() > 0);
fwdButton.setEnabled(historyFwd.size() > 0);
}
};
cmds.setFloatable(false);
add(scroll, BorderLayout.CENTER);
add(cmds, BorderLayout.SOUTH);
valueChanged(null);
}
void gotoBid(long bid) {
displayer.getBundleSelectionModel().clearSelection();
displayer.getBundleSelectionModel().setSelected(bid, true);
}
void setServiceHTML(long sid) {
StringBuffer sb = new StringBuffer();
try {
ServiceReference[] srl =
Activator.bc.getServiceReferences(null,
"(" + Constants.SERVICE_ID + "=" + sid + ")");
if(srl != null && srl.length == 1) {
sb.append("<html>");
sb.append("<table border=0>");
sb.append("<tr><td width=\"100%\" bgcolor=\"#eeeeee\">");
startFont(sb, "-1");
sb.append("Service #" + sid);
sb.append(", ");
Util.bundleLink(sb, srl[0].getBundle());
sb.append("</font>\n");
sb.append("</td>\n");
sb.append("</tr>\n");
sb.append("</table>");
try {
Object serviceObj = Activator.bc.getService(srl[0]);
if(serviceObj != null) {
sb.append(formatServiceObject(serviceObj,
(String[])srl[0].getProperty("objectClass")));
}
} catch (Exception e) {
sb.append("Failed to format service object: " + e);
}
startFont(sb);
sb.append("<b>Properties</b>");
sb.append("</font>");
sb.append("<table cellpadding=0 cellspacing=1 border=0>");
String[] keys = srl[0].getPropertyKeys();
for(int i = 0; keys != null && i < keys.length; i++) {
StringWriter sw = new StringWriter();
PrintWriter pr = new PrintWriter(sw);
printObject(pr, srl[0].getProperty(keys[i]));
sb.append("<tr>");
sb.append("<td valign=top>");
startFont(sb);
sb.append(keys[i]);
stopFont(sb);
sb.append("</td>");
sb.append("<td valign=top>");
sb.append(sw.toString());
sb.append("</td>");
sb.append("</tr>");
}
sb.append("</table>");
sb.append("</html>");
} else {
sb.append("No service with sid=" + sid);
}
} catch (Exception e2) {
e2.printStackTrace();
}
setHTML(sb.toString());
}
StringBuffer formatServiceObject(Object obj, String[] names) {
StringBuffer sb = new StringBuffer();
startFont(sb);
sb.append("<b>Implemented interfaces</b>");
sb.append("<br>");
for(int i = 0; i < names.length; i++) {
sb.append(names[i]);
if(i < names.length -1) {
sb.append(", ");
}
}
sb.append("</font>");
sb.append("<br>");
startFont(sb);
sb.append("<b>Methods</b>");
sb.append("<br>");
sb.append("<table>");
Class clazz = obj.getClass();
sb.append(formatClass(clazz).toString());
sb.append("</table>");
return sb;
}
StringBuffer formatClass(Class clazz) {
Method[] methods = clazz.getDeclaredMethods();
StringBuffer sb = new StringBuffer();
sb.append("<tr>");
sb.append("<td colspan=3 valign=top bgcolor=\"#eeeeee\">");
startFont(sb);
sb.append(clazz.getName());
sb.append("</font>");
sb.append("</td>");
sb.append("</tr>");
for(int i = 0; i < methods.length; i++) {
if(!Modifier.isPublic(methods[i].getModifiers())) {
continue;
}
Class[] params = methods[i].getParameterTypes();
sb.append("<tr>");
sb.append("<td valign=top colspan=3>");
startFont(sb);
sb.append(className(methods[i].getReturnType().getName()));
sb.append(" ");
sb.append(methods[i].getName());
sb.append("(");
for(int j = 0; j < params.length; j++) {
sb.append(className(params[j].getName()));
if(j < params.length - 1) {
sb.append(", ");
}
}
sb.append(");");
sb.append("</font>");
sb.append("</td>");
sb.append("</tr>");
}
return sb;
}
String className(String name) {
if(name.startsWith("[L") && name.endsWith(";")) {
name = name.substring(2, name.length() - 1) + "[]";
}
if(name.startsWith("java.lang.")) {
name = name.substring(10);
}
return name;
}
/**
* Override this to provide special bundle info in HTML
* format.
*/
public abstract StringBuffer bundleInfo(Bundle b);
/**
* Get header text for no selected bundle page.
*/
public String getNoBundleSelectedHeader() {
return "No bundle selected";
}
/**
* Get main text for no selected bundle page.
*/
public String getNoBundleSelectedText() {
return
"Select one or more bundles in the main view to " +
"view detail information";
}
/**
* Get header text for selected bundle page.
*/
public String getBundleSelectedHeader(Bundle b) {
return
"#" + b.getBundleId() + " " + Util.getBundleName(b);
}
public void valueChanged(Bundle[] bl) {
StringBuffer sb = new StringBuffer("<html>\n");
// System.out.println("valueChanged bl=" + (bl != null ? ("#" + bl.length) : "null"));
if(bl == null || bl.length == 0) {
sb.append("<html>\n");
sb.append("<table border=0>\n");
sb.append("<tr><td bgcolor=\"#eeeeee\">");
startFont(sb, "-1");
sb.append(getNoBundleSelectedHeader());
sb.append("</font>\n");
sb.append("</td>\n");
sb.append("</tr>\n");
sb.append("</table>\n");
startFont(sb);
sb.append(getNoBundleSelectedText());
sb.append("</font>\n" +
"</p>\n" +
"</html>");
} else {
if(bl.length == 1) {
if(bl[0].getBundleId() == getCurrentBID()) {
// System.out.println("skip already set bid=" + getCurrentBID());
// return;
}
}
// System.out.println("new bundle " + bl[0].getBundleId());
setCurrentBID(bl[0].getBundleId());
for(int i = 0; i < bl.length; i++) {
sb.append("<table border=0 width=\"100%\">\n");
sb.append("<tr><td width=\"100%\" bgcolor=\"#eeeeee\">");
startFont(sb, "-1");
sb.append(getBundleSelectedHeader(bl[i]));
sb.append("</font>\n");
sb.append("</td>\n");
sb.append("</tr>\n");
sb.append("<tr><td bgcolor=\"#ffffff\">");
sb.append(bundleInfo(bl[i]).toString());
sb.append("</td>\n");
sb.append("</tr>\n");
sb.append("</table>\n");
}
}
sb.append("\n</html>");
setHTML(sb.toString());
}
protected void setCurrentBID(long bid) {
this.currentBid = bid;
}
public long getCurrentBID() {
return currentBid;
}
void setHTML(String s) {
html.setText(s);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JViewport vp = scroll.getViewport();
if(vp != null) {
vp.setViewPosition(new Point(0,0));
scroll.setViewport(vp);
}
}
});
}
void appendRow(StringBuffer sb, String c1, String c2) {
sb.append("<tr>" +
" <td valign=top><b>");
startFont(sb);
sb.append(c1);
sb.append("</font>");
sb.append("</b></td>\n");
sb.append(" <td valign=top>");
startFont(sb);
sb.append(c2);
sb.append("</td>\n" +
"</tr>\n");
}
void startFont(StringBuffer sb) {
startFont(sb, "-2");
}
void stopFont(StringBuffer sb) {
sb.append("</font>");
}
void startFont(StringBuffer sb, String size) {
sb.append("<font size=\"" + size + "\" face=\"Verdana, Arial, Helvetica, sans-serif\">");
}
String fontify(Object o) {
return fontify(o, -2);
}
String fontify(Object o, int size) {
return "<font size=\"" + size + "\" face=\"Verdana, Arial, Helvetica, sans-serif\">" + o + "</font>";
}
void printObject(PrintWriter out, Object val) throws IOException {
if(val == null) {
out.println("null");
} else if(val.getClass().isArray()) {
printArray(out, (Object[])val);
} else if(val instanceof Vector) {
printVector(out, (Vector)val);
} else if(val instanceof Map) {
printMap(out, (Map)val);
} else if(val instanceof Set) {
printSet(out, (Set)val);
} else if(val instanceof Dictionary) {
printDictionary(out, (Dictionary)val);
} else {
out.print(fontify(val));
// out.print(" (" + val.getClass().getName() + ")");
}
}
void printDictionary(PrintWriter out, Dictionary d) throws IOException {
out.println("<table border=0>");
for(Enumeration e = d.keys(); e.hasMoreElements();) {
Object key = e.nextElement();
Object val = d.get(key);
out.println("<tr>");
out.println("<td valign=top>");
printObject(out, key);
out.println("</td>");
out.println("<td valign=top>");
printObject(out, val);
out.println("</td>");
out.println("</tr>");
}
out.println("</table>");
}
void printMap(PrintWriter out, Map m) throws IOException {
out.println("<table border=0>");
for(Iterator it = m.keySet().iterator(); it.hasNext();) {
Object key = it.next();
Object val = m.get(key);
out.println("<tr>");
out.println("<td valign=top>");
printObject(out, key);
out.println("</td>");
out.println("<td valign=top>");
printObject(out, val);
out.println("</td>");
out.println("</tr>");
}
out.println("</table>");
}
void printArray(PrintWriter out, Object[] a) throws IOException {
for(int i = 0; i < a.length; i++) {
printObject(out, a[i]);
if(i < a.length - 1) {
out.println("<br>");
}
}
}
void printSet(PrintWriter out, Set a) throws IOException {
for(Iterator it = a.iterator(); it.hasNext();) {
printObject(out, it.next());
if(it.hasNext()) {
out.println("<br>");
}
}
}
void printVector(PrintWriter out, Vector a) throws IOException {
for(int i = 0; i < a.size(); i++) {
printObject(out, a.elementAt(i));
if(i < a.size() - 1) {
out.println("<br>");
}
}
}
}
| osgi/bundles/desktop/src/org/knopflerfish/bundle/desktop/swing/JHTMLBundle.java | /*
* Copyright (c) 2003, KNOPFLERFISH project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the KNOPFLERFISH project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.knopflerfish.bundle.desktop.swing;
import org.osgi.framework.*;
import org.osgi.util.tracker.*;
import javax.swing.table.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.net.URL;
import java.io.*;
import java.lang.reflect.*;
/**
* Utiliy swing component which display bundle info as
* HTML.
*
*<p>
* Intended to be used as base class. Subclasses should override
* the <tt>valueChanged</tt> method and retur an HTML string.
*</p>
*
* <p>
* If the <tt>Util.bundleLink</tt> method is used to create
* text for bundles, these will become selection links for
* the bundle.
* </p>
*/
public abstract class JHTMLBundle extends JPanel {
JPanel panel;
JTextPane html;
JScrollPane scroll;
DefaultSwingBundleDisplayer displayer;
ArrayList historyBack = new ArrayList();
ArrayList historyFwd = new ArrayList();
JButton backButton = null;
JButton fwdButton = null;
private long currentBid = -1;
JHTMLBundle(DefaultSwingBundleDisplayer _displayer) {
setLayout(new BorderLayout());
this.displayer = _displayer;
html = new JTextPane();
html.setText(Strings.get("bundleinfo_startup"));
html.setContentType("text/html");
html.setEditable(false);
html.addHyperlinkListener(new HyperlinkListener()
{
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
URL url = e.getURL();
if(Util.isBundleLink(url)) {
long bid = Util.bidFromURL(url);
if(getCurrentBID() != -1) {
historyBack.add(new Long(getCurrentBID()));
backButton.setEnabled(!historyBack.isEmpty());
}
displayer.getBundleSelectionModel().clearSelection();
displayer.getBundleSelectionModel().setSelected(bid, true);
} else if(Util.isServiceLink(url)) {
long sid = Util.sidFromURL(url);
setServiceHTML(sid);
}
}
}
}
);
scroll =
new JScrollPane(html,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
html.setPreferredSize(new Dimension(300, 300));
JToolBar cmds = new JToolBar() {
{
add(backButton = new JButton(Activator.desktop.prevIcon) {
{
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
if(!historyBack.isEmpty()) {
Long bid = (Long)historyBack.get(historyBack.size()-1);
historyBack.remove(historyBack.size()-1);
if(getCurrentBID() != -1) {
historyFwd.add(new Long(getCurrentBID()));
}
// System.out.println("back to " + bid);
gotoBid(bid.longValue());
}
backButton.setEnabled(historyBack.size() > 0);
fwdButton.setEnabled(historyFwd.size() > 0);
}
});
setToolTipText(Strings.get("tt_html_back"));
}
});
add(fwdButton = new JButton(Activator.desktop.nextIcon) {
{
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
if(historyFwd.size() > 0) {
Long bid = (Long)historyFwd.get(historyFwd.size()-1);
historyFwd.remove(historyFwd.size()-1);
if(getCurrentBID() != -1) {
historyBack.add(new Long(getCurrentBID()));
}
// System.out.println("fwd to " + bid);
gotoBid(bid.longValue());
}
backButton.setEnabled(historyBack.size() > 0);
fwdButton.setEnabled(historyFwd.size() > 0);
}
});
setToolTipText(Strings.get("tt_html_back"));
}
});
backButton.setEnabled(historyBack.size() > 0);
fwdButton.setEnabled(historyFwd.size() > 0);
}
};
cmds.setFloatable(false);
add(scroll, BorderLayout.CENTER);
add(cmds, BorderLayout.SOUTH);
valueChanged(null);
}
void gotoBid(long bid) {
displayer.getBundleSelectionModel().clearSelection();
displayer.getBundleSelectionModel().setSelected(bid, true);
}
void setServiceHTML(long sid) {
StringBuffer sb = new StringBuffer();
try {
ServiceReference[] srl =
Activator.bc.getServiceReferences(null,
"(" + Constants.SERVICE_ID + "=" + sid + ")");
if(srl != null && srl.length == 1) {
sb.append("<html>");
sb.append("<table border=0>");
sb.append("<tr><td width=\"100%\" bgcolor=\"#eeeeee\">");
startFont(sb, "-1");
sb.append("Service #" + sid);
sb.append(", ");
Util.bundleLink(sb, srl[0].getBundle());
sb.append("</font>\n");
sb.append("</td>\n");
sb.append("</tr>\n");
sb.append("</table>");
try {
Object serviceObj = Activator.bc.getService(srl[0]);
if(serviceObj != null) {
sb.append(formatServiceObject(serviceObj,
(String[])srl[0].getProperty("objectClass")));
}
} catch (Exception e) {
sb.append("Failed to format service object: " + e);
}
startFont(sb);
sb.append("<b>Properties</b>");
sb.append("</font>");
sb.append("<table cellpadding=0 cellspacing=1 border=0>");
String[] keys = srl[0].getPropertyKeys();
for(int i = 0; keys != null && i < keys.length; i++) {
StringWriter sw = new StringWriter();
PrintWriter pr = new PrintWriter(sw);
printObject(pr, srl[0].getProperty(keys[i]));
sb.append("<tr>");
sb.append("<td valign=top>");
startFont(sb);
sb.append(keys[i]);
stopFont(sb);
sb.append("</td>");
sb.append("<td valign=top>");
sb.append(sw.toString());
sb.append("</td>");
sb.append("</tr>");
}
sb.append("</table>");
sb.append("</html>");
} else {
sb.append("No service with sid=" + sid);
}
} catch (Exception e2) {
e2.printStackTrace();
}
setHTML(sb.toString());
}
StringBuffer formatServiceObject(Object obj, String[] names) {
StringBuffer sb = new StringBuffer();
startFont(sb);
sb.append("<b>Implemented interfaces</b>");
sb.append("<br>");
for(int i = 0; i < names.length; i++) {
sb.append(names[i]);
if(i < names.length -1) {
sb.append(", ");
}
}
sb.append("</font>");
sb.append("<br>");
startFont(sb);
sb.append("<b>Methods</b>");
sb.append("<br>");
sb.append("<table>");
Class clazz = obj.getClass();
sb.append(formatClass(clazz).toString());
sb.append("</table>");
return sb;
}
StringBuffer formatClass(Class clazz) {
Method[] methods = clazz.getDeclaredMethods();
StringBuffer sb = new StringBuffer();
sb.append("<tr>");
sb.append("<td colspan=3 valign=top bgcolor=\"#eeeeee\">");
startFont(sb);
sb.append(clazz.getName());
sb.append("</font>");
sb.append("</td>");
sb.append("</tr>");
for(int i = 0; i < methods.length; i++) {
if(!Modifier.isPublic(methods[i].getModifiers())) {
continue;
}
Class[] params = methods[i].getParameterTypes();
sb.append("<tr>");
sb.append("<td valign=top colspan=3>");
startFont(sb);
sb.append(className(methods[i].getReturnType().getName()));
sb.append(" ");
sb.append(methods[i].getName());
sb.append("(");
for(int j = 0; j < params.length; j++) {
sb.append(className(params[j].getName()));
if(j < params.length - 1) {
sb.append(", ");
}
}
sb.append(");");
sb.append("</font>");
sb.append("</td>");
sb.append("</tr>");
}
return sb;
}
String className(String name) {
if(name.startsWith("[L") && name.endsWith(";")) {
name = name.substring(2, name.length() - 1) + "[]";
}
if(name.startsWith("java.lang.")) {
name = name.substring(10);
}
return name;
}
/**
* Override this to provide special bundle info in HTML
* format.
*/
public abstract StringBuffer bundleInfo(Bundle b);
/**
* Get header text for no selected bundle page.
*/
public String getNoBundleSelectedHeader() {
return "No bundle selected";
}
/**
* Get main text for no selected bundle page.
*/
public String getNoBundleSelectedText() {
return
"Select one or more bundles in the main view to " +
"view detail information";
}
/**
* Get header text for selected bundle page.
*/
public String getBundleSelectedHeader(Bundle b) {
return
"#" + b.getBundleId() + " " + Util.getBundleName(b);
}
public void valueChanged(Bundle[] bl) {
StringBuffer sb = new StringBuffer("<html>\n");
// System.out.println("valueChanged bl=" + (bl != null ? ("#" + bl.length) : "null"));
if(bl == null || bl.length == 0) {
sb.append("<html>\n");
sb.append("<table border=0>\n");
sb.append("<tr><td bgcolor=\"#eeeeee\">");
startFont(sb, "-1");
sb.append(getNoBundleSelectedHeader());
sb.append("</font>\n");
sb.append("</td>\n");
sb.append("</tr>\n");
sb.append("</table>\n");
startFont(sb);
sb.append(getNoBundleSelectedText());
sb.append("</font>\n" +
"</p>\n" +
"</html>");
} else {
if(bl.length == 1) {
if(bl[0].getBundleId() == getCurrentBID()) {
// System.out.println("skip already set bid=" + getCurrentBID());
return;
}
}
// System.out.println("new bundle " + bl[0].getBundleId());
setCurrentBID(bl[0].getBundleId());
for(int i = 0; i < bl.length; i++) {
sb.append("<table border=0 width=\"100%\">\n");
sb.append("<tr><td width=\"100%\" bgcolor=\"#eeeeee\">");
startFont(sb, "-1");
sb.append(getBundleSelectedHeader(bl[i]));
sb.append("</font>\n");
sb.append("</td>\n");
sb.append("</tr>\n");
sb.append("<tr><td bgcolor=\"#ffffff\">");
sb.append(bundleInfo(bl[i]).toString());
sb.append("</td>\n");
sb.append("</tr>\n");
sb.append("</table>\n");
}
}
sb.append("\n</html>");
setHTML(sb.toString());
}
protected void setCurrentBID(long bid) {
this.currentBid = bid;
}
public long getCurrentBID() {
return currentBid;
}
void setHTML(String s) {
html.setText(s);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JViewport vp = scroll.getViewport();
if(vp != null) {
vp.setViewPosition(new Point(0,0));
scroll.setViewport(vp);
}
}
});
}
void appendRow(StringBuffer sb, String c1, String c2) {
sb.append("<tr>" +
" <td valign=top><b>");
startFont(sb);
sb.append(c1);
sb.append("</font>");
sb.append("</b></td>\n");
sb.append(" <td valign=top>");
startFont(sb);
sb.append(c2);
sb.append("</td>\n" +
"</tr>\n");
}
void startFont(StringBuffer sb) {
startFont(sb, "-2");
}
void stopFont(StringBuffer sb) {
sb.append("</font>");
}
void startFont(StringBuffer sb, String size) {
sb.append("<font size=\"" + size + "\" face=\"Verdana, Arial, Helvetica, sans-serif\">");
}
String fontify(Object o) {
return fontify(o, -2);
}
String fontify(Object o, int size) {
return "<font size=\"" + size + "\" face=\"Verdana, Arial, Helvetica, sans-serif\">" + o + "</font>";
}
void printObject(PrintWriter out, Object val) throws IOException {
if(val == null) {
out.println("null");
} else if(val.getClass().isArray()) {
printArray(out, (Object[])val);
} else if(val instanceof Vector) {
printVector(out, (Vector)val);
} else if(val instanceof Map) {
printMap(out, (Map)val);
} else if(val instanceof Set) {
printSet(out, (Set)val);
} else if(val instanceof Dictionary) {
printDictionary(out, (Dictionary)val);
} else {
out.print(fontify(val));
// out.print(" (" + val.getClass().getName() + ")");
}
}
void printDictionary(PrintWriter out, Dictionary d) throws IOException {
out.println("<table border=0>");
for(Enumeration e = d.keys(); e.hasMoreElements();) {
Object key = e.nextElement();
Object val = d.get(key);
out.println("<tr>");
out.println("<td valign=top>");
printObject(out, key);
out.println("</td>");
out.println("<td valign=top>");
printObject(out, val);
out.println("</td>");
out.println("</tr>");
}
out.println("</table>");
}
void printMap(PrintWriter out, Map m) throws IOException {
out.println("<table border=0>");
for(Iterator it = m.keySet().iterator(); it.hasNext();) {
Object key = it.next();
Object val = m.get(key);
out.println("<tr>");
out.println("<td valign=top>");
printObject(out, key);
out.println("</td>");
out.println("<td valign=top>");
printObject(out, val);
out.println("</td>");
out.println("</tr>");
}
out.println("</table>");
}
void printArray(PrintWriter out, Object[] a) throws IOException {
for(int i = 0; i < a.length; i++) {
printObject(out, a[i]);
if(i < a.length - 1) {
out.println("<br>");
}
}
}
void printSet(PrintWriter out, Set a) throws IOException {
for(Iterator it = a.iterator(); it.hasNext();) {
printObject(out, it.next());
if(it.hasNext()) {
out.println("<br>");
}
}
}
void printVector(PrintWriter out, Vector a) throws IOException {
for(int i = 0; i < a.size(); i++) {
printObject(out, a.elementAt(i));
if(i < a.size() - 1) {
out.println("<br>");
}
}
}
}
| html back fix for service view | osgi/bundles/desktop/src/org/knopflerfish/bundle/desktop/swing/JHTMLBundle.java | html back fix for service view | <ide><path>sgi/bundles/desktop/src/org/knopflerfish/bundle/desktop/swing/JHTMLBundle.java
<ide>
<ide> } else if(Util.isServiceLink(url)) {
<ide> long sid = Util.sidFromURL(url);
<add>
<add> if(getCurrentBID() != -1) {
<add> historyBack.add(new Long(getCurrentBID()));
<add>
<add> backButton.setEnabled(!historyBack.isEmpty());
<add> }
<ide>
<ide> setServiceHTML(sid);
<ide>
<ide> if(bl.length == 1) {
<ide> if(bl[0].getBundleId() == getCurrentBID()) {
<ide> // System.out.println("skip already set bid=" + getCurrentBID());
<del> return;
<add> // return;
<ide> }
<ide> }
<ide> |
|
JavaScript | mit | a870ff8447705223682d24b8dd5cf6f50aae0254 | 0 | benjamminf/craft-neo,benjamminf/craft-neo,benjamminf/craft-neo | import $ from 'jquery'
import Garnish from 'garnish'
import Craft from 'craft'
import NS from '../namespace'
import Settings from './BlockTypeSettings'
import FieldLayout from './BlockTypeFieldLayout'
import renderTemplate from './templates/blocktype.twig'
import '../twig-extensions'
const _defaults = {
namespace: [],
settings: null,
fieldLayout: null
}
export default Garnish.Base.extend({
_templateNs: [],
_selected: false,
init(settings = {})
{
settings = Object.assign({}, _defaults, settings)
this._templateNs = NS.parse(settings.namespace)
this._settings = settings.settings
this._fieldLayout = settings.fieldLayout
NS.enter(this._templateNs)
this.$container = $(renderTemplate({
settings: this._settings,
fieldLayout: this._fieldLayout
}))
NS.leave()
const $neo = this.$container.find('[data-neo-bt]')
this.$nameText = $neo.filter('[data-neo-bt="text.name"]')
this.$moveButton = $neo.filter('[data-neo-bt="button.move"]')
if(this._settings)
{
this._settings.on('change', () => this._updateTemplate())
this._settings.on('delete', () => this.trigger('delete'))
}
this.deselect()
},
getSettings()
{
return this._settings
},
getFieldLayout()
{
return this._fieldLayout
},
select()
{
this.toggleSelect(true)
},
deselect()
{
this.toggleSelect(false)
},
toggleSelect: function(select)
{
this._selected = (typeof select === 'boolean' ? select : !this._selected)
if(this._settings)
{
this._settings.$container.toggleClass('hidden', !this._selected)
}
if(this._fieldLayout)
{
this._fieldLayout.$container.toggleClass('hidden', !this._selected)
}
this.$container.toggleClass('is-selected', this._selected)
},
isSelected()
{
return this._selected
},
_updateTemplate()
{
const settings = this.getSettings()
const fieldLayout = this.getFieldLayout()
if(settings)
{
this.$nameText.text(settings.getName())
if(fieldLayout)
{
fieldLayout.setBlockName(settings.getName())
}
}
}
})
| neo/resources/src/configurator/BlockType.js | import $ from 'jquery'
import Garnish from 'garnish'
import Craft from 'craft'
import NS from '../namespace'
import Settings from './BlockTypeSettings'
import FieldLayout from './BlockTypeFieldLayout'
import renderTemplate from './templates/blocktype.twig'
import '../twig-extensions'
const _defaults = {
namespace: [],
settings: null,
fieldLayout: null
}
export default Garnish.Base.extend({
_templateNs: [],
_parsed: false,
_selected: false,
init(settings = {})
{
settings = Object.assign({}, _defaults, settings)
this._templateNs = NS.parse(settings.namespace)
this._settings = settings.settings
this._fieldLayout = settings.fieldLayout
NS.enter(this._templateNs)
this.$container = $(renderTemplate({
settings: this._settings,
fieldLayout: this._fieldLayout
}))
NS.leave()
const $neo = this.$container.find('[data-neo-bt]')
this.$nameText = $neo.filter('[data-neo-bt="text.name"]')
this.$moveButton = $neo.filter('[data-neo-bt="button.move"]')
if(this._settings)
{
this._settings.on('change', () => this._updateTemplate())
this._settings.on('delete', () => this.trigger('delete'))
}
this.deselect()
},
getSettings()
{
return this._settings
},
getFieldLayout()
{
return this._fieldLayout
},
select()
{
this.toggleSelect(true)
},
deselect()
{
this.toggleSelect(false)
},
toggleSelect: function(select)
{
this._selected = (typeof select === 'boolean' ? select : !this._selected)
if(this._settings)
{
this._settings.$container.toggleClass('hidden', !this._selected)
}
if(this._fieldLayout)
{
this._fieldLayout.$container.toggleClass('hidden', !this._selected)
}
this.$container.toggleClass('is-selected', this._selected)
},
isSelected()
{
return this._selected
},
_updateTemplate()
{
const settings = this.getSettings()
const fieldLayout = this.getFieldLayout()
if(settings)
{
this.$nameText.text(settings.getName())
if(fieldLayout)
{
fieldLayout.setBlockName(settings.getName())
}
}
}
})
| Removed unused property
| neo/resources/src/configurator/BlockType.js | Removed unused property | <ide><path>eo/resources/src/configurator/BlockType.js
<ide> export default Garnish.Base.extend({
<ide>
<ide> _templateNs: [],
<del> _parsed: false,
<ide> _selected: false,
<ide>
<ide> init(settings = {}) |
|
Java | apache-2.0 | f8e90f6c288aed55fee77655d84c8cf8a6a10d23 | 0 | mrkcsc/android-mg-bootstrap,mrkcsc/android-mg-bootstrap | package com.miguelgaeta.bootstrap.mg_delay;
import java.util.concurrent.TimeUnit;
import rx.Observable;
/**
* Created by Miguel Gaeta on 2/17/15.
*/
class MGDelayUtil {
/**
* Setup an observable object based
* on the specified delay parameters.
*/
static Observable<Void> observe(long delayMilliseconds, boolean loop, boolean startImmediately) {
// Create timer or looping observable.
Observable<Long> observable = loop ?
Observable.interval(delayMilliseconds, TimeUnit.MILLISECONDS) :
Observable.timer (delayMilliseconds, TimeUnit.MILLISECONDS);
if (startImmediately) {
// Start right away.
observable = observable.startWith(0L);
}
return observable.onBackpressureDrop().map(r -> null);
}
}
| mg-bootstrap/lib/src/main/java/com/miguelgaeta/bootstrap/mg_delay/MGDelayUtil.java | package com.miguelgaeta.bootstrap.mg_delay;
import java.util.concurrent.TimeUnit;
import rx.Observable;
/**
* Created by Miguel Gaeta on 2/17/15.
*/
class MGDelayUtil {
/**
* Setup an observable object based
* on the specified delay parameters.
*/
static Observable<Void> observe(long delayMilliseconds, boolean loop, boolean startImmediately) {
// Create timer or looping observable.
Observable<Long> observable = loop ?
Observable.interval(delayMilliseconds, TimeUnit.MILLISECONDS) :
Observable.timer (delayMilliseconds, TimeUnit.MILLISECONDS);
if (startImmediately) {
// Start right away.
observable = observable.startWith(0L);
}
return observable.flatMap(aLong -> Observable.create(subscriber -> {
subscriber.onNext(null);
subscriber.onCompleted();
})).onBackpressureDrop().map(r -> null);
}
}
| Removed a flat map that was not necessary.
| mg-bootstrap/lib/src/main/java/com/miguelgaeta/bootstrap/mg_delay/MGDelayUtil.java | Removed a flat map that was not necessary. | <ide><path>g-bootstrap/lib/src/main/java/com/miguelgaeta/bootstrap/mg_delay/MGDelayUtil.java
<ide> observable = observable.startWith(0L);
<ide> }
<ide>
<del> return observable.flatMap(aLong -> Observable.create(subscriber -> {
<del>
<del> subscriber.onNext(null);
<del> subscriber.onCompleted();
<del>
<del> })).onBackpressureDrop().map(r -> null);
<add> return observable.onBackpressureDrop().map(r -> null);
<ide> }
<ide> } |
|
JavaScript | mit | 638e06d17ac9055ec9746870db2fc6cd52d85f19 | 0 | mcardozo/Leaflet.AccuratePosition,gwilson/getAccurateCurrentPosition,zevero/getAccurateCurrentPosition,johan--/Leaflet.AccuratePosition,mcardozo/Leaflet.AccuratePosition,johan--/Leaflet.AccuratePosition,M165437/Leaflet.AccuratePosition,M165437/Leaflet.AccuratePosition | navigator.geolocation.getAccurateCurrentPosition = function (geolocationSuccess, geolocationError, geoprogress, options) {
var lastCheckedPosition,
locationEventCount = 0,
watchID,
timerID;
options = options || {};
var checkLocation = function (position) {
lastCheckedPosition = position;
locationEventCount = locationEventCount + 1;
// We ignore the first event unless it's the only one received because some devices seem to send a cached
// location even when maxaimumAge is set to zero
if ((position.coords.accuracy <= options.desiredAccuracy) && (locationEventCount > 1)) {
clearTimeout(timerID);
navigator.geolocation.clearWatch(watchID);
foundPosition(position);
} else {
geoprogress(position);
}
};
var stopTrying = function () {
navigator.geolocation.clearWatch(watchID);
foundPosition(lastCheckedPosition);
};
var onError = function (error) {
clearTimeout(timerID);
navigator.geolocation.clearWatch(watchID);
geolocationError(error);
};
var foundPosition = function (position) {
geolocationSuccess(position);
};
if (!options.maxWait) options.maxWait = 10000; // Default 10 seconds
if (!options.desiredAccuracy) options.desiredAccuracy = 20; // Default 20 meters
if (!options.timeout) options.timeout = options.maxWait; // Default to maxWait
options.maximumAge = 0; // Force current locations only
options.enableHighAccuracy = true; // Force high accuracy (otherwise, why are you using this function?)
watchID = navigator.geolocation.watchPosition(checkLocation, onError, options);
timerID = setTimeout(stopTrying, options.maxWait); // Set a timeout that will abandon the location loop
};
| geo.js | navigator.geolocation.getAccurateCurrentPosition = function (geolocationSuccess, geolocationError, geoprogress, options) {
var lastCheckedPosition,
locationEventCount = 0,
watchID,
timerID;
options = options || {};
var checkLocation = function (position) {
lastCheckedPosition = position;
locationEventCount = locationEventCount + 1;
// We ignore the first event unless it's the only one received because some devices seem to send a cached
// location even when maxaimumAge is set to zero
if ((position.coords.accuracy <= options.desiredAccuracy) && (locationEventCount > 1)) {
clearTimeout(timerID);
navigator.geolocation.clearWatch(watchID);
foundPosition(position);
} else {
geoprogress(position);
}
};
var stopTrying = function () {
navigator.geolocation.clearWatch(watchID);
foundPosition(lastCheckedPosition);
};
var onError = function (error) {
clearTimeout(timerID);
navigator.geolocation.clearWatch(watchID);
geolocationError(error);
};
var foundPosition = function (position) {
geolocationSuccess(position);
};
if (!options.maxWait) options.maxWait = 10000; // Default 10 seconds
if (!options.desiredAccuracy) options.desiredAccuracy = 20; // Default 20 meters
if (!options.timeout) options.timeout = options.maxWait; // Default to maxWait
options.maximumAge = 0; // Force current locations only
options.enableHighAccuracy = true; // Force high accuracy (otherwise, why are you using this function?)
watchID = navigator.geolocation.watchPosition(checkLocation, onError, options);
timerID = setTimeout(stopTrying, options.maxWait); // Set a timeout that will abandon the location loop
};
| Cleaned up code a bit
| geo.js | Cleaned up code a bit | <ide><path>eo.js
<ide> locationEventCount = 0,
<ide> watchID,
<ide> timerID;
<del>
<add>
<ide> options = options || {};
<ide>
<ide> var checkLocation = function (position) { |
|
Java | mit | 4385128aa4ad16016c2f3b579cfab233bf3996ca | 0 | Qyotta/axon-eventstore,Qyotta/axon-eventstore | package de.qyotta.eventstore;
import de.qyotta.eventstore.model.Event;
import de.qyotta.eventstore.model.EventResponse;
import de.qyotta.eventstore.utils.EventStreamReader;
import de.qyotta.eventstore.utils.EventStreamReaderImpl.EventStreamReaderCallback;
import static com.jayway.awaitility.Awaitility.await;
import static com.jayway.awaitility.Duration.FIVE_SECONDS;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.After;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.google.gson.Gson;
@SuppressWarnings("nls")
public class EventStreamReaderTest extends AbstractEsTest {
@After
public void tearDown() {
// try hard deleting created streams. This might not do anything depending on the test
deleteStream(streamUrl);
}
@Test
public void shouldTraverseAllEventsInOrder() throws InterruptedException {
createEvents(10);
final EventStreamReader eventStreamReader = client.newEventStreamReader(streamName, -1, new EventStreamReaderCallback() {
private long previousEventNumber = -1;
@Override
public void readEvent(final EventResponse event) {
final Event expected = expectedEvents.remove(event.getContent()
.getEventId());
assertThat(expected, is(notNullValue()));
final Long currentEventNumber = event.getContent()
.getEventNumber();
assertThat(currentEventNumber, is(greaterThan(previousEventNumber)));
previousEventNumber = currentEventNumber;
}
});
eventStreamReader.start();
}
@Test
public void shouldCatchUpOnStream() throws InterruptedException {
final String firsteventId = prepareAnEventInStream();
final EventStreamReaderCallback callback = mock(EventStreamReaderCallback.class);
final EventStreamReader eventStreamReader = client.newEventStreamReader(streamName, -1, callback);
eventStreamReader.start(firsteventId);
verify(callback, never()).readEvent(any(EventResponse.class));
final Event expected = Event.builder()
.eventId(UUID.randomUUID()
.toString())
.eventType("something")
.data(new Gson().toJson(new MyEvent(UUID.randomUUID()
.toString())))
.metadata(metaData())
.build();
client.appendEvent(streamName, expected);
eventStreamReader.catchUp();
final ArgumentCaptor<EventResponse> argument = ArgumentCaptor.forClass(EventResponse.class);
verify(callback).readEvent(argument.capture());
final Event actual = argument.getValue()
.getContent();
assertThat(actual.getEventId(), is(equalTo(expected.getEventId())));
assertThat(actual.getEventType(), is(equalTo(expected.getEventType())));
assertThat(actual.getMetadata(), is(equalTo(expected.getMetadata())));
assertThat(actual.getData(), is(equalTo(expected.getData())));
}
@Test
@Ignore("TODO sha Fix this please! Timing!")
public void shouldCatchUpAfterIntervalExpires() throws InterruptedException {
final String firsteventId = prepareAnEventInStream();
final EventStreamReaderCallback callback = mock(EventStreamReaderCallback.class);
final int intervalMillis = 500;
final EventStreamReader eventStreamReader = client.newEventStreamReader(streamName, intervalMillis, callback);
eventStreamReader.start(firsteventId);
verify(callback, never()).readEvent(any(EventResponse.class));
final AtomicBoolean condition = new AtomicBoolean(false);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
condition.set(true);
return null;
}
}).when(callback)
.readEvent(any(EventResponse.class));
createEvents(1);
await().atMost(FIVE_SECONDS)
.until(() -> condition.get()); // just wait twice the time we scheduled the reader
}
@Test
public void shouldCatchUpOnStreamWithMultipleEventsInBetween() throws InterruptedException {
final String firsteventId = prepareAnEventInStream();
final EventStreamReaderCallback callback = mock(EventStreamReaderCallback.class);
final EventStreamReader eventStreamReader = client.newEventStreamReader(streamName, -1, callback);
eventStreamReader.start(firsteventId);
verify(callback, never()).readEvent(any(EventResponse.class));
createEvents(10);
eventStreamReader.catchUp();
verify(callback, times(10)).readEvent(any(EventResponse.class));
}
@Test
public void shouldHaveNoInteractionsIfCatchingUpOnUnchangedStream() throws InterruptedException {
createEvents(78);
final EventStreamReaderCallback callback = mock(EventStreamReaderCallback.class);
final EventStreamReader eventStreamReader = client.newEventStreamReader(streamName, -1, callback);
eventStreamReader.start();
eventStreamReader.catchUp();
verify(callback, times(78)).readEvent(any(EventResponse.class));
eventStreamReader.catchUp();
verifyNoMoreInteractions(callback);
}
@Test
public void shouldCatchUpAfterRestart() throws InterruptedException {
createEvents(75);
final EventStreamReaderCallback callback = mock(EventStreamReaderCallback.class);
final EventStreamReader eventStreamReader = client.newEventStreamReader(streamName, -1, callback);
eventStreamReader.start(13 + "@" + streamName);
eventStreamReader.catchUp();
verify(callback, times(61)).readEvent(any(EventResponse.class));
createEvents(55);
eventStreamReader.catchUp();
verify(callback, times(116)).readEvent(any(EventResponse.class));
}
private String prepareAnEventInStream() {
final Event given = Event.builder()
.eventId(UUID.randomUUID()
.toString())
.eventType("Testtype")
.data(new Gson().toJson(new MyEvent(UUID.randomUUID()
.toString())))
.metadata(metaData())
.build();
client.appendEvent(streamName, given);
return client.readEvents(streamName)
.next()
.getTitle();
}
}
| eventstore-client/src/test/java/de/qyotta/eventstore/EventStreamReaderTest.java | package de.qyotta.eventstore;
import static com.jayway.awaitility.Awaitility.await;
import static com.jayway.awaitility.Duration.FIVE_SECONDS;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.After;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.google.gson.Gson;
import de.qyotta.eventstore.model.Event;
import de.qyotta.eventstore.model.EventResponse;
import de.qyotta.eventstore.utils.EventStreamReader;
import de.qyotta.eventstore.utils.EventStreamReaderImpl.EventStreamReaderCallback;
@SuppressWarnings("nls")
public class EventStreamReaderTest extends AbstractEsTest {
@After
public void tearDown() {
// try hard deleting created streams. This might not do anything depending on the test
deleteStream(streamUrl);
}
@Test
public void shouldTraverseAllEventsInOrder() throws InterruptedException {
createEvents(10);
final EventStreamReader eventStreamReader = client.newEventStreamReader(streamName, -1, new EventStreamReaderCallback() {
private long previousEventNumber = -1;
@Override
public void readEvent(final EventResponse event) {
final Event expected = expectedEvents.remove(event.getContent()
.getEventId());
assertThat(expected, is(notNullValue()));
final Long currentEventNumber = event.getContent()
.getEventNumber();
assertThat(currentEventNumber, is(greaterThan(previousEventNumber)));
previousEventNumber = currentEventNumber;
}
});
eventStreamReader.start();
}
@Test
public void shouldCatchUpOnStream() throws InterruptedException {
final String firsteventId = prepareAnEventInStream();
final EventStreamReaderCallback callback = mock(EventStreamReaderCallback.class);
final EventStreamReader eventStreamReader = client.newEventStreamReader(streamName, -1, callback);
eventStreamReader.start(firsteventId);
verify(callback, never()).readEvent(any(EventResponse.class));
final Event expected = Event.builder()
.eventId(UUID.randomUUID()
.toString())
.eventType("something")
.data(new Gson().toJson(new MyEvent(UUID.randomUUID()
.toString())))
.metadata(metaData())
.build();
client.appendEvent(streamName, expected);
eventStreamReader.catchUp();
final ArgumentCaptor<EventResponse> argument = ArgumentCaptor.forClass(EventResponse.class);
verify(callback).readEvent(argument.capture());
final Event actual = argument.getValue()
.getContent();
assertThat(actual.getEventId(), is(equalTo(expected.getEventId())));
assertThat(actual.getEventType(), is(equalTo(expected.getEventType())));
assertThat(actual.getMetadata(), is(equalTo(expected.getMetadata())));
assertThat(actual.getData(), is(equalTo(expected.getData())));
}
@Test
@Ignore("TODO sha Fix this please! Timing!")
public void shouldCatchUpAfterIntervalExpires() throws InterruptedException {
final String firsteventId = prepareAnEventInStream();
final EventStreamReaderCallback callback = mock(EventStreamReaderCallback.class);
final int intervalMillis = 500;
final EventStreamReader eventStreamReader = client.newEventStreamReader(streamName, intervalMillis, callback);
eventStreamReader.start(firsteventId);
verify(callback, never()).readEvent(any(EventResponse.class));
final AtomicBoolean condition = new AtomicBoolean(false);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
condition.set(true);
return null;
}
}).when(callback)
.readEvent(any(EventResponse.class));
createEvents(1);
await().atMost(FIVE_SECONDS)
.until(() -> condition.get()); // just wait twice the time we scheduled the reader
}
@Test
public void shouldCatchUpOnStreamWithMultipleEventsInBetween() throws InterruptedException {
final String firsteventId = prepareAnEventInStream();
final EventStreamReaderCallback callback = mock(EventStreamReaderCallback.class);
final EventStreamReader eventStreamReader = client.newEventStreamReader(streamName, -1, callback);
eventStreamReader.start(firsteventId);
verify(callback, never()).readEvent(any(EventResponse.class));
createEvents(10);
eventStreamReader.catchUp();
verify(callback, times(10)).readEvent(any(EventResponse.class));
}
@Test
public void shouldHaveNoInteractionsIfCatchingUpOnUnchangedStream() throws InterruptedException {
createEvents(78);
final EventStreamReaderCallback callback = mock(EventStreamReaderCallback.class);
final EventStreamReader eventStreamReader = client.newEventStreamReader(streamName, -1, callback);
eventStreamReader.start();
verify(callback, times(78)).readEvent(any(EventResponse.class));
eventStreamReader.catchUp();
verifyNoMoreInteractions(callback);
}
@Test
public void shouldCatchUpAfterRestart() throws InterruptedException {
createEvents(75);
final EventStreamReaderCallback callback = mock(EventStreamReaderCallback.class);
final EventStreamReader eventStreamReader = client.newEventStreamReader(streamName, -1, callback);
eventStreamReader.start(13 + "@" + streamName);
verify(callback, times(61)).readEvent(any(EventResponse.class));
createEvents(55);
eventStreamReader.catchUp();
verify(callback, times(116)).readEvent(any(EventResponse.class));
}
private String prepareAnEventInStream() {
final Event given = Event.builder()
.eventId(UUID.randomUUID()
.toString())
.eventType("Testtype")
.data(new Gson().toJson(new MyEvent(UUID.randomUUID()
.toString())))
.metadata(metaData())
.build();
client.appendEvent(streamName, given);
return client.readEvents(streamName)
.next()
.getTitle();
}
}
| Fix test
| eventstore-client/src/test/java/de/qyotta/eventstore/EventStreamReaderTest.java | Fix test | <ide><path>ventstore-client/src/test/java/de/qyotta/eventstore/EventStreamReaderTest.java
<ide> package de.qyotta.eventstore;
<add>
<add>import de.qyotta.eventstore.model.Event;
<add>import de.qyotta.eventstore.model.EventResponse;
<add>import de.qyotta.eventstore.utils.EventStreamReader;
<add>import de.qyotta.eventstore.utils.EventStreamReaderImpl.EventStreamReaderCallback;
<ide>
<ide> import static com.jayway.awaitility.Awaitility.await;
<ide> import static com.jayway.awaitility.Duration.FIVE_SECONDS;
<ide> import org.mockito.stubbing.Answer;
<ide>
<ide> import com.google.gson.Gson;
<del>
<del>import de.qyotta.eventstore.model.Event;
<del>import de.qyotta.eventstore.model.EventResponse;
<del>import de.qyotta.eventstore.utils.EventStreamReader;
<del>import de.qyotta.eventstore.utils.EventStreamReaderImpl.EventStreamReaderCallback;
<ide>
<ide> @SuppressWarnings("nls")
<ide> public class EventStreamReaderTest extends AbstractEsTest {
<ide> final EventStreamReader eventStreamReader = client.newEventStreamReader(streamName, -1, callback);
<ide>
<ide> eventStreamReader.start();
<add> eventStreamReader.catchUp();
<ide> verify(callback, times(78)).readEvent(any(EventResponse.class));
<ide> eventStreamReader.catchUp();
<ide> verifyNoMoreInteractions(callback);
<ide> final EventStreamReaderCallback callback = mock(EventStreamReaderCallback.class);
<ide> final EventStreamReader eventStreamReader = client.newEventStreamReader(streamName, -1, callback);
<ide> eventStreamReader.start(13 + "@" + streamName);
<add> eventStreamReader.catchUp();
<ide> verify(callback, times(61)).readEvent(any(EventResponse.class));
<ide> createEvents(55);
<ide> eventStreamReader.catchUp(); |
|
Java | apache-2.0 | error: pathspec 'kurento-integration-tests/kurento-test/src/test/java/org/kurento/test/stability/recorder/RecorderThreeWebRtcSimultaneous.java' did not match any file(s) known to git
| f8684c78f4f06c368084f2afd52cc9f0e6341892 | 1 | EugenioFidel/kurento-java,EugenioFidel/kurento-java,EugenioFidel/kurento-java,Kurento/kurento-java,EugenioFidel/kurento-java,Kurento/kurento-java,Kurento/kurento-java,Kurento/kurento-java | /*
* (C) Copyright 2015 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
package org.kurento.test.stability.recorder;
import static org.kurento.client.MediaProfileSpecType.MP4;
import static org.kurento.client.MediaProfileSpecType.WEBM;
import static org.kurento.test.config.TestConfiguration.TEST_DURATION_PROPERTY;
import static org.kurento.test.functional.recorder.BaseRecorder.EXPECTED_AUDIO_CODEC_MP4;
import static org.kurento.test.functional.recorder.BaseRecorder.EXPECTED_AUDIO_CODEC_WEBM;
import static org.kurento.test.functional.recorder.BaseRecorder.EXPECTED_VIDEO_CODEC_MP4;
import static org.kurento.test.functional.recorder.BaseRecorder.EXPECTED_VIDEO_CODEC_WEBM;
import static org.kurento.test.functional.recorder.BaseRecorder.EXTENSION_MP4;
import static org.kurento.test.functional.recorder.BaseRecorder.EXTENSION_WEBM;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runners.Parameterized.Parameters;
import org.kurento.client.MediaPipeline;
import org.kurento.client.MediaProfileSpecType;
import org.kurento.client.RecorderEndpoint;
import org.kurento.client.WebRtcEndpoint;
import org.kurento.commons.PropertiesManager;
import org.kurento.test.base.StabilityTest;
import org.kurento.test.browser.WebRtcChannel;
import org.kurento.test.browser.WebRtcMode;
import org.kurento.test.config.Protocol;
import org.kurento.test.config.TestScenario;
import org.kurento.test.mediainfo.AssertMedia;
/**
* Stability test for Recorder. Create three connections WebRTC and record it. </p> Media
* Pipeline(s):
* <ul>
* <li>WebRtcEndpoint -> RecorderEndpoint</li>
* </ul>
* Browser(s):
* <ul>
* <li>Chrome</li>
* <li>Firefox</li>
* </ul>
* Test logic:
* <ol>
* <li>(Browser) WebRtcPeer in send-only sends media to KMS</li>
* <li>(KMS) WebRtcEndpoint receives media and it is recorded by RecorderEndpoint.</li>
* </ol>
* Main assertion(s):
* <ul>
* <li>Recorded files are OK (seekable, length, content)</li>
* </ul>
* Secondary assertion(s):
* <ul>
* <li>--</li>
* </ul>
*
* @author Raul Benitez ([email protected])
* @since 6.3.1
*/
public class RecorderThreeWebRtcSimultaneous extends StabilityTest {
private static final int RECORD_MS = 2 * 60 * 1000; // ms
private static final int THRESHOLD_MS = 5000; // ms
private static final int NUM_BROWSERS = 3;
@Parameters(name = "{index}: {0}")
public static Collection<Object[]> data() {
return TestScenario.localChromes(NUM_BROWSERS);
}
@Test
public void testRecorderWebRtcSimultaneousWebm() throws Exception {
long testDurationMillis =
PropertiesManager.getProperty(TEST_DURATION_PROPERTY, DEFAULT_TEST_DURATION);
endTestTime = System.currentTimeMillis() + testDurationMillis;
while (!isTimeToFinishTest()) {
doTest(WEBM, EXPECTED_VIDEO_CODEC_WEBM, EXPECTED_AUDIO_CODEC_WEBM, EXTENSION_WEBM);
}
}
@Test
public void testRecorderWebRtcSimultaneousMp4() throws Exception {
long testDurationMillis =
PropertiesManager.getProperty(TEST_DURATION_PROPERTY, DEFAULT_TEST_DURATION);
endTestTime = System.currentTimeMillis() + testDurationMillis;
while (!isTimeToFinishTest()) {
doTest(MP4, EXPECTED_VIDEO_CODEC_MP4, EXPECTED_AUDIO_CODEC_MP4, EXTENSION_MP4);
}
}
public void doTest(final MediaProfileSpecType mediaProfileSpecType, String expectedVideoCodec,
String expectedAudioCodec, final String extension) throws Exception {
MediaPipeline mp = null;
// Media Pipeline
mp = kurentoClient.createMediaPipeline();
final WebRtcEndpoint[] webRtcSender = new WebRtcEndpoint[NUM_BROWSERS];
final RecorderEndpoint[] recorder = new RecorderEndpoint[NUM_BROWSERS];
final String[] recordingFile = new String[NUM_BROWSERS];
ExecutorService executor = Executors.newFixedThreadPool(NUM_BROWSERS);
final CountDownLatch latch = new CountDownLatch(NUM_BROWSERS);
final MediaPipeline pipeline = mp;
for (int j = 0; j < NUM_BROWSERS; j++) {
final int i = j;
executor.execute(new Runnable() {
@Override
public void run() {
try {
// N viewer
webRtcSender[i] = new WebRtcEndpoint.Builder(pipeline).build();
// N recorders
recordingFile[i] = getDefaultOutputFile("-receiver" + i + extension);
recorder[i] =
new RecorderEndpoint.Builder(pipeline, Protocol.FILE + "://" + recordingFile[i])
.withMediaProfile(mediaProfileSpecType).build();
// WebRTC receiver negotiation
getPage(i).subscribeLocalEvents("playing");
getPage(i).initWebRtc(webRtcSender[i], WebRtcChannel.AUDIO_AND_VIDEO,
WebRtcMode.SEND_ONLY);
Assert.assertTrue("Not received media in sender" + i, getPage(i)
.waitForEvent("playing"));
webRtcSender[i].connect(recorder[i]);
// Start record
recorder[i].record();
// Wait play time
Thread.sleep(RECORD_MS);
// Stop record
recorder[i].stop();
// Guard time to stop recording
Thread.sleep(4000);
getPage(i).reload();
} catch (Throwable e) {
log.error("Exception in receiver " + i, e);
} finally {
latch.countDown();
}
}
});
}
// Wait to finish all recorders
latch.await();
// Assessment
for (int j = 0; j < NUM_BROWSERS; j++) {
AssertMedia.assertCodecs(recordingFile[j], expectedVideoCodec, expectedAudioCodec);
AssertMedia.assertDuration(recordingFile[j], RECORD_MS, THRESHOLD_MS);
}
// Release Media Pipeline
if (mp != null) {
mp.release();
}
}
}
| kurento-integration-tests/kurento-test/src/test/java/org/kurento/test/stability/recorder/RecorderThreeWebRtcSimultaneous.java | Add new test. Create 3 browsers, 3 webRtcs and 3 recorders and work simultaneous
Change-Id: I8731f799848206d28f4dd2c4e7a8ccf1549ce26e
| kurento-integration-tests/kurento-test/src/test/java/org/kurento/test/stability/recorder/RecorderThreeWebRtcSimultaneous.java | Add new test. Create 3 browsers, 3 webRtcs and 3 recorders and work simultaneous | <ide><path>urento-integration-tests/kurento-test/src/test/java/org/kurento/test/stability/recorder/RecorderThreeWebRtcSimultaneous.java
<add>/*
<add> * (C) Copyright 2015 Kurento (http://kurento.org/)
<add> *
<add> * All rights reserved. This program and the accompanying materials
<add> * are made available under the terms of the GNU Lesser General Public License
<add> * (LGPL) version 2.1 which accompanies this distribution, and is available at
<add> * http://www.gnu.org/licenses/lgpl-2.1.html
<add> *
<add> * This library is distributed in the hope that it will be useful,
<add> * but WITHOUT ANY WARRANTY; without even the implied warranty of
<add> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
<add> * Lesser General Public License for more details.
<add> *
<add> */
<add>
<add>package org.kurento.test.stability.recorder;
<add>
<add>import static org.kurento.client.MediaProfileSpecType.MP4;
<add>import static org.kurento.client.MediaProfileSpecType.WEBM;
<add>import static org.kurento.test.config.TestConfiguration.TEST_DURATION_PROPERTY;
<add>import static org.kurento.test.functional.recorder.BaseRecorder.EXPECTED_AUDIO_CODEC_MP4;
<add>import static org.kurento.test.functional.recorder.BaseRecorder.EXPECTED_AUDIO_CODEC_WEBM;
<add>import static org.kurento.test.functional.recorder.BaseRecorder.EXPECTED_VIDEO_CODEC_MP4;
<add>import static org.kurento.test.functional.recorder.BaseRecorder.EXPECTED_VIDEO_CODEC_WEBM;
<add>import static org.kurento.test.functional.recorder.BaseRecorder.EXTENSION_MP4;
<add>import static org.kurento.test.functional.recorder.BaseRecorder.EXTENSION_WEBM;
<add>
<add>import java.util.Collection;
<add>import java.util.concurrent.CountDownLatch;
<add>import java.util.concurrent.ExecutorService;
<add>import java.util.concurrent.Executors;
<add>
<add>import org.junit.Assert;
<add>import org.junit.Test;
<add>import org.junit.runners.Parameterized.Parameters;
<add>import org.kurento.client.MediaPipeline;
<add>import org.kurento.client.MediaProfileSpecType;
<add>import org.kurento.client.RecorderEndpoint;
<add>import org.kurento.client.WebRtcEndpoint;
<add>import org.kurento.commons.PropertiesManager;
<add>import org.kurento.test.base.StabilityTest;
<add>import org.kurento.test.browser.WebRtcChannel;
<add>import org.kurento.test.browser.WebRtcMode;
<add>import org.kurento.test.config.Protocol;
<add>import org.kurento.test.config.TestScenario;
<add>import org.kurento.test.mediainfo.AssertMedia;
<add>
<add>/**
<add> * Stability test for Recorder. Create three connections WebRTC and record it. </p> Media
<add> * Pipeline(s):
<add> * <ul>
<add> * <li>WebRtcEndpoint -> RecorderEndpoint</li>
<add> * </ul>
<add> * Browser(s):
<add> * <ul>
<add> * <li>Chrome</li>
<add> * <li>Firefox</li>
<add> * </ul>
<add> * Test logic:
<add> * <ol>
<add> * <li>(Browser) WebRtcPeer in send-only sends media to KMS</li>
<add> * <li>(KMS) WebRtcEndpoint receives media and it is recorded by RecorderEndpoint.</li>
<add> * </ol>
<add> * Main assertion(s):
<add> * <ul>
<add> * <li>Recorded files are OK (seekable, length, content)</li>
<add> * </ul>
<add> * Secondary assertion(s):
<add> * <ul>
<add> * <li>--</li>
<add> * </ul>
<add> *
<add> * @author Raul Benitez ([email protected])
<add> * @since 6.3.1
<add> */
<add>public class RecorderThreeWebRtcSimultaneous extends StabilityTest {
<add>
<add> private static final int RECORD_MS = 2 * 60 * 1000; // ms
<add> private static final int THRESHOLD_MS = 5000; // ms
<add> private static final int NUM_BROWSERS = 3;
<add>
<add> @Parameters(name = "{index}: {0}")
<add> public static Collection<Object[]> data() {
<add> return TestScenario.localChromes(NUM_BROWSERS);
<add> }
<add>
<add> @Test
<add> public void testRecorderWebRtcSimultaneousWebm() throws Exception {
<add> long testDurationMillis =
<add> PropertiesManager.getProperty(TEST_DURATION_PROPERTY, DEFAULT_TEST_DURATION);
<add>
<add> endTestTime = System.currentTimeMillis() + testDurationMillis;
<add> while (!isTimeToFinishTest()) {
<add> doTest(WEBM, EXPECTED_VIDEO_CODEC_WEBM, EXPECTED_AUDIO_CODEC_WEBM, EXTENSION_WEBM);
<add> }
<add> }
<add>
<add> @Test
<add> public void testRecorderWebRtcSimultaneousMp4() throws Exception {
<add> long testDurationMillis =
<add> PropertiesManager.getProperty(TEST_DURATION_PROPERTY, DEFAULT_TEST_DURATION);
<add>
<add> endTestTime = System.currentTimeMillis() + testDurationMillis;
<add> while (!isTimeToFinishTest()) {
<add> doTest(MP4, EXPECTED_VIDEO_CODEC_MP4, EXPECTED_AUDIO_CODEC_MP4, EXTENSION_MP4);
<add> }
<add> }
<add>
<add> public void doTest(final MediaProfileSpecType mediaProfileSpecType, String expectedVideoCodec,
<add> String expectedAudioCodec, final String extension) throws Exception {
<add>
<add> MediaPipeline mp = null;
<add>
<add> // Media Pipeline
<add> mp = kurentoClient.createMediaPipeline();
<add>
<add> final WebRtcEndpoint[] webRtcSender = new WebRtcEndpoint[NUM_BROWSERS];
<add> final RecorderEndpoint[] recorder = new RecorderEndpoint[NUM_BROWSERS];
<add> final String[] recordingFile = new String[NUM_BROWSERS];
<add>
<add> ExecutorService executor = Executors.newFixedThreadPool(NUM_BROWSERS);
<add> final CountDownLatch latch = new CountDownLatch(NUM_BROWSERS);
<add> final MediaPipeline pipeline = mp;
<add> for (int j = 0; j < NUM_BROWSERS; j++) {
<add> final int i = j;
<add> executor.execute(new Runnable() {
<add> @Override
<add> public void run() {
<add> try {
<add> // N viewer
<add> webRtcSender[i] = new WebRtcEndpoint.Builder(pipeline).build();
<add> // N recorders
<add> recordingFile[i] = getDefaultOutputFile("-receiver" + i + extension);
<add> recorder[i] =
<add> new RecorderEndpoint.Builder(pipeline, Protocol.FILE + "://" + recordingFile[i])
<add> .withMediaProfile(mediaProfileSpecType).build();
<add>
<add> // WebRTC receiver negotiation
<add> getPage(i).subscribeLocalEvents("playing");
<add> getPage(i).initWebRtc(webRtcSender[i], WebRtcChannel.AUDIO_AND_VIDEO,
<add> WebRtcMode.SEND_ONLY);
<add> Assert.assertTrue("Not received media in sender" + i, getPage(i)
<add> .waitForEvent("playing"));
<add>
<add> webRtcSender[i].connect(recorder[i]);
<add>
<add> // Start record
<add> recorder[i].record();
<add>
<add> // Wait play time
<add> Thread.sleep(RECORD_MS);
<add>
<add> // Stop record
<add> recorder[i].stop();
<add>
<add> // Guard time to stop recording
<add> Thread.sleep(4000);
<add> getPage(i).reload();
<add> } catch (Throwable e) {
<add> log.error("Exception in receiver " + i, e);
<add>
<add> } finally {
<add> latch.countDown();
<add> }
<add> }
<add> });
<add> }
<add>
<add> // Wait to finish all recorders
<add> latch.await();
<add>
<add> // Assessment
<add> for (int j = 0; j < NUM_BROWSERS; j++) {
<add> AssertMedia.assertCodecs(recordingFile[j], expectedVideoCodec, expectedAudioCodec);
<add> AssertMedia.assertDuration(recordingFile[j], RECORD_MS, THRESHOLD_MS);
<add> }
<add>
<add> // Release Media Pipeline
<add> if (mp != null) {
<add> mp.release();
<add> }
<add> }
<add>} |
|
Java | mit | 3d397054c827c8db9d295f7b0b835e2b47a103e8 | 0 | jruby/joni | /*
* 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.joni;
final class StackEntry {
int type;
private int E1, E2, E3, E4, E5;
// first union member
/* byte code position */
void setStatePCode(int pcode) {
E1 = pcode;
}
int getStatePCode() {
return E1;
}
/* string position */
void setStatePStr(int pstr) {
E2 = pstr;
}
int getStatePStr() {
return E2;
}
/* previous char position of pstr */
void setStatePStrPrev(int pstrPrev) {
E3 = pstrPrev;
}
int getStatePStrPrev() {
return E3;
}
void setPKeep(int pkeep) {
E4 = pkeep;
}
int getPKeep() {
return E4;
}
void setStateCheck(int check) {
E5 = check;
}
int getStateCheck() {
return E5;
}
// second union member
/* for OP_REPEAT_INC, OP_REPEAT_INC_NG */
void setRepeatCount(int count) {
E1 = count;
}
int getRepeatCount() {
return E1;
}
void decreaseRepeatCount() {
E1--;
}
void increaseRepeatCount() {
E1++;
}
/* byte code position (head of repeated target) */
void setRepeatPCode(int pcode) {
E2 = pcode;
}
int getRepeatPCode() {
return E2;
}
/* repeat id */
void setRepeatNum(int num) {
E3 = num;
}
int getRepeatNum() {
return E3;
}
// third union member
/* index of stack */ /*int repeat_inc struct*/
void setSi(int si) {
E1 = si;
}
int getSi() {
return E1;
}
// fourth union member
/* memory num */
void setMemNum(int num) {
E1 = num;
}
int getMemNum() {
return E1;
}
/* start/end position */
void setMemPstr(int pstr) {
E2 = pstr;
}
int getMemPStr() {
return E2;
}
/* Following information is set, if this stack type is MEM-START */
/* prev. info (for backtrack "(...)*" ) */
void setMemStart(int start) {
E3 = start;
}
int getMemStart() {
return E3;
}
/* prev. info (for backtrack "(...)*" ) */
void setMemEnd(int end) {
E4 = end;
}
int getMemEnd() {
return E4;
}
// fifth union member
/* null check id */
void setNullCheckNum(int num) {
E1 = num;
}
int getNullCheckNum() {
return E1;
}
/* start position */
void setNullCheckPStr(int pstr) {
E2 = pstr;
}
int getNullCheckPStr() {
return E2;
}
// sixth union member
/* byte code position */
void setCallFrameRetAddr(int addr) {
E1 = addr;
}
int getCallFrameRetAddr() {
return E1;
}
/* null check id */
void setCallFrameNum(int num) {
E2 = num;
}
int getCallFrameNum() {
return E2;
}
/* string position */
void setCallFramePStr(int pstr) {
E3 = pstr;
}
int getCallFramePStr() {
return E3;
}
void setAbsentStr(int pos) {
E1 = pos;
}
int getAbsentStr() {
return E1;
}
void setAbsentEndStr(int pos) {
E2 = pos;
}
int getAbsentEndStr() {
return E2;
}
}
| src/org/joni/StackEntry.java | /*
* 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.joni;
final class StackEntry {
int type;
private int E1, E2, E3, E4, E5;
// first union member
/* byte code position */
void setStatePCode(int pcode) {
E1 = pcode;
}
int getStatePCode() {
return E1;
}
/* string position */
void setStatePStr(int pstr) {
E2 = pstr;
}
int getStatePStr() {
return E2;
}
/* previous char position of pstr */
void setStatePStrPrev(int pstrPrev) {
E3 = pstrPrev;
}
int getStatePStrPrev() {
return E3;
}
void setStateCheck(int check) {
E4 = check;
}
int getStateCheck() {
return E4;
}
void setPKeep(int pkeep) {
E5 = pkeep;
}
int getPKeep() {
return E5;
}
// second union member
/* for OP_REPEAT_INC, OP_REPEAT_INC_NG */
void setRepeatCount(int count) {
E1 = count;
}
int getRepeatCount() {
return E1;
}
void decreaseRepeatCount() {
E1--;
}
void increaseRepeatCount() {
E1++;
}
/* byte code position (head of repeated target) */
void setRepeatPCode(int pcode) {
E2 = pcode;
}
int getRepeatPCode() {
return E2;
}
/* repeat id */
void setRepeatNum(int num) {
E3 = num;
}
int getRepeatNum() {
return E3;
}
// third union member
/* index of stack */ /*int repeat_inc struct*/
void setSi(int si) {
E1 = si;
}
int getSi() {
return E1;
}
// fourth union member
/* memory num */
void setMemNum(int num) {
E1 = num;
}
int getMemNum() {
return E1;
}
/* start/end position */
void setMemPstr(int pstr) {
E2 = pstr;
}
int getMemPStr() {
return E2;
}
/* Following information is set, if this stack type is MEM-START */
/* prev. info (for backtrack "(...)*" ) */
void setMemStart(int start) {
E3 = start;
}
int getMemStart() {
return E3;
}
/* prev. info (for backtrack "(...)*" ) */
void setMemEnd(int end) {
E4 = end;
}
int getMemEnd() {
return E4;
}
// fifth union member
/* null check id */
void setNullCheckNum(int num) {
E1 = num;
}
int getNullCheckNum() {
return E1;
}
/* start position */
void setNullCheckPStr(int pstr) {
E2 = pstr;
}
int getNullCheckPStr() {
return E2;
}
// sixth union member
/* byte code position */
void setCallFrameRetAddr(int addr) {
E1 = addr;
}
int getCallFrameRetAddr() {
return E1;
}
/* null check id */
void setCallFrameNum(int num) {
E2 = num;
}
int getCallFrameNum() {
return E2;
}
/* string position */
void setCallFramePStr(int pstr) {
E3 = pstr;
}
int getCallFramePStr() {
return E3;
}
void setAbsentStr(int pos) {
E1 = pos;
}
int getAbsentStr() {
return E1;
}
void setAbsentEndStr(int pos) {
E2 = pos;
}
int getAbsentEndStr() {
return E2;
}
}
| swap pkeep and state check union members
| src/org/joni/StackEntry.java | swap pkeep and state check union members | <ide><path>rc/org/joni/StackEntry.java
<ide> return E3;
<ide> }
<ide>
<add> void setPKeep(int pkeep) {
<add> E4 = pkeep;
<add> }
<add>
<add> int getPKeep() {
<add> return E4;
<add> }
<add>
<ide> void setStateCheck(int check) {
<del> E4 = check;
<add> E5 = check;
<ide> }
<ide>
<ide> int getStateCheck() {
<del> return E4;
<add> return E5;
<ide> }
<ide>
<del> void setPKeep(int pkeep) {
<del> E5 = pkeep;
<del> }
<del>
<del> int getPKeep() {
<del> return E5;
<del> }
<ide> // second union member
<ide> /* for OP_REPEAT_INC, OP_REPEAT_INC_NG */
<ide> void setRepeatCount(int count) { |
|
Java | apache-2.0 | 7b09ec01cea2c50dae230dd892dc1f9eb98b2ad5 | 0 | jinahya/bit-io,jinahya/bit-io | package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, 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.
* #L%
*/
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeUnsigned16;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeUnsigned8;
/**
* An abstract class for implementing {@link BitInput} interface.
*
* @author Jin Kwon <jinahya_at_gmail.com>
* @see AbstractBitOutput
*/
public abstract class AbstractBitInput implements BitInput {
// -----------------------------------------------------------------------------------------------------------------
/**
* Returns a string representation of the object.
*
* @return a string representation of the object.
*/
@Override
public String toString() {
return super.toString() + "{"
+ "count=" + count
+ "}";
}
// -----------------------------------------------------------------------------------------------------------------
/**
* Reads an unsigned 8-bit integer.
*
* @return an unsigned 8-bit integer.
* @throws IOException if an I/O error occurs.
*/
protected abstract int read() throws IOException;
// -----------------------------------------------------------------------------------------------------------------
/**
* Reads an unsigned value whose size is, in maximum, {@value Byte#SIZE}.
*
* @param size the number of bits for the value; between {@code 1} and {@value Byte#SIZE}, both inclusive.
* @return an unsigned byte value.
* @throws IOException if an I/O error occurs.
*/
protected int unsigned8(final int size) throws IOException {
requireValidSizeUnsigned8(size);
if (available == 0) {
octet = read();
count++;
available = Byte.SIZE;
}
final int required = size - available;
if (required > 0) {
return (unsigned8(available) << required) | unsigned8(required);
}
return (octet >> (available -= size)) & ((1 << size) - 1);
}
// -----------------------------------------------------------------------------------------------------------------
/**
* Reads an unsigned value whose size is, in maximum, {@value Short#SIZE}.
*
* @param size the number of bits for the value; between {@code 1} and {@value Short#SIZE}, both inclusive.
* @return an unsigned short value.
* @throws IOException if an I/O error occurs.
*/
protected int unsigned16(final int size) throws IOException {
requireValidSizeUnsigned16(size);
int value = 0x00;
final int quotient = size / Byte.SIZE;
for (int i = 0; i < quotient; i++) {
value <<= Byte.SIZE;
value |= unsigned8(Byte.SIZE);
}
final int remainder = size % Byte.SIZE;
if (remainder > 0) {
value <<= remainder;
value |= unsigned8(remainder);
}
return value;
}
// --------------------------------------------------------------------------------------------------------- boolean
@Override
public boolean readBoolean() throws IOException {
return readInt(true, 1) == 1;
}
// ------------------------------------------------------------------------------------------------------------ byte
@Override
public byte readByte(final boolean unsigned, final int size) throws IOException {
return (byte) readInt(unsigned, requireValidSizeByte(unsigned, size));
}
// @Override
// public byte readSignedByte(final int size) throws IOException {
// return readByte(false, size);
// }
//
// @Override
// public byte readUnsignedByte(final int size) throws IOException {
// return readByte(true, size);
// }
// ----------------------------------------------------------------------------------------------------------- short
@Override
public short readShort(final boolean unsigned, final int size) throws IOException {
return (short) readInt(unsigned, requireValidSizeShort(unsigned, size));
}
// @Override
// public short readSignedShort(final int size) throws IOException {
// return readShort(false, size);
// }
//
// @Override
// public short readUnsignedShort(final int size) throws IOException {
// return readShort(true, size);
// }
// ------------------------------------------------------------------------------------------------------------- int
@Override
public int readInt(final boolean unsigned, final int size) throws IOException {
requireValidSizeInt(unsigned, size);
if (!unsigned) {
int value = 0 - readInt(true, 1);
final int usize = size - 1;
if (usize > 0) {
value <<= usize;
value |= readInt(true, usize);
}
return value;
}
int value = 0x00;
final int quotient = size / Short.SIZE;
for (int i = 0; i < quotient; i++) {
value <<= Short.SIZE;
value |= unsigned16(Short.SIZE);
}
final int remainder = size % Short.SIZE;
if (remainder > 0) {
value <<= remainder;
value |= unsigned16(remainder);
}
return value;
}
// @Override
// public int readSignedInt(final int size) throws IOException {
// return readInt(false, size);
// }
//
// @Override
// public int readUnsignedInt(final int size) throws IOException {
// return readInt(true, size);
// }
// ------------------------------------------------------------------------------------------------------------ long
@Override
public long readLong(final boolean unsigned, final int size) throws IOException {
requireValidSizeLong(unsigned, size);
if (!unsigned) {
long value = 0L - readLong(true, 1);
final int usize = size - 1;
if (usize > 0) {
value <<= usize;
value |= readLong(true, usize);
}
return value;
}
long value = 0x00L;
final int quotient = size / Integer.SIZE;
for (int i = 0; i < quotient; i++) {
value <<= Integer.SIZE;
value |= readInt(false, Integer.SIZE) & 0xFFFFFFFFL;
}
final int remainder = size % Integer.SIZE;
if (remainder > 0) {
value <<= remainder;
value |= readInt(true, remainder);
}
return value;
}
// @Override
// public long readSignedLong(final int size) throws IOException {
// return readLong(false, size);
// }
//
// @Override
// public long readUnsignedLong(final int size) throws IOException {
// return readLong(true, size);
// }
// ------------------------------------------------------------------------------------------------------------ char
@Override
public char readChar(final int size) throws IOException {
return (char) readInt(true, requireValidSizeChar(size));
}
// -----------------------------------------------------------------------------------------------------------------
@Override
public long align(final int bytes) throws IOException {
if (bytes <= 0) {
throw new IllegalArgumentException("bytes(" + bytes + ") <= 0");
}
long bits = 0; // number of bits to be discarded
if (available > 0) {
bits += available;
readInt(true, available);
}
for (; count % bytes > 0; bits += Byte.SIZE) {
readInt(true, Byte.SIZE);
}
return bits;
}
// -----------------------------------------------------------------------------------------------------------------
/**
* Returns the number bytes read so far.
*
* @return the number of bytes read so far.
*/
public long getCount() {
return count;
}
// -----------------------------------------------------------------------------------------------------------------
/**
* The current octet.
*/
private int octet;
/**
* The number of available bits in {@link #octet} for reading..
*/
private int available;
/**
* The number of bytes read so far.
*/
private long count;
}
| src/main/java/com/github/jinahya/bit/io/AbstractBitInput.java | package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, 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.
* #L%
*/
import java.io.IOException;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeUnsigned16;
import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeUnsigned8;
/**
* An abstract class for implementing {@link BitInput} interface.
*
* @author Jin Kwon <jinahya_at_gmail.com>
* @see AbstractBitOutput
*/
public abstract class AbstractBitInput implements BitInput {
// -----------------------------------------------------------------------------------------------------------------
/**
* Returns a string representation of the object.
*
* @return a string representation of the object.
*/
@Override
public String toString() {
return super.toString() + "{"
+ "count=" + count
+ "}";
}
// -----------------------------------------------------------------------------------------------------------------
/**
* Reads an unsigned 8-bit integer.
*
* @return an unsigned 8-bit integer.
* @throws IOException if an I/O error occurs.
*/
protected abstract int read() throws IOException;
// -----------------------------------------------------------------------------------------------------------------
/**
* Reads an unsigned value whose maximum size is {@value Byte#SIZE}.
*
* @param size the number of bits for the value; between {@code 1} and {@value Byte#SIZE}, both inclusive.
* @return an unsigned byte value.
* @throws IOException if an I/O error occurs.
*/
protected int unsigned8(final int size) throws IOException {
requireValidSizeUnsigned8(size);
if (available == 0) {
octet = read();
count++;
available = Byte.SIZE;
}
final int required = size - available;
if (required > 0) {
return (unsigned8(available) << required) | unsigned8(required);
}
return (octet >> (available -= size)) & ((1 << size) - 1);
}
// -----------------------------------------------------------------------------------------------------------------
/**
* Reads an unsigned value whose maximum size is {@value Short#SIZE}.
*
* @param size the number of bits for the value; between {@code 1} and {@value Short#SIZE}, both inclusive.
* @return an unsigned short value.
* @throws IOException if an I/O error occurs.
*/
protected int unsigned16(final int size) throws IOException {
requireValidSizeUnsigned16(size);
int value = 0x00;
final int quotient = size / Byte.SIZE;
for (int i = 0; i < quotient; i++) {
value <<= Byte.SIZE;
value |= unsigned8(Byte.SIZE);
}
final int remainder = size % Byte.SIZE;
if (remainder > 0) {
value <<= remainder;
value |= unsigned8(remainder);
}
return value;
}
// --------------------------------------------------------------------------------------------------------- boolean
@Override
public boolean readBoolean() throws IOException {
return readInt(true, 1) == 1;
}
// ------------------------------------------------------------------------------------------------------------ byte
@Override
public byte readByte(final boolean unsigned, final int size) throws IOException {
return (byte) readInt(unsigned, requireValidSizeByte(unsigned, size));
}
// @Override
// public byte readSignedByte(final int size) throws IOException {
// return readByte(false, size);
// }
//
// @Override
// public byte readUnsignedByte(final int size) throws IOException {
// return readByte(true, size);
// }
// ----------------------------------------------------------------------------------------------------------- short
@Override
public short readShort(final boolean unsigned, final int size) throws IOException {
return (short) readInt(unsigned, requireValidSizeShort(unsigned, size));
}
// @Override
// public short readSignedShort(final int size) throws IOException {
// return readShort(false, size);
// }
//
// @Override
// public short readUnsignedShort(final int size) throws IOException {
// return readShort(true, size);
// }
// ------------------------------------------------------------------------------------------------------------- int
@Override
public int readInt(final boolean unsigned, final int size) throws IOException {
requireValidSizeInt(unsigned, size);
if (!unsigned) {
int value = 0 - readInt(true, 1);
final int usize = size - 1;
if (usize > 0) {
value <<= usize;
value |= readInt(true, usize);
}
return value;
}
int value = 0x00;
final int quotient = size / Short.SIZE;
for (int i = 0; i < quotient; i++) {
value <<= Short.SIZE;
value |= unsigned16(Short.SIZE);
}
final int remainder = size % Short.SIZE;
if (remainder > 0) {
value <<= remainder;
value |= unsigned16(remainder);
}
return value;
}
// @Override
// public int readSignedInt(final int size) throws IOException {
// return readInt(false, size);
// }
//
// @Override
// public int readUnsignedInt(final int size) throws IOException {
// return readInt(true, size);
// }
// ------------------------------------------------------------------------------------------------------------ long
@Override
public long readLong(final boolean unsigned, final int size) throws IOException {
requireValidSizeLong(unsigned, size);
if (!unsigned) {
long value = 0L - readLong(true, 1);
final int usize = size - 1;
if (usize > 0) {
value <<= usize;
value |= readLong(true, usize);
}
return value;
}
long value = 0x00L;
final int quotient = size / Integer.SIZE;
for (int i = 0; i < quotient; i++) {
value <<= Integer.SIZE;
value |= readInt(false, Integer.SIZE) & 0xFFFFFFFFL;
}
final int remainder = size % Integer.SIZE;
if (remainder > 0) {
value <<= remainder;
value |= readInt(true, remainder);
}
return value;
}
// @Override
// public long readSignedLong(final int size) throws IOException {
// return readLong(false, size);
// }
//
// @Override
// public long readUnsignedLong(final int size) throws IOException {
// return readLong(true, size);
// }
// ------------------------------------------------------------------------------------------------------------ char
@Override
public char readChar(final int size) throws IOException {
return (char) readInt(true, requireValidSizeChar(size));
}
// -----------------------------------------------------------------------------------------------------------------
@Override
public long align(final int bytes) throws IOException {
if (bytes <= 0) {
throw new IllegalArgumentException("bytes(" + bytes + ") <= 0");
}
long bits = 0; // number of bits to be discarded
if (available > 0) {
bits += available;
readInt(true, available);
}
for (; count % bytes > 0; bits += Byte.SIZE) {
readInt(true, Byte.SIZE);
}
return bits;
}
// -----------------------------------------------------------------------------------------------------------------
/**
* Returns the number bytes read so far.
*
* @return the number of bytes read so far.
*/
public long getCount() {
return count;
}
// -----------------------------------------------------------------------------------------------------------------
/**
* The current octet.
*/
private int octet;
/**
* The number of available bits in {@link #octet} for reading..
*/
private int available;
/**
* The number of bytes read so far.
*/
private long count;
}
| Update javadoc
| src/main/java/com/github/jinahya/bit/io/AbstractBitInput.java | Update javadoc | <ide><path>rc/main/java/com/github/jinahya/bit/io/AbstractBitInput.java
<ide> // -----------------------------------------------------------------------------------------------------------------
<ide>
<ide> /**
<del> * Reads an unsigned value whose maximum size is {@value Byte#SIZE}.
<add> * Reads an unsigned value whose size is, in maximum, {@value Byte#SIZE}.
<ide> *
<ide> * @param size the number of bits for the value; between {@code 1} and {@value Byte#SIZE}, both inclusive.
<ide> * @return an unsigned byte value.
<ide> // -----------------------------------------------------------------------------------------------------------------
<ide>
<ide> /**
<del> * Reads an unsigned value whose maximum size is {@value Short#SIZE}.
<add> * Reads an unsigned value whose size is, in maximum, {@value Short#SIZE}.
<ide> *
<ide> * @param size the number of bits for the value; between {@code 1} and {@value Short#SIZE}, both inclusive.
<ide> * @return an unsigned short value. |
|
Java | apache-2.0 | 039ab7fdf7d33f77758a0259e25744f7f13c9e2b | 0 | adaptris/interlok | /*
* Copyright 2015 Adaptris Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adaptris.core;
import java.util.concurrent.TimeUnit;
import com.adaptris.core.stubs.MockNonStandardRequestReplyProducer;
import com.adaptris.core.stubs.MockRequestReplyProducer;
import com.adaptris.util.TimeInterval;
import org.mockito.Mock;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@SuppressWarnings("deprecation")
public class StandaloneRequestorTest extends GeneralServiceExample {
public StandaloneRequestorTest(String name) {
super(name);
}
@Override
protected void setUp() throws Exception {
}
public void testSetTimeoutOverride() throws Exception {
MockRequestReplyProducer m = new MockRequestReplyProducer();
StandaloneRequestor service = new StandaloneRequestor(m);
assertNull(service.getReplyTimeout());
assertEquals(-1, service.timeoutOverrideMs());
TimeInterval interval = new TimeInterval(10L, TimeUnit.SECONDS);
service.setReplyTimeout(interval);
assertEquals(interval, service.getReplyTimeout());
assertEquals(interval.toMilliseconds(), service.timeoutOverrideMs());
service.setReplyTimeout(null);
assertNull(service.getReplyTimeout());
assertEquals(-1, service.timeoutOverrideMs());
}
public void testStandardDoService() throws Exception {
MockRequestReplyProducer m = new MockRequestReplyProducer();
StandaloneRequestor service = new StandaloneRequestor(m);
AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage("XYZ");
execute(service, msg);
assertTrue(msg.containsKey(MockRequestReplyProducer.REPLY_METADATA_KEY));
assertEquals(MockRequestReplyProducer.REPLY_METADATA_VALUE, msg.getMetadataValue(MockRequestReplyProducer.REPLY_METADATA_KEY));
assertEquals(1, m.getProducedMessages().size());
}
public void testNonStandardDoService() throws Exception {
MockNonStandardRequestReplyProducer m = new MockNonStandardRequestReplyProducer();
StandaloneRequestor service = new StandaloneRequestor(m);
AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage("XYZ");
execute(service, msg);
assertTrue(msg.containsKey(MockNonStandardRequestReplyProducer.REPLY_METADATA_KEY));
assertEquals(MockNonStandardRequestReplyProducer.REPLY_METADATA_VALUE, msg
.getMetadataValue(MockNonStandardRequestReplyProducer.REPLY_METADATA_KEY));
assertEquals(1, m.getProducedMessages().size());
}
public void testDoServiceNoTimeout() throws Exception {
MockRequestReplyProducer m = new MockRequestReplyProducer();
StandaloneRequestor service = new StandaloneRequestor(m);
service.setReplyTimeout(null);
AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage("XYZ");
execute(service, msg);
assertTrue(msg.containsKey(MockRequestReplyProducer.REPLY_METADATA_KEY));
assertEquals(MockRequestReplyProducer.REPLY_METADATA_VALUE, msg.getMetadataValue(MockRequestReplyProducer.REPLY_METADATA_KEY));
assertEquals(1, m.getProducedMessages().size());
}
public void testCreateName() throws Exception {
MockRequestReplyProducer m = new MockRequestReplyProducer();
StandaloneRequestor service = new StandaloneRequestor(m);
assertEquals(MockRequestReplyProducer.class.getName(), service.createName());
assertEquals(service.getProducer().createName(), service.createName());
}
public void testCreateQualifier() throws Exception {
MockRequestReplyProducer mp = new MockRequestReplyProducer();
StandaloneRequestor service = new StandaloneRequestor(mp);
mp.setUniqueId("abc");
assertEquals("abc", service.createQualifier());
assertEquals(service.getProducer().createQualifier(), service.createQualifier());
}
public void testNullProducer() throws Exception {
StandaloneRequestor service = new StandaloneRequestor();
AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage("XYZ");
execute(service, msg);
// all we care here is that a NPE isn't thrown (see INTERLOK-2829)
}
public void testNullMessage() throws Exception {
StandaloneRequestor service = new StandaloneRequestor();
service.doService(null);
}
public void testConsumerProducer() throws Exception {
AdaptrisMessageProducer mp = mock(AdaptrisMessageProducer.class);
StandaloneRequestor service = new StandaloneRequestor(mp);
service.setReplyTimeout(new TimeInterval(-1L, TimeUnit.MILLISECONDS));
AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage("XYZ");
doReturn(msg).when(mp).request(msg);
execute(service, msg);
}
@Override
protected Object retrieveObjectForSampleConfig() {
return new StandaloneRequestor();
}
}
| interlok-core/src/test/java/com/adaptris/core/StandaloneRequestorTest.java | /*
* Copyright 2015 Adaptris Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adaptris.core;
import java.util.concurrent.TimeUnit;
import com.adaptris.core.stubs.MockNonStandardRequestReplyProducer;
import com.adaptris.core.stubs.MockRequestReplyProducer;
import com.adaptris.util.TimeInterval;
@SuppressWarnings("deprecation")
public class StandaloneRequestorTest extends GeneralServiceExample {
public StandaloneRequestorTest(String name) {
super(name);
}
@Override
protected void setUp() throws Exception {
}
public void testSetTimeoutOverride() throws Exception {
MockRequestReplyProducer m = new MockRequestReplyProducer();
StandaloneRequestor service = new StandaloneRequestor(m);
assertNull(service.getReplyTimeout());
assertEquals(-1, service.timeoutOverrideMs());
TimeInterval interval = new TimeInterval(10L, TimeUnit.SECONDS);
service.setReplyTimeout(interval);
assertEquals(interval, service.getReplyTimeout());
assertEquals(interval.toMilliseconds(), service.timeoutOverrideMs());
service.setReplyTimeout(null);
assertNull(service.getReplyTimeout());
assertEquals(-1, service.timeoutOverrideMs());
}
public void testStandardDoService() throws Exception {
MockRequestReplyProducer m = new MockRequestReplyProducer();
StandaloneRequestor service = new StandaloneRequestor(m);
AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage("XYZ");
execute(service, msg);
assertTrue(msg.containsKey(MockRequestReplyProducer.REPLY_METADATA_KEY));
assertEquals(MockRequestReplyProducer.REPLY_METADATA_VALUE, msg.getMetadataValue(MockRequestReplyProducer.REPLY_METADATA_KEY));
assertEquals(1, m.getProducedMessages().size());
}
public void testNonStandardDoService() throws Exception {
MockNonStandardRequestReplyProducer m = new MockNonStandardRequestReplyProducer();
StandaloneRequestor service = new StandaloneRequestor(m);
AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage("XYZ");
execute(service, msg);
assertTrue(msg.containsKey(MockNonStandardRequestReplyProducer.REPLY_METADATA_KEY));
assertEquals(MockNonStandardRequestReplyProducer.REPLY_METADATA_VALUE, msg
.getMetadataValue(MockNonStandardRequestReplyProducer.REPLY_METADATA_KEY));
assertEquals(1, m.getProducedMessages().size());
}
public void testDoServiceNoTimeout() throws Exception {
MockRequestReplyProducer m = new MockRequestReplyProducer();
StandaloneRequestor service = new StandaloneRequestor(m);
service.setReplyTimeout(null);
AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage("XYZ");
execute(service, msg);
assertTrue(msg.containsKey(MockRequestReplyProducer.REPLY_METADATA_KEY));
assertEquals(MockRequestReplyProducer.REPLY_METADATA_VALUE, msg.getMetadataValue(MockRequestReplyProducer.REPLY_METADATA_KEY));
assertEquals(1, m.getProducedMessages().size());
}
public void testCreateName() throws Exception {
MockRequestReplyProducer m = new MockRequestReplyProducer();
StandaloneRequestor service = new StandaloneRequestor(m);
assertEquals(MockRequestReplyProducer.class.getName(), service.createName());
assertEquals(service.getProducer().createName(), service.createName());
}
public void testCreateQualifier() throws Exception {
MockRequestReplyProducer mp = new MockRequestReplyProducer();
StandaloneRequestor service = new StandaloneRequestor(mp);
mp.setUniqueId("abc");
assertEquals("abc", service.createQualifier());
assertEquals(service.getProducer().createQualifier(), service.createQualifier());
}
public void testNullProducer() throws Exception {
StandaloneRequestor service = new StandaloneRequestor();
AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage("XYZ");
execute(service, msg);
// all we care here is that a NPE isn't thrown (see INTERLOK-2829)
}
@Override
protected Object retrieveObjectForSampleConfig() {
return new StandaloneRequestor();
}
}
| INTERLOK-2829 Add a couple more unit tests
| interlok-core/src/test/java/com/adaptris/core/StandaloneRequestorTest.java | INTERLOK-2829 Add a couple more unit tests | <ide><path>nterlok-core/src/test/java/com/adaptris/core/StandaloneRequestorTest.java
<ide> import com.adaptris.core.stubs.MockNonStandardRequestReplyProducer;
<ide> import com.adaptris.core.stubs.MockRequestReplyProducer;
<ide> import com.adaptris.util.TimeInterval;
<add>import org.mockito.Mock;
<add>
<add>import static org.mockito.Mockito.doReturn;
<add>import static org.mockito.Mockito.mock;
<add>import static org.mockito.Mockito.when;
<ide>
<ide> @SuppressWarnings("deprecation")
<ide> public class StandaloneRequestorTest extends GeneralServiceExample {
<ide> // all we care here is that a NPE isn't thrown (see INTERLOK-2829)
<ide> }
<ide>
<add> public void testNullMessage() throws Exception {
<add> StandaloneRequestor service = new StandaloneRequestor();
<add> service.doService(null);
<add> }
<add>
<add> public void testConsumerProducer() throws Exception {
<add> AdaptrisMessageProducer mp = mock(AdaptrisMessageProducer.class);
<add> StandaloneRequestor service = new StandaloneRequestor(mp);
<add> service.setReplyTimeout(new TimeInterval(-1L, TimeUnit.MILLISECONDS));
<add> AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage("XYZ");
<add> doReturn(msg).when(mp).request(msg);
<add> execute(service, msg);
<add> }
<add>
<ide> @Override
<ide> protected Object retrieveObjectForSampleConfig() {
<ide> return new StandaloneRequestor(); |
|
Java | apache-2.0 | edc0e86dffa8a6f73018bc548833f1187eaae726 | 0 | nmcl/scratch,nmcl/scratch,nmcl/wfswarm-example-arjuna-old,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch | import java.util.Objects;
public class MovementRoutine
{
public MovementRoutine (String command, int numberOfCommands)
{
_command = command;
_numberOfCommands = numberOfCommands;
System.out.println("NumberOfCommands "+numberOfCommands);
if ((command == null) || (command.equals("")))
{
System.out.println("OOPS");
System.exit(0);
}
}
public boolean containsRoutine (MovementRoutine compare)
{
return (_command.indexOf(compare.getCommand()) != -1);
}
public void removeRoutine (MovementRoutine compare)
{
System.out.println("Removing "+compare.getCommand()+" from "+_command);
_command = _command.replace(compare.getCommand(), "");
_numberOfCommands -= compare.numberOfCommands();
}
public String getCommand ()
{
return _command;
}
public int getLength ()
{
return ((_command == null) ? 0 : _command.length());
}
public int numberOfCommands ()
{
return _numberOfCommands;
}
@Override
public String toString ()
{
return _command;
}
@Override
public int hashCode ()
{
return Objects.hash(_command, _numberOfCommands);
}
@Override
public boolean equals (Object obj)
{
if (obj == null)
return false;
if (this == obj)
return true;
if (getClass() == obj.getClass())
{
MovementRoutine temp = (MovementRoutine) obj;
return (_command.equals(temp._command));
}
return false;
}
private String _command;
private int _numberOfCommands;
} | AdventOfCode/2019/day17/part2/MovementRoutine.java | import java.util.Objects;
public class MovementRoutine
{
public MovementRoutine (String command, int numberOfCommands)
{
_command = command;
_numberOfCommands = numberOfCommands;
System.out.println("NumberOfCommands "+numberOfCommands);
if ((command == null) || (command.equals("")))
{
System.out.println("OOPS");
System.exit(0);
}
}
public boolean containsRoutine (MovementRoutine compare)
{
return (_command.indexOf(compare.getCommand()) != -1);
}
public void removeRoutine (MovementRoutine compare)
{
_command.replace(compare.getCommand(), "");
_numberOfCommands -= compare.numberOfCommands();
}
public String getCommand ()
{
return _command;
}
public int getLength ()
{
return ((_command == null) ? 0 : _command.length());
}
public int numberOfCommands ()
{
return _numberOfCommands;
}
@Override
public String toString ()
{
return _command;
}
@Override
public int hashCode ()
{
return Objects.hash(_command, _numberOfCommands);
}
@Override
public boolean equals (Object obj)
{
if (obj == null)
return false;
if (this == obj)
return true;
if (getClass() == obj.getClass())
{
MovementRoutine temp = (MovementRoutine) obj;
return (_command.equals(temp._command));
}
return false;
}
private String _command;
private int _numberOfCommands;
} | Update MovementRoutine.java
| AdventOfCode/2019/day17/part2/MovementRoutine.java | Update MovementRoutine.java | <ide><path>dventOfCode/2019/day17/part2/MovementRoutine.java
<ide>
<ide> public void removeRoutine (MovementRoutine compare)
<ide> {
<del> _command.replace(compare.getCommand(), "");
<add> System.out.println("Removing "+compare.getCommand()+" from "+_command);
<add>
<add> _command = _command.replace(compare.getCommand(), "");
<ide> _numberOfCommands -= compare.numberOfCommands();
<ide> }
<ide> |
|
Java | apache-2.0 | 61c37eeadeb95016db6d2180c313cdb1d2287ddc | 0 | CzBiX/v2ex-android,CzBiX/v2ex-android | package com.czbix.v2ex.parser;
import com.czbix.v2ex.common.exception.FatalException;
import com.czbix.v2ex.model.Avatar;
import com.czbix.v2ex.model.Member;
import com.czbix.v2ex.model.Node;
import com.czbix.v2ex.model.Page;
import com.czbix.v2ex.model.Tab;
import com.czbix.v2ex.model.Topic;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TopicListParser extends Parser {
private static final Pattern PATTERN_REPLY_TIME = Pattern.compile("•\\s*(.+?)(?:\\s+•|$)");
public static List<Topic> parseDoc(Document doc, Page page) throws IOException, SAXException {
if (page instanceof Node) {
return parseDocForNode(doc, (Node) page);
} else if (page instanceof Tab || page == Page.PAGE_FAV_TOPIC) {
return parseDocForTab(doc);
} else {
throw new IllegalArgumentException("unknown page type: " + page);
}
}
private static List<Topic> parseDocForTab(Document doc) throws IOException, SAXException {
final Elements elements = doc.select("#Main > div:nth-child(2) > .item tr");
final List<Topic> result = Lists.newArrayListWithCapacity(elements.size());
for (Element item : elements) {
result.add(parseItemForTab(item));
}
return result;
}
private static List<Topic> parseDocForNode(Document doc, Node node) throws IOException, SAXException {
final Elements elements = doc.select("#TopicsNode > .cell tr");
final List<Topic> result = Lists.newArrayListWithCapacity(elements.size());
for (Element item : elements) {
result.add(parseItemForNode(item, node));
}
return result;
}
private static Topic parseItemForTab(Element item) {
final Elements list = item.children();
final Topic.Builder topicBuilder = new Topic.Builder();
parseMember(topicBuilder, list.get(0));
final Element ele = list.get(2);
parseTitle(topicBuilder, ele);
parseInfo(topicBuilder, ele, null);
parseReplyCount(topicBuilder, list.get(3));
return topicBuilder.createTopic();
}
private static Topic parseItemForNode(Element item, Node node) {
final Elements list = item.children();
final Topic.Builder topicBuilder = new Topic.Builder();
parseMember(topicBuilder, list.get(0));
final Element ele = list.get(2);
parseTitle(topicBuilder, ele);
parseInfo(topicBuilder, ele, node);
parseReplyCount(topicBuilder, list.get(3));
return topicBuilder.createTopic();
}
private static void parseReplyCount(Topic.Builder topicBuilder, Element ele) {
final Elements children = ele.children();
final int count;
if (children.size() > 0) {
final String numStr = ele.child(0).text();
count = Integer.parseInt(numStr);
} else {
// do not have reply yet
count = 0;
}
topicBuilder.setReplyCount(count);
}
private static void parseInfo(Topic.Builder topicBuilder, Element ele, Node node) {
ele = ele.select(".small").get(0);
boolean hasNode;
if (node == null) {
hasNode = false;
final Elements nodeEle = ele.select("> a");
node = parseNode(nodeEle.get(0));
} else {
hasNode = true;
}
topicBuilder.setNode(node);
parseReplyTime(topicBuilder, ele.textNodes().get(hasNode ? 0 : 1));
}
static Node parseNode(Element nodeEle) {
final String title = nodeEle.text();
final String url = nodeEle.attr("href");
final String name = Node.getNameFromUrl(url);
return new Node.Builder().setTitle(title).setName(name).createNode();
}
private static void parseReplyTime(Topic.Builder topicBuilder, TextNode textNode) {
final String text = textNode.text();
final Matcher matcher = PATTERN_REPLY_TIME.matcher(text);
if (!matcher.find()) {
throw new FatalException("match reply time for topic failed: " + text);
}
final String time = matcher.group(1);
topicBuilder.setReplyTime(time);
}
private static void parseTitle(Topic.Builder topicBuilder, Element ele) {
ele = ele.select(".item_title > a").get(0);
Preconditions.checkState(ele.tagName().equals("a"));
String url = ele.attr("href");
topicBuilder.setId(Topic.getIdFromUrl(url));
topicBuilder.setTitle(ele.html());
}
static void parseMember(Topic.Builder builder, Element ele) {
final Member.Builder memberBuilder = new Member.Builder();
// get member url
ele = ele.child(0);
Preconditions.checkState(ele.tagName().equals("a"));
final String url = ele.attr("href");
memberBuilder.setUsername(Member.getNameFromUrl(url));
// get member avatar
final Avatar.Builder avatarBuilder = new Avatar.Builder();
ele = ele.child(0);
Preconditions.checkState(ele.tagName().equals("img"));
avatarBuilder.setUrl(ele.attr("src"));
memberBuilder.setAvatar(avatarBuilder.createAvatar());
builder.setMember(memberBuilder.createMember());
}
}
| app/src/main/java/com/czbix/v2ex/parser/TopicListParser.java | package com.czbix.v2ex.parser;
import com.czbix.v2ex.common.exception.FatalException;
import com.czbix.v2ex.model.Avatar;
import com.czbix.v2ex.model.Member;
import com.czbix.v2ex.model.Node;
import com.czbix.v2ex.model.Page;
import com.czbix.v2ex.model.Tab;
import com.czbix.v2ex.model.Topic;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TopicListParser extends Parser {
private static final Pattern PATTERN_REPLY_TIME = Pattern.compile("•\\s*(.+?)(?:\\s+•|$)");
public static List<Topic> parseDoc(Document doc, Page page) throws IOException, SAXException {
if (page instanceof Node) {
return parseDocForNode(doc, (Node) page);
} else if (page instanceof Tab) {
return parseDocForTab(doc);
} else {
throw new IllegalArgumentException("unknown page type: " + page);
}
}
private static List<Topic> parseDocForTab(Document doc) throws IOException, SAXException {
final Elements elements = doc.select("#Main > div:nth-child(2) > .item tr");
final List<Topic> result = Lists.newArrayListWithCapacity(elements.size());
for (Element item : elements) {
result.add(parseItemForTab(item));
}
return result;
}
private static List<Topic> parseDocForNode(Document doc, Node node) throws IOException, SAXException {
final Elements elements = doc.select("#TopicsNode > .cell tr");
final List<Topic> result = Lists.newArrayListWithCapacity(elements.size());
for (Element item : elements) {
result.add(parseItemForNode(item, node));
}
return result;
}
private static Topic parseItemForTab(Element item) {
final Elements list = item.children();
final Topic.Builder topicBuilder = new Topic.Builder();
parseMember(topicBuilder, list.get(0));
final Element ele = list.get(2);
parseTitle(topicBuilder, ele);
parseInfo(topicBuilder, ele, null);
parseReplyCount(topicBuilder, list.get(3));
return topicBuilder.createTopic();
}
private static Topic parseItemForNode(Element item, Node node) {
final Elements list = item.children();
final Topic.Builder topicBuilder = new Topic.Builder();
parseMember(topicBuilder, list.get(0));
final Element ele = list.get(2);
parseTitle(topicBuilder, ele);
parseInfo(topicBuilder, ele, node);
parseReplyCount(topicBuilder, list.get(3));
return topicBuilder.createTopic();
}
private static void parseReplyCount(Topic.Builder topicBuilder, Element ele) {
final Elements children = ele.children();
final int count;
if (children.size() > 0) {
final String numStr = ele.child(0).text();
count = Integer.parseInt(numStr);
} else {
// do not have reply yet
count = 0;
}
topicBuilder.setReplyCount(count);
}
private static void parseInfo(Topic.Builder topicBuilder, Element ele, Node node) {
ele = ele.select(".small").get(0);
boolean hasNode;
if (node == null) {
hasNode = false;
final Elements nodeEle = ele.select("> a");
node = parseNode(nodeEle.get(0));
} else {
hasNode = true;
}
topicBuilder.setNode(node);
parseReplyTime(topicBuilder, ele.textNodes().get(hasNode ? 0 : 1));
}
static Node parseNode(Element nodeEle) {
final String title = nodeEle.text();
final String url = nodeEle.attr("href");
final String name = Node.getNameFromUrl(url);
return new Node.Builder().setTitle(title).setName(name).createNode();
}
private static void parseReplyTime(Topic.Builder topicBuilder, TextNode textNode) {
final String text = textNode.text();
final Matcher matcher = PATTERN_REPLY_TIME.matcher(text);
if (!matcher.find()) {
throw new FatalException("match reply time for topic failed: " + text);
}
final String time = matcher.group(1);
topicBuilder.setReplyTime(time);
}
private static void parseTitle(Topic.Builder topicBuilder, Element ele) {
ele = ele.select(".item_title > a").get(0);
Preconditions.checkState(ele.tagName().equals("a"));
String url = ele.attr("href");
topicBuilder.setId(Topic.getIdFromUrl(url));
topicBuilder.setTitle(ele.html());
}
static void parseMember(Topic.Builder builder, Element ele) {
final Member.Builder memberBuilder = new Member.Builder();
// get member url
ele = ele.child(0);
Preconditions.checkState(ele.tagName().equals("a"));
final String url = ele.attr("href");
memberBuilder.setUsername(Member.getNameFromUrl(url));
// get member avatar
final Avatar.Builder avatarBuilder = new Avatar.Builder();
ele = ele.child(0);
Preconditions.checkState(ele.tagName().equals("img"));
avatarBuilder.setUrl(ele.attr("src"));
memberBuilder.setAvatar(avatarBuilder.createAvatar());
builder.setMember(memberBuilder.createMember());
}
}
| minor fix
| app/src/main/java/com/czbix/v2ex/parser/TopicListParser.java | minor fix | <ide><path>pp/src/main/java/com/czbix/v2ex/parser/TopicListParser.java
<ide> public static List<Topic> parseDoc(Document doc, Page page) throws IOException, SAXException {
<ide> if (page instanceof Node) {
<ide> return parseDocForNode(doc, (Node) page);
<del> } else if (page instanceof Tab) {
<add> } else if (page instanceof Tab || page == Page.PAGE_FAV_TOPIC) {
<ide> return parseDocForTab(doc);
<ide> } else {
<ide> throw new IllegalArgumentException("unknown page type: " + page); |
|
JavaScript | mit | 0926f52ee5755fa6e450278395a03ff276f5b516 | 0 | aframevr/aframe,aframevr/aframe | /* global ImageData, Map, Set */
var arrowURL = 'data:image/webp;base64,UklGRkQHAABXRUJQVlA4WAoAAAAQAAAA/wEA/wEAQUxQSL0DAAARDzD/ERGCjrY9sYYFfgo6aa1kJ7K0w9Lo3AadLSVeFxevQwj5kuM8RfR/Atw/C0+ozB/oUBrloFZs6ElSW88j1KA4yExNWQaqRZquIDF0JYmlq0hAuUDTFu66tng3teW7pa3cQf1V1edvur54M/Slm6Wv3Gx9zw0MXlQLntcsBN6wkHjTQuYtC4W3LTw8mGRVG57TbAROtxHfZNhInGkjc5aNwtk2Hg6Mvki14k+NkZzCwQgCxalcAv3kddRTPI1DcUrXId1FLf1uHpzaQz4tquhZVLlKesbVpqKeTj0n0F5PpXDlFN9UqmhalL/ImuZFo6KmToWLoKlddMprqlS8cKovBvHo2kTiFV2LN4msaxKZl3QNiair8xYRdDWivIvXVXmbcMqJ51UebZuFXxZt6xd4laxtciqRtA3Cv0nU1t+kEUFbI8JvCa+tvkm3FDlO/W+OR99+kWEp/YYo+tYfTVnf/K8cE/F///3vv//993eeL+a+uvjawLcX3xjYvJotBFY3kVjTRGFtE+BU2AiMbiQyhpHMWEYeBozAH5qNBYRDB5KBCaTDBKKBAZTDBoKBDjwHAN5ABeCJBsAZcAAC0YHHxAYSMYBiYgGZWEA2MYFCbCCZGAAIANFEB+AnYgMQTDQAYSJ2AN5EBZAm4gDgTDgAeSIu4DGygTIRN1CMLOCZiACykQlg4jsAycgA8AO+BxCNdJyDkcbwRirDGXGnx8w+FDPrkM3MQ9JQZMYhiiwV/RDMtIM3U1/DmXHUo+IR2kSR2ToWkQ1NIn2qf2J8LCqJKiDUiSADHY3whirhdHgZ94HKaR97PhE+twEUJUFoAcgyTct8hfSxSkShASDKdMJ/ritKHwgyQ0sD4D/miCxU5SbhOOUDTnZpccCjYP/i0bZ/8bAgtVGEoGapWIQXyzKVKLwgNJFk2rtMIgoNRJlOZF7SNSSyUEeQmbxBFKEmtYjEe8S8zOZ1AkJVCmS88FJOtF40Ksg4oUaFiygk3C8qlTVNyl8UTevCUdAE2t14PfVqU1FPp57TopKeQZWromddTQp6QOfTOEQt/ZDuipZ11w/wOiqO8dRORcc6BQEkDQMClaHcn5wV9yLbxsNZNgpn2sicYSNxuo34Js1G4FQbnuNsOPa28PCWhcKbFjJvWEi8ZiHwqgXPcxbc5db33Cx95WboSzddX7yp+vyN0+eul7ZyN7Xlu64t3jVt4c5pc4JLV5EYupJE0xUknC4nOjVlmaYpyLit53HCQ0+ScnqceNcS5dzUkd0/CwMAVlA4IGADAAAQXwCdASoAAgACP8ne6Wy/tjCpqJ/IA/A5CWlu4XYBG/Pz8AfwD8APz//f3v8E1fuHZnxKYACtfuHZnxKYACrYTb5mOslhxu843ecbvON3nG7zjd3a0VCn7G1MABVxwH/Xd25gAK1+4dmfEpe2+PHhQaj75++riG6FuYACtfuHZnxKYACRrK3q9xO8Ss3uWKnMhs/rDF1hi6wxdYYusMXWGI5QRcCFDZog5OgqNlse1NDuz/UoFa/cOzPiUwAEsAOK4/nu5eZHK2tlXxJfNYlMABWv3Dsz4bvNJ5YA/LtxJ38SmAArX7h2Z8Sk5vdZUYv7mZPiUwAFa/cOzPh21s5OgZxf1mfEpemRyFr/rM+JS9noA/LtxJ38SmAAlUJIotzAASn6TjdhK+D3Dsz4dyvB7h2Z8O2tnJ0DOL+sz4lL2nKLT4lL/+iSLOocxq639w7M34MNZdm55uJ8v8ra2cpVZnxKTq2F3PN/cNksAfl24k7+JTAASqrD37h2Z7b1W+VtbOUqsz4lJ1bC7nm/uGyWAPy7cSd/EpgAJVVh79w7M9t6rfK2tnKVWZ8Sk6thdzzf3DZLAH5duJO/iUwAEqqw9+4dme29VvlbWzlKrM+JSdWwu55v7hslgD8u3EnfxKYACVVYe/cOzPbeq3ytrZylVme0kYJ8557FLerqFrzIbPrrf3DZLAH5duJO/iUvaVMS9BoaF4p7pSDFTP1XMyfElelrM0DOL+sz4eBJ13nV1OppBGPuKb4YzXQgq9uH19uS/0+JS9t9fr6ZUlQBelDG6GMgq97otb5QMPJwtKyBTbFp8Sl7b6/X0ykkawEOsgdiE6Fi0vb/Eve6xkwsmug0Z4nGNHQO8839bpTsjpz7SWIJxKagvd1QWMa6FYT1KEw3j4XDT6vJ9Xk+nyfT5Pq8n1eEmk5dinMM/9Fcfz4Z3Dsz3KD2dw7LxBRxKrqUUGQPH/7zxr1KIfNpLEJ0MZB2ITM/0Z2EFoh12NlXnEcpYcbvON3nG7zjd5xu84vfcNIAAP7+y8ceyzbVxkakPYY4lcr72fqOnDwipv+yxC71wAADBrjKnAAAAAAAAAAAAAAw7oNGHttqWONcoFN/2WIDc2pa6WVFtFYROlsaMaTXdcOjXHz93+YxAglKa4AAAAA=';
var register = require('../../core/component').registerComponent;
var THREE = require('../../lib/three');
var CAM_LAYER = 21;
var applyPose = (function () {
var tempQuaternion = new THREE.Quaternion();
var tempVec3 = new THREE.Vector3();
function applyPose (pose, object3D, offset) {
object3D.position.copy(pose.transform.position);
object3D.quaternion.copy(pose.transform.orientation);
tempVec3.copy(offset);
tempQuaternion.copy(pose.transform.orientation);
tempVec3.applyQuaternion(tempQuaternion);
object3D.position.sub(tempVec3);
}
return applyPose;
}());
applyPose.tempFakePose = {
transform: {
orientation: new THREE.Quaternion(),
position: new THREE.Vector3()
}
};
/**
* Class to handle hit-test from a single source
*
* For a normal space provide it as a space option
* new HitTest(renderer, {
* space: viewerSpace
* });
*
* this is also useful for the targetRaySpace of an XRInputSource
*
* It can also describe a transient input source like so:
*
* var profileToSupport = 'generic-touchscreen';
* var transientHitTest = new HitTest(renderer, {
* profile: profileToSupport
* });
*
* Where the profile matches an item in a type of controller, profiles matching 'generic-touchscreen'
* will always be a transient input and as of 08/2021 all transient inputs are 'generic-touchscreen'
*
* @param {WebGLRenderer} renderer THREE.JS Renderer
* @param {} hitTestSourceDetails The source information either as the information for a transient hit-test or a regular hit-test
*/
function HitTest (renderer, hitTestSourceDetails) {
this.renderer = renderer;
this.xrHitTestSource = null;
renderer.xr.addEventListener('sessionend', function () {
this.xrHitTestSource = null;
}.bind(this));
renderer.xr.addEventListener('sessionstart', function () {
this.sessionStart(hitTestSourceDetails);
}.bind(this));
if (this.renderer.xr.isPresenting) {
this.sessionStart(hitTestSourceDetails);
}
}
HitTest.prototype.previousFrameAnchors = new Set();
HitTest.prototype.anchorToObject3D = new Map();
HitTest.prototype.sessionStart = function sessionStart (hitTestSourceDetails) {
this.session = this.renderer.xr.getSession();
try {
if (hitTestSourceDetails.space) {
this.session.requestHitTestSource(hitTestSourceDetails)
.then(function (xrHitTestSource) {
this.xrHitTestSource = xrHitTestSource;
}.bind(this));
} else if (hitTestSourceDetails.profile) {
this.session.requestHitTestSourceForTransientInput(hitTestSourceDetails)
.then(function (xrHitTestSource) {
this.xrHitTestSource = xrHitTestSource;
this.transient = true;
}.bind(this));
}
} catch (e) {
console.warn(e.message);
console.warn('Cannot requestHitTestSource Are you missing: webxr="optionalFeatures: hit-test;" from <a-scene>?');
}
};
/**
* Turns the last hit test into an anchor, the provided Object3D will have it's
* position update to track the anchor.
*
* @param {Object3D} object3D object to track
* @param {Vector3} offset offset of the object from the origin that gets subtracted
* @returns
*/
HitTest.prototype.anchorFromLastHitTestResult = function (object3D, offset) {
var hitTest = this.lastHitTest;
if (!hitTest) { return; }
var object3DOptions = {
object3D: object3D,
offset: offset
};
Array.from(this.anchorToObject3D.entries())
.forEach(function (entry) {
var entryObject = entry[1].object3D;
var anchor = entry[0];
if (entryObject === object3D) {
this.anchorToObject3D.delete(anchor);
anchor.delete();
}
}.bind(this));
if (hitTest.createAnchor) {
hitTest.createAnchor()
.then(function (anchor) {
this.anchorToObject3D.set(anchor, object3DOptions);
}.bind(this))
.catch(function (e) {
console.warn(e.message);
console.warn('Cannot create anchor, are you missing: webxr="optionalFeatures: anchors;" from <a-scene>?');
});
}
};
HitTest.prototype.doHit = function doHit (frame) {
if (!this.renderer.xr.isPresenting) { return; }
var refSpace = this.renderer.xr.getReferenceSpace();
var xrViewerPose = frame.getViewerPose(refSpace);
var hitTestResults;
var results;
if (this.xrHitTestSource && xrViewerPose) {
if (this.transient) {
hitTestResults = frame.getHitTestResultsForTransientInput(this.xrHitTestSource);
if (hitTestResults.length > 0) {
results = hitTestResults[0].results;
if (results.length > 0) {
this.lastHitTest = results[0];
return results[0].getPose(refSpace);
} else {
return false;
}
} else {
return false;
}
} else {
hitTestResults = frame.getHitTestResults(this.xrHitTestSource);
if (hitTestResults.length > 0) {
this.lastHitTest = hitTestResults[0];
return hitTestResults[0].getPose(refSpace);
} else {
return false;
}
}
}
};
// static function
HitTest.updateAnchorPoses = function (frame, refSpace) {
// If tracked anchors isn't defined because it's not supported then just use the empty set
var trackedAnchors = frame.trackedAnchors || HitTest.prototype.previousFrameAnchors;
HitTest.prototype.previousFrameAnchors.forEach(function (anchor) {
// Handle anchor tracking loss - `anchor` was present
// in the present frame but is no longer tracked.
if (!trackedAnchors.has(anchor)) {
HitTest.prototype.anchorToObject3D.delete(anchor);
}
});
trackedAnchors.forEach(function (anchor) {
var anchorPose;
var object3DOptions;
var offset;
var object3D;
try {
// Query most recent pose of the anchor relative to some reference space:
anchorPose = frame.getPose(anchor.anchorSpace, refSpace);
} catch (e) {
// This will fail if the anchor has been deleted that frame
}
if (anchorPose) {
object3DOptions = HitTest.prototype.anchorToObject3D.get(anchor);
offset = object3DOptions.offset;
object3D = object3DOptions.object3D;
applyPose(anchorPose, object3D, offset);
}
});
};
var hitTestCache;
module.exports.Component = register('ar-hit-test', {
schema: {
target: { type: 'selector' },
enabled: { default: true },
src: {
default: arrowURL,
type: 'map'
},
type: {
default: 'footprint',
oneOf: ['footprint', 'map']
},
footprintDepth: {
default: 0.1
}
},
init: function () {
this.hitTest = null;
this.imageDataArray = new Uint8ClampedArray(512 * 512 * 4);
this.imageData = new ImageData(this.imageDataArray, 512, 512);
this.textureCache = new Map();
this.orthoCam = new THREE.OrthographicCamera();
this.orthoCam.layers.set(CAM_LAYER);
this.textureTarget = new THREE.WebGLRenderTarget(512, 512, {});
this.basicMaterial = new THREE.MeshBasicMaterial({
color: 0x000000,
side: THREE.DoubleSide
});
this.canvas = document.createElement('canvas');
this.context = this.canvas.getContext('2d');
this.context.imageSmoothingEnabled = false;
this.canvas.width = 512;
this.canvas.height = 512;
this.canvasTexture = new THREE.CanvasTexture(this.canvas, {
alpha: true
});
this.canvasTexture.flipY = false;
// Update WebXR to support hit-test and anchors
var webxrData = this.el.getAttribute('webxr');
var optionalFeaturesArray = webxrData.optionalFeatures;
if (
!optionalFeaturesArray.includes('hit-test') ||
!optionalFeaturesArray.includes('anchors')
) {
optionalFeaturesArray.push('hit-test');
optionalFeaturesArray.push('anchors');
this.el.setAttribute('webxr', webxrData);
}
this.el.sceneEl.renderer.xr.addEventListener('sessionend', function () {
this.hitTest = null;
}.bind(this));
this.el.sceneEl.renderer.xr.addEventListener('sessionstart', function () {
var renderer = this.el.sceneEl.renderer;
var session = this.session = renderer.xr.getSession();
this.hasPosedOnce = false;
this.bboxMesh.visible = false;
if (!hitTestCache) { hitTestCache = new Map(); }
// Default to selecting through the face
session.requestReferenceSpace('viewer')
.then(function (viewerSpace) {
this.hitTest = new HitTest(renderer, {
space: viewerSpace
});
hitTestCache.set(viewerSpace, this.hitTest);
this.el.emit('ar-hit-test-start');
}.bind(this));
// These are transient inputs so need to be handled seperately
var profileToSupport = 'generic-touchscreen';
var transientHitTest = new HitTest(renderer, {
profile: profileToSupport
});
session.addEventListener('selectstart', function (e) {
if (this.data.enabled !== true) { return; }
var inputSource = e.inputSource;
this.bboxMesh.visible = true;
if (this.hasPosedOnce === true) {
this.el.emit('ar-hit-test-select-start', {
inputSource: inputSource,
position: this.bboxMesh.position,
orientation: this.bboxMesh.quaternion
});
if (inputSource.profiles[0] === profileToSupport) {
this.hitTest = transientHitTest;
} else {
this.hitTest = hitTestCache.get(inputSource) || new HitTest(renderer, {
space: inputSource.targetRaySpace
});
hitTestCache.set(inputSource, this.hitTest);
}
}
}.bind(this));
session.addEventListener('selectend', function (e) {
if (!this.hitTest || this.data.enabled !== true) {
this.hitTest = null;
return;
}
var inputSource = e.inputSource;
var object;
if (this.hasPosedOnce === true) {
this.bboxMesh.visible = false;
object = this.data.target.object3D;
// if we have a target with a 3D object then automatically generate an anchor for it.
if (this.data.target && object) {
applyPose.tempFakePose.transform.position.copy(this.bboxMesh.position);
applyPose.tempFakePose.transform.orientation.copy(this.bboxMesh.quaternion);
applyPose(applyPose.tempFakePose, object, this.bboxOffset);
object.visible = true;
// create an anchor attatched to the object
this.hitTest.anchorFromLastHitTestResult(object, this.bboxOffset);
}
this.el.emit('ar-hit-test-select', {
inputSource: inputSource,
position: this.bboxMesh.position,
orientation: this.bboxMesh.quaternion
});
}
this.hitTest = null;
}.bind(this));
}.bind(this));
this.bboxOffset = new THREE.Vector3();
this.update = this.update.bind(this);
this.makeBBox();
},
update: function () {
if (this.data.target) {
if (this.data.target.object3D) {
this.data.target.addEventListener('model-loaded', this.update);
this.bboxNeedsUpdate = true;
this.data.target.object3D.layers.enable(CAM_LAYER);
this.data.target.object3D.traverse(function (child) {
child.layers.enable(CAM_LAYER);
});
} else {
this.data.target.addEventListener('loaded', this.update, {once: true});
}
}
},
makeBBox: function () {
var geometry = new THREE.PlaneGeometry(1, 1);
var material = new THREE.MeshBasicMaterial({
transparent: true,
color: 0xffffff
});
geometry.rotateX(-Math.PI / 2);
geometry.rotateY(-Math.PI / 2);
this.bbox = new THREE.Box3();
this.bboxMesh = new THREE.Mesh(geometry, material);
this.el.setObject3D('ar-hit-test', this.bboxMesh);
this.bboxMesh.visible = false;
},
updateFootprint: function () {
var tempImageData;
var renderer = this.el.sceneEl.renderer;
var oldRenderTarget, oldBackground;
this.bboxMesh.material.map = this.canvasTexture;
this.bboxMesh.material.needsUpdate = true;
this.orthoCam.rotation.set(-Math.PI / 2, 0, -Math.PI / 2);
this.orthoCam.position.copy(this.bboxMesh.position);
this.orthoCam.position.y -= this.bboxMesh.scale.y / 2;
this.orthoCam.near = 0.1;
this.orthoCam.far = this.orthoCam.near + (this.data.footprintDepth * this.bboxMesh.scale.y);
this.orthoCam.position.y += this.orthoCam.far;
this.orthoCam.right = this.bboxMesh.scale.z / 2;
this.orthoCam.left = -this.bboxMesh.scale.z / 2;
this.orthoCam.top = this.bboxMesh.scale.x / 2;
this.orthoCam.bottom = -this.bboxMesh.scale.x / 2;
this.orthoCam.updateProjectionMatrix();
oldRenderTarget = renderer.getRenderTarget();
renderer.setRenderTarget(this.textureTarget);
oldBackground = this.el.object3D.background;
this.el.object3D.overrideMaterial = this.basicMaterial;
this.el.object3D.background = null;
renderer.render(this.el.object3D, this.orthoCam);
this.el.object3D.background = oldBackground;
this.el.object3D.overrideMaterial = null;
renderer.setRenderTarget(oldRenderTarget);
renderer.readRenderTargetPixels(this.textureTarget, 0, 0, 512, 512, this.imageDataArray);
this.context.putImageData(this.imageData, 0, 0);
this.context.shadowColor = 'white';
this.context.shadowBlur = 10;
this.context.drawImage(this.canvas, 0, 0);
tempImageData = this.context.getImageData(0, 0, 512, 512);
for (var i = 0; i < 512 * 512; i++) {
// if it's a little bit transparent but not opaque make it middle transparent
if (tempImageData.data[ i * 4 + 3 ] !== 0 && tempImageData.data[ i * 4 + 3 ] !== 255) {
tempImageData.data[ i * 4 + 3 ] = 128;
}
}
this.context.putImageData(tempImageData, 0, 0);
this.canvasTexture.needsUpdate = true;
},
tick: function () {
var pose;
var frame = this.el.sceneEl.frame;
var renderer = this.el.sceneEl.renderer;
if (frame) {
// if we are in XR then update the positions of the objects attatched to anchors
HitTest.updateAnchorPoses(frame, renderer.xr.getReferenceSpace());
}
if (this.bboxNeedsUpdate) {
this.bboxNeedsUpdate = false;
if (!this.data.target || this.data.type === 'map') {
var texture;
if (this.textureCache.has(this.data.src)) {
texture = this.textureCache.get(this.data.src);
} else {
texture = new THREE.TextureLoader().load(this.data.src);
this.textureCache.set(this.data.src, texture);
}
this.bboxMesh.material.map = texture;
this.bboxMesh.material.needsUpdate = true;
}
if (this.data.target && this.data.target.object3D) {
this.bbox.setFromObject(this.data.target.object3D);
this.bbox.getCenter(this.bboxMesh.position);
this.bbox.getSize(this.bboxMesh.scale);
if (this.data.type === 'footprint') {
// Add a little buffer for the footprint border
this.bboxMesh.scale.x *= 1.04;
this.bboxMesh.scale.z *= 1.04;
this.updateFootprint();
}
this.bboxMesh.position.y -= this.bboxMesh.scale.y / 2;
this.bboxOffset.copy(this.bboxMesh.position);
this.bboxOffset.sub(this.data.target.object3D.position);
}
}
if (this.hitTest) {
pose = this.hitTest.doHit(frame);
if (pose) {
if (this.hasPosedOnce !== true) {
this.hasPosedOnce = true;
this.el.emit('ar-hit-test-achieved');
}
this.bboxMesh.visible = true;
this.bboxMesh.position.copy(pose.transform.position);
this.bboxMesh.quaternion.copy(pose.transform.orientation);
}
}
}
});
| src/components/scene/ar-hit-test.js | /* global ImageData, Map, Set */
var arrowURL = 'data:image/webp;base64,UklGRkQHAABXRUJQVlA4WAoAAAAQAAAA/wEA/wEAQUxQSL0DAAARDzD/ERGCjrY9sYYFfgo6aa1kJ7K0w9Lo3AadLSVeFxevQwj5kuM8RfR/Atw/C0+ozB/oUBrloFZs6ElSW88j1KA4yExNWQaqRZquIDF0JYmlq0hAuUDTFu66tng3teW7pa3cQf1V1edvur54M/Slm6Wv3Gx9zw0MXlQLntcsBN6wkHjTQuYtC4W3LTw8mGRVG57TbAROtxHfZNhInGkjc5aNwtk2Hg6Mvki14k+NkZzCwQgCxalcAv3kddRTPI1DcUrXId1FLf1uHpzaQz4tquhZVLlKesbVpqKeTj0n0F5PpXDlFN9UqmhalL/ImuZFo6KmToWLoKlddMprqlS8cKovBvHo2kTiFV2LN4msaxKZl3QNiair8xYRdDWivIvXVXmbcMqJ51UebZuFXxZt6xd4laxtciqRtA3Cv0nU1t+kEUFbI8JvCa+tvkm3FDlO/W+OR99+kWEp/YYo+tYfTVnf/K8cE/F///3vv//993eeL+a+uvjawLcX3xjYvJotBFY3kVjTRGFtE+BU2AiMbiQyhpHMWEYeBozAH5qNBYRDB5KBCaTDBKKBAZTDBoKBDjwHAN5ABeCJBsAZcAAC0YHHxAYSMYBiYgGZWEA2MYFCbCCZGAAIANFEB+AnYgMQTDQAYSJ2AN5EBZAm4gDgTDgAeSIu4DGygTIRN1CMLOCZiACykQlg4jsAycgA8AO+BxCNdJyDkcbwRirDGXGnx8w+FDPrkM3MQ9JQZMYhiiwV/RDMtIM3U1/DmXHUo+IR2kSR2ToWkQ1NIn2qf2J8LCqJKiDUiSADHY3whirhdHgZ94HKaR97PhE+twEUJUFoAcgyTct8hfSxSkShASDKdMJ/ritKHwgyQ0sD4D/miCxU5SbhOOUDTnZpccCjYP/i0bZ/8bAgtVGEoGapWIQXyzKVKLwgNJFk2rtMIgoNRJlOZF7SNSSyUEeQmbxBFKEmtYjEe8S8zOZ1AkJVCmS88FJOtF40Ksg4oUaFiygk3C8qlTVNyl8UTevCUdAE2t14PfVqU1FPp57TopKeQZWromddTQp6QOfTOEQt/ZDuipZ11w/wOiqO8dRORcc6BQEkDQMClaHcn5wV9yLbxsNZNgpn2sicYSNxuo34Js1G4FQbnuNsOPa28PCWhcKbFjJvWEi8ZiHwqgXPcxbc5db33Cx95WboSzddX7yp+vyN0+eul7ZyN7Xlu64t3jVt4c5pc4JLV5EYupJE0xUknC4nOjVlmaYpyLit53HCQ0+ScnqceNcS5dzUkd0/CwMAVlA4IGADAAAQXwCdASoAAgACP8ne6Wy/tjCpqJ/IA/A5CWlu4XYBG/Pz8AfwD8APz//f3v8E1fuHZnxKYACtfuHZnxKYACrYTb5mOslhxu843ecbvON3nG7zjd3a0VCn7G1MABVxwH/Xd25gAK1+4dmfEpe2+PHhQaj75++riG6FuYACtfuHZnxKYACRrK3q9xO8Ss3uWKnMhs/rDF1hi6wxdYYusMXWGI5QRcCFDZog5OgqNlse1NDuz/UoFa/cOzPiUwAEsAOK4/nu5eZHK2tlXxJfNYlMABWv3Dsz4bvNJ5YA/LtxJ38SmAArX7h2Z8Sk5vdZUYv7mZPiUwAFa/cOzPh21s5OgZxf1mfEpemRyFr/rM+JS9noA/LtxJ38SmAAlUJIotzAASn6TjdhK+D3Dsz4dyvB7h2Z8O2tnJ0DOL+sz4lL2nKLT4lL/+iSLOocxq639w7M34MNZdm55uJ8v8ra2cpVZnxKTq2F3PN/cNksAfl24k7+JTAASqrD37h2Z7b1W+VtbOUqsz4lJ1bC7nm/uGyWAPy7cSd/EpgAJVVh79w7M9t6rfK2tnKVWZ8Sk6thdzzf3DZLAH5duJO/iUwAEqqw9+4dme29VvlbWzlKrM+JSdWwu55v7hslgD8u3EnfxKYACVVYe/cOzPbeq3ytrZylVme0kYJ8557FLerqFrzIbPrrf3DZLAH5duJO/iUvaVMS9BoaF4p7pSDFTP1XMyfElelrM0DOL+sz4eBJ13nV1OppBGPuKb4YzXQgq9uH19uS/0+JS9t9fr6ZUlQBelDG6GMgq97otb5QMPJwtKyBTbFp8Sl7b6/X0ykkawEOsgdiE6Fi0vb/Eve6xkwsmug0Z4nGNHQO8839bpTsjpz7SWIJxKagvd1QWMa6FYT1KEw3j4XDT6vJ9Xk+nyfT5Pq8n1eEmk5dinMM/9Fcfz4Z3Dsz3KD2dw7LxBRxKrqUUGQPH/7zxr1KIfNpLEJ0MZB2ITM/0Z2EFoh12NlXnEcpYcbvON3nG7zjd5xu84vfcNIAAP7+y8ceyzbVxkakPYY4lcr72fqOnDwipv+yxC71wAADBrjKnAAAAAAAAAAAAAAw7oNGHttqWONcoFN/2WIDc2pa6WVFtFYROlsaMaTXdcOjXHz93+YxAglKa4AAAAA=';
var register = require('../../core/component').registerComponent;
var THREE = require('../../lib/three');
var CAM_LAYER = 21;
var applyPose = (function () {
var tempQuaternion = new THREE.Quaternion();
var tempVec3 = new THREE.Vector3();
function applyPose (pose, object3D, offset) {
object3D.position.copy(pose.transform.position);
object3D.quaternion.copy(pose.transform.orientation);
tempVec3.copy(offset);
tempQuaternion.copy(pose.transform.orientation);
tempVec3.applyQuaternion(tempQuaternion);
object3D.position.sub(tempVec3);
}
return applyPose;
}());
applyPose.tempFakePose = {
transform: {
orientation: new THREE.Quaternion(),
position: new THREE.Vector3()
}
};
/**
* Class to handle hit-test from a single source
*
* For a normal space provide it as a space option
* new HitTest(renderer, {
* space: viewerSpace
* });
*
* this is also useful for the targetRaySpace of an XRInputSource
*
* It can also describe a transient input source like so:
*
* var profileToSupport = 'generic-touchscreen';
* var transientHitTest = new HitTest(renderer, {
* profile: profileToSupport
* });
*
* Where the profile matches an item in a type of controller, profiles matching 'generic-touchscreen'
* will always be a transient input and as of 08/2021 all transient inputs are 'generic-touchscreen'
*
* @param {WebGLRenderer} renderer THREE.JS Renderer
* @param {} hitTestSourceDetails The source information either as the information for a transient hit-test or a regular hit-test
*/
function HitTest (renderer, hitTestSourceDetails) {
this.renderer = renderer;
this.xrHitTestSource = null;
renderer.xr.addEventListener('sessionend', function () {
this.xrHitTestSource = null;
}.bind(this));
renderer.xr.addEventListener('sessionstart', function () {
this.sessionStart(hitTestSourceDetails);
}.bind(this));
if (this.renderer.xr.isPresenting) {
this.sessionStart(hitTestSourceDetails);
}
}
HitTest.prototype.previousFrameAnchors = new Set();
HitTest.prototype.anchorToObject3D = new Map();
HitTest.prototype.sessionStart = function sessionStart (hitTestSourceDetails) {
this.session = this.renderer.xr.getSession();
try {
if (hitTestSourceDetails.space) {
this.session.requestHitTestSource(hitTestSourceDetails)
.then(function (xrHitTestSource) {
this.xrHitTestSource = xrHitTestSource;
}.bind(this));
} else if (hitTestSourceDetails.profile) {
this.session.requestHitTestSourceForTransientInput(hitTestSourceDetails)
.then(function (xrHitTestSource) {
this.xrHitTestSource = xrHitTestSource;
this.transient = true;
}.bind(this));
}
} catch (e) {
console.warn(e.message);
console.warn('Cannot requestHitTestSource Are you missing: webxr="optionalFeatures: hit-test;" from <a-scene>?');
}
};
/**
* Turns the last hit test into an anchor, the provided Object3D will have it's
* position update to track the anchor.
*
* @param {Object3D} object3D object to track
* @param {Vector3} offset offset of the object from the origin that gets subtracted
* @returns
*/
HitTest.prototype.anchorFromLastHitTestResult = function (object3D, offset) {
var hitTest = this.lastHitTest;
if (!hitTest) { return; }
var object3DOptions = {
object3D: object3D,
offset: offset
};
Array.from(this.anchorToObject3D.entries())
.forEach(function (entry) {
var entryObject = entry[1].object3D;
var anchor = entry[0];
if (entryObject === object3D) {
this.anchorToObject3D.delete(anchor);
anchor.delete();
}
}.bind(this));
if (hitTest.createAnchor) {
hitTest.createAnchor()
.then(function (anchor) {
this.anchorToObject3D.set(anchor, object3DOptions);
}.bind(this))
.catch(function (e) {
console.warn(e.message);
console.warn('Cannot create anchor, are you missing: webxr="optionalFeatures: anchors;" from <a-scene>?');
});
}
};
HitTest.prototype.doHit = function doHit (frame) {
if (!this.renderer.xr.isPresenting) { return; }
var refSpace = this.renderer.xr.getReferenceSpace();
var xrViewerPose = frame.getViewerPose(refSpace);
var hitTestResults;
var results;
if (this.xrHitTestSource && xrViewerPose) {
if (this.transient) {
hitTestResults = frame.getHitTestResultsForTransientInput(this.xrHitTestSource);
if (hitTestResults.length > 0) {
results = hitTestResults[0].results;
if (results.length > 0) {
this.lastHitTest = results[0];
return results[0].getPose(refSpace);
} else {
return false;
}
} else {
return false;
}
} else {
hitTestResults = frame.getHitTestResults(this.xrHitTestSource);
if (hitTestResults.length > 0) {
this.lastHitTest = hitTestResults[0];
return hitTestResults[0].getPose(refSpace);
} else {
return false;
}
}
}
};
// static function
HitTest.updateAnchorPoses = function (frame, refSpace) {
// If tracked anchors isn't defined because it's not supported then just use the empty set
var trackedAnchors = frame.trackedAnchors || HitTest.prototype.previousFrameAnchors;
HitTest.prototype.previousFrameAnchors.forEach(function (anchor) {
// Handle anchor tracking loss - `anchor` was present
// in the present frame but is no longer tracked.
if (!trackedAnchors.has(anchor)) {
HitTest.prototype.anchorToObject3D.delete(anchor);
}
});
trackedAnchors.forEach(function (anchor) {
var anchorPose;
var object3DOptions;
var offset;
var object3D;
try {
// Query most recent pose of the anchor relative to some reference space:
anchorPose = frame.getPose(anchor.anchorSpace, refSpace);
} catch (e) {
// This will fail if the anchor has been deleted that frame
}
if (anchorPose) {
object3DOptions = HitTest.prototype.anchorToObject3D.get(anchor);
offset = object3DOptions.offset;
object3D = object3DOptions.object3D;
applyPose(anchorPose, object3D, offset);
}
});
};
var hitTestCache;
var tempQuaternion = new THREE.Quaternion();
module.exports.Component = register('ar-hit-test', {
schema: {
target: { type: 'selector' },
enabled: { default: true },
src: {
default: arrowURL,
type: 'map'
},
type: {
default: 'footprint',
oneOf: ['footprint', 'map']
},
footprintDepth: {
default: 0.1
}
},
init: function () {
this.hitTest = null;
this.imageDataArray = new Uint8ClampedArray(512 * 512 * 4);
this.imageData = new ImageData(this.imageDataArray, 512, 512);
this.textureCache = new Map();
this.orthoCam = new THREE.OrthographicCamera();
this.orthoCam.layers.set(CAM_LAYER);
this.textureTarget = new THREE.WebGLRenderTarget(512, 512, {});
this.basicMaterial = new THREE.MeshBasicMaterial({
color: 0x000000
});
this.canvas = document.createElement('canvas');
this.context = this.canvas.getContext('2d');
this.context.imageSmoothingEnabled = false;
this.canvas.width = 512;
this.canvas.height = 512;
this.canvasTexture = new THREE.CanvasTexture(this.canvas, {
alpha: true
});
// Update WebXR to support hit-test and anchors
var webxrData = this.el.getAttribute('webxr');
var optionalFeaturesArray = webxrData.optionalFeatures;
if (
!optionalFeaturesArray.includes('hit-test') ||
!optionalFeaturesArray.includes('anchors')
) {
optionalFeaturesArray.push('hit-test');
optionalFeaturesArray.push('anchors');
this.el.setAttribute('webxr', webxrData);
}
this.el.sceneEl.renderer.xr.addEventListener('sessionend', function () {
this.hitTest = null;
}.bind(this));
this.el.sceneEl.renderer.xr.addEventListener('sessionstart', function () {
var renderer = this.el.sceneEl.renderer;
var session = this.session = renderer.xr.getSession();
this.hasPosedOnce = false;
this.bboxMesh.visible = false;
if (!hitTestCache) { hitTestCache = new Map(); }
// Default to selecting through the face
session.requestReferenceSpace('viewer')
.then(function (viewerSpace) {
this.hitTest = new HitTest(renderer, {
space: viewerSpace
});
hitTestCache.set(viewerSpace, this.hitTest);
this.el.emit('ar-hit-test-start');
}.bind(this));
// These are transient inputs so need to be handled seperately
var profileToSupport = 'generic-touchscreen';
var transientHitTest = new HitTest(renderer, {
profile: profileToSupport
});
session.addEventListener('selectstart', function (e) {
if (this.data.enabled !== true) { return; }
var inputSource = e.inputSource;
this.bboxMesh.visible = true;
if (this.hasPosedOnce === true) {
this.el.emit('ar-hit-test-select-start', {
inputSource: inputSource,
position: this.bboxMesh.position,
orientation: this.bboxMesh.quaternion
});
if (inputSource.profiles[0] === profileToSupport) {
this.hitTest = transientHitTest;
} else {
this.hitTest = hitTestCache.get(inputSource) || new HitTest(renderer, {
space: inputSource.targetRaySpace
});
hitTestCache.set(inputSource, this.hitTest);
}
}
}.bind(this));
session.addEventListener('selectend', function (e) {
if (!this.hitTest || this.data.enabled !== true) {
this.hitTest = null;
return;
}
var inputSource = e.inputSource;
var object;
if (this.hasPosedOnce === true) {
this.bboxMesh.visible = false;
object = this.data.target.object3D;
// if we have a target with a 3D object then automatically generate an anchor for it.
if (this.data.target && object) {
applyPose.tempFakePose.transform.position.copy(this.bboxMesh.position);
applyPose.tempFakePose.transform.orientation.copy(this.bboxMesh.quaternion);
applyPose(applyPose.tempFakePose, object, this.bboxOffset);
object.visible = true;
// create an anchor attatched to the object
this.hitTest.anchorFromLastHitTestResult(object, this.bboxOffset);
}
this.el.emit('ar-hit-test-select', {
inputSource: inputSource,
position: this.bboxMesh.position,
orientation: this.bboxMesh.quaternion
});
}
this.hitTest = null;
}.bind(this));
}.bind(this));
this.bboxOffset = new THREE.Vector3();
this.update = this.update.bind(this);
this.makeBBox();
},
update: function () {
if (this.data.target) {
if (this.data.target.object3D) {
this.data.target.addEventListener('model-loaded', this.update);
this.bboxNeedsUpdate = true;
this.data.target.object3D.layers.enable(CAM_LAYER);
this.data.target.object3D.traverse(function (child) {
child.layers.enable(CAM_LAYER);
});
} else {
this.data.target.addEventListener('loaded', this.update, {once: true});
}
}
},
makeBBox: function () {
var geometry = new THREE.PlaneGeometry(1, 1);
var material = new THREE.MeshBasicMaterial({
transparent: true
});
geometry.rotateX(-Math.PI / 2);
this.bbox = new THREE.Box3();
this.bboxMesh = new THREE.Mesh(geometry, material);
this.el.setObject3D('ar-hit-test', this.bboxMesh);
this.bboxMesh.visible = false;
},
updateFootprint: function () {
var tempImageData;
var renderer = this.el.sceneEl.renderer;
var oldRenderTarget, oldBackground;
this.bboxMesh.material.map = this.canvasTexture;
this.bboxMesh.material.needsUpdate = true;
this.orthoCam.rotation.set(-Math.PI / 2, 0, -Math.PI / 2);
this.orthoCam.position.copy(this.bboxMesh.position);
this.orthoCam.position.y -= this.bboxMesh.scale.y / 2;
this.orthoCam.near = 0.1;
this.orthoCam.far = this.orthoCam.near + (this.data.footprintDepth * this.bboxMesh.scale.y);
this.orthoCam.position.y += this.orthoCam.far;
this.orthoCam.right = this.bboxMesh.scale.x / 2;
this.orthoCam.left = -this.bboxMesh.scale.x / 2;
this.orthoCam.top = this.bboxMesh.scale.z / 2;
this.orthoCam.bottom = -this.bboxMesh.scale.z / 2;
this.orthoCam.updateProjectionMatrix();
oldRenderTarget = renderer.getRenderTarget();
renderer.setRenderTarget(this.textureTarget);
oldBackground = this.el.object3D.background;
this.el.object3D.overrideMaterial = this.basicMaterial;
this.el.object3D.background = null;
renderer.render(this.el.object3D, this.orthoCam);
this.el.object3D.background = oldBackground;
this.el.object3D.overrideMaterial = null;
renderer.setRenderTarget(oldRenderTarget);
renderer.readRenderTargetPixels(this.textureTarget, 0, 0, 512, 512, this.imageDataArray);
this.context.putImageData(this.imageData, 0, 0);
this.context.shadowColor = 'white';
this.context.shadowBlur = 10;
this.context.drawImage(this.canvas, 0, 0);
tempImageData = this.context.getImageData(0, 0, 512, 512);
for (var i = 0; i < 512 * 512; i++) {
// if it's a little bit transparent but not opaque make it middle transparent
if (tempImageData.data[ i * 4 + 3 ] !== 0 && tempImageData.data[ i * 4 + 3 ] !== 255) {
tempImageData.data[ i * 4 + 3 ] = 128;
}
}
this.context.putImageData(tempImageData, 0, 0);
this.canvasTexture.needsUpdate = true;
},
tick: function () {
var pose;
var frame = this.el.sceneEl.frame;
var renderer = this.el.sceneEl.renderer;
if (frame) {
// if we are in XR then update the positions of the objects attatched to anchors
HitTest.updateAnchorPoses(frame, renderer.xr.getReferenceSpace());
}
if (this.bboxNeedsUpdate) {
this.bboxNeedsUpdate = false;
if (!this.data.target || this.data.type === 'map') {
var texture;
if (this.textureCache.has(this.data.src)) {
texture = this.textureCache.get(this.data.src);
} else {
texture = new THREE.TextureLoader().load(this.data.src);
this.textureCache.set(this.data.src, texture);
}
this.bboxMesh.material.map = texture;
this.bboxMesh.material.needsUpdate = true;
}
if (this.data.target && this.data.target.object3D) {
tempQuaternion.copy(this.data.target.object3D.quaternion);
this.data.target.object3D.quaternion.identity();
this.bbox.setFromObject(this.data.target.object3D);
this.bbox.getCenter(this.bboxMesh.position);
this.bbox.getSize(this.bboxMesh.scale);
if (this.data.type === 'footprint') {
// Add a little buffer for the footprint border
this.bboxMesh.scale.x *= 1.04;
this.bboxMesh.scale.z *= 1.04;
this.updateFootprint();
}
this.bboxMesh.position.y -= this.bboxMesh.scale.y / 2;
this.bboxOffset.copy(this.bboxMesh.position);
this.bboxOffset.sub(this.data.target.object3D.position);
this.data.target.object3D.quaternion.copy(tempQuaternion);
this.bboxMesh.quaternion.copy(tempQuaternion);
}
}
if (this.hitTest) {
pose = this.hitTest.doHit(frame);
if (pose) {
if (this.hasPosedOnce !== true) {
this.hasPosedOnce = true;
this.el.emit('ar-hit-test-achieved');
}
this.bboxMesh.visible = true;
this.bboxMesh.position.copy(pose.transform.position);
this.bboxMesh.quaternion.copy(pose.transform.orientation);
}
}
}
});
| remove smart things that broke everything (#4916)
| src/components/scene/ar-hit-test.js | remove smart things that broke everything (#4916) | <ide><path>rc/components/scene/ar-hit-test.js
<ide> };
<ide>
<ide> var hitTestCache;
<del>var tempQuaternion = new THREE.Quaternion();
<ide> module.exports.Component = register('ar-hit-test', {
<ide> schema: {
<ide> target: { type: 'selector' },
<ide> this.orthoCam.layers.set(CAM_LAYER);
<ide> this.textureTarget = new THREE.WebGLRenderTarget(512, 512, {});
<ide> this.basicMaterial = new THREE.MeshBasicMaterial({
<del> color: 0x000000
<add> color: 0x000000,
<add> side: THREE.DoubleSide
<ide> });
<ide> this.canvas = document.createElement('canvas');
<ide> this.context = this.canvas.getContext('2d');
<ide> this.canvasTexture = new THREE.CanvasTexture(this.canvas, {
<ide> alpha: true
<ide> });
<add> this.canvasTexture.flipY = false;
<ide>
<ide> // Update WebXR to support hit-test and anchors
<ide> var webxrData = this.el.getAttribute('webxr');
<ide> makeBBox: function () {
<ide> var geometry = new THREE.PlaneGeometry(1, 1);
<ide> var material = new THREE.MeshBasicMaterial({
<del> transparent: true
<add> transparent: true,
<add> color: 0xffffff
<ide> });
<ide> geometry.rotateX(-Math.PI / 2);
<add> geometry.rotateY(-Math.PI / 2);
<ide> this.bbox = new THREE.Box3();
<ide> this.bboxMesh = new THREE.Mesh(geometry, material);
<ide> this.el.setObject3D('ar-hit-test', this.bboxMesh);
<ide> this.orthoCam.near = 0.1;
<ide> this.orthoCam.far = this.orthoCam.near + (this.data.footprintDepth * this.bboxMesh.scale.y);
<ide> this.orthoCam.position.y += this.orthoCam.far;
<del> this.orthoCam.right = this.bboxMesh.scale.x / 2;
<del> this.orthoCam.left = -this.bboxMesh.scale.x / 2;
<del> this.orthoCam.top = this.bboxMesh.scale.z / 2;
<del> this.orthoCam.bottom = -this.bboxMesh.scale.z / 2;
<add> this.orthoCam.right = this.bboxMesh.scale.z / 2;
<add> this.orthoCam.left = -this.bboxMesh.scale.z / 2;
<add> this.orthoCam.top = this.bboxMesh.scale.x / 2;
<add> this.orthoCam.bottom = -this.bboxMesh.scale.x / 2;
<ide> this.orthoCam.updateProjectionMatrix();
<ide>
<ide> oldRenderTarget = renderer.getRenderTarget();
<ide> }
<ide>
<ide> if (this.data.target && this.data.target.object3D) {
<del> tempQuaternion.copy(this.data.target.object3D.quaternion);
<del> this.data.target.object3D.quaternion.identity();
<ide> this.bbox.setFromObject(this.data.target.object3D);
<ide> this.bbox.getCenter(this.bboxMesh.position);
<ide> this.bbox.getSize(this.bboxMesh.scale);
<ide> this.bboxMesh.position.y -= this.bboxMesh.scale.y / 2;
<ide> this.bboxOffset.copy(this.bboxMesh.position);
<ide> this.bboxOffset.sub(this.data.target.object3D.position);
<del> this.data.target.object3D.quaternion.copy(tempQuaternion);
<del> this.bboxMesh.quaternion.copy(tempQuaternion);
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 973c32f54012609bef2ba1e89fcad4d8d0b83956 | 0 | SpineEventEngine/base,SpineEventEngine/base,SpineEventEngine/base | /*
* Copyright 2019, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.tools.check.vbuild;
import com.google.protobuf.AbstractMessage;
import com.google.protobuf.Empty;
import io.spine.base.FieldPath;
import io.spine.protobuf.ValidatingBuilder;
import java.util.function.Supplier;
/**
* Contains statements for which the {@link UseVBuild} bug pattern should
* generate no warning.
*/
abstract class UseVBuildNegatives {
/** This method calls the generated vBuild() method. */
void callOnVBuilder() {
FieldPath.newBuilder()
.vBuild();
}
/** This method is annotated suppressing the warning. */
@SuppressWarnings("UseVBuild")
void callUnderWarningSuppressed() {
FieldPath.newBuilder()
.build();
}
/** This method calls buildPartial() to explititly state that the message is not validated. */
void callBuildPartial() {
FieldPath.newBuilder()
.buildPartial();
}
abstract class SomeBuilder implements ValidatingBuilder<Empty> {
/** The call to builder is made inside a builder class. */
void callInsideBuilder() {
FieldPath.newBuilder()
.build();
}
void useMethodRefInsimeBuilder() {
Supplier<?> sup = FieldPath.newBuilder()::build;
sup.get();
}
/** Added to satisfy the compiler. Does not affect the ErrorProne checks. */
@Override
public abstract SomeBuilder clone();
}
abstract class SomeMessage extends AbstractMessage {
/** The call to builder is made inside a message class. */
void callInsideMessage() {
FieldPath.newBuilder()
.build();
}
void useMethodRefInsimeMessage() {
Supplier<?> sup = FieldPath.newBuilder()::build;
sup.get();
}
}
}
| tools/errorprone-checks/src/test/resources/io/spine/tools/check/vbuild/UseVBuildNegatives.java | /*
* Copyright 2019, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.tools.check.vbuild;
import com.google.protobuf.AbstractMessage;
import com.google.protobuf.Empty;
import io.spine.base.FieldPath;
import io.spine.protobuf.ValidatingBuilder;
/**
* Contains statements for which the {@link UseVBuild} bug pattern should
* generate no warning.
*/
abstract class UseVBuildNegatives {
/** This method calls the generated vBuild() method. */
void callOnVBuilder() {
FieldPath.newBuilder()
.vBuild();
}
/** This method is annotated suppressing the warning. */
@SuppressWarnings("UseVBuild")
void callUnderWarningSuppressed() {
FieldPath.newBuilder()
.build();
}
/** This method calls buildPartial() to explititly state that the message is not validated. */
void callBuildPartial() {
FieldPath.newBuilder().buildPartial();
}
abstract class SomeBuilder implements ValidatingBuilder<Empty> {
/** The call to builder is made inside a builder class. */
void callInsideBuilder() {
FieldPath.newBuilder()
.build();
}
/** Added to satisfy the compiler. Does not affect the ErrorProne checks. */
@Override
public abstract SomeBuilder clone();
}
abstract class SomeMessage extends AbstractMessage {
/** The call to builder is made inside a message class. */
void callInsideMessage() {
FieldPath.newBuilder()
.build();
}
}
}
| Add more test cases
| tools/errorprone-checks/src/test/resources/io/spine/tools/check/vbuild/UseVBuildNegatives.java | Add more test cases | <ide><path>ools/errorprone-checks/src/test/resources/io/spine/tools/check/vbuild/UseVBuildNegatives.java
<ide> import io.spine.base.FieldPath;
<ide> import io.spine.protobuf.ValidatingBuilder;
<ide>
<add>import java.util.function.Supplier;
<add>
<ide> /**
<ide> * Contains statements for which the {@link UseVBuild} bug pattern should
<ide> * generate no warning.
<ide>
<ide> /** This method calls buildPartial() to explititly state that the message is not validated. */
<ide> void callBuildPartial() {
<del> FieldPath.newBuilder().buildPartial();
<add> FieldPath.newBuilder()
<add> .buildPartial();
<ide> }
<ide>
<ide> abstract class SomeBuilder implements ValidatingBuilder<Empty> {
<ide> void callInsideBuilder() {
<ide> FieldPath.newBuilder()
<ide> .build();
<add> }
<add>
<add> void useMethodRefInsimeBuilder() {
<add> Supplier<?> sup = FieldPath.newBuilder()::build;
<add> sup.get();
<ide> }
<ide>
<ide> /** Added to satisfy the compiler. Does not affect the ErrorProne checks. */
<ide> FieldPath.newBuilder()
<ide> .build();
<ide> }
<add>
<add> void useMethodRefInsimeMessage() {
<add> Supplier<?> sup = FieldPath.newBuilder()::build;
<add> sup.get();
<add> }
<ide> }
<ide> } |
|
Java | apache-2.0 | 18f03b10c4773e5ec4a9d96ec6cff3fd38f613e6 | 0 | osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi | /*
* $Header$
*
* Copyright (c) IBM Corporation (2005)
*
* These materials have been contributed to the OSGi Alliance as
* "MEMBER LICENSED MATERIALS" as defined in, and subject to the terms of,
* the OSGi Member Agreement, specifically including but not limited to,
* the license rights and warranty disclaimers as set forth in Sections 3.2
* and 12.1 thereof, and the applicable Statement of Work.
*
* All company, brand and product names contained within this document may be
* trademarks that are the sole property of the respective owners.
*/
package org.eclipse.osgi.component.instance;
import java.util.Hashtable;
import java.util.List;
import org.eclipse.osgi.component.Log;
import org.eclipse.osgi.component.model.ComponentDescription;
import org.eclipse.osgi.component.model.ComponentDescriptionProp;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentException;
import org.osgi.service.component.ComponentInstance;
/**
* Static utility class to register a Component Configuration's provided service.
* A ServiceFactory is used to enable lazy activation
*
* @version $Revision$
*/
abstract class RegisterComponentService {
/* set this to true to compile in debug messages */
static final boolean DEBUG = false;
// cannot instantiate - this is a utility class
private RegisterComponentService() {
}
/**
* Register the Component Configuration's service
*
* @param ip - InstanceProcess
* @param cdp - ComponentDescription plus Properties
*/
static void registerService(InstanceProcess instanceProcess,
ComponentDescriptionProp cdp) {
ComponentDescription cd = cdp.getComponentDescription();
//make final references for use by anonymous inner class
final InstanceProcess finalInstanceProcess = instanceProcess;
final ComponentDescriptionProp finalCDP = cdp;
List servicesProvided = cd.getServicesProvided();
String[] servicesProvidedArray = (String[]) servicesProvided
.toArray(new String[servicesProvided.size()]);
// register the service using a ServiceFactory
ServiceRegistration serviceRegistration = null;
if (cd.getService().isServicefactory()) {
// register the service using a ServiceFactory
serviceRegistration = cd.getBundleContext().registerService(
servicesProvidedArray, new ServiceFactory() {
// map of Bundle:componentInstance
Hashtable instances;
// ServiceFactory.getService method.
public Object getService(Bundle bundle,
ServiceRegistration registration) {
if (DEBUG)
System.out
.println("RegisterComponentServiceFactory:getService: registration:"
+ registration);
ComponentInstance componentInstance = null;
try {
componentInstance = finalInstanceProcess.buildDispose
.build(bundle, finalCDP);
}
catch (ComponentException e) {
Log
.log(
1,
"[SCR] Error attempting to register a Service Factory.",
e);
}
if (componentInstance != null) {
// save so we can dispose later
synchronized (this) {
if (instances == null) {
instances = new Hashtable();
}
}
instances.put(bundle, componentInstance);
}
return componentInstance.getInstance();
}
// ServiceFactory.ungetService method.
public void ungetService(Bundle bundle,
ServiceRegistration registration, Object service) {
if (DEBUG)
System.out
.println("RegisterComponentServiceFactory:ungetService: registration = "
+ registration);
((ComponentInstance) instances.get(bundle))
.dispose();
instances.remove(bundle);
synchronized (this) {
if (instances.isEmpty()) {
instances = null;
}
}
}
}, cdp.getProperties());
}
else {
// servicefactory=false
// always return the same instance
serviceRegistration = cd.getBundleContext().registerService(
servicesProvidedArray, new ServiceFactory() {
int references = 0;
//keep track of whether the componentInstance was created
//by this class' getService method or if it already
//existed - if we create it then we have to dispose
//of it when it is no longer in use (references == 0)
boolean disposeComponentInstance = false;
// ServiceFactory.getService method.
public Object getService(Bundle bundle,
ServiceRegistration registration) {
if (DEBUG)
System.out
.println("RegisterComponentService: getService: registration = "
+ registration);
synchronized (this) {
if (finalCDP.getInstances().isEmpty()) {
try {
//track that we created this instance
//so we know to dispose of it later
finalInstanceProcess.buildDispose
.build(null, finalCDP);
disposeComponentInstance = true;
}
catch (ComponentException e) {
Log
.log(
1,
"[SCR] Error attempting to register Service.",
e);
return null;
}
}
references++;
}
return ((ComponentInstance) finalCDP.getInstances()
.get(0)).getInstance();
}
// ServiceFactory.ungetService method.
public void ungetService(Bundle bundle,
ServiceRegistration registration, Object service) {
if (DEBUG)
System.out
.println("RegisterComponentService: ungetService: registration = "
+ registration);
synchronized (this) {
references--;
if (references < 1 && disposeComponentInstance) {
// if disposeComponentInstance then we
// created it in getService so we should
// dispose of it now
((ComponentInstance) finalCDP.getInstances()
.get(0)).dispose();
disposeComponentInstance = false;
}
}
}
}, cdp.getProperties());
}
if (DEBUG)
System.out.println("RegisterComponentService: register: "
+ serviceRegistration);
cdp.setServiceRegistration(serviceRegistration);
}
}
| org.osgi.impl.service.component/src/org/eclipse/osgi/component/instance/RegisterComponentService.java | /*
* $Header$
*
* Copyright (c) IBM Corporation (2005)
*
* These materials have been contributed to the OSGi Alliance as
* "MEMBER LICENSED MATERIALS" as defined in, and subject to the terms of,
* the OSGi Member Agreement, specifically including but not limited to,
* the license rights and warranty disclaimers as set forth in Sections 3.2
* and 12.1 thereof, and the applicable Statement of Work.
*
* All company, brand and product names contained within this document may be
* trademarks that are the sole property of the respective owners.
*/
package org.eclipse.osgi.component.instance;
import java.util.Hashtable;
import java.util.List;
import org.eclipse.osgi.component.Log;
import org.eclipse.osgi.component.model.ComponentDescription;
import org.eclipse.osgi.component.model.ComponentDescriptionProp;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentException;
import org.osgi.service.component.ComponentInstance;
/**
* Static utility class to register a Component Configuration's provided service.
* A ServiceFactory is used to enable lazy activation
*
* @version $Revision$
*/
abstract class RegisterComponentService {
/* set this to true to compile in debug messages */
static final boolean DEBUG = false;
// cannot instantiate - this is a utility class
private RegisterComponentService() {
}
/**
* registerService
*
* @param ip - InstanceProcess
* @param cdp - ComponentDescription plus Properties
*/
static void registerService(InstanceProcess instanceProcess,
ComponentDescriptionProp cdp) {
ComponentDescription cd = cdp.getComponentDescription();
//make final references for use by anonymous inner class
final InstanceProcess finalInstanceProcess = instanceProcess;
final ComponentDescriptionProp finalCDP = cdp;
List servicesProvided = cd.getServicesProvided();
String[] servicesProvidedArray = (String[]) servicesProvided
.toArray(new String[servicesProvided.size()]);
// register the service using a ServiceFactory
ServiceRegistration serviceRegistration = null;
if (cd.getService().isServicefactory()) {
// register the service using a ServiceFactory
serviceRegistration = cd.getBundleContext().registerService(
servicesProvidedArray, new ServiceFactory() {
// map of Bundle:componentInstance
Hashtable instances;
// ServiceFactory.getService method.
public Object getService(Bundle bundle,
ServiceRegistration registration) {
if (DEBUG)
System.out
.println("RegisterComponentServiceFactory:getService: registration:"
+ registration);
ComponentInstance componentInstance = null;
try {
componentInstance = finalInstanceProcess.buildDispose
.build(bundle, finalCDP);
}
catch (ComponentException e) {
Log
.log(
1,
"[SCR] Error attempting to register a Service Factory.",
e);
}
if (componentInstance != null) {
// save so we can dispose later
synchronized (this) {
if (instances == null) {
instances = new Hashtable();
}
}
instances.put(bundle, componentInstance);
}
return componentInstance.getInstance();
}
// ServiceFactory.ungetService method.
public void ungetService(Bundle bundle,
ServiceRegistration registration, Object service) {
if (DEBUG)
System.out
.println("RegisterComponentServiceFactory:ungetService: registration = "
+ registration);
((ComponentInstance) instances.get(bundle))
.dispose();
instances.remove(bundle);
synchronized (this) {
if (instances.isEmpty()) {
instances = null;
}
}
}
}, cdp.getProperties());
}
else {
// servicefactory=false
// always return the same instance
serviceRegistration = cd.getBundleContext().registerService(
servicesProvidedArray, new ServiceFactory() {
int references = 0;
// if we create an instance, keep track of it
ComponentInstance instance;
// ServiceFactory.getService method.
public Object getService(Bundle bundle,
ServiceRegistration registration) {
if (DEBUG)
System.out
.println("RegisterComponentService: getService: registration = "
+ registration);
synchronized (this) {
if (finalCDP.getInstances().isEmpty()) {
try {
instance = finalInstanceProcess.buildDispose
.build(null, finalCDP);
}
catch (ComponentException e) {
Log
.log(
1,
"[SCR] Error attempting to register Service.",
e);
return null;
}
}
references++;
}
return ((ComponentInstance) finalCDP.getInstances()
.get(0)).getInstance();
}
// ServiceFactory.ungetService method.
public void ungetService(Bundle bundle,
ServiceRegistration registration, Object service) {
if (DEBUG)
System.out
.println("RegisterComponentService: ungetService: registration = "
+ registration);
synchronized (this) {
references--;
if (references < 1 && instance != null) {
// if instance != null then we created it
// dispose instance
instance.dispose();
instance = null;
}
}
}
}, cdp.getProperties());
}
if (DEBUG)
System.out.println("RegisterComponentService: register: "
+ serviceRegistration);
cdp.setServiceRegistration(serviceRegistration);
}
}
| Use boolean flag to remember if we need to dispose of CDP instance
| org.osgi.impl.service.component/src/org/eclipse/osgi/component/instance/RegisterComponentService.java | Use boolean flag to remember if we need to dispose of CDP instance | <ide><path>rg.osgi.impl.service.component/src/org/eclipse/osgi/component/instance/RegisterComponentService.java
<ide> }
<ide>
<ide> /**
<del> * registerService
<add> * Register the Component Configuration's service
<ide> *
<ide> * @param ip - InstanceProcess
<ide> * @param cdp - ComponentDescription plus Properties
<ide> servicesProvidedArray, new ServiceFactory() {
<ide>
<ide> int references = 0;
<del> // if we create an instance, keep track of it
<del> ComponentInstance instance;
<add>
<add> //keep track of whether the componentInstance was created
<add> //by this class' getService method or if it already
<add> //existed - if we create it then we have to dispose
<add> //of it when it is no longer in use (references == 0)
<add> boolean disposeComponentInstance = false;
<ide>
<ide> // ServiceFactory.getService method.
<ide> public Object getService(Bundle bundle,
<ide>
<ide> if (finalCDP.getInstances().isEmpty()) {
<ide> try {
<del> instance = finalInstanceProcess.buildDispose
<add> //track that we created this instance
<add> //so we know to dispose of it later
<add> finalInstanceProcess.buildDispose
<ide> .build(null, finalCDP);
<add> disposeComponentInstance = true;
<ide> }
<ide> catch (ComponentException e) {
<ide> Log
<ide>
<ide> synchronized (this) {
<ide> references--;
<del> if (references < 1 && instance != null) {
<del> // if instance != null then we created it
<del> // dispose instance
<del> instance.dispose();
<del> instance = null;
<add> if (references < 1 && disposeComponentInstance) {
<add> // if disposeComponentInstance then we
<add> // created it in getService so we should
<add> // dispose of it now
<add> ((ComponentInstance) finalCDP.getInstances()
<add> .get(0)).dispose();
<add> disposeComponentInstance = false;
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | d0570d85d02fb24744e5437cd4d86ee6edd6406e | 0 | nivanov/ignite,nivanov/ignite,nivanov/ignite,nivanov/ignite,nivanov/ignite,nivanov/ignite,nivanov/ignite,nivanov/ignite | /*
* 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.ignite.math.impls;
import org.apache.ignite.math.Vector;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.*;
import static org.junit.Assert.*;
/** See also: {@link AbstractVectorTest}. */
public class DenseLocalOnHeapVectorTest {
/** */ @Test
public void sizeTest() {
final AtomicReference<Integer> expSize = new AtomicReference<>(0);
final AtomicReference<String> desc = new AtomicReference<>("");
consumeSampleVectors(
(expSizeParam, descParam) -> {
expSize.set(expSizeParam);
desc.set(descParam);
},
(v) -> assertEquals("Expected size for " + desc.get(),
(int) expSize.get(), v.size())
);
}
/** */ @Test
public void isDenseTest() {
alwaysTrueAttributeTest(DenseLocalOnHeapVector::isDense);
}
/** */ @Test
public void isSequentialAccessTest() {
alwaysTrueAttributeTest(DenseLocalOnHeapVector::isSequentialAccess);
}
/** */ @Test
public void getElementTest() {
consumeSampleVectors(v -> new ElementsChecker(v).assertCloseEnough(v));
}
/** */ @Test
public void copyTest() {
consumeSampleVectors(v -> new ElementsChecker(v).assertCloseEnough(v.copy()));
}
/** */ @Test
public void divideTest() {
operationTest((val, operand) -> val / operand, Vector::divide);
}
/** */ @Test
public void likeTest() {
for (int card : new int[] {1, 2, 4, 8, 16, 32, 64, 128})
consumeSampleVectors(v -> assertEquals("Expect size equal to cardinality.", card, v.like(card).size()));
}
/** */ @Test
public void minusTest() {
operationVectorTest((operand1, operand2) -> operand1 - operand2, Vector::minus);
}
/** */ @Test
public void normalizeTest() {
normalizeTest(2, (val, len) -> val / len, Vector::normalize);
}
/** */ @Test
public void normalizePowerTest() {
for (double pow : new double[] {0, 0.5, 1, 2, 2.5, Double.POSITIVE_INFINITY})
normalizeTest(pow, (val, norm) -> val / norm, (v) -> v.normalize(pow));
}
/** */ @Test
public void logNormalizeTest() {
normalizeTest(2, (val, len) -> Math.log1p(val) / (len * Math.log(2)), Vector::logNormalize);
}
/** */ @Test
public void logNormalizePowerTest() {
for (double pow : new double[] {1.1, 2, 2.5})
normalizeTest(pow, (val, norm) -> Math.log1p(val) / (norm * Math.log(pow)), (v) -> v.logNormalize(pow));
}
/** */ @Test
public void kNormTest() {
for (double pow : new double[] {0, 0.5, 1, 2, 2.5, Double.POSITIVE_INFINITY})
consumeSampleVectors(v -> {
final int size = v.size();
final double[] ref = new double[size];
new ElementsChecker(v, ref); // IMPL NOTE this initialises vector and reference array
final double exp = new Norm(ref, pow).calculate();
final double obtained = v.kNorm(pow);
final Metric metric = new Metric(exp, obtained);
assertTrue("Not close enough at power " + pow + ", size " + size + ", " + metric,
metric.closeEnough());
});
}
/** */ @Test
public void plusVectorTest() {
operationVectorTest((operand1, operand2) -> operand1 + operand2, Vector::plus);
}
/** */ @Test
public void plusDoubleTest() {
operationTest((val, operand) -> val + operand, Vector::plus);
}
/** */ @Test
public void timesVectorTest() {
operationVectorTest((operand1, operand2) -> operand1 * operand2, Vector::times);
}
/** */ @Test
public void timesDoubleTest() {
operationTest((val, operand) -> val * operand, Vector::times);
}
/** */ @Test
public void viewPartTest() { // TODO write test
}
/** */ @Test
public void sumTest() { // TODO write test
}
/** */ @Test
public void crossTest() { // TODO write test
}
/** */ @Test
public void getLookupCostTest() { // TODO write test
}
/** */ @Test
public void isAddConstantTimeTest() {
alwaysTrueAttributeTest(DenseLocalOnHeapVector::isAddConstantTime);
}
/** */ @Test
public void clusterGroupTest() { // TODO write test
}
/** */ @Test
public void guidTest() { // TODO write test
}
/** */
private void normalizeTest(double pow, BiFunction<Double, Double, Double> operation,
Function<Vector, Vector> vecOperation) {
consumeSampleVectors(v -> {
final int size = v.size();
final double[] ref = new double[size];
final ElementsChecker checker = new ElementsChecker(v, ref);
final double norm = new Norm(ref, pow).calculate();
for (int idx = 0; idx < size; idx++)
ref[idx] = operation.apply(ref[idx], norm);
checker.assertCloseEnough(vecOperation.apply(v), ref);
});
}
/** */
private void operationVectorTest(BiFunction<Double, Double, Double> operation,
BiFunction<Vector, Vector, Vector> vecOperation) {
consumeSampleVectors(v -> {
// TODO find out if more elaborate testing scenario is needed or it's okay as is.
final int size = v.size();
final double[] ref = new double[size];
final ElementsChecker checker = new ElementsChecker(v, ref);
final Vector operand = v.copy();
for (int idx = 0; idx < size; idx++)
ref[idx] = operation.apply(ref[idx], ref[idx]);
checker.assertCloseEnough(vecOperation.apply(v, operand), ref);
});
}
/** */
private void operationTest(BiFunction<Double, Double, Double> operation,
BiFunction<Vector, Double, Vector> vecOperation) {
for (double value : new double[] {0, 0.1, 1, 2, 10})
consumeSampleVectors(v -> {
final int size = v.size();
final double[] ref = new double[size];
final ElementsChecker checker = new ElementsChecker(v, ref);
for (int idx = 0; idx < size; idx++)
ref[idx] = operation.apply(ref[idx], value);
checker.assertCloseEnough(vecOperation.apply(v, value), ref);
});
}
/** */
private void alwaysTrueAttributeTest(Predicate<DenseLocalOnHeapVector> pred) {
assertTrue("Default size for null args.",
pred.test(new DenseLocalOnHeapVector((Map<String, Object>)null)));
assertTrue("Size from args.",
pred.test(new DenseLocalOnHeapVector(new HashMap<String, Object>(){{ put("size", 99); }})));
final double[] test = new double[99];
assertTrue("Size from array in args.",
pred.test(new DenseLocalOnHeapVector(new HashMap<String, Object>(){{
put("arr", test);
put("shallowCopy", false);
}})));
assertTrue("Size from array in args, shallow copy.",
pred.test(new DenseLocalOnHeapVector(new HashMap<String, Object>(){{
put("arr", test);
put("shallowCopy", true);
}})));
assertTrue("Default constructor.",
pred.test(new DenseLocalOnHeapVector()));
assertTrue("Null array shallow copy.",
pred.test(new DenseLocalOnHeapVector(null, true)));
assertTrue("0 size shallow copy.",
pred.test(new DenseLocalOnHeapVector(new double[0], true)));
assertTrue("0 size.",
pred.test(new DenseLocalOnHeapVector(new double[0], false)));
assertTrue("1 size shallow copy.",
pred.test(new DenseLocalOnHeapVector(new double[1], true)));
assertTrue("1 size.",
pred.test(new DenseLocalOnHeapVector(new double[1], false)));
assertTrue("0 size default copy.",
pred.test(new DenseLocalOnHeapVector(new double[0])));
assertTrue("1 size default copy",
pred.test(new DenseLocalOnHeapVector(new double[1])));
}
/** */
private void consumeSampleVectors(Consumer<DenseLocalOnHeapVector> consumer) {
consumeSampleVectors(null, consumer);
}
/** */
private void consumeSampleVectors(BiConsumer<Integer, String> paramsConsumer,
Consumer<DenseLocalOnHeapVector> consumer) {
for (int size : new int[] {1, 2, 4, 8, 16, 32, 64, 128})
for (int delta : new int[] {-1, 0, 1})
for (boolean shallowCopy : new boolean[] {false, true}) {
final int expSize = size + delta;
if (paramsConsumer != null)
paramsConsumer.accept(expSize, "size " + expSize + ", shallow copy " + shallowCopy);
consumer.accept(new DenseLocalOnHeapVector(new double[expSize], shallowCopy));
}
}
/** */
private static class Norm {
/** */
private final double[] arr;
/** */
private final Double pow;
/** */
Norm(double[] arr, double pow) {
this.arr = arr;
this.pow = pow;
}
/** */
double calculate() {
if (pow.equals(0.0))
return countNonZeroes(); // IMPL NOTE this is beautiful if you think of it
if (pow.equals(Double.POSITIVE_INFINITY))
return maxAbs();
double norm = 0;
for (double val : arr)
norm += Math.pow(val, pow);
return Math.pow(norm, 1 / pow);
}
/** */
private int countNonZeroes() {
int cnt = 0;
final Double zero = 0.0;
for (double val : arr)
if (!zero.equals(val))
cnt++;
return cnt;
}
/** */
private double maxAbs() {
double res = 0;
for (double val : arr) {
final double abs = Math.abs(val);
if (abs > res)
res = abs;
}
return res;
}
}
/** */
private static class ElementsChecker {
/** */
ElementsChecker(Vector v, double[] ref) {
init(v, ref);
}
/** */
ElementsChecker(Vector v) {
this(v, null);
}
/** */
void assertCloseEnough(Vector obtained, double[] exp) {
final int size = obtained.size();
for (int i = 0; i < size; i++) {
final Vector.Element e = obtained.getElement(i);
final Metric metric = new Metric(exp == null ? i : exp[i], e.get());
assertEquals("Vector index.", i, e.index());
assertTrue("Not close enough at index " + i + ", size " + size + ", " + metric, metric.closeEnough());
}
}
/** */
void assertCloseEnough(Vector obtained) {
assertCloseEnough(obtained, null);
}
/** */
private void init(Vector v, double[] ref) {
for (Vector.Element e : v.all()) {
int idx = e.index();
e.set(e.index());
if (ref != null)
ref[idx] = idx;
}
}
}
/** */
private static class Metric { // todo consider if softer tolerance (like say 0.1 or 0.01) would make sense here
/** */
private final double exp;
/** */
private final double obtained;
/** **/
Metric(double exp, double obtained) {
this.exp = exp;
this.obtained = obtained;
}
/** */
boolean closeEnough() {
return new Double(exp).equals(obtained);
}
/** @{inheritDoc} */
@Override public String toString() {
return "Metric{" + "expected=" + exp +
", obtained=" + obtained +
'}';
}
}
}
| modules/core/src/test/java/org/apache/ignite/math/impls/DenseLocalOnHeapVectorTest.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.ignite.math.impls;
import org.apache.ignite.math.Vector;
import org.junit.Ignore;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.*;
import static org.junit.Assert.*;
/** See also: {@link AbstractVectorTest}. */
public class DenseLocalOnHeapVectorTest {
/** */ @Test
public void sizeTest() {
final AtomicReference<Integer> expSize = new AtomicReference<>(0);
final AtomicReference<String> desc = new AtomicReference<>("");
consumeSampleVectors(
(expSizeParam, descParam) -> {
expSize.set(expSizeParam);
desc.set(descParam);
},
(v) -> assertEquals("Expected size for " + desc.get(),
(int) expSize.get(), v.size())
);
}
/** */ @Test
public void isDenseTest() {
alwaysTrueAttributeTest(DenseLocalOnHeapVector::isDense);
}
/** */ @Test
public void isSequentialAccessTest() {
alwaysTrueAttributeTest(DenseLocalOnHeapVector::isSequentialAccess);
}
/** */ @Test
public void getElementTest() {
consumeSampleVectors(v -> new ElementsChecker(v).assertCloseEnough(v));
}
/** */ @Test
public void copyTest() {
consumeSampleVectors(v -> new ElementsChecker(v).assertCloseEnough(v.copy()));
}
/** */ @Test
public void divideTest() {
operationTest((val, operand) -> val / operand, Vector::divide);
}
/** */ @Test
public void likeTest() {
for (int card : new int[] {1, 2, 4, 8, 16, 32, 64, 128})
consumeSampleVectors(v -> assertEquals("Expect size equal to cardinality.", card, v.like(card).size()));
}
/** */ @Test
public void minusTest() {
operationVectorTest((operand1, operand2) -> operand1 - operand2, Vector::minus);
}
/** */ @Test
public void normalizeTest() {
normalizeTest(2, (val, len) -> val / len, Vector::normalize);
}
/** */ @Test
@Ignore("Test case ignored: need to fix either test or implementation or both") // todo fix this
public void normalizePowerTest() {
for (double pow : new double[] {0, 0.5, 1, 2, 2.5, Double.POSITIVE_INFINITY})
normalizeTest(pow, (val, norm) -> val / norm, (v) -> v.normalize(pow));
}
/** */ @Test
public void logNormalizeTest() {
normalizeTest(2, (val, len) -> Math.log1p(val) / (len * Math.log(2)), Vector::logNormalize);
}
/** */ @Test
public void logNormalizePowerTest() {
for (double pow : new double[] {1.1, 2, 2.5})
normalizeTest(pow, (val, norm) -> Math.log1p(val) / (norm * Math.log(pow)), (v) -> v.logNormalize(pow));
}
/** */ @Test
public void kNormTest() { // TODO write test
}
/** */ @Test
public void plusVectorTest() {
operationVectorTest((operand1, operand2) -> operand1 + operand2, Vector::plus);
}
/** */ @Test
public void plusDoubleTest() {
operationTest((val, operand) -> val + operand, Vector::plus);
}
/** */ @Test
public void timesVectorTest() {
operationVectorTest((operand1, operand2) -> operand1 * operand2, Vector::times);
}
/** */ @Test
public void timesDoubleTest() {
operationTest((val, operand) -> val * operand, Vector::times);
}
/** */ @Test
public void viewPartTest() { // TODO write test
}
/** */ @Test
public void sumTest() { // TODO write test
}
/** */ @Test
public void crossTest() { // TODO write test
}
/** */ @Test
public void getLookupCostTest() { // TODO write test
}
/** */ @Test
public void isAddConstantTimeTest() {
alwaysTrueAttributeTest(DenseLocalOnHeapVector::isAddConstantTime);
}
/** */ @Test
public void clusterGroupTest() { // TODO write test
}
/** */ @Test
public void guidTest() { // TODO write test
}
/** */
private void normalizeTest(double pow, BiFunction<Double, Double, Double> operation,
Function<Vector, Vector> vecOperation) {
consumeSampleVectors(v -> {
final int size = v.size();
final double[] ref = new double[size];
final ElementsChecker checker = new ElementsChecker(v, ref);
double norm = 0;
for (double val : ref)
norm += Math.pow(val, pow);
norm = Math.pow(norm, 1 / pow);
for (int idx = 0; idx < size; idx++)
ref[idx] = operation.apply(ref[idx], norm);
checker.assertCloseEnough(vecOperation.apply(v), ref);
});
}
/** */
private void operationVectorTest(BiFunction<Double, Double, Double> operation,
BiFunction<Vector, Vector, Vector> vecOperation) {
consumeSampleVectors(v -> {
// TODO find out if more elaborate testing scenario is needed or it's okay as is.
final int size = v.size();
final double[] ref = new double[size];
final ElementsChecker checker = new ElementsChecker(v, ref);
final Vector operand = v.copy();
for (int idx = 0; idx < size; idx++)
ref[idx] = operation.apply(ref[idx], ref[idx]);
checker.assertCloseEnough(vecOperation.apply(v, operand), ref);
});
}
/** */
private void operationTest(BiFunction<Double, Double, Double> operation,
BiFunction<Vector, Double, Vector> vecOperation) {
for (double value : new double[] {0, 0.1, 1, 2, 10})
consumeSampleVectors(v -> {
final int size = v.size();
final double[] ref = new double[size];
final ElementsChecker checker = new ElementsChecker(v, ref);
for (int idx = 0; idx < size; idx++)
ref[idx] = operation.apply(ref[idx], value);
checker.assertCloseEnough(vecOperation.apply(v, value), ref);
});
}
/** */
private void alwaysTrueAttributeTest(Predicate<DenseLocalOnHeapVector> pred) {
assertTrue("Default size for null args.",
pred.test(new DenseLocalOnHeapVector((Map<String, Object>)null)));
assertTrue("Size from args.",
pred.test(new DenseLocalOnHeapVector(new HashMap<String, Object>(){{ put("size", 99); }})));
final double[] test = new double[99];
assertTrue("Size from array in args.",
pred.test(new DenseLocalOnHeapVector(new HashMap<String, Object>(){{
put("arr", test);
put("shallowCopy", false);
}})));
assertTrue("Size from array in args, shallow copy.",
pred.test(new DenseLocalOnHeapVector(new HashMap<String, Object>(){{
put("arr", test);
put("shallowCopy", true);
}})));
assertTrue("Default constructor.",
pred.test(new DenseLocalOnHeapVector()));
assertTrue("Null array shallow copy.",
pred.test(new DenseLocalOnHeapVector(null, true)));
assertTrue("0 size shallow copy.",
pred.test(new DenseLocalOnHeapVector(new double[0], true)));
assertTrue("0 size.",
pred.test(new DenseLocalOnHeapVector(new double[0], false)));
assertTrue("1 size shallow copy.",
pred.test(new DenseLocalOnHeapVector(new double[1], true)));
assertTrue("1 size.",
pred.test(new DenseLocalOnHeapVector(new double[1], false)));
assertTrue("0 size default copy.",
pred.test(new DenseLocalOnHeapVector(new double[0])));
assertTrue("1 size default copy",
pred.test(new DenseLocalOnHeapVector(new double[1])));
}
/** */
private void consumeSampleVectors(Consumer<DenseLocalOnHeapVector> consumer) {
consumeSampleVectors(null, consumer);
}
/** */
private void consumeSampleVectors(BiConsumer<Integer, String> paramsConsumer,
Consumer<DenseLocalOnHeapVector> consumer) {
for (int size : new int[] {1, 2, 4, 8, 16, 32, 64, 128})
for (int delta : new int[] {-1, 0, 1})
for (boolean shallowCopy : new boolean[] {false, true}) {
final int expSize = size + delta;
if (paramsConsumer != null)
paramsConsumer.accept(expSize, "size " + expSize + ", shallow copy " + shallowCopy);
consumer.accept(new DenseLocalOnHeapVector(new double[expSize], shallowCopy));
}
}
/** */
private static class ElementsChecker {
/** */
ElementsChecker(Vector v, double[] ref) {
init(v, ref);
}
/** */
ElementsChecker(Vector v) {
this(v, null);
}
/** */
void assertCloseEnough(Vector obtained, double[] exp) {
final int size = obtained.size();
for (int i = 0; i < size; i++) {
final Vector.Element e = obtained.getElement(i);
final Metric metric = new Metric(exp == null ? i : exp[i], e.get());
assertEquals("Vector index.", i, e.index());
assertTrue("Not close enough at index " + i + ", size " + size + ", " + metric, metric.closeEnough());
}
}
/** */
void assertCloseEnough(Vector obtained) {
assertCloseEnough(obtained, null);
}
/** */
private void init(Vector v, double[] ref) {
for (Vector.Element e : v.all()) {
int idx = e.index();
e.set(e.index());
if (ref != null)
ref[idx] = idx;
}
}
}
/** */
private static class Metric { // todo consider if softer tolerance (like say 0.1 or 0.01) would make sense here
/** */
private final double exp;
/** */
private final double obtained;
/** **/
Metric(double exp, double obtained) {
this.exp = exp;
this.obtained = obtained;
}
/** */
boolean closeEnough() {
return new Double(exp).equals(obtained);
}
/** @{inheritDoc} */
@Override public String toString() {
return "Metric{" + "expected=" + exp +
", obtained=" + obtained +
'}';
}
}
}
| IGN-6530 wip
- DenseLocalOnHeapVector in progress
// normalizePower and kNorm test
-- verified with diffs overview, rebuild and execution of unit tests
| modules/core/src/test/java/org/apache/ignite/math/impls/DenseLocalOnHeapVectorTest.java | IGN-6530 wip - DenseLocalOnHeapVector in progress // normalizePower and kNorm test -- verified with diffs overview, rebuild and execution of unit tests | <ide><path>odules/core/src/test/java/org/apache/ignite/math/impls/DenseLocalOnHeapVectorTest.java
<ide> package org.apache.ignite.math.impls;
<ide>
<ide> import org.apache.ignite.math.Vector;
<del>import org.junit.Ignore;
<ide> import org.junit.Test;
<ide>
<ide> import java.util.HashMap;
<ide> }
<ide>
<ide> /** */ @Test
<del> @Ignore("Test case ignored: need to fix either test or implementation or both") // todo fix this
<ide> public void normalizePowerTest() {
<ide> for (double pow : new double[] {0, 0.5, 1, 2, 2.5, Double.POSITIVE_INFINITY})
<ide> normalizeTest(pow, (val, norm) -> val / norm, (v) -> v.normalize(pow));
<ide> }
<ide>
<ide> /** */ @Test
<del> public void kNormTest() { // TODO write test
<del>
<add> public void kNormTest() {
<add> for (double pow : new double[] {0, 0.5, 1, 2, 2.5, Double.POSITIVE_INFINITY})
<add> consumeSampleVectors(v -> {
<add> final int size = v.size();
<add>
<add> final double[] ref = new double[size];
<add>
<add> new ElementsChecker(v, ref); // IMPL NOTE this initialises vector and reference array
<add>
<add> final double exp = new Norm(ref, pow).calculate();
<add>
<add> final double obtained = v.kNorm(pow);
<add>
<add> final Metric metric = new Metric(exp, obtained);
<add>
<add> assertTrue("Not close enough at power " + pow + ", size " + size + ", " + metric,
<add> metric.closeEnough());
<add> });
<ide> }
<ide>
<ide> /** */ @Test
<ide>
<ide> final ElementsChecker checker = new ElementsChecker(v, ref);
<ide>
<del> double norm = 0;
<del>
<del> for (double val : ref)
<del> norm += Math.pow(val, pow);
<del>
<del> norm = Math.pow(norm, 1 / pow);
<add> final double norm = new Norm(ref, pow).calculate();
<ide>
<ide> for (int idx = 0; idx < size; idx++)
<ide> ref[idx] = operation.apply(ref[idx], norm);
<ide> checker.assertCloseEnough(vecOperation.apply(v), ref);
<ide> });
<ide> }
<del>
<del>
<ide>
<ide> /** */
<ide> private void operationVectorTest(BiFunction<Double, Double, Double> operation,
<ide> }
<ide>
<ide> /** */
<add> private static class Norm {
<add> /** */
<add> private final double[] arr;
<add>
<add> /** */
<add> private final Double pow;
<add>
<add>
<add> /** */
<add> Norm(double[] arr, double pow) {
<add> this.arr = arr;
<add> this.pow = pow;
<add> }
<add>
<add> /** */
<add> double calculate() {
<add> if (pow.equals(0.0))
<add> return countNonZeroes(); // IMPL NOTE this is beautiful if you think of it
<add>
<add> if (pow.equals(Double.POSITIVE_INFINITY))
<add> return maxAbs();
<add>
<add> double norm = 0;
<add>
<add> for (double val : arr)
<add> norm += Math.pow(val, pow);
<add>
<add> return Math.pow(norm, 1 / pow);
<add> }
<add>
<add> /** */
<add> private int countNonZeroes() {
<add> int cnt = 0;
<add>
<add> final Double zero = 0.0;
<add>
<add> for (double val : arr)
<add> if (!zero.equals(val))
<add> cnt++;
<add>
<add> return cnt;
<add> }
<add>
<add> /** */
<add> private double maxAbs() {
<add> double res = 0;
<add>
<add> for (double val : arr) {
<add> final double abs = Math.abs(val);
<add>
<add> if (abs > res)
<add> res = abs;
<add> }
<add>
<add> return res;
<add> }
<add> }
<add>
<add> /** */
<ide> private static class ElementsChecker {
<ide> /** */
<ide> ElementsChecker(Vector v, double[] ref) { |
|
Java | bsd-2-clause | 85ba345f6c958e8951003f77fddbc17ff97135b6 | 0 | markphip/testing,markphip/testing,edgehosting/jira-dvcs-connector,markphip/testing,edgehosting/jira-dvcs-connector,edgehosting/jira-dvcs-connector | package com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.restpoints;
import java.util.List;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.client.ClientUtils;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketGroup;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.RemoteRequestor;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.RemoteResponse;
import com.google.gson.reflect.TypeToken;
/**
* GroupRemoteRestpoint
*
*
* <br /><br />
* Created on 13.7.2012, 17:29:24
* <br /><br />
* @author [email protected]
*
*/
public class GroupRemoteRestpoint
{
private RemoteRequestor requestor;
public GroupRemoteRestpoint(RemoteRequestor remoteRequestor)
{
this.requestor = remoteRequestor;
}
/**
* <b>Requires authorization.</b>
*
* @param owner
* @return
*/
public List<BitbucketGroup> getGroups(String owner)
{
String getGroupUrl = String.format("/groups/%s", owner);
RemoteResponse response = requestor.get(getGroupUrl, null);
return ClientUtils.fromJson(response.getResponse(),
new TypeToken<List<BitbucketGroup>>(){}.getType());
}
}
| bitbucket-client/src/main/java/com/atlassian/jira/plugins/dvcs/spi/bitbucket/clientlibrary/restpoints/GroupRemoteRestpoint.java | package com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.restpoints;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.client.ClientUtils;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketGroup;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.RemoteRequestor;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.RemoteResponse;
/**
* GroupRemoteRestpoint
*
*
* <br /><br />
* Created on 13.7.2012, 17:29:24
* <br /><br />
* @author [email protected]
*
*/
public class GroupRemoteRestpoint
{
private RemoteRequestor requestor;
public GroupRemoteRestpoint(RemoteRequestor remoteRequestor)
{
this.requestor = remoteRequestor;
}
/**
* <b>Requires authorization.</b>
*
* @param owner
* @return
*/
public BitbucketGroup getGroup(String owner)
{
String getGroupUrl = String.format("/groups/%s", owner);
RemoteResponse response = requestor.get(getGroupUrl, null);
return ClientUtils.fromJson(response.getResponse(), BitbucketGroup.class);
}
}
| BBC-217 - GroupRemoteRestpoint now returns correct returt type - List<BitbucketGroup> instead of BitbucketGroup
| bitbucket-client/src/main/java/com/atlassian/jira/plugins/dvcs/spi/bitbucket/clientlibrary/restpoints/GroupRemoteRestpoint.java | BBC-217 - GroupRemoteRestpoint now returns correct returt type - List<BitbucketGroup> instead of BitbucketGroup | <ide><path>itbucket-client/src/main/java/com/atlassian/jira/plugins/dvcs/spi/bitbucket/clientlibrary/restpoints/GroupRemoteRestpoint.java
<ide> package com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.restpoints;
<add>
<add>import java.util.List;
<ide>
<ide> import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.client.ClientUtils;
<ide> import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketGroup;
<ide> import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.RemoteRequestor;
<ide> import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.RemoteResponse;
<add>import com.google.gson.reflect.TypeToken;
<ide>
<ide> /**
<ide> * GroupRemoteRestpoint
<ide> * @param owner
<ide> * @return
<ide> */
<del> public BitbucketGroup getGroup(String owner)
<add> public List<BitbucketGroup> getGroups(String owner)
<ide> {
<ide> String getGroupUrl = String.format("/groups/%s", owner);
<ide>
<ide> RemoteResponse response = requestor.get(getGroupUrl, null);
<ide>
<del> return ClientUtils.fromJson(response.getResponse(), BitbucketGroup.class);
<add> return ClientUtils.fromJson(response.getResponse(),
<add> new TypeToken<List<BitbucketGroup>>(){}.getType());
<ide> }
<ide> }
<ide> |
|
Java | mit | 876d09be834a8a4c06a80fe73fb75931cebbbb66 | 0 | JBYoshi/SpongeCommon,SpongePowered/Sponge,sanman00/SpongeCommon,SpongePowered/Sponge,sanman00/SpongeCommon,JBYoshi/SpongeCommon,Grinch/SpongeCommon,Grinch/SpongeCommon,SpongePowered/SpongeCommon,SpongePowered/Sponge,SpongePowered/SpongeCommon | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://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.common.world;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.base.Throwables;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.MapMaker;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.datafix.FixTypes;
import net.minecraft.world.DimensionType;
import net.minecraft.world.GameType;
import net.minecraft.world.MinecraftException;
import net.minecraft.world.ServerWorldEventHandler;
import net.minecraft.world.World;
import net.minecraft.world.WorldProvider;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldServerMulti;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldType;
import net.minecraft.world.chunk.storage.AnvilSaveHandler;
import net.minecraft.world.storage.ISaveHandler;
import net.minecraft.world.storage.SaveHandler;
import net.minecraft.world.storage.WorldInfo;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.NamedCause;
import org.spongepowered.api.util.file.CopyFileVisitor;
import org.spongepowered.api.util.file.DeleteFileVisitor;
import org.spongepowered.api.util.file.ForwardingFileVisitor;
import org.spongepowered.api.world.DimensionTypes;
import org.spongepowered.api.world.WorldArchetype;
import org.spongepowered.api.world.storage.WorldProperties;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.config.SpongeConfig;
import org.spongepowered.common.data.util.DataUtil;
import org.spongepowered.common.data.util.NbtDataUtil;
import org.spongepowered.common.interfaces.IMixinIntegratedServer;
import org.spongepowered.common.interfaces.IMixinMinecraftServer;
import org.spongepowered.common.interfaces.entity.player.IMixinEntityPlayerMP;
import org.spongepowered.common.interfaces.world.IMixinDimensionType;
import org.spongepowered.common.interfaces.world.IMixinWorldInfo;
import org.spongepowered.common.interfaces.world.IMixinWorldServer;
import org.spongepowered.common.interfaces.world.IMixinWorldSettings;
import org.spongepowered.common.scheduler.SpongeScheduler;
import org.spongepowered.common.util.SpongeHooks;
import org.spongepowered.common.world.storage.WorldServerMultiAdapterWorldInfo;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nullable;
public final class WorldManager {
public static final DirectoryStream.Filter<Path> LEVEL_AND_SPONGE =
entry -> Files.isDirectory(entry) && Files.exists(entry.resolve("level.dat")) && Files.exists(entry.resolve("level_sponge.dat"));
private static final Int2ObjectMap<DimensionType> dimensionTypeByTypeId = new Int2ObjectOpenHashMap<>(3);
private static final Int2ObjectMap<DimensionType> dimensionTypeByDimensionId = new Int2ObjectOpenHashMap<>(3);
private static final IntSet unregisterableDimensions = new IntOpenHashSet(3);
private static final Int2ObjectMap<Path> dimensionPathByDimensionId = new Int2ObjectOpenHashMap<>(3);
private static final Int2ObjectOpenHashMap<WorldServer> worldByDimensionId = new Int2ObjectOpenHashMap<>(3);
private static final Map<String, WorldProperties> worldPropertiesByFolderName = new HashMap<>(3);
private static final Map<UUID, WorldProperties> worldPropertiesByWorldUuid = new HashMap<>(3);
private static final Map<Integer, String> worldFolderByDimensionId = new HashMap<>();
private static final BiMap<String, UUID> worldUuidByFolderName = HashBiMap.create(3);
private static final BitSet dimensionBits = new BitSet(Long.SIZE << 4);
private static final Map<WorldServer, WorldServer> weakWorldByWorld = new MapMaker().weakKeys().weakValues().concurrencyLevel(1).makeMap();
private static final Queue<WorldServer> unloadQueue = new ArrayDeque<>();
private static final Comparator<WorldServer>
WORLD_SERVER_COMPARATOR =
(world1, world2) -> {
final Integer world1DimId = ((IMixinWorldServer) world1).getDimensionId();
if (world2 == null) {
return world1DimId;
}
final Integer world2DimId = ((IMixinWorldServer) world2).getDimensionId();
return world1DimId - world2DimId;
};
private static boolean isVanillaRegistered = false;
static {
WorldManager.registerVanillaTypesAndDimensions();
}
public static void registerVanillaTypesAndDimensions() {
if (!isVanillaRegistered) {
WorldManager.registerDimensionType(0, DimensionType.OVERWORLD);
WorldManager.registerDimensionType(-1, DimensionType.NETHER);
WorldManager.registerDimensionType(1, DimensionType.THE_END);
WorldManager.registerDimension(0, DimensionType.OVERWORLD, false);
WorldManager.registerDimension(-1, DimensionType.NETHER, false);
WorldManager.registerDimension(1, DimensionType.THE_END, false);
}
isVanillaRegistered = true;
}
public static boolean registerDimensionType(DimensionType type) {
checkNotNull(type);
final Optional<Integer> optNextDimensionTypeId = getNextFreeDimensionTypeId();
return optNextDimensionTypeId.isPresent() && registerDimensionType(optNextDimensionTypeId.get(), type);
}
public static boolean registerDimensionType(int dimensionTypeId, DimensionType type) {
checkNotNull(type);
if (dimensionTypeByTypeId.containsKey(dimensionTypeId)) {
return false;
}
dimensionTypeByTypeId.put(dimensionTypeId, type);
return true;
}
private static Optional<Integer> getNextFreeDimensionTypeId() {
Integer highestDimensionTypeId = null;
for (Integer dimensionTypeId : dimensionTypeByTypeId.keySet()) {
if (highestDimensionTypeId == null || highestDimensionTypeId < dimensionTypeId) {
highestDimensionTypeId = dimensionTypeId;
}
}
if (highestDimensionTypeId != null && highestDimensionTypeId < 127) {
return Optional.of(++highestDimensionTypeId);
}
return Optional.empty();
}
public static Integer getNextFreeDimensionId() {
return dimensionBits.nextClearBit(0);
}
public static boolean registerDimension(int dimensionId, DimensionType type, boolean canBeUnregistered) {
checkNotNull(type);
if (!dimensionTypeByTypeId.containsValue(type)) {
return false;
}
if (dimensionTypeByDimensionId.containsKey(dimensionId)) {
return false;
}
dimensionTypeByDimensionId.put(dimensionId, type);
if (dimensionId >= 0) {
dimensionBits.set(dimensionId);
}
if (canBeUnregistered) {
unregisterableDimensions.add(dimensionId);
}
return true;
}
public static void unregisterDimension(int dimensionId) {
if (!dimensionTypeByDimensionId.containsKey(dimensionId))
{
throw new IllegalArgumentException("Failed to unregister dimension [" + dimensionId + "] as it is not registered!");
}
dimensionTypeByDimensionId.remove(dimensionId);
}
public static void registerVanillaDimensionPaths(final Path savePath) {
WorldManager.registerDimensionPath(0, savePath);
WorldManager.registerDimensionPath(-1, savePath.resolve("DIM-1"));
WorldManager.registerDimensionPath(1, savePath.resolve("DIM1"));
}
public static void registerDimensionPath(int dimensionId, Path dimensionDataRoot) {
checkNotNull(dimensionDataRoot);
dimensionPathByDimensionId.put(dimensionId, dimensionDataRoot);
}
public static Optional<Path> getDimensionPath(int dimensionId) {
return Optional.ofNullable(dimensionPathByDimensionId.get(dimensionId));
}
public static Optional<DimensionType> getDimensionType(int dimensionId) {
return Optional.ofNullable(dimensionTypeByDimensionId.get(dimensionId));
}
public static Optional<DimensionType> getDimensionType(Class<? extends WorldProvider> providerClass) {
checkNotNull(providerClass);
for (Object rawDimensionType : dimensionTypeByTypeId.values()) {
final DimensionType dimensionType = (DimensionType) rawDimensionType;
if (((org.spongepowered.api.world.DimensionType) (Object) dimensionType).getDimensionClass().equals(providerClass)) {
return Optional.of(dimensionType);
}
}
return Optional.empty();
}
public static Collection<DimensionType> getDimensionTypes() {
return dimensionTypeByTypeId.values();
}
public static int[] getRegisteredDimensionIdsFor(DimensionType type) {
return dimensionTypeByDimensionId.int2ObjectEntrySet().stream()
.filter(entry -> entry.getValue().equals(type))
.mapToInt(Int2ObjectMap.Entry::getIntKey)
.toArray();
}
public static int[] getRegisteredDimensionIds() {
return dimensionTypeByTypeId.keySet().toIntArray();
}
public static Optional<Path> getWorldFolder(DimensionType dimensionType, int dimensionId) {
return Optional.ofNullable(dimensionPathByDimensionId.get(dimensionId));
}
public static boolean isDimensionRegistered(int dimensionId) {
return dimensionTypeByDimensionId.containsKey(dimensionId);
}
public static Map<Integer, DimensionType> sortedDimensionMap() {
Int2ObjectMap<DimensionType> copy = new Int2ObjectOpenHashMap<>(dimensionTypeByDimensionId);
HashMap<Integer, DimensionType> newMap = new LinkedHashMap<>();
newMap.put(0, copy.remove(0));
newMap.put(-1, copy.remove(-1));
newMap.put(1, copy.remove(1));
int[] ids = copy.keySet().toIntArray();
Arrays.sort(ids);
for (int id : ids) {
newMap.put(id, copy.get(id));
}
return newMap;
}
public static ObjectIterator<Int2ObjectMap.Entry<WorldServer>> worldsIterator() {
return worldByDimensionId.int2ObjectEntrySet().fastIterator();
}
public static Collection<WorldServer> getWorlds() {
return worldByDimensionId.values();
}
public static Optional<WorldServer> getWorldByDimensionId(int dimensionId) {
return Optional.ofNullable(worldByDimensionId.get(dimensionId));
}
public static Optional<String> getWorldFolderByDimensionId(int dimensionId) {
return Optional.ofNullable(worldFolderByDimensionId.get(dimensionId));
}
public static int[] getLoadedWorldDimensionIds() {
return worldByDimensionId.keySet().toIntArray();
}
public static Optional<WorldServer> getWorld(String worldName) {
for (WorldServer worldServer : getWorlds()) {
final org.spongepowered.api.world.World apiWorld = (org.spongepowered.api.world.World) worldServer;
if (apiWorld.getName().equals(worldName)) {
return Optional.of(worldServer);
}
}
return Optional.empty();
}
public static void registerWorldProperties(WorldProperties properties) {
checkNotNull(properties);
worldPropertiesByFolderName.put(properties.getWorldName(), properties);
worldPropertiesByWorldUuid.put(properties.getUniqueId(), properties);
worldUuidByFolderName.put(properties.getWorldName(), properties.getUniqueId());
worldFolderByDimensionId.put(((IMixinWorldInfo) properties).getDimensionId(), properties.getWorldName());
}
public static void unregisterWorldProperties(WorldProperties properties, boolean freeDimensionId) {
checkNotNull(properties);
worldPropertiesByFolderName.remove(properties.getWorldName());
worldPropertiesByWorldUuid.remove(properties.getUniqueId());
worldUuidByFolderName.remove(properties.getWorldName());
if (((IMixinWorldInfo) properties).getDimensionId() != null && freeDimensionId) {
dimensionBits.clear(((IMixinWorldInfo) properties).getDimensionId());
}
}
// used by SpongeForge client
public static void unregisterAllWorldSettings() {
worldPropertiesByFolderName.clear();
worldPropertiesByWorldUuid.clear();
worldUuidByFolderName.clear();
worldByDimensionId.clear();
worldFolderByDimensionId.clear();
dimensionTypeByDimensionId.clear();
dimensionPathByDimensionId.clear();
dimensionBits.clear();
weakWorldByWorld.clear();
unregisterableDimensions.clear();
isVanillaRegistered = false;
// This is needed to ensure that DimensionType is usable by GuiListWorldSelection, which is only ever used when the server isn't running
registerVanillaTypesAndDimensions();
}
public static Optional<WorldProperties> getWorldProperties(String folderName) {
checkNotNull(folderName);
return Optional.ofNullable(worldPropertiesByFolderName.get(folderName));
}
public static Collection<WorldProperties> getAllWorldProperties() {
return Collections.unmodifiableCollection(worldPropertiesByFolderName.values());
}
public static Optional<WorldProperties> getWorldProperties(UUID uuid) {
checkNotNull(uuid);
return Optional.ofNullable(worldPropertiesByWorldUuid.get(uuid));
}
public static Optional<UUID> getUuidForFolder(String folderName) {
checkNotNull(folderName);
return Optional.ofNullable(worldUuidByFolderName.get(folderName));
}
public static Optional<String> getFolderForUuid(UUID uuid) {
checkNotNull(uuid);
return Optional.ofNullable(worldUuidByFolderName.inverse().get(uuid));
}
public static WorldProperties createWorldProperties(String folderName, WorldArchetype archetype) {
checkNotNull(folderName);
checkNotNull(archetype);
final Optional<WorldServer> optWorldServer = getWorld(folderName);
if (optWorldServer.isPresent()) {
return ((org.spongepowered.api.world.World) optWorldServer.get()).getProperties();
}
final Optional<WorldProperties> optWorldProperties = WorldManager.getWorldProperties(folderName);
if (optWorldProperties.isPresent()) {
return optWorldProperties.get();
}
final ISaveHandler saveHandler = new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), folderName, true, SpongeImpl
.getServer().getDataFixer());
WorldInfo worldInfo = saveHandler.loadWorldInfo();
if (worldInfo == null) {
worldInfo = new WorldInfo((WorldSettings) (Object) archetype, folderName);
} else {
// DimensionType must be set before world config is created to get proper path
((IMixinWorldInfo) worldInfo).setDimensionType(archetype.getDimensionType());
((IMixinWorldInfo) worldInfo).createWorldConfig();
((WorldProperties) worldInfo).setGeneratorModifiers(archetype.getGeneratorModifiers());
}
setUuidOnProperties(getCurrentSavesDirectory().get(), (WorldProperties) worldInfo);
if (((IMixinWorldInfo) worldInfo).getDimensionId() == null || ((IMixinWorldInfo) worldInfo).getDimensionId() == Integer.MIN_VALUE) {
((IMixinWorldInfo) worldInfo).setDimensionId(WorldManager.getNextFreeDimensionId());
}
((WorldProperties) worldInfo).setGeneratorType(archetype.getGeneratorType());
((IMixinWorldInfo) worldInfo).getWorldConfig().save();
registerWorldProperties((WorldProperties) worldInfo);
SpongeImpl.postEvent(SpongeEventFactory.createConstructWorldPropertiesEvent(Cause.of(NamedCause.source(Sponge.getServer())), archetype,
(WorldProperties) worldInfo));
saveHandler.saveWorldInfoWithPlayer(worldInfo, SpongeImpl.getServer().getPlayerList().getHostPlayerData());
return (WorldProperties) worldInfo;
}
public static boolean saveWorldProperties(WorldProperties properties) {
checkNotNull(properties);
final Optional<WorldServer> optWorldServer = getWorldByDimensionId(((IMixinWorldInfo) properties).getDimensionId());
// If the World represented in the properties is still loaded, save the properties and have the World reload its info
if (optWorldServer.isPresent()) {
final WorldServer worldServer = optWorldServer.get();
worldServer.getSaveHandler().saveWorldInfo((WorldInfo) properties);
worldServer.getSaveHandler().loadWorldInfo();
} else {
new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), properties.getWorldName(), true, SpongeImpl.getServer()
.getDataFixer()).saveWorldInfo((WorldInfo) properties);
}
// No return values or exceptions so can only assume true.
return true;
}
public static void unloadQueuedWorlds() {
while (unloadQueue.peek() != null) {
unloadWorld(unloadQueue.poll(), true);
}
unloadQueue.clear();
}
public static void queueWorldToUnload(WorldServer worldServer) {
checkNotNull(worldServer);
unloadQueue.add(worldServer);
}
// TODO Result
public static boolean unloadWorld(WorldServer worldServer, boolean checkConfig) {
checkNotNull(worldServer);
final MinecraftServer server = SpongeImpl.getServer();
// Likely leaked, don't want to drop leaked world data
if (!worldByDimensionId.containsValue(worldServer)) {
return false;
}
// Vanilla sometimes doesn't remove player entities from world first
if (server.isServerRunning()) {
if (!worldServer.playerEntities.isEmpty()) {
return false;
}
// We only check config if base game wants to unload world. If mods/plugins say unload, we unload
if (checkConfig) {
if (((IMixinWorldServer) worldServer).getActiveConfig().getConfig().getWorld().getKeepSpawnLoaded()) {
return false;
}
}
}
final IMixinWorldServer mixinWorldServer = (IMixinWorldServer) worldServer;
final int dimensionId = mixinWorldServer.getDimensionId();
try {
// Don't save if server is stopping to avoid duplicate saving.
if (server.isServerRunning()) {
saveWorld(worldServer, true);
mixinWorldServer.getActiveConfig().save();
}
} catch (MinecraftException e) {
e.printStackTrace();
} finally {
worldByDimensionId.remove(dimensionId);
weakWorldByWorld.remove(worldServer);
((IMixinMinecraftServer) server).removeWorldTickTimes(dimensionId);
SpongeImpl.getLogger().info("Unloading world [{}] (DIM{})", worldServer.getWorldInfo().getWorldName(), dimensionId);
reorderWorldsVanillaFirst();
}
SpongeImpl.postEvent(SpongeEventFactory.createUnloadWorldEvent(Cause.of(NamedCause.source(server)), (org.spongepowered.api.world.World)
worldServer));
if (!server.isServerRunning() && unregisterableDimensions.contains(dimensionId)) {
unregisterDimension(dimensionId);
}
return true;
}
public static void saveWorld(WorldServer worldServer, boolean flush) throws MinecraftException {
worldServer.saveAllChunks(true, null);
if (flush) {
worldServer.flush();
}
}
public static Collection<WorldProperties> getUnloadedWorlds() throws IOException {
final Optional<Path> optCurrentSavesDir = getCurrentSavesDirectory();
checkState(optCurrentSavesDir.isPresent(), "Attempt made to get unloaded worlds too early!");
final List<WorldProperties> worlds = new ArrayList<>();
try (final DirectoryStream<Path> stream = Files.newDirectoryStream(optCurrentSavesDir.get(), LEVEL_AND_SPONGE)) {
for (Path worldFolder : stream) {
final String worldFolderName = worldFolder.getFileName().toString();
final WorldInfo worldInfo = new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), worldFolderName, true,
SpongeImpl.getServer().getDataFixer()).loadWorldInfo();
if (worldInfo != null) {
worlds.add((WorldProperties) worldInfo);
}
}
}
return worlds;
}
public static Optional<WorldServer> loadWorld(UUID uuid) {
checkNotNull(uuid);
// If someone tries to load loaded world, return it
Sponge.getServer().getWorld(uuid).ifPresent(Optional::of);
// Check if we even know of this UUID's folder
final String worldFolder = worldUuidByFolderName.inverse().get(uuid);
// We don't know of this UUID at all. TODO Search files?
if (worldFolder == null) {
return Optional.empty();
}
return loadWorld(worldFolder, null, null);
}
public static Optional<WorldServer> loadWorld(String worldName) {
checkNotNull(worldName);
return loadWorld(worldName, null, null);
}
public static Optional<WorldServer> loadWorld(WorldProperties properties) {
checkNotNull(properties);
return loadWorld(properties.getWorldName(), null, properties);
}
private static Optional<WorldServer> loadWorld(String worldName, @Nullable ISaveHandler saveHandler, @Nullable WorldProperties properties) {
checkNotNull(worldName);
final Path currentSavesDir = WorldManager.getCurrentSavesDirectory().orElseThrow(() -> new IllegalStateException("Attempt "
+ "made to load world too early!"));
final MinecraftServer server = SpongeImpl.getServer();
final Optional<WorldServer> optExistingWorldServer = getWorld(worldName);
if (optExistingWorldServer.isPresent()) {
return optExistingWorldServer;
}
if (!server.getAllowNether()) {
SpongeImpl.getLogger().error("Unable to load world [{}]. Multi-world is disabled via [allow-nether] in [server.properties].", worldName);
return Optional.empty();
}
final Path worldFolder = currentSavesDir.resolve(worldName);
if (!Files.isDirectory(worldFolder)) {
SpongeImpl.getLogger().error("Unable to load world [{}]. We cannot find its folder under [{}].", worldFolder, currentSavesDir);
return Optional.empty();
}
if (saveHandler == null) {
saveHandler = new AnvilSaveHandler(currentSavesDir.toFile(), worldName, true, SpongeImpl.getServer()
.getDataFixer());
}
// We weren't given a properties, see if one is cached
if (properties == null) {
properties = (WorldProperties) saveHandler.loadWorldInfo();
// We tried :'(
if (properties == null) {
SpongeImpl.getLogger().error("Unable to load world [{}]. No world properties was found!", worldName);
return Optional.empty();
}
}
if (((IMixinWorldInfo) properties).getDimensionId() == null || ((IMixinWorldInfo) properties).getDimensionId() == Integer.MIN_VALUE) {
((IMixinWorldInfo) properties).setDimensionId(getNextFreeDimensionId());
}
setUuidOnProperties(getCurrentSavesDirectory().get(), properties);
registerWorldProperties(properties);
final WorldInfo worldInfo = (WorldInfo) properties;
((IMixinWorldInfo) worldInfo).createWorldConfig();
// check if enabled
if (!((WorldProperties) worldInfo).isEnabled()) {
SpongeImpl.getLogger().error("Unable to load world [{}]. It is disabled.", worldName);
return Optional.empty();
}
final int dimensionId = ((IMixinWorldInfo) properties).getDimensionId();
registerDimension(dimensionId, (DimensionType) (Object) properties.getDimensionType(), true);
registerDimensionPath(dimensionId, worldFolder);
SpongeImpl.getLogger().info("Loading world [{}] ({})", properties.getWorldName(), getDimensionType
(dimensionId).get().getName());
final WorldServer worldServer = createWorldFromProperties(dimensionId, saveHandler, (WorldInfo) properties, new WorldSettings((WorldInfo)
properties));
return Optional.of(worldServer);
}
public static void loadAllWorlds(String worldName, long defaultSeed, WorldType defaultWorldType, String generatorOptions) {
final MinecraftServer server = SpongeImpl.getServer();
// We cannot call getCurrentSavesDirectory here as that would generate a savehandler and trigger a session lock.
// We'll go ahead and make the directories for the save name here so that the migrator won't fail
final Path currentSavesDir = server.anvilFile.toPath().resolve(server.getFolderName());
try {
// Symlink needs special handling
if (Files.isSymbolicLink(currentSavesDir)) {
final Path actualPathLink = Files.readSymbolicLink(currentSavesDir);
if (Files.notExists(actualPathLink)) {
// TODO Need to test symlinking to see if this is even legal...
Files.createDirectories(actualPathLink);
} else if (!Files.isDirectory(actualPathLink)) {
throw new IOException("Saves directory [" + currentSavesDir + "] symlinked to [" + actualPathLink + "] is not a directory!");
}
} else {
Files.createDirectories(currentSavesDir);
}
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
WorldManager.registerVanillaDimensionPaths(currentSavesDir);
WorldMigrator.migrateWorldsTo(currentSavesDir);
registerExistingSpongeDimensions(currentSavesDir);
for (Map.Entry<Integer, DimensionType> entry: sortedDimensionMap().entrySet()) {
final int dimensionId = entry.getKey();
final DimensionType dimensionType = entry.getValue();
// Skip all worlds besides dimension 0 if multi-world is disabled
if (dimensionId != 0 && !server.getAllowNether()) {
continue;
}
// Skip already loaded worlds by plugins
if (getWorldByDimensionId(dimensionId).isPresent()) {
continue;
}
// Step 1 - Grab the world's data folder
final Optional<Path> optWorldFolder = getWorldFolder(dimensionType, dimensionId);
if (!optWorldFolder.isPresent()) {
SpongeImpl.getLogger().error("An attempt was made to load a world with dimension id [{}] that has no registered world folder!",
dimensionId);
continue;
}
final Path worldFolder = optWorldFolder.get();
final String worldFolderName = worldFolder.getFileName().toString();
// Step 2 - See if we are allowed to load it
if (dimensionId != 0) {
final SpongeConfig<?> activeConfig = SpongeHooks.getActiveConfig(((IMixinDimensionType)(Object) dimensionType).getConfigPath(), worldFolderName);
if (!activeConfig.getConfig().getWorld().isWorldEnabled()) {
SpongeImpl.getLogger().warn("World [{}] (DIM{}) is disabled. World will not be loaded...", worldFolder,
dimensionId);
continue;
}
}
// Step 3 - Get our world information from disk
final ISaveHandler saveHandler;
if (dimensionId == 0) {
saveHandler = server.getActiveAnvilConverter().getSaveLoader(server.getFolderName(), true);
} else {
saveHandler = new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), worldFolderName, true, server
.getDataFixer());
}
WorldInfo worldInfo = saveHandler.loadWorldInfo();
WorldSettings worldSettings;
// If this is integrated server, we need to use the WorldSettings from the client's Single Player menu to construct the worlds
if (server instanceof IMixinIntegratedServer) {
worldSettings = ((IMixinIntegratedServer) server).getSettings();
// If this is overworld and a new save, the WorldInfo has already been made but we want to still fire the construct event.
if (dimensionId == 0 && ((IMixinIntegratedServer) server).isNewSave()) {
SpongeImpl.postEvent(SpongeEventFactory.createConstructWorldPropertiesEvent(Cause.of(NamedCause.source(server)), (WorldArchetype)
(Object) worldSettings, (WorldProperties) worldInfo));
}
} else {
// WorldSettings will be null here on dedicated server so we need to build one
worldSettings = new WorldSettings(defaultSeed, server.getGameType(), server.canStructuresSpawn(), server.isHardcore(),
defaultWorldType);
}
if (worldInfo == null) {
// Step 4 - At this point, we have either have the WorldInfo or we have none. If we have none, we'll use the settings built above to
// create the WorldInfo
worldInfo = createWorldInfoFromSettings(currentSavesDir, (org.spongepowered.api.world.DimensionType) (Object) dimensionType,
dimensionId, worldFolderName, worldSettings, generatorOptions);
} else {
// create config
((IMixinWorldInfo) worldInfo).setDimensionType((org.spongepowered.api.world.DimensionType)(Object) dimensionType);
((IMixinWorldInfo) worldInfo).createWorldConfig();
((WorldProperties) worldInfo).setGenerateSpawnOnLoad(((IMixinDimensionType)(Object) dimensionType).shouldGenerateSpawnOnLoad());
}
// Safety check to ensure we'll get a unique id no matter what
if (((WorldProperties) worldInfo).getUniqueId() == null) {
setUuidOnProperties(dimensionId == 0 ? currentSavesDir.getParent() : currentSavesDir, (WorldProperties) worldInfo);
}
// Safety check to ensure the world info has the dimension id set
if (((IMixinWorldInfo) worldInfo).getDimensionId() == null) {
((IMixinWorldInfo) worldInfo).setDimensionId(dimensionId);
}
// Keep the LevelName in the LevelInfo up to date with the directory name
if (!worldInfo.getWorldName().equals(worldFolderName)) {
worldInfo.setWorldName(worldFolderName);
}
// Step 5 - Load server resource pack from dimension 0
if (dimensionId == 0) {
server.setResourcePackFromWorld(worldFolderName, saveHandler);
}
// Step 6 - Cache the WorldProperties we've made so we don't load from disk later.
registerWorldProperties((WorldProperties) worldInfo);
if (dimensionId != 0 && !((WorldProperties) worldInfo).loadOnStartup()) {
SpongeImpl.getLogger().warn("World [{}] (DIM{}) is set to not load on startup. To load it later, enable [load-on-startup] in config "
+ "or use a plugin", worldFolder, dimensionId);
continue;
}
// Step 7 - Finally, we can create the world and tell it to load
final WorldServer worldServer = createWorldFromProperties(dimensionId, saveHandler, worldInfo, worldSettings);
SpongeImpl.getLogger().info("Loading world [{}] ({})", ((org.spongepowered.api.world.World) worldServer).getName(), getDimensionType
(dimensionId).get().getName());
}
}
public static WorldInfo createWorldInfoFromSettings(Path currentSaveRoot, org.spongepowered.api.world.DimensionType dimensionType, int
dimensionId, String worldFolderName, WorldSettings worldSettings, String generatorOptions) {
final MinecraftServer server = SpongeImpl.getServer();
worldSettings.setGeneratorOptions(generatorOptions);
((IMixinWorldSettings) (Object) worldSettings).setDimensionType(dimensionType);
((IMixinWorldSettings)(Object) worldSettings).setGenerateSpawnOnLoad(((IMixinDimensionType) dimensionType).shouldGenerateSpawnOnLoad());
final WorldInfo worldInfo = new WorldInfo(worldSettings, worldFolderName);
setUuidOnProperties(dimensionId == 0 ? currentSaveRoot.getParent() : currentSaveRoot, (WorldProperties) worldInfo);
((IMixinWorldInfo) worldInfo).setDimensionId(dimensionId);
SpongeImpl.postEvent(SpongeEventFactory.createConstructWorldPropertiesEvent(Cause.of(NamedCause.source(server)),
(WorldArchetype) (Object) worldSettings, (WorldProperties) worldInfo));
return worldInfo;
}
public static WorldServer createWorldFromProperties(int dimensionId, ISaveHandler saveHandler, WorldInfo worldInfo, @Nullable WorldSettings
worldSettings) {
final MinecraftServer server = SpongeImpl.getServer();
final WorldServer worldServer;
if (dimensionId == 0) {
worldServer = new WorldServer(server, saveHandler, worldInfo, dimensionId, server.theProfiler);
} else {
final WorldServerMultiAdapterWorldInfo info = new WorldServerMultiAdapterWorldInfo(saveHandler, worldInfo);
worldServer = new WorldServerMulti(server, info, dimensionId, worldByDimensionId.get(0), server.theProfiler);
}
worldServer.init();
// WorldSettings is only non-null here if this is a newly generated WorldInfo and therefore we need to initialize to calculate spawn.
if (worldSettings != null) {
worldServer.initialize(worldSettings);
}
worldServer.addEventListener(new ServerWorldEventHandler(server, worldServer));
// This code changes from Mojang's to account for per-world API-set GameModes.
if (!server.isSinglePlayer() && worldServer.getWorldInfo().getGameType().equals(GameType.NOT_SET)) {
worldServer.getWorldInfo().setGameType(server.getGameType());
}
worldByDimensionId.put(dimensionId, worldServer);
weakWorldByWorld.put(worldServer, worldServer);
((IMixinMinecraftServer) SpongeImpl.getServer()).putWorldTickTimes(dimensionId, new long[100]);
// Set the worlds on the Minecraft server
reorderWorldsVanillaFirst();
SpongeImpl.postEvent(SpongeEventFactory.createLoadWorldEvent(Cause.of(NamedCause.source(Sponge.getServer())),
(org.spongepowered.api.world.World) worldServer));
((IMixinMinecraftServer) server).prepareSpawnArea(worldServer);
return worldServer;
}
/**
* Internal use only - Namely for SpongeForge.
* @param dimensionId The world instance dimension id
* @param worldServer The world server
*/
public static void forceAddWorld(int dimensionId, WorldServer worldServer) {
worldByDimensionId.put(dimensionId, worldServer);
weakWorldByWorld.put(worldServer, worldServer);
((IMixinMinecraftServer) SpongeImpl.getServer()).putWorldTickTimes(dimensionId, new long[100]);
}
public static void reorderWorldsVanillaFirst() {
final List<WorldServer> worlds = new ArrayList<>(worldByDimensionId.values());
final List<WorldServer> sorted = new LinkedList<>();
int vanillaWorldsCount = 0;
WorldServer worldServer = worldByDimensionId.get(0);
if (worldServer != null) {
sorted.add(worldServer);
vanillaWorldsCount++;
}
worldServer = worldByDimensionId.get(-1);
if (worldServer != null) {
sorted.add(worldServer);
vanillaWorldsCount++;
}
worldServer = worldByDimensionId.get(1);
if (worldServer != null) {
sorted.add(worldServer);
vanillaWorldsCount++;
}
final List<WorldServer> nonVanillaWorlds = worlds.subList(vanillaWorldsCount, worlds.size());
nonVanillaWorlds.sort(WORLD_SERVER_COMPARATOR);
sorted.addAll(nonVanillaWorlds);
SpongeImpl.getServer().worlds = sorted.toArray(new WorldServer[sorted.size()]);
}
/**
* Parses a {@link UUID} from disk from other known plugin platforms and sets it on the
* {@link WorldProperties}. Currently only Bukkit is supported.
*/
public static UUID setUuidOnProperties(Path savesRoot, WorldProperties properties) {
checkNotNull(properties);
UUID uuid;
if (properties.getUniqueId() == null || properties.getUniqueId().equals
(UUID.fromString("00000000-0000-0000-0000-000000000000"))) {
// Check if Bukkit's uid.dat file is here and use it
final Path uidPath = savesRoot.resolve(properties.getWorldName()).resolve("uid.dat");
if (Files.notExists(uidPath)) {
uuid = UUID.randomUUID();
} else {
try(final DataInputStream dis = new DataInputStream(Files.newInputStream(uidPath))) {
uuid = new UUID(dis.readLong(), dis.readLong());
} catch (IOException e) {
SpongeImpl.getLogger().error("World folder [{}] has an existing Bukkit unique identifier for it but we encountered issues parsing "
+ "the file. We will have to use a new unique id. Please report this to Sponge ASAP.", properties.getWorldName(), e);
uuid = UUID.randomUUID();
}
}
} else {
uuid = properties.getUniqueId();
}
((IMixinWorldInfo) properties).setUniqueId(uuid);
return uuid;
}
/**
* Handles registering existing Sponge dimensions that are not the root dimension (known as overworld).
*/
private static void registerExistingSpongeDimensions(Path rootPath) {
try (final DirectoryStream<Path> stream = Files.newDirectoryStream(rootPath, LEVEL_AND_SPONGE)) {
for (Path worldPath : stream) {
final Path spongeLevelPath = worldPath.resolve("level_sponge.dat");
final String worldFolderName = worldPath.getFileName().toString();
NBTTagCompound compound;
try {
compound = CompressedStreamTools.readCompressed(Files.newInputStream(spongeLevelPath));
} catch (IOException e) {
SpongeImpl.getLogger().error("Failed loading Sponge data for World [{}]}. Report to Sponge ASAP.", worldFolderName, e);
continue;
}
NBTTagCompound spongeDataCompound = compound.getCompoundTag(NbtDataUtil.SPONGE_DATA);
if (!compound.hasKey(NbtDataUtil.SPONGE_DATA)) {
SpongeImpl.getLogger()
.error("World [{}] has Sponge related data in the form of [level-sponge.dat] but the structure is not proper."
+ " Generally, the data is within a [{}] tag but it is not for this world. Report to Sponge ASAP.",
worldFolderName, NbtDataUtil.SPONGE_DATA);
continue;
}
if (!spongeDataCompound.hasKey(NbtDataUtil.DIMENSION_ID)) {
SpongeImpl.getLogger().error("World [{}] has no dimension id. Report this to Sponge ASAP.", worldFolderName);
continue;
}
int dimensionId = spongeDataCompound.getInteger(NbtDataUtil.DIMENSION_ID);
if (dimensionId == Integer.MIN_VALUE) {
// temporary fix for existing worlds created with wrong dimension id
dimensionId = WorldManager.getNextFreeDimensionId();
}
// We do not handle Vanilla dimensions, skip them
if (dimensionId == 0 || dimensionId == -1 || dimensionId == 1) {
continue;
}
spongeDataCompound = DataUtil.spongeDataFixer.process(FixTypes.LEVEL, spongeDataCompound);
String dimensionTypeId = "overworld";
if (spongeDataCompound.hasKey(NbtDataUtil.DIMENSION_TYPE)) {
dimensionTypeId = spongeDataCompound.getString(NbtDataUtil.DIMENSION_TYPE);
} else {
SpongeImpl.getLogger().warn("World [{}] (DIM{}) has no specified dimension type. Defaulting to [{}}]...", worldFolderName,
dimensionId, DimensionTypes.OVERWORLD.getName());
}
dimensionTypeId = fixDimensionTypeId(dimensionTypeId);
org.spongepowered.api.world.DimensionType dimensionType
= Sponge.getRegistry().getType(org.spongepowered.api.world.DimensionType.class, dimensionTypeId).orElse(null);
if (dimensionType == null) {
SpongeImpl.getLogger().warn("World [{}] (DIM{}) has specified dimension type that is not registered. Skipping...",
worldFolderName, dimensionId);
continue;
}
spongeDataCompound.setString(NbtDataUtil.DIMENSION_TYPE, dimensionTypeId);
if (!spongeDataCompound.hasUniqueId(NbtDataUtil.UUID)) {
SpongeImpl.getLogger().error("World [{}] (DIM{}) has no valid unique identifier. This is a critical error and should be reported"
+ " to Sponge ASAP.", worldFolderName, dimensionId);
continue;
}
if (isDimensionRegistered(dimensionId)) {
SpongeImpl.getLogger().error("Unable to register dim id ({}) from world folder [{}]. This dim id has already been registered "
+ "from world folder [{}].", dimensionId, worldFolderName, worldFolderByDimensionId.get(dimensionId));
continue;
}
worldFolderByDimensionId.put(dimensionId, worldFolderName);
registerDimension(dimensionId, (DimensionType)(Object) dimensionType, true);
registerDimensionPath(dimensionId, rootPath.resolve(worldFolderName));
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Checks if the saved dimension type contains a modid and if not, attempts to locate one
public static String fixDimensionTypeId(String name) {
// Since we now store the modid, we need to support older save files that only include id without modid.
if (!name.contains(":")) {
for (org.spongepowered.api.world.DimensionType type : Sponge.getRegistry().getAllOf(org.spongepowered.api.world.DimensionType.class)) {
String typeId = (type.getId().substring(type.getId().lastIndexOf(":") + 1));
if (typeId.equals(name)) {
return type.getId();
// Note: We don't update the NBT here but instead fix it on next
// world save in case there are 2 types using same name.
}
}
}
return name;
}
public static CompletableFuture<Optional<WorldProperties>> copyWorld(WorldProperties worldProperties, String copyName) {
checkArgument(worldPropertiesByFolderName.containsKey(worldProperties.getWorldName()), "World properties not registered!");
checkArgument(!worldPropertiesByFolderName.containsKey(copyName), "Destination world name already is registered!");
final WorldInfo info = (WorldInfo) worldProperties;
final WorldServer worldServer = worldByDimensionId.get(((IMixinWorldInfo) info).getDimensionId().intValue());
if (worldServer != null) {
try {
saveWorld(worldServer, true);
} catch (MinecraftException e) {
Throwables.propagate(e);
}
((IMixinMinecraftServer) SpongeImpl.getServer()).setSaveEnabled(false);
}
final CompletableFuture<Optional<WorldProperties>> future = SpongeScheduler.getInstance().submitAsyncTask(new CopyWorldTask(info, copyName));
if (worldServer != null) { // World was loaded
future.thenRun(() -> ((IMixinMinecraftServer) SpongeImpl.getServer()).setSaveEnabled(true));
}
return future;
}
public static Optional<WorldProperties> renameWorld(WorldProperties worldProperties, String newName) {
checkNotNull(worldProperties);
checkNotNull(newName);
checkState(!worldByDimensionId.containsKey(((IMixinWorldInfo) worldProperties).getDimensionId()), "World is still loaded!");
final Path oldWorldFolder = getCurrentSavesDirectory().get().resolve(worldProperties.getWorldName());
final Path newWorldFolder = oldWorldFolder.resolveSibling(newName);
if (Files.exists(newWorldFolder)) {
return Optional.empty();
}
try {
Files.move(oldWorldFolder, newWorldFolder);
} catch (IOException e) {
return Optional.empty();
}
unregisterWorldProperties(worldProperties, false);
final WorldInfo info = new WorldInfo((WorldInfo) worldProperties);
info.setWorldName(newName);
((IMixinWorldInfo) info).createWorldConfig();
new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), newName, true, SpongeImpl.getServer().getDataFixer())
.saveWorldInfo(info);
registerWorldProperties((WorldProperties) info);
return Optional.of((WorldProperties) info);
}
public static CompletableFuture<Boolean> deleteWorld(WorldProperties worldProperties) {
checkNotNull(worldProperties);
checkArgument(worldPropertiesByWorldUuid.containsKey(worldProperties.getUniqueId()), "World properties not registered!");
checkState(!worldByDimensionId.containsKey(((IMixinWorldInfo) worldProperties).getDimensionId()), "World not unloaded!");
return SpongeScheduler.getInstance().submitAsyncTask(new DeleteWorldTask(worldProperties));
}
private static class CopyWorldTask implements Callable<Optional<WorldProperties>> {
private final WorldInfo oldInfo;
private final String newName;
public CopyWorldTask(WorldInfo info, String newName) {
this.oldInfo = info;
this.newName = newName;
}
@Override
public Optional<WorldProperties> call() throws Exception {
Path oldWorldFolder = getCurrentSavesDirectory().get().resolve(this.oldInfo.getWorldName());
final Path newWorldFolder = getCurrentSavesDirectory().get().resolve(this.newName);
if (Files.exists(newWorldFolder)) {
return Optional.empty();
}
FileVisitor<Path> visitor = new CopyFileVisitor(newWorldFolder);
if (((IMixinWorldInfo) this.oldInfo).getDimensionId() == 0) {
oldWorldFolder = getCurrentSavesDirectory().get();
visitor = new ForwardingFileVisitor<Path>(visitor) {
private boolean root = true;
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (!this.root && Files.exists(dir.resolve("level.dat"))) {
return FileVisitResult.SKIP_SUBTREE;
}
this.root = false;
return super.preVisitDirectory(dir, attrs);
}
};
}
// Copy the world folder
Files.walkFileTree(oldWorldFolder, visitor);
final WorldInfo info = new WorldInfo(this.oldInfo);
info.setWorldName(this.newName);
((IMixinWorldInfo) info).setDimensionId(getNextFreeDimensionId());
((IMixinWorldInfo) info).setUniqueId(UUID.randomUUID());
((IMixinWorldInfo) info).createWorldConfig();
registerWorldProperties((WorldProperties) info);
new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), newName, true, SpongeImpl.getServer().getDataFixer())
.saveWorldInfo(info);
return Optional.of((WorldProperties) info);
}
}
private static class DeleteWorldTask implements Callable<Boolean> {
private final WorldProperties props;
public DeleteWorldTask(WorldProperties props) {
this.props = props;
}
@Override
public Boolean call() throws Exception {
final Path worldFolder = getCurrentSavesDirectory().get().resolve(props.getWorldName());
if (!Files.exists(worldFolder)) {
unregisterWorldProperties(this.props, true);
return true;
}
try {
Files.walkFileTree(worldFolder, DeleteFileVisitor.INSTANCE);
unregisterWorldProperties(this.props, true);
return true;
} catch (IOException e) {
return false;
}
}
}
public static void sendDimensionRegistration(EntityPlayerMP playerMP, WorldProvider provider) {
// Do nothing in Common
}
public static void loadDimensionDataMap(@Nullable NBTTagCompound compound) {
dimensionBits.clear();
if (compound == null) {
dimensionTypeByDimensionId.keySet().stream().filter(dimensionId -> dimensionId >= 0).forEach(dimensionBits::set);
} else {
final int[] intArray = compound.getIntArray("DimensionArray");
for (int i = 0; i < intArray.length; i++) {
for (int j = 0; j < Integer.SIZE; j++) {
dimensionBits.set(i * Integer.SIZE + j, (intArray[i] & (1 << j)) != 0);
}
}
}
}
public static NBTTagCompound saveDimensionDataMap() {
int[] data = new int[(dimensionBits.length() + Integer.SIZE - 1 )/ Integer.SIZE];
NBTTagCompound dimMap = new NBTTagCompound();
for (int i = 0; i < data.length; i++) {
int val = 0;
for (int j = 0; j < Integer.SIZE; j++) {
val |= dimensionBits.get(i * Integer.SIZE + j) ? (1 << j) : 0;
}
data[i] = val;
}
dimMap.setIntArray("DimensionArray", data);
return dimMap;
}
public static Optional<Path> getCurrentSavesDirectory() {
final Optional<WorldServer> optWorldServer = getWorldByDimensionId(0);
if (optWorldServer.isPresent()) {
return Optional.of(optWorldServer.get().getSaveHandler().getWorldDirectory().toPath());
} else if (SpongeImpl.getServer() != null) {
SaveHandler saveHandler = (SaveHandler) SpongeImpl.getServer().getActiveAnvilConverter().getSaveLoader(SpongeImpl.getServer().getFolderName(), false);
return Optional.of(saveHandler.getWorldDirectory().toPath());
}
return Optional.empty();
}
public static Map<WorldServer, WorldServer> getWeakWorldMap() {
return weakWorldByWorld;
}
public static int getClientDimensionId(EntityPlayerMP player, World world) {
if (!((IMixinEntityPlayerMP) player).usesCustomClient()) {
DimensionType type = world.provider.getDimensionType();
if (type == DimensionType.OVERWORLD) {
return 0;
} else if (type == DimensionType.NETHER) {
return -1;
}
return 1;
}
return ((IMixinWorldServer) world).getDimensionId();
}
public static int getDimensionId(WorldServer world) {
return ((IMixinWorldInfo) world.getWorldInfo()).getDimensionId();
}
}
| src/main/java/org/spongepowered/common/world/WorldManager.java | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://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.common.world;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.base.Throwables;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.MapMaker;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.datafix.FixTypes;
import net.minecraft.world.DimensionType;
import net.minecraft.world.GameType;
import net.minecraft.world.MinecraftException;
import net.minecraft.world.ServerWorldEventHandler;
import net.minecraft.world.World;
import net.minecraft.world.WorldProvider;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldServerMulti;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldType;
import net.minecraft.world.chunk.storage.AnvilSaveHandler;
import net.minecraft.world.storage.ISaveHandler;
import net.minecraft.world.storage.SaveHandler;
import net.minecraft.world.storage.WorldInfo;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.NamedCause;
import org.spongepowered.api.util.file.CopyFileVisitor;
import org.spongepowered.api.util.file.DeleteFileVisitor;
import org.spongepowered.api.util.file.ForwardingFileVisitor;
import org.spongepowered.api.world.DimensionTypes;
import org.spongepowered.api.world.WorldArchetype;
import org.spongepowered.api.world.storage.WorldProperties;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.config.SpongeConfig;
import org.spongepowered.common.data.util.DataUtil;
import org.spongepowered.common.data.util.NbtDataUtil;
import org.spongepowered.common.interfaces.IMixinIntegratedServer;
import org.spongepowered.common.interfaces.IMixinMinecraftServer;
import org.spongepowered.common.interfaces.entity.player.IMixinEntityPlayerMP;
import org.spongepowered.common.interfaces.world.IMixinDimensionType;
import org.spongepowered.common.interfaces.world.IMixinWorldInfo;
import org.spongepowered.common.interfaces.world.IMixinWorldServer;
import org.spongepowered.common.interfaces.world.IMixinWorldSettings;
import org.spongepowered.common.scheduler.SpongeScheduler;
import org.spongepowered.common.util.SpongeHooks;
import org.spongepowered.common.world.storage.WorldServerMultiAdapterWorldInfo;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
public final class WorldManager {
public static final DirectoryStream.Filter<Path> LEVEL_AND_SPONGE =
entry -> Files.isDirectory(entry) && Files.exists(entry.resolve("level.dat")) && Files.exists(entry.resolve("level_sponge.dat"));
private static final Int2ObjectMap<DimensionType> dimensionTypeByTypeId = new Int2ObjectOpenHashMap<>(3);
private static final Int2ObjectMap<DimensionType> dimensionTypeByDimensionId = new Int2ObjectOpenHashMap<>(3);
private static final IntSet unregisterableDimensions = new IntOpenHashSet(3);
private static final Int2ObjectMap<Path> dimensionPathByDimensionId = new Int2ObjectOpenHashMap<>(3);
private static final Int2ObjectOpenHashMap<WorldServer> worldByDimensionId = new Int2ObjectOpenHashMap<>(3);
private static final Map<String, WorldProperties> worldPropertiesByFolderName = new HashMap<>(3);
private static final Map<UUID, WorldProperties> worldPropertiesByWorldUuid = new HashMap<>(3);
private static final Map<Integer, String> worldFolderByDimensionId = new HashMap<>();
private static final BiMap<String, UUID> worldUuidByFolderName = HashBiMap.create(3);
private static final BitSet dimensionBits = new BitSet(Long.SIZE << 4);
private static final Map<WorldServer, WorldServer> weakWorldByWorld = new MapMaker().weakKeys().weakValues().concurrencyLevel(1).makeMap();
private static final Queue<WorldServer> unloadQueue = new ArrayDeque<>();
private static final Comparator<WorldServer>
WORLD_SERVER_COMPARATOR =
(world1, world2) -> {
final Integer world1DimId = ((IMixinWorldServer) world1).getDimensionId();
if (world2 == null) {
return world1DimId;
}
final Integer world2DimId = ((IMixinWorldServer) world2).getDimensionId();
return world1DimId - world2DimId;
};
private static boolean isVanillaRegistered = false;
static {
WorldManager.registerVanillaTypesAndDimensions();
}
public static void registerVanillaTypesAndDimensions() {
if (!isVanillaRegistered) {
WorldManager.registerDimensionType(0, DimensionType.OVERWORLD);
WorldManager.registerDimensionType(-1, DimensionType.NETHER);
WorldManager.registerDimensionType(1, DimensionType.THE_END);
WorldManager.registerDimension(0, DimensionType.OVERWORLD, false);
WorldManager.registerDimension(-1, DimensionType.NETHER, false);
WorldManager.registerDimension(1, DimensionType.THE_END, false);
}
isVanillaRegistered = true;
}
public static boolean registerDimensionType(DimensionType type) {
checkNotNull(type);
final Optional<Integer> optNextDimensionTypeId = getNextFreeDimensionTypeId();
return optNextDimensionTypeId.isPresent() && registerDimensionType(optNextDimensionTypeId.get(), type);
}
public static boolean registerDimensionType(int dimensionTypeId, DimensionType type) {
checkNotNull(type);
if (dimensionTypeByTypeId.containsKey(dimensionTypeId)) {
return false;
}
dimensionTypeByTypeId.put(dimensionTypeId, type);
return true;
}
private static Optional<Integer> getNextFreeDimensionTypeId() {
Integer highestDimensionTypeId = null;
for (Integer dimensionTypeId : dimensionTypeByTypeId.keySet()) {
if (highestDimensionTypeId == null || highestDimensionTypeId < dimensionTypeId) {
highestDimensionTypeId = dimensionTypeId;
}
}
if (highestDimensionTypeId != null && highestDimensionTypeId < 127) {
return Optional.of(++highestDimensionTypeId);
}
return Optional.empty();
}
public static Integer getNextFreeDimensionId() {
return dimensionBits.nextClearBit(0);
}
public static boolean registerDimension(int dimensionId, DimensionType type, boolean canBeUnregistered) {
checkNotNull(type);
if (!dimensionTypeByTypeId.containsValue(type)) {
return false;
}
if (dimensionTypeByDimensionId.containsKey(dimensionId)) {
return false;
}
dimensionTypeByDimensionId.put(dimensionId, type);
if (dimensionId >= 0) {
dimensionBits.set(dimensionId);
}
if (canBeUnregistered) {
unregisterableDimensions.add(dimensionId);
}
return true;
}
public static void unregisterDimension(int dimensionId) {
if (!dimensionTypeByDimensionId.containsKey(dimensionId))
{
throw new IllegalArgumentException("Failed to unregister dimension [" + dimensionId + "] as it is not registered!");
}
dimensionTypeByDimensionId.remove(dimensionId);
}
public static void registerVanillaDimensionPaths(final Path savePath) {
WorldManager.registerDimensionPath(0, savePath);
WorldManager.registerDimensionPath(-1, savePath.resolve("DIM-1"));
WorldManager.registerDimensionPath(1, savePath.resolve("DIM1"));
}
public static void registerDimensionPath(int dimensionId, Path dimensionDataRoot) {
checkNotNull(dimensionDataRoot);
dimensionPathByDimensionId.put(dimensionId, dimensionDataRoot);
}
public static Optional<Path> getDimensionPath(int dimensionId) {
return Optional.ofNullable(dimensionPathByDimensionId.get(dimensionId));
}
public static Optional<DimensionType> getDimensionType(int dimensionId) {
return Optional.ofNullable(dimensionTypeByDimensionId.get(dimensionId));
}
public static Optional<DimensionType> getDimensionType(Class<? extends WorldProvider> providerClass) {
checkNotNull(providerClass);
for (Object rawDimensionType : dimensionTypeByTypeId.values()) {
final DimensionType dimensionType = (DimensionType) rawDimensionType;
if (((org.spongepowered.api.world.DimensionType) (Object) dimensionType).getDimensionClass().equals(providerClass)) {
return Optional.of(dimensionType);
}
}
return Optional.empty();
}
public static Collection<DimensionType> getDimensionTypes() {
return dimensionTypeByTypeId.values();
}
public static Integer[] getRegisteredDimensionIdsFor(DimensionType type) {
return (Integer[]) dimensionTypeByDimensionId.entrySet().stream().filter(entry -> entry.getValue().equals(type))
.map(Map.Entry::getKey).collect(Collectors.toList()).toArray();
}
public static int[] getRegisteredDimensionIds() {
return dimensionTypeByTypeId.keySet().toIntArray();
}
public static Optional<Path> getWorldFolder(DimensionType dimensionType, int dimensionId) {
return Optional.ofNullable(dimensionPathByDimensionId.get(dimensionId));
}
public static boolean isDimensionRegistered(int dimensionId) {
return dimensionTypeByDimensionId.containsKey(dimensionId);
}
public static Map<Integer, DimensionType> sortedDimensionMap() {
Int2ObjectMap<DimensionType> copy = new Int2ObjectOpenHashMap<>(dimensionTypeByDimensionId);
HashMap<Integer, DimensionType> newMap = new LinkedHashMap<>();
newMap.put(0, copy.remove(0));
newMap.put(-1, copy.remove(-1));
newMap.put(1, copy.remove(1));
int[] ids = copy.keySet().toIntArray();
Arrays.sort(ids);
for (int id : ids) {
newMap.put(id, copy.get(id));
}
return newMap;
}
public static ObjectIterator<Int2ObjectMap.Entry<WorldServer>> worldsIterator() {
return worldByDimensionId.int2ObjectEntrySet().fastIterator();
}
public static Collection<WorldServer> getWorlds() {
return worldByDimensionId.values();
}
public static Optional<WorldServer> getWorldByDimensionId(int dimensionId) {
return Optional.ofNullable(worldByDimensionId.get(dimensionId));
}
public static Optional<String> getWorldFolderByDimensionId(int dimensionId) {
return Optional.ofNullable(worldFolderByDimensionId.get(dimensionId));
}
public static int[] getLoadedWorldDimensionIds() {
return worldByDimensionId.keySet().toIntArray();
}
public static Optional<WorldServer> getWorld(String worldName) {
for (WorldServer worldServer : getWorlds()) {
final org.spongepowered.api.world.World apiWorld = (org.spongepowered.api.world.World) worldServer;
if (apiWorld.getName().equals(worldName)) {
return Optional.of(worldServer);
}
}
return Optional.empty();
}
public static void registerWorldProperties(WorldProperties properties) {
checkNotNull(properties);
worldPropertiesByFolderName.put(properties.getWorldName(), properties);
worldPropertiesByWorldUuid.put(properties.getUniqueId(), properties);
worldUuidByFolderName.put(properties.getWorldName(), properties.getUniqueId());
worldFolderByDimensionId.put(((IMixinWorldInfo) properties).getDimensionId(), properties.getWorldName());
}
public static void unregisterWorldProperties(WorldProperties properties, boolean freeDimensionId) {
checkNotNull(properties);
worldPropertiesByFolderName.remove(properties.getWorldName());
worldPropertiesByWorldUuid.remove(properties.getUniqueId());
worldUuidByFolderName.remove(properties.getWorldName());
if (((IMixinWorldInfo) properties).getDimensionId() != null && freeDimensionId) {
dimensionBits.clear(((IMixinWorldInfo) properties).getDimensionId());
}
}
// used by SpongeForge client
public static void unregisterAllWorldSettings() {
worldPropertiesByFolderName.clear();
worldPropertiesByWorldUuid.clear();
worldUuidByFolderName.clear();
worldByDimensionId.clear();
worldFolderByDimensionId.clear();
dimensionTypeByDimensionId.clear();
dimensionPathByDimensionId.clear();
dimensionBits.clear();
weakWorldByWorld.clear();
unregisterableDimensions.clear();
isVanillaRegistered = false;
// This is needed to ensure that DimensionType is usable by GuiListWorldSelection, which is only ever used when the server isn't running
registerVanillaTypesAndDimensions();
}
public static Optional<WorldProperties> getWorldProperties(String folderName) {
checkNotNull(folderName);
return Optional.ofNullable(worldPropertiesByFolderName.get(folderName));
}
public static Collection<WorldProperties> getAllWorldProperties() {
return Collections.unmodifiableCollection(worldPropertiesByFolderName.values());
}
public static Optional<WorldProperties> getWorldProperties(UUID uuid) {
checkNotNull(uuid);
return Optional.ofNullable(worldPropertiesByWorldUuid.get(uuid));
}
public static Optional<UUID> getUuidForFolder(String folderName) {
checkNotNull(folderName);
return Optional.ofNullable(worldUuidByFolderName.get(folderName));
}
public static Optional<String> getFolderForUuid(UUID uuid) {
checkNotNull(uuid);
return Optional.ofNullable(worldUuidByFolderName.inverse().get(uuid));
}
public static WorldProperties createWorldProperties(String folderName, WorldArchetype archetype) {
checkNotNull(folderName);
checkNotNull(archetype);
final Optional<WorldServer> optWorldServer = getWorld(folderName);
if (optWorldServer.isPresent()) {
return ((org.spongepowered.api.world.World) optWorldServer.get()).getProperties();
}
final Optional<WorldProperties> optWorldProperties = WorldManager.getWorldProperties(folderName);
if (optWorldProperties.isPresent()) {
return optWorldProperties.get();
}
final ISaveHandler saveHandler = new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), folderName, true, SpongeImpl
.getServer().getDataFixer());
WorldInfo worldInfo = saveHandler.loadWorldInfo();
if (worldInfo == null) {
worldInfo = new WorldInfo((WorldSettings) (Object) archetype, folderName);
} else {
// DimensionType must be set before world config is created to get proper path
((IMixinWorldInfo) worldInfo).setDimensionType(archetype.getDimensionType());
((IMixinWorldInfo) worldInfo).createWorldConfig();
((WorldProperties) worldInfo).setGeneratorModifiers(archetype.getGeneratorModifiers());
}
setUuidOnProperties(getCurrentSavesDirectory().get(), (WorldProperties) worldInfo);
if (((IMixinWorldInfo) worldInfo).getDimensionId() == null || ((IMixinWorldInfo) worldInfo).getDimensionId() == Integer.MIN_VALUE) {
((IMixinWorldInfo) worldInfo).setDimensionId(WorldManager.getNextFreeDimensionId());
}
((WorldProperties) worldInfo).setGeneratorType(archetype.getGeneratorType());
((IMixinWorldInfo) worldInfo).getWorldConfig().save();
registerWorldProperties((WorldProperties) worldInfo);
SpongeImpl.postEvent(SpongeEventFactory.createConstructWorldPropertiesEvent(Cause.of(NamedCause.source(Sponge.getServer())), archetype,
(WorldProperties) worldInfo));
saveHandler.saveWorldInfoWithPlayer(worldInfo, SpongeImpl.getServer().getPlayerList().getHostPlayerData());
return (WorldProperties) worldInfo;
}
public static boolean saveWorldProperties(WorldProperties properties) {
checkNotNull(properties);
final Optional<WorldServer> optWorldServer = getWorldByDimensionId(((IMixinWorldInfo) properties).getDimensionId());
// If the World represented in the properties is still loaded, save the properties and have the World reload its info
if (optWorldServer.isPresent()) {
final WorldServer worldServer = optWorldServer.get();
worldServer.getSaveHandler().saveWorldInfo((WorldInfo) properties);
worldServer.getSaveHandler().loadWorldInfo();
} else {
new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), properties.getWorldName(), true, SpongeImpl.getServer()
.getDataFixer()).saveWorldInfo((WorldInfo) properties);
}
// No return values or exceptions so can only assume true.
return true;
}
public static void unloadQueuedWorlds() {
while (unloadQueue.peek() != null) {
unloadWorld(unloadQueue.poll(), true);
}
unloadQueue.clear();
}
public static void queueWorldToUnload(WorldServer worldServer) {
checkNotNull(worldServer);
unloadQueue.add(worldServer);
}
// TODO Result
public static boolean unloadWorld(WorldServer worldServer, boolean checkConfig) {
checkNotNull(worldServer);
final MinecraftServer server = SpongeImpl.getServer();
// Likely leaked, don't want to drop leaked world data
if (!worldByDimensionId.containsValue(worldServer)) {
return false;
}
// Vanilla sometimes doesn't remove player entities from world first
if (server.isServerRunning()) {
if (!worldServer.playerEntities.isEmpty()) {
return false;
}
// We only check config if base game wants to unload world. If mods/plugins say unload, we unload
if (checkConfig) {
if (((IMixinWorldServer) worldServer).getActiveConfig().getConfig().getWorld().getKeepSpawnLoaded()) {
return false;
}
}
}
final IMixinWorldServer mixinWorldServer = (IMixinWorldServer) worldServer;
final int dimensionId = mixinWorldServer.getDimensionId();
try {
// Don't save if server is stopping to avoid duplicate saving.
if (server.isServerRunning()) {
saveWorld(worldServer, true);
mixinWorldServer.getActiveConfig().save();
}
} catch (MinecraftException e) {
e.printStackTrace();
} finally {
worldByDimensionId.remove(dimensionId);
weakWorldByWorld.remove(worldServer);
((IMixinMinecraftServer) server).removeWorldTickTimes(dimensionId);
SpongeImpl.getLogger().info("Unloading world [{}] (DIM{})", worldServer.getWorldInfo().getWorldName(), dimensionId);
reorderWorldsVanillaFirst();
}
SpongeImpl.postEvent(SpongeEventFactory.createUnloadWorldEvent(Cause.of(NamedCause.source(server)), (org.spongepowered.api.world.World)
worldServer));
if (!server.isServerRunning() && unregisterableDimensions.contains(dimensionId)) {
unregisterDimension(dimensionId);
}
return true;
}
public static void saveWorld(WorldServer worldServer, boolean flush) throws MinecraftException {
worldServer.saveAllChunks(true, null);
if (flush) {
worldServer.flush();
}
}
public static Collection<WorldProperties> getUnloadedWorlds() throws IOException {
final Optional<Path> optCurrentSavesDir = getCurrentSavesDirectory();
checkState(optCurrentSavesDir.isPresent(), "Attempt made to get unloaded worlds too early!");
final List<WorldProperties> worlds = new ArrayList<>();
try (final DirectoryStream<Path> stream = Files.newDirectoryStream(optCurrentSavesDir.get(), LEVEL_AND_SPONGE)) {
for (Path worldFolder : stream) {
final String worldFolderName = worldFolder.getFileName().toString();
final WorldInfo worldInfo = new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), worldFolderName, true,
SpongeImpl.getServer().getDataFixer()).loadWorldInfo();
if (worldInfo != null) {
worlds.add((WorldProperties) worldInfo);
}
}
}
return worlds;
}
public static Optional<WorldServer> loadWorld(UUID uuid) {
checkNotNull(uuid);
// If someone tries to load loaded world, return it
Sponge.getServer().getWorld(uuid).ifPresent(Optional::of);
// Check if we even know of this UUID's folder
final String worldFolder = worldUuidByFolderName.inverse().get(uuid);
// We don't know of this UUID at all. TODO Search files?
if (worldFolder == null) {
return Optional.empty();
}
return loadWorld(worldFolder, null, null);
}
public static Optional<WorldServer> loadWorld(String worldName) {
checkNotNull(worldName);
return loadWorld(worldName, null, null);
}
public static Optional<WorldServer> loadWorld(WorldProperties properties) {
checkNotNull(properties);
return loadWorld(properties.getWorldName(), null, properties);
}
private static Optional<WorldServer> loadWorld(String worldName, @Nullable ISaveHandler saveHandler, @Nullable WorldProperties properties) {
checkNotNull(worldName);
final Path currentSavesDir = WorldManager.getCurrentSavesDirectory().orElseThrow(() -> new IllegalStateException("Attempt "
+ "made to load world too early!"));
final MinecraftServer server = SpongeImpl.getServer();
final Optional<WorldServer> optExistingWorldServer = getWorld(worldName);
if (optExistingWorldServer.isPresent()) {
return optExistingWorldServer;
}
if (!server.getAllowNether()) {
SpongeImpl.getLogger().error("Unable to load world [{}]. Multi-world is disabled via [allow-nether] in [server.properties].", worldName);
return Optional.empty();
}
final Path worldFolder = currentSavesDir.resolve(worldName);
if (!Files.isDirectory(worldFolder)) {
SpongeImpl.getLogger().error("Unable to load world [{}]. We cannot find its folder under [{}].", worldFolder, currentSavesDir);
return Optional.empty();
}
if (saveHandler == null) {
saveHandler = new AnvilSaveHandler(currentSavesDir.toFile(), worldName, true, SpongeImpl.getServer()
.getDataFixer());
}
// We weren't given a properties, see if one is cached
if (properties == null) {
properties = (WorldProperties) saveHandler.loadWorldInfo();
// We tried :'(
if (properties == null) {
SpongeImpl.getLogger().error("Unable to load world [{}]. No world properties was found!", worldName);
return Optional.empty();
}
}
if (((IMixinWorldInfo) properties).getDimensionId() == null || ((IMixinWorldInfo) properties).getDimensionId() == Integer.MIN_VALUE) {
((IMixinWorldInfo) properties).setDimensionId(getNextFreeDimensionId());
}
setUuidOnProperties(getCurrentSavesDirectory().get(), properties);
registerWorldProperties(properties);
final WorldInfo worldInfo = (WorldInfo) properties;
((IMixinWorldInfo) worldInfo).createWorldConfig();
// check if enabled
if (!((WorldProperties) worldInfo).isEnabled()) {
SpongeImpl.getLogger().error("Unable to load world [{}]. It is disabled.", worldName);
return Optional.empty();
}
final int dimensionId = ((IMixinWorldInfo) properties).getDimensionId();
registerDimension(dimensionId, (DimensionType) (Object) properties.getDimensionType(), true);
registerDimensionPath(dimensionId, worldFolder);
SpongeImpl.getLogger().info("Loading world [{}] ({})", properties.getWorldName(), getDimensionType
(dimensionId).get().getName());
final WorldServer worldServer = createWorldFromProperties(dimensionId, saveHandler, (WorldInfo) properties, new WorldSettings((WorldInfo)
properties));
return Optional.of(worldServer);
}
public static void loadAllWorlds(String worldName, long defaultSeed, WorldType defaultWorldType, String generatorOptions) {
final MinecraftServer server = SpongeImpl.getServer();
// We cannot call getCurrentSavesDirectory here as that would generate a savehandler and trigger a session lock.
// We'll go ahead and make the directories for the save name here so that the migrator won't fail
final Path currentSavesDir = server.anvilFile.toPath().resolve(server.getFolderName());
try {
// Symlink needs special handling
if (Files.isSymbolicLink(currentSavesDir)) {
final Path actualPathLink = Files.readSymbolicLink(currentSavesDir);
if (Files.notExists(actualPathLink)) {
// TODO Need to test symlinking to see if this is even legal...
Files.createDirectories(actualPathLink);
} else if (!Files.isDirectory(actualPathLink)) {
throw new IOException("Saves directory [" + currentSavesDir + "] symlinked to [" + actualPathLink + "] is not a directory!");
}
} else {
Files.createDirectories(currentSavesDir);
}
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
WorldManager.registerVanillaDimensionPaths(currentSavesDir);
WorldMigrator.migrateWorldsTo(currentSavesDir);
registerExistingSpongeDimensions(currentSavesDir);
for (Map.Entry<Integer, DimensionType> entry: sortedDimensionMap().entrySet()) {
final int dimensionId = entry.getKey();
final DimensionType dimensionType = entry.getValue();
// Skip all worlds besides dimension 0 if multi-world is disabled
if (dimensionId != 0 && !server.getAllowNether()) {
continue;
}
// Skip already loaded worlds by plugins
if (getWorldByDimensionId(dimensionId).isPresent()) {
continue;
}
// Step 1 - Grab the world's data folder
final Optional<Path> optWorldFolder = getWorldFolder(dimensionType, dimensionId);
if (!optWorldFolder.isPresent()) {
SpongeImpl.getLogger().error("An attempt was made to load a world with dimension id [{}] that has no registered world folder!",
dimensionId);
continue;
}
final Path worldFolder = optWorldFolder.get();
final String worldFolderName = worldFolder.getFileName().toString();
// Step 2 - See if we are allowed to load it
if (dimensionId != 0) {
final SpongeConfig<?> activeConfig = SpongeHooks.getActiveConfig(((IMixinDimensionType)(Object) dimensionType).getConfigPath(), worldFolderName);
if (!activeConfig.getConfig().getWorld().isWorldEnabled()) {
SpongeImpl.getLogger().warn("World [{}] (DIM{}) is disabled. World will not be loaded...", worldFolder,
dimensionId);
continue;
}
}
// Step 3 - Get our world information from disk
final ISaveHandler saveHandler;
if (dimensionId == 0) {
saveHandler = server.getActiveAnvilConverter().getSaveLoader(server.getFolderName(), true);
} else {
saveHandler = new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), worldFolderName, true, server
.getDataFixer());
}
WorldInfo worldInfo = saveHandler.loadWorldInfo();
WorldSettings worldSettings;
// If this is integrated server, we need to use the WorldSettings from the client's Single Player menu to construct the worlds
if (server instanceof IMixinIntegratedServer) {
worldSettings = ((IMixinIntegratedServer) server).getSettings();
// If this is overworld and a new save, the WorldInfo has already been made but we want to still fire the construct event.
if (dimensionId == 0 && ((IMixinIntegratedServer) server).isNewSave()) {
SpongeImpl.postEvent(SpongeEventFactory.createConstructWorldPropertiesEvent(Cause.of(NamedCause.source(server)), (WorldArchetype)
(Object) worldSettings, (WorldProperties) worldInfo));
}
} else {
// WorldSettings will be null here on dedicated server so we need to build one
worldSettings = new WorldSettings(defaultSeed, server.getGameType(), server.canStructuresSpawn(), server.isHardcore(),
defaultWorldType);
}
if (worldInfo == null) {
// Step 4 - At this point, we have either have the WorldInfo or we have none. If we have none, we'll use the settings built above to
// create the WorldInfo
worldInfo = createWorldInfoFromSettings(currentSavesDir, (org.spongepowered.api.world.DimensionType) (Object) dimensionType,
dimensionId, worldFolderName, worldSettings, generatorOptions);
} else {
// create config
((IMixinWorldInfo) worldInfo).setDimensionType((org.spongepowered.api.world.DimensionType)(Object) dimensionType);
((IMixinWorldInfo) worldInfo).createWorldConfig();
((WorldProperties) worldInfo).setGenerateSpawnOnLoad(((IMixinDimensionType)(Object) dimensionType).shouldGenerateSpawnOnLoad());
}
// Safety check to ensure we'll get a unique id no matter what
if (((WorldProperties) worldInfo).getUniqueId() == null) {
setUuidOnProperties(dimensionId == 0 ? currentSavesDir.getParent() : currentSavesDir, (WorldProperties) worldInfo);
}
// Safety check to ensure the world info has the dimension id set
if (((IMixinWorldInfo) worldInfo).getDimensionId() == null) {
((IMixinWorldInfo) worldInfo).setDimensionId(dimensionId);
}
// Keep the LevelName in the LevelInfo up to date with the directory name
if (!worldInfo.getWorldName().equals(worldFolderName)) {
worldInfo.setWorldName(worldFolderName);
}
// Step 5 - Load server resource pack from dimension 0
if (dimensionId == 0) {
server.setResourcePackFromWorld(worldFolderName, saveHandler);
}
// Step 6 - Cache the WorldProperties we've made so we don't load from disk later.
registerWorldProperties((WorldProperties) worldInfo);
if (dimensionId != 0 && !((WorldProperties) worldInfo).loadOnStartup()) {
SpongeImpl.getLogger().warn("World [{}] (DIM{}) is set to not load on startup. To load it later, enable [load-on-startup] in config "
+ "or use a plugin", worldFolder, dimensionId);
continue;
}
// Step 7 - Finally, we can create the world and tell it to load
final WorldServer worldServer = createWorldFromProperties(dimensionId, saveHandler, worldInfo, worldSettings);
SpongeImpl.getLogger().info("Loading world [{}] ({})", ((org.spongepowered.api.world.World) worldServer).getName(), getDimensionType
(dimensionId).get().getName());
}
}
public static WorldInfo createWorldInfoFromSettings(Path currentSaveRoot, org.spongepowered.api.world.DimensionType dimensionType, int
dimensionId, String worldFolderName, WorldSettings worldSettings, String generatorOptions) {
final MinecraftServer server = SpongeImpl.getServer();
worldSettings.setGeneratorOptions(generatorOptions);
((IMixinWorldSettings) (Object) worldSettings).setDimensionType(dimensionType);
((IMixinWorldSettings)(Object) worldSettings).setGenerateSpawnOnLoad(((IMixinDimensionType) dimensionType).shouldGenerateSpawnOnLoad());
final WorldInfo worldInfo = new WorldInfo(worldSettings, worldFolderName);
setUuidOnProperties(dimensionId == 0 ? currentSaveRoot.getParent() : currentSaveRoot, (WorldProperties) worldInfo);
((IMixinWorldInfo) worldInfo).setDimensionId(dimensionId);
SpongeImpl.postEvent(SpongeEventFactory.createConstructWorldPropertiesEvent(Cause.of(NamedCause.source(server)),
(WorldArchetype) (Object) worldSettings, (WorldProperties) worldInfo));
return worldInfo;
}
public static WorldServer createWorldFromProperties(int dimensionId, ISaveHandler saveHandler, WorldInfo worldInfo, @Nullable WorldSettings
worldSettings) {
final MinecraftServer server = SpongeImpl.getServer();
final WorldServer worldServer;
if (dimensionId == 0) {
worldServer = new WorldServer(server, saveHandler, worldInfo, dimensionId, server.theProfiler);
} else {
final WorldServerMultiAdapterWorldInfo info = new WorldServerMultiAdapterWorldInfo(saveHandler, worldInfo);
worldServer = new WorldServerMulti(server, info, dimensionId, worldByDimensionId.get(0), server.theProfiler);
}
worldServer.init();
// WorldSettings is only non-null here if this is a newly generated WorldInfo and therefore we need to initialize to calculate spawn.
if (worldSettings != null) {
worldServer.initialize(worldSettings);
}
worldServer.addEventListener(new ServerWorldEventHandler(server, worldServer));
// This code changes from Mojang's to account for per-world API-set GameModes.
if (!server.isSinglePlayer() && worldServer.getWorldInfo().getGameType().equals(GameType.NOT_SET)) {
worldServer.getWorldInfo().setGameType(server.getGameType());
}
worldByDimensionId.put(dimensionId, worldServer);
weakWorldByWorld.put(worldServer, worldServer);
((IMixinMinecraftServer) SpongeImpl.getServer()).putWorldTickTimes(dimensionId, new long[100]);
// Set the worlds on the Minecraft server
reorderWorldsVanillaFirst();
SpongeImpl.postEvent(SpongeEventFactory.createLoadWorldEvent(Cause.of(NamedCause.source(Sponge.getServer())),
(org.spongepowered.api.world.World) worldServer));
((IMixinMinecraftServer) server).prepareSpawnArea(worldServer);
return worldServer;
}
/**
* Internal use only - Namely for SpongeForge.
* @param dimensionId The world instance dimension id
* @param worldServer The world server
*/
public static void forceAddWorld(int dimensionId, WorldServer worldServer) {
worldByDimensionId.put(dimensionId, worldServer);
weakWorldByWorld.put(worldServer, worldServer);
((IMixinMinecraftServer) SpongeImpl.getServer()).putWorldTickTimes(dimensionId, new long[100]);
}
public static void reorderWorldsVanillaFirst() {
final List<WorldServer> worlds = new ArrayList<>(worldByDimensionId.values());
final List<WorldServer> sorted = new LinkedList<>();
int vanillaWorldsCount = 0;
WorldServer worldServer = worldByDimensionId.get(0);
if (worldServer != null) {
sorted.add(worldServer);
vanillaWorldsCount++;
}
worldServer = worldByDimensionId.get(-1);
if (worldServer != null) {
sorted.add(worldServer);
vanillaWorldsCount++;
}
worldServer = worldByDimensionId.get(1);
if (worldServer != null) {
sorted.add(worldServer);
vanillaWorldsCount++;
}
final List<WorldServer> nonVanillaWorlds = worlds.subList(vanillaWorldsCount, worlds.size());
nonVanillaWorlds.sort(WORLD_SERVER_COMPARATOR);
sorted.addAll(nonVanillaWorlds);
SpongeImpl.getServer().worlds = sorted.toArray(new WorldServer[sorted.size()]);
}
/**
* Parses a {@link UUID} from disk from other known plugin platforms and sets it on the
* {@link WorldProperties}. Currently only Bukkit is supported.
*/
public static UUID setUuidOnProperties(Path savesRoot, WorldProperties properties) {
checkNotNull(properties);
UUID uuid;
if (properties.getUniqueId() == null || properties.getUniqueId().equals
(UUID.fromString("00000000-0000-0000-0000-000000000000"))) {
// Check if Bukkit's uid.dat file is here and use it
final Path uidPath = savesRoot.resolve(properties.getWorldName()).resolve("uid.dat");
if (Files.notExists(uidPath)) {
uuid = UUID.randomUUID();
} else {
try(final DataInputStream dis = new DataInputStream(Files.newInputStream(uidPath))) {
uuid = new UUID(dis.readLong(), dis.readLong());
} catch (IOException e) {
SpongeImpl.getLogger().error("World folder [{}] has an existing Bukkit unique identifier for it but we encountered issues parsing "
+ "the file. We will have to use a new unique id. Please report this to Sponge ASAP.", properties.getWorldName(), e);
uuid = UUID.randomUUID();
}
}
} else {
uuid = properties.getUniqueId();
}
((IMixinWorldInfo) properties).setUniqueId(uuid);
return uuid;
}
/**
* Handles registering existing Sponge dimensions that are not the root dimension (known as overworld).
*/
private static void registerExistingSpongeDimensions(Path rootPath) {
try (final DirectoryStream<Path> stream = Files.newDirectoryStream(rootPath, LEVEL_AND_SPONGE)) {
for (Path worldPath : stream) {
final Path spongeLevelPath = worldPath.resolve("level_sponge.dat");
final String worldFolderName = worldPath.getFileName().toString();
NBTTagCompound compound;
try {
compound = CompressedStreamTools.readCompressed(Files.newInputStream(spongeLevelPath));
} catch (IOException e) {
SpongeImpl.getLogger().error("Failed loading Sponge data for World [{}]}. Report to Sponge ASAP.", worldFolderName, e);
continue;
}
NBTTagCompound spongeDataCompound = compound.getCompoundTag(NbtDataUtil.SPONGE_DATA);
if (!compound.hasKey(NbtDataUtil.SPONGE_DATA)) {
SpongeImpl.getLogger()
.error("World [{}] has Sponge related data in the form of [level-sponge.dat] but the structure is not proper."
+ " Generally, the data is within a [{}] tag but it is not for this world. Report to Sponge ASAP.",
worldFolderName, NbtDataUtil.SPONGE_DATA);
continue;
}
if (!spongeDataCompound.hasKey(NbtDataUtil.DIMENSION_ID)) {
SpongeImpl.getLogger().error("World [{}] has no dimension id. Report this to Sponge ASAP.", worldFolderName);
continue;
}
int dimensionId = spongeDataCompound.getInteger(NbtDataUtil.DIMENSION_ID);
if (dimensionId == Integer.MIN_VALUE) {
// temporary fix for existing worlds created with wrong dimension id
dimensionId = WorldManager.getNextFreeDimensionId();
}
// We do not handle Vanilla dimensions, skip them
if (dimensionId == 0 || dimensionId == -1 || dimensionId == 1) {
continue;
}
spongeDataCompound = DataUtil.spongeDataFixer.process(FixTypes.LEVEL, spongeDataCompound);
String dimensionTypeId = "overworld";
if (spongeDataCompound.hasKey(NbtDataUtil.DIMENSION_TYPE)) {
dimensionTypeId = spongeDataCompound.getString(NbtDataUtil.DIMENSION_TYPE);
} else {
SpongeImpl.getLogger().warn("World [{}] (DIM{}) has no specified dimension type. Defaulting to [{}}]...", worldFolderName,
dimensionId, DimensionTypes.OVERWORLD.getName());
}
dimensionTypeId = fixDimensionTypeId(dimensionTypeId);
org.spongepowered.api.world.DimensionType dimensionType
= Sponge.getRegistry().getType(org.spongepowered.api.world.DimensionType.class, dimensionTypeId).orElse(null);
if (dimensionType == null) {
SpongeImpl.getLogger().warn("World [{}] (DIM{}) has specified dimension type that is not registered. Skipping...",
worldFolderName, dimensionId);
continue;
}
spongeDataCompound.setString(NbtDataUtil.DIMENSION_TYPE, dimensionTypeId);
if (!spongeDataCompound.hasUniqueId(NbtDataUtil.UUID)) {
SpongeImpl.getLogger().error("World [{}] (DIM{}) has no valid unique identifier. This is a critical error and should be reported"
+ " to Sponge ASAP.", worldFolderName, dimensionId);
continue;
}
if (isDimensionRegistered(dimensionId)) {
SpongeImpl.getLogger().error("Unable to register dim id ({}) from world folder [{}]. This dim id has already been registered "
+ "from world folder [{}].", dimensionId, worldFolderName, worldFolderByDimensionId.get(dimensionId));
continue;
}
worldFolderByDimensionId.put(dimensionId, worldFolderName);
registerDimension(dimensionId, (DimensionType)(Object) dimensionType, true);
registerDimensionPath(dimensionId, rootPath.resolve(worldFolderName));
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Checks if the saved dimension type contains a modid and if not, attempts to locate one
public static String fixDimensionTypeId(String name) {
// Since we now store the modid, we need to support older save files that only include id without modid.
if (!name.contains(":")) {
for (org.spongepowered.api.world.DimensionType type : Sponge.getRegistry().getAllOf(org.spongepowered.api.world.DimensionType.class)) {
String typeId = (type.getId().substring(type.getId().lastIndexOf(":") + 1));
if (typeId.equals(name)) {
return type.getId();
// Note: We don't update the NBT here but instead fix it on next
// world save in case there are 2 types using same name.
}
}
}
return name;
}
public static CompletableFuture<Optional<WorldProperties>> copyWorld(WorldProperties worldProperties, String copyName) {
checkArgument(worldPropertiesByFolderName.containsKey(worldProperties.getWorldName()), "World properties not registered!");
checkArgument(!worldPropertiesByFolderName.containsKey(copyName), "Destination world name already is registered!");
final WorldInfo info = (WorldInfo) worldProperties;
final WorldServer worldServer = worldByDimensionId.get(((IMixinWorldInfo) info).getDimensionId().intValue());
if (worldServer != null) {
try {
saveWorld(worldServer, true);
} catch (MinecraftException e) {
Throwables.propagate(e);
}
((IMixinMinecraftServer) SpongeImpl.getServer()).setSaveEnabled(false);
}
final CompletableFuture<Optional<WorldProperties>> future = SpongeScheduler.getInstance().submitAsyncTask(new CopyWorldTask(info, copyName));
if (worldServer != null) { // World was loaded
future.thenRun(() -> ((IMixinMinecraftServer) SpongeImpl.getServer()).setSaveEnabled(true));
}
return future;
}
public static Optional<WorldProperties> renameWorld(WorldProperties worldProperties, String newName) {
checkNotNull(worldProperties);
checkNotNull(newName);
checkState(!worldByDimensionId.containsKey(((IMixinWorldInfo) worldProperties).getDimensionId()), "World is still loaded!");
final Path oldWorldFolder = getCurrentSavesDirectory().get().resolve(worldProperties.getWorldName());
final Path newWorldFolder = oldWorldFolder.resolveSibling(newName);
if (Files.exists(newWorldFolder)) {
return Optional.empty();
}
try {
Files.move(oldWorldFolder, newWorldFolder);
} catch (IOException e) {
return Optional.empty();
}
unregisterWorldProperties(worldProperties, false);
final WorldInfo info = new WorldInfo((WorldInfo) worldProperties);
info.setWorldName(newName);
((IMixinWorldInfo) info).createWorldConfig();
new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), newName, true, SpongeImpl.getServer().getDataFixer())
.saveWorldInfo(info);
registerWorldProperties((WorldProperties) info);
return Optional.of((WorldProperties) info);
}
public static CompletableFuture<Boolean> deleteWorld(WorldProperties worldProperties) {
checkNotNull(worldProperties);
checkArgument(worldPropertiesByWorldUuid.containsKey(worldProperties.getUniqueId()), "World properties not registered!");
checkState(!worldByDimensionId.containsKey(((IMixinWorldInfo) worldProperties).getDimensionId()), "World not unloaded!");
return SpongeScheduler.getInstance().submitAsyncTask(new DeleteWorldTask(worldProperties));
}
private static class CopyWorldTask implements Callable<Optional<WorldProperties>> {
private final WorldInfo oldInfo;
private final String newName;
public CopyWorldTask(WorldInfo info, String newName) {
this.oldInfo = info;
this.newName = newName;
}
@Override
public Optional<WorldProperties> call() throws Exception {
Path oldWorldFolder = getCurrentSavesDirectory().get().resolve(this.oldInfo.getWorldName());
final Path newWorldFolder = getCurrentSavesDirectory().get().resolve(this.newName);
if (Files.exists(newWorldFolder)) {
return Optional.empty();
}
FileVisitor<Path> visitor = new CopyFileVisitor(newWorldFolder);
if (((IMixinWorldInfo) this.oldInfo).getDimensionId() == 0) {
oldWorldFolder = getCurrentSavesDirectory().get();
visitor = new ForwardingFileVisitor<Path>(visitor) {
private boolean root = true;
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (!this.root && Files.exists(dir.resolve("level.dat"))) {
return FileVisitResult.SKIP_SUBTREE;
}
this.root = false;
return super.preVisitDirectory(dir, attrs);
}
};
}
// Copy the world folder
Files.walkFileTree(oldWorldFolder, visitor);
final WorldInfo info = new WorldInfo(this.oldInfo);
info.setWorldName(this.newName);
((IMixinWorldInfo) info).setDimensionId(getNextFreeDimensionId());
((IMixinWorldInfo) info).setUniqueId(UUID.randomUUID());
((IMixinWorldInfo) info).createWorldConfig();
registerWorldProperties((WorldProperties) info);
new AnvilSaveHandler(WorldManager.getCurrentSavesDirectory().get().toFile(), newName, true, SpongeImpl.getServer().getDataFixer())
.saveWorldInfo(info);
return Optional.of((WorldProperties) info);
}
}
private static class DeleteWorldTask implements Callable<Boolean> {
private final WorldProperties props;
public DeleteWorldTask(WorldProperties props) {
this.props = props;
}
@Override
public Boolean call() throws Exception {
final Path worldFolder = getCurrentSavesDirectory().get().resolve(props.getWorldName());
if (!Files.exists(worldFolder)) {
unregisterWorldProperties(this.props, true);
return true;
}
try {
Files.walkFileTree(worldFolder, DeleteFileVisitor.INSTANCE);
unregisterWorldProperties(this.props, true);
return true;
} catch (IOException e) {
return false;
}
}
}
public static void sendDimensionRegistration(EntityPlayerMP playerMP, WorldProvider provider) {
// Do nothing in Common
}
public static void loadDimensionDataMap(@Nullable NBTTagCompound compound) {
dimensionBits.clear();
if (compound == null) {
dimensionTypeByDimensionId.keySet().stream().filter(dimensionId -> dimensionId >= 0).forEach(dimensionBits::set);
} else {
final int[] intArray = compound.getIntArray("DimensionArray");
for (int i = 0; i < intArray.length; i++) {
for (int j = 0; j < Integer.SIZE; j++) {
dimensionBits.set(i * Integer.SIZE + j, (intArray[i] & (1 << j)) != 0);
}
}
}
}
public static NBTTagCompound saveDimensionDataMap() {
int[] data = new int[(dimensionBits.length() + Integer.SIZE - 1 )/ Integer.SIZE];
NBTTagCompound dimMap = new NBTTagCompound();
for (int i = 0; i < data.length; i++) {
int val = 0;
for (int j = 0; j < Integer.SIZE; j++) {
val |= dimensionBits.get(i * Integer.SIZE + j) ? (1 << j) : 0;
}
data[i] = val;
}
dimMap.setIntArray("DimensionArray", data);
return dimMap;
}
public static Optional<Path> getCurrentSavesDirectory() {
final Optional<WorldServer> optWorldServer = getWorldByDimensionId(0);
if (optWorldServer.isPresent()) {
return Optional.of(optWorldServer.get().getSaveHandler().getWorldDirectory().toPath());
} else if (SpongeImpl.getServer() != null) {
SaveHandler saveHandler = (SaveHandler) SpongeImpl.getServer().getActiveAnvilConverter().getSaveLoader(SpongeImpl.getServer().getFolderName(), false);
return Optional.of(saveHandler.getWorldDirectory().toPath());
}
return Optional.empty();
}
public static Map<WorldServer, WorldServer> getWeakWorldMap() {
return weakWorldByWorld;
}
public static int getClientDimensionId(EntityPlayerMP player, World world) {
if (!((IMixinEntityPlayerMP) player).usesCustomClient()) {
DimensionType type = world.provider.getDimensionType();
if (type == DimensionType.OVERWORLD) {
return 0;
} else if (type == DimensionType.NETHER) {
return -1;
}
return 1;
}
return ((IMixinWorldServer) world).getDimensionId();
}
public static int getDimensionId(WorldServer world) {
return ((IMixinWorldInfo) world.getWorldInfo()).getDimensionId();
}
}
| Generate int[] dimension ID array directly instead of using invalid casts
Fixes #1140
| src/main/java/org/spongepowered/common/world/WorldManager.java | Generate int[] dimension ID array directly instead of using invalid casts | <ide><path>rc/main/java/org/spongepowered/common/world/WorldManager.java
<ide> import java.util.UUID;
<ide> import java.util.concurrent.Callable;
<ide> import java.util.concurrent.CompletableFuture;
<del>import java.util.stream.Collectors;
<ide>
<ide> import javax.annotation.Nullable;
<ide>
<ide> return dimensionTypeByTypeId.values();
<ide> }
<ide>
<del> public static Integer[] getRegisteredDimensionIdsFor(DimensionType type) {
<del> return (Integer[]) dimensionTypeByDimensionId.entrySet().stream().filter(entry -> entry.getValue().equals(type))
<del> .map(Map.Entry::getKey).collect(Collectors.toList()).toArray();
<add> public static int[] getRegisteredDimensionIdsFor(DimensionType type) {
<add> return dimensionTypeByDimensionId.int2ObjectEntrySet().stream()
<add> .filter(entry -> entry.getValue().equals(type))
<add> .mapToInt(Int2ObjectMap.Entry::getIntKey)
<add> .toArray();
<ide> }
<ide>
<ide> public static int[] getRegisteredDimensionIds() { |
|
Java | lgpl-2.1 | 35c54e5e51cc83a4702c80b709e0d43da248e04a | 0 | danieljue/beast-mcmc,danieljue/beast-mcmc,evolvedmicrobe/beast-mcmc,danieljue/beast-mcmc,evolvedmicrobe/beast-mcmc,danieljue/beast-mcmc,danieljue/beast-mcmc,evolvedmicrobe/beast-mcmc,evolvedmicrobe/beast-mcmc,evolvedmicrobe/beast-mcmc | /*
* RandomWalkOperator.java
*
* Copyright (c) 2002-2013 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.inference.operators;
import java.util.ArrayList;
import java.util.List;
import dr.inference.model.Bounds;
import dr.inference.model.Parameter;
import dr.inferencexml.operators.RandomWalkOperatorParser;
import dr.math.MathUtils;
import dr.util.Transform;
/**
* A random walk operator that takes a (list of) parameter(s) and corresponding transformations.
*
* @author Guy Baele
*/
public class TransformedRandomWalkOperator extends AbstractCoercableOperator {
private Parameter parameter = null;
private final Transform[] transformations;
private double windowSize = 0.01;
private List<Integer> updateMap = null;
private int updateMapSize;
private final BoundaryCondition condition;
private final Double lowerOperatorBound;
private final Double upperOperatorBound;
public enum BoundaryCondition {
reflecting,
absorbing
}
public TransformedRandomWalkOperator(Parameter parameter, Transform[] transformations, double windowSize, BoundaryCondition bc, double weight, CoercionMode mode) {
this(parameter, transformations, null, windowSize, bc, weight, mode);
}
public TransformedRandomWalkOperator(Parameter parameter, Transform[] transformations, Parameter updateIndex, double windowSize, BoundaryCondition bc,
double weight, CoercionMode mode) {
this(parameter, transformations, updateIndex, windowSize, bc, weight, mode, null, null);
}
public TransformedRandomWalkOperator(Parameter parameter, Transform[] transformations, Parameter updateIndex, double windowSize, BoundaryCondition bc,
double weight, CoercionMode mode, Double lowerOperatorBound, Double upperOperatorBound) {
super(mode);
this.parameter = parameter;
this.transformations = transformations;
this.windowSize = windowSize;
this.condition = bc;
setWeight(weight);
if (updateIndex != null) {
updateMap = new ArrayList<Integer>();
for (int i = 0; i < updateIndex.getDimension(); i++) {
if (updateIndex.getParameterValue(i) == 1.0)
updateMap.add(i);
}
updateMapSize=updateMap.size();
}
this.lowerOperatorBound = lowerOperatorBound;
this.upperOperatorBound = upperOperatorBound;
}
/**
* @return the parameter this operator acts on.
*/
public Parameter getParameter() {
return parameter;
}
public final double getWindowSize() {
return windowSize;
}
/**
* change the parameter and return the hastings ratio.
*/
public final double doOperation() throws OperatorFailedException {
//store MH-ratio in logq
double logJacobian = 0.0;
// a random dimension to perturb
int index;
if (updateMap == null) {
index = MathUtils.nextInt(parameter.getDimension());
} else {
index = updateMap.get(MathUtils.nextInt(updateMapSize));
}
//System.err.println("index: " + index);
// a random point around old value within windowSize * 2
double draw = (2.0 * MathUtils.nextDouble() - 1.0) * windowSize;
//System.err.println("draw: " + draw);
//transform parameter values first
double[] x = parameter.getParameterValues();
int dim = parameter.getDimension();
//System.err.println("parameter " + index + ": " + x[index]);
double[] transformedX = new double[dim];
for (int i = 0; i < dim; i++) {
transformedX[i] = transformations[i].transform(x[i]);
}
//System.err.println("transformed parameter " + index + ": " + transformedX[index]);
//double newValue = parameter.getParameterValue(index) + draw;
double newValue = transformedX[index] + draw;
//System.err.println("new value: " + newValue);
final Bounds<Double> bounds = parameter.getBounds();
final double lower = (lowerOperatorBound == null ? bounds.getLowerLimit(index) : Math.max(bounds.getLowerLimit(index), lowerOperatorBound));
final double upper = (upperOperatorBound == null ? bounds.getUpperLimit(index) : Math.min(bounds.getUpperLimit(index), upperOperatorBound));
if (condition == BoundaryCondition.reflecting) {
newValue = reflectValue(newValue, lower, upper);
} else if (newValue < lower || newValue > upper) {
throw new OperatorFailedException("proposed value outside boundaries");
}
//parameter.setParameterValue(index, newValue);
parameter.setParameterValue(index, transformations[index].inverse(newValue));
//System.err.println("set parameter to: " + parameter.getValue(index));
//this should be correct
//logJacobian += transformations[index].getLogJacobian(parameter.getParameterValue(index)) - transformations[index].getLogJacobian(x[index]);
logJacobian += transformations[index].getLogJacobian(x[index]) - transformations[index].getLogJacobian(parameter.getParameterValue(index));
//return 0.0;
return logJacobian;
}
public double reflectValue(double value, double lower, double upper) {
double newValue = value;
if (value < lower) {
if (Double.isInfinite(upper)) {
// we are only going to reflect once as the upper bound is at infinity...
newValue = lower + (lower - value);
} else {
double remainder = lower - value;
double widths = Math.floor(remainder / (upper - lower));
remainder -= (upper - lower) * widths;
// even reflections
if (widths % 2 == 0) {
newValue = lower + remainder;
// odd reflections
} else {
newValue = upper - remainder;
}
}
} else if (value > upper) {
if (Double.isInfinite(lower)) {
// we are only going to reflect once as the lower bound is at -infinity...
newValue = upper - (newValue - upper);
} else {
double remainder = value - upper;
double widths = Math.floor(remainder / (upper - lower));
remainder -= (upper - lower) * widths;
// even reflections
if (widths % 2 == 0) {
newValue = upper - remainder;
// odd reflections
} else {
newValue = lower + remainder;
}
}
}
return newValue;
}
public double reflectValueLoop(double value, double lower, double upper) {
double newValue = value;
while (newValue < lower || newValue > upper) {
if (newValue < lower) {
newValue = lower + (lower - newValue);
}
if (newValue > upper) {
newValue = upper - (newValue - upper);
}
}
return newValue;
}
//MCMCOperator INTERFACE
public final String getOperatorName() {
return parameter.getParameterName();
}
public double getCoercableParameter() {
return Math.log(windowSize);
}
public void setCoercableParameter(double value) {
windowSize = Math.exp(value);
}
public double getRawParameter() {
return windowSize;
}
public double getTargetAcceptanceProbability() {
return 0.234;
}
public double getMinimumAcceptanceLevel() {
return 0.1;
}
public double getMaximumAcceptanceLevel() {
return 0.4;
}
public double getMinimumGoodAcceptanceLevel() {
return 0.20;
}
public double getMaximumGoodAcceptanceLevel() {
return 0.30;
}
public final String getPerformanceSuggestion() {
double prob = MCMCOperator.Utils.getAcceptanceProbability(this);
double targetProb = getTargetAcceptanceProbability();
double ws = OperatorUtils.optimizeWindowSize(windowSize, parameter.getParameterValue(0) * 2.0, prob, targetProb);
if (prob < getMinimumGoodAcceptanceLevel()) {
return "Try decreasing windowSize to about " + ws;
} else if (prob > getMaximumGoodAcceptanceLevel()) {
return "Try increasing windowSize to about " + ws;
} else return "";
}
public String toString() {
return RandomWalkOperatorParser.RANDOM_WALK_OPERATOR + "(" + parameter.getParameterName() + ", " + windowSize + ", " + getWeight() + ")";
}
}
| src/dr/inference/operators/TransformedRandomWalkOperator.java | /*
* RandomWalkOperator.java
*
* Copyright (c) 2002-2013 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.inference.operators;
import dr.inference.model.Bounds;
import dr.inference.model.Parameter;
import dr.inferencexml.operators.RandomWalkOperatorParser;
import dr.math.MathUtils;
import dr.util.Transform;
import java.util.ArrayList;
import java.util.List;
/**
* A random walk operator that takes a (list of) parameter(s) and corresponding transformations.
*
* @author Guy Baele
*/
public class TransformedRandomWalkOperator extends AbstractCoercableOperator {
private Parameter parameter = null;
private final Transform[] transformations;
private double windowSize = 0.01;
private List<Integer> updateMap = null;
private int updateMapSize;
private final BoundaryCondition condition;
private final Double lowerOperatorBound;
private final Double upperOperatorBound;
public enum BoundaryCondition {
reflecting,
absorbing
}
public TransformedRandomWalkOperator(Parameter parameter, Transform[] transformations, double windowSize, BoundaryCondition bc, double weight, CoercionMode mode) {
this(parameter, transformations, null, windowSize, bc, weight, mode);
}
public TransformedRandomWalkOperator(Parameter parameter, Transform[] transformations, Parameter updateIndex, double windowSize, BoundaryCondition bc,
double weight, CoercionMode mode) {
this(parameter, transformations, updateIndex, windowSize, bc, weight, mode, null, null);
}
public TransformedRandomWalkOperator(Parameter parameter, Transform[] transformations, Parameter updateIndex, double windowSize, BoundaryCondition bc,
double weight, CoercionMode mode, Double lowerOperatorBound, Double upperOperatorBound) {
super(mode);
this.parameter = parameter;
this.transformations = transformations;
this.windowSize = windowSize;
this.condition = bc;
setWeight(weight);
if (updateIndex != null) {
updateMap = new ArrayList<Integer>();
for (int i = 0; i < updateIndex.getDimension(); i++) {
if (updateIndex.getParameterValue(i) == 1.0)
updateMap.add(i);
}
updateMapSize=updateMap.size();
}
this.lowerOperatorBound = lowerOperatorBound;
this.upperOperatorBound = upperOperatorBound;
}
/**
* @return the parameter this operator acts on.
*/
public Parameter getParameter() {
return parameter;
}
public final double getWindowSize() {
return windowSize;
}
/**
* change the parameter and return the hastings ratio.
*/
public final double doOperation() throws OperatorFailedException {
//store MH-ratio in logq
double logJacobian = 0.0;
// a random dimension to perturb
int index;
if (updateMap == null) {
index = MathUtils.nextInt(parameter.getDimension());
} else {
index = updateMap.get(MathUtils.nextInt(updateMapSize));
}
//System.err.println("index: " + index);
// a random point around old value within windowSize * 2
double draw = (2.0 * MathUtils.nextDouble() - 1.0) * windowSize;
//System.err.println("draw: " + draw);
//transform parameter values first
double[] x = parameter.getParameterValues();
int dim = parameter.getDimension();
//System.err.println("parameter " + index + ": " + x[index]);
double[] transformedX = new double[dim];
for (int i = 0; i < dim; i++) {
transformedX[i] = transformations[i].transform(x[i]);
}
//System.err.println("transformed parameter " + index + ": " + transformedX[index]);
//double newValue = parameter.getParameterValue(index) + draw;
double newValue = transformedX[index] + draw;
//System.err.println("new value: " + newValue);
final Bounds<Double> bounds = parameter.getBounds();
final double lower = (lowerOperatorBound == null ? bounds.getLowerLimit(index) : Math.max(bounds.getLowerLimit(index), lowerOperatorBound));
final double upper = (upperOperatorBound == null ? bounds.getUpperLimit(index) : Math.min(bounds.getUpperLimit(index), upperOperatorBound));
if (condition == BoundaryCondition.reflecting) {
newValue = reflectValue(newValue, lower, upper);
} else if (newValue < lower || newValue > upper) {
throw new OperatorFailedException("proposed value outside boundaries");
}
//parameter.setParameterValue(index, newValue);
parameter.setParameterValue(index, transformations[index].inverse(newValue));
//System.err.println("set parameter to: " + parameter.getValue(index));
logJacobian += transformations[index].getLogJacobian(parameter.getParameterValue(index)) - transformations[index].getLogJacobian(x[index]);
//return 0.0;
return logJacobian;
}
public double reflectValue(double value, double lower, double upper) {
double newValue = value;
if (value < lower) {
if (Double.isInfinite(upper)) {
// we are only going to reflect once as the upper bound is at infinity...
newValue = lower + (lower - value);
} else {
double remainder = lower - value;
double widths = Math.floor(remainder / (upper - lower));
remainder -= (upper - lower) * widths;
// even reflections
if (widths % 2 == 0) {
newValue = lower + remainder;
// odd reflections
} else {
newValue = upper - remainder;
}
}
} else if (value > upper) {
if (Double.isInfinite(lower)) {
// we are only going to reflect once as the lower bound is at -infinity...
newValue = upper - (newValue - upper);
} else {
double remainder = value - upper;
double widths = Math.floor(remainder / (upper - lower));
remainder -= (upper - lower) * widths;
// even reflections
if (widths % 2 == 0) {
newValue = upper - remainder;
// odd reflections
} else {
newValue = lower + remainder;
}
}
}
return newValue;
}
public double reflectValueLoop(double value, double lower, double upper) {
double newValue = value;
while (newValue < lower || newValue > upper) {
if (newValue < lower) {
newValue = lower + (lower - newValue);
}
if (newValue > upper) {
newValue = upper - (newValue - upper);
}
}
return newValue;
}
//MCMCOperator INTERFACE
public final String getOperatorName() {
return parameter.getParameterName();
}
public double getCoercableParameter() {
return Math.log(windowSize);
}
public void setCoercableParameter(double value) {
windowSize = Math.exp(value);
}
public double getRawParameter() {
return windowSize;
}
public double getTargetAcceptanceProbability() {
return 0.234;
}
public double getMinimumAcceptanceLevel() {
return 0.1;
}
public double getMaximumAcceptanceLevel() {
return 0.4;
}
public double getMinimumGoodAcceptanceLevel() {
return 0.20;
}
public double getMaximumGoodAcceptanceLevel() {
return 0.30;
}
public final String getPerformanceSuggestion() {
double prob = MCMCOperator.Utils.getAcceptanceProbability(this);
double targetProb = getTargetAcceptanceProbability();
double ws = OperatorUtils.optimizeWindowSize(windowSize, parameter.getParameterValue(0) * 2.0, prob, targetProb);
if (prob < getMinimumGoodAcceptanceLevel()) {
return "Try decreasing windowSize to about " + ws;
} else if (prob > getMaximumGoodAcceptanceLevel()) {
return "Try increasing windowSize to about " + ws;
} else return "";
}
public String toString() {
return RandomWalkOperatorParser.RANDOM_WALK_OPERATOR + "(" + parameter.getParameterName() + ", " + windowSize + ", " + getWeight() + ")";
}
}
| Fix Jacobian ratio in TransformedRandomWalkOperator. | src/dr/inference/operators/TransformedRandomWalkOperator.java | Fix Jacobian ratio in TransformedRandomWalkOperator. | <ide><path>rc/dr/inference/operators/TransformedRandomWalkOperator.java
<ide>
<ide> package dr.inference.operators;
<ide>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<ide> import dr.inference.model.Bounds;
<ide> import dr.inference.model.Parameter;
<ide> import dr.inferencexml.operators.RandomWalkOperatorParser;
<ide> import dr.math.MathUtils;
<ide> import dr.util.Transform;
<del>
<del>import java.util.ArrayList;
<del>import java.util.List;
<ide>
<ide> /**
<ide> * A random walk operator that takes a (list of) parameter(s) and corresponding transformations.
<ide>
<ide> private final Double lowerOperatorBound;
<ide> private final Double upperOperatorBound;
<del>
<add>
<ide> public enum BoundaryCondition {
<ide> reflecting,
<ide> absorbing
<ide> }
<ide>
<ide> public TransformedRandomWalkOperator(Parameter parameter, Transform[] transformations, Parameter updateIndex, double windowSize, BoundaryCondition bc,
<del> double weight, CoercionMode mode) {
<add> double weight, CoercionMode mode) {
<ide> this(parameter, transformations, updateIndex, windowSize, bc, weight, mode, null, null);
<ide> }
<ide>
<ide> public TransformedRandomWalkOperator(Parameter parameter, Transform[] transformations, Parameter updateIndex, double windowSize, BoundaryCondition bc,
<del> double weight, CoercionMode mode, Double lowerOperatorBound, Double upperOperatorBound) {
<add> double weight, CoercionMode mode, Double lowerOperatorBound, Double upperOperatorBound) {
<ide> super(mode);
<ide> this.parameter = parameter;
<ide> this.transformations = transformations;
<ide>
<ide> //store MH-ratio in logq
<ide> double logJacobian = 0.0;
<del>
<add>
<ide> // a random dimension to perturb
<ide> int index;
<ide> if (updateMap == null) {
<ide> } else {
<ide> index = updateMap.get(MathUtils.nextInt(updateMapSize));
<ide> }
<del>
<add>
<ide> //System.err.println("index: " + index);
<ide>
<ide> // a random point around old value within windowSize * 2
<ide> double draw = (2.0 * MathUtils.nextDouble() - 1.0) * windowSize;
<del>
<add>
<ide> //System.err.println("draw: " + draw);
<del>
<add>
<ide> //transform parameter values first
<ide> double[] x = parameter.getParameterValues();
<ide> int dim = parameter.getDimension();
<ide>
<ide> //System.err.println("parameter " + index + ": " + x[index]);
<del>
<add>
<ide> double[] transformedX = new double[dim];
<ide> for (int i = 0; i < dim; i++) {
<ide> transformedX[i] = transformations[i].transform(x[i]);
<ide> }
<del>
<add>
<ide> //System.err.println("transformed parameter " + index + ": " + transformedX[index]);
<del>
<add>
<ide> //double newValue = parameter.getParameterValue(index) + draw;
<ide> double newValue = transformedX[index] + draw;
<del>
<add>
<ide> //System.err.println("new value: " + newValue);
<del>
<add>
<ide> final Bounds<Double> bounds = parameter.getBounds();
<ide> final double lower = (lowerOperatorBound == null ? bounds.getLowerLimit(index) : Math.max(bounds.getLowerLimit(index), lowerOperatorBound));
<ide> final double upper = (upperOperatorBound == null ? bounds.getUpperLimit(index) : Math.min(bounds.getUpperLimit(index), upperOperatorBound));
<ide>
<ide> //parameter.setParameterValue(index, newValue);
<ide> parameter.setParameterValue(index, transformations[index].inverse(newValue));
<del>
<add>
<ide> //System.err.println("set parameter to: " + parameter.getValue(index));
<del>
<del> logJacobian += transformations[index].getLogJacobian(parameter.getParameterValue(index)) - transformations[index].getLogJacobian(x[index]);
<del>
<add>
<add> //this should be correct
<add> //logJacobian += transformations[index].getLogJacobian(parameter.getParameterValue(index)) - transformations[index].getLogJacobian(x[index]);
<add>
<add> logJacobian += transformations[index].getLogJacobian(x[index]) - transformations[index].getLogJacobian(parameter.getParameterValue(index));
<add>
<ide> //return 0.0;
<ide> return logJacobian;
<ide> } |
|
Java | mit | a1920d5de6e372d3a220c726d103b7403b1b9107 | 0 | NyaaCat/RPGitems-reloaded | package think.rpgitems.power.impl;
import cat.nyaa.nyaacore.Pair;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerToggleSneakEvent;
import org.bukkit.event.player.PlayerToggleSprintEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.BlockIterator;
import org.bukkit.util.BoundingBox;
import org.bukkit.util.RayTraceResult;
import org.bukkit.util.Vector;
import think.rpgitems.I18n;
import think.rpgitems.RPGItems;
import think.rpgitems.power.*;
import static think.rpgitems.power.Utils.checkCooldown;
/**
* Power teleport.
* <p>
* The teleport power will teleport you
* in the direction you're looking in
* or to the place where the projectile hit
* with maximum distance of {@link #distance} blocks
* </p>
*/
@SuppressWarnings("WeakerAccess")
@PowerMeta(defaultTrigger = {"RIGHT_CLICK", "PROJECTILE_HIT"})
public class PowerTeleport extends BasePower implements PowerSneak, PowerLeftClick, PowerSprint, PowerRightClick, PowerProjectileHit {
/**
* Maximum distance.
*/
@Property(order = 1)
public int distance = 5;
/**
* Cooldown time of this power
*/
@Property(order = 0)
public long cooldown = 20;
/**
* Cost of this power
*/
@Property
public int cost = 0;
@Property
public TargetMode targetMode = TargetMode.DEFAULT;
@Override
public PowerResult<Void> rightClick(Player player, ItemStack stack, PlayerInteractEvent event) {
return fire(player, stack);
}
@Override
public PowerResult<Void> leftClick(Player player, ItemStack stack, PlayerInteractEvent event) {
return fire(player, stack);
}
@Override
public PowerResult<Void> sneak(Player player, ItemStack stack, PlayerToggleSneakEvent event) {
return fire(player, stack);
}
@Override
public PowerResult<Void> sprint(Player player, ItemStack stack, PlayerToggleSprintEvent event) {
return fire(player, stack);
}
public PowerResult<Void> fire(Player player, ItemStack stack) {
if (!checkCooldown(this, player, cooldown, true, true)) return PowerResult.cd();
if (!getItem().consumeDurability(stack, cost)) return PowerResult.cost();
World world = player.getWorld();
Location location = player.getLocation();
Location start = location.clone().add(new Vector(0, 1.6, 0));
Location eyeLocation = player.getEyeLocation();
Vector direction = eyeLocation.getDirection();
Block lastSafe = world.getBlockAt(start);
Location newLoc = lastSafe.getLocation();
boolean ignorePassable = true;
switch (targetMode) {
case RAY_TRACING_EXACT:
case RAY_TRACING_EXACT_SWEEP:
ignorePassable = false;
case RAY_TRACING:
case RAY_TRACING_SWEEP: {
RayTraceResult result = player.getWorld().rayTraceBlocks(eyeLocation, direction, distance, FluidCollisionMode.NEVER, ignorePassable);
Block firstUnsafe = result == null ? null : result.getHitBlock();
if (firstUnsafe == null) {
newLoc = location.add(direction.clone().multiply(distance));
break;
} else {
newLoc = result.getHitPosition().toLocation(world);
}
if (targetMode == TargetMode.RAY_TRACING || targetMode == TargetMode.RAY_TRACING_EXACT) {
break;
}
Vector move = newLoc.toVector().subtract(location.toVector());
Pair<Vector, Vector> sweep = Utils.sweep(player.getBoundingBox(), BoundingBox.of(firstUnsafe), move);
if (sweep != null) {
newLoc = location.clone().add(sweep.getKey());
}
break;
}
case DEFAULT: {
try {
BlockIterator bi = new BlockIterator(player, distance);
while (bi.hasNext()) {
Block block = bi.next();
if (!block.getType().isSolid() || (block.getType() == Material.AIR)) {
lastSafe = block;
} else {
break;
}
}
} catch (IllegalStateException ex) {
ex.printStackTrace();
RPGItems.logger.info("This exception may be harmless");
}
newLoc = lastSafe.getLocation();
break;
}
}
newLoc.setPitch(eyeLocation.getPitch());
newLoc.setYaw(eyeLocation.getYaw());
Vector velocity = player.getVelocity();
boolean gliding = player.isGliding();
player.teleport(newLoc);
if (gliding) {
player.setVelocity(velocity);
}
world.playEffect(newLoc, Effect.ENDER_SIGNAL, 0);
world.playSound(newLoc, Sound.ENTITY_ENDERMAN_TELEPORT, 1.0f, 0.3f);
return PowerResult.ok();
}
@Override
public PowerResult<Void> projectileHit(Player player, ItemStack stack, ProjectileHitEvent event) {
if (!checkCooldown(this, player, cooldown, true, true)) return PowerResult.cd();
if (!getItem().consumeDurability(stack, cost)) return PowerResult.cost();
World world = player.getWorld();
Location start = player.getLocation();
Location newLoc = event.getEntity().getLocation();
if (start.distanceSquared(newLoc) >= distance * distance) {
player.sendMessage(I18n.format("message.too.far"));
return PowerResult.noop();
}
newLoc.setPitch(start.getPitch());
newLoc.setYaw(start.getYaw());
player.teleport(newLoc);
world.playEffect(newLoc, Effect.ENDER_SIGNAL, 0);
world.playSound(newLoc, Sound.ENTITY_ENDERMAN_TELEPORT, 1.0f, 0.3f);
return PowerResult.ok();
}
@Override
public String getName() {
return "teleport";
}
@Override
public String displayText() {
return I18n.format("power.teleport", distance, (double) cooldown / 20d);
}
public enum TargetMode {
DEFAULT,
RAY_TRACING_SWEEP,
RAY_TRACING_EXACT,
RAY_TRACING_EXACT_SWEEP,
RAY_TRACING
}
}
| src/main/java/think/rpgitems/power/impl/PowerTeleport.java | package think.rpgitems.power.impl;
import cat.nyaa.nyaacore.Pair;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.BlockIterator;
import org.bukkit.util.BoundingBox;
import org.bukkit.util.RayTraceResult;
import org.bukkit.util.Vector;
import think.rpgitems.I18n;
import think.rpgitems.RPGItems;
import think.rpgitems.power.*;
import static think.rpgitems.power.Utils.checkCooldown;
/**
* Power teleport.
* <p>
* The teleport power will teleport you
* in the direction you're looking in
* or to the place where the projectile hit
* with maximum distance of {@link #distance} blocks
* </p>
*/
@SuppressWarnings("WeakerAccess")
@PowerMeta(defaultTrigger = {"RIGHT_CLICK", "PROJECTILE_HIT"})
public class PowerTeleport extends BasePower implements PowerRightClick, PowerProjectileHit {
/**
* Maximum distance.
*/
@Property(order = 1)
public int distance = 5;
/**
* Cooldown time of this power
*/
@Property(order = 0)
public long cooldown = 20;
/**
* Cost of this power
*/
@Property
public int cost = 0;
@Property
public TargetMode targetMode = TargetMode.DEFAULT;
@Override
public PowerResult<Void> rightClick(Player player, ItemStack stack, PlayerInteractEvent event) {
if (!checkCooldown(this, player, cooldown, true, true)) return PowerResult.cd();
if (!getItem().consumeDurability(stack, cost)) return PowerResult.cost();
World world = player.getWorld();
Location location = player.getLocation();
Location start = location.clone().add(new Vector(0, 1.6, 0));
Location eyeLocation = player.getEyeLocation();
Vector direction = eyeLocation.getDirection();
Block lastSafe = world.getBlockAt(start);
Location newLoc = lastSafe.getLocation();
boolean ignorePassable = true;
switch (targetMode) {
case RAY_TRACING_EXACT:
case RAY_TRACING_EXACT_SWEEP:
ignorePassable = false;
case RAY_TRACING:
case RAY_TRACING_SWEEP: {
RayTraceResult result = player.getWorld().rayTraceBlocks(eyeLocation, direction, distance, FluidCollisionMode.NEVER, ignorePassable);
Block firstUnsafe = result == null ? null : result.getHitBlock();
if (firstUnsafe == null) {
newLoc = location.add(direction.clone().multiply(distance));
break;
} else {
newLoc = result.getHitPosition().toLocation(world);
}
if (targetMode == TargetMode.RAY_TRACING || targetMode == TargetMode.RAY_TRACING_EXACT) {
break;
}
Vector move = newLoc.toVector().subtract(location.toVector());
Pair<Vector, Vector> sweep = Utils.sweep(player.getBoundingBox(), BoundingBox.of(firstUnsafe), move);
if (sweep != null) {
newLoc = location.clone().add(sweep.getKey());
}
break;
}
case DEFAULT: {
try {
BlockIterator bi = new BlockIterator(player, distance);
while (bi.hasNext()) {
Block block = bi.next();
if (!block.getType().isSolid() || (block.getType() == Material.AIR)) {
lastSafe = block;
} else {
break;
}
}
} catch (IllegalStateException ex) {
ex.printStackTrace();
RPGItems.logger.info("This exception may be harmless");
}
newLoc = lastSafe.getLocation();
break;
}
}
newLoc.setPitch(eyeLocation.getPitch());
newLoc.setYaw(eyeLocation.getYaw());
Vector velocity = player.getVelocity();
boolean gliding = player.isGliding();
player.teleport(newLoc);
if (gliding) {
player.setVelocity(velocity);
}
world.playEffect(newLoc, Effect.ENDER_SIGNAL, 0);
world.playSound(newLoc, Sound.ENTITY_ENDERMAN_TELEPORT, 1.0f, 0.3f);
return PowerResult.ok();
}
@Override
public PowerResult<Void> projectileHit(Player player, ItemStack stack, ProjectileHitEvent event) {
if (!checkCooldown(this, player, cooldown, true, true)) return PowerResult.cd();
if (!getItem().consumeDurability(stack, cost)) return PowerResult.cost();
World world = player.getWorld();
Location start = player.getLocation();
Location newLoc = event.getEntity().getLocation();
if (start.distanceSquared(newLoc) >= distance * distance) {
player.sendMessage(I18n.format("message.too.far"));
return PowerResult.noop();
}
newLoc.setPitch(start.getPitch());
newLoc.setYaw(start.getYaw());
player.teleport(newLoc);
world.playEffect(newLoc, Effect.ENDER_SIGNAL, 0);
world.playSound(newLoc, Sound.ENTITY_ENDERMAN_TELEPORT, 1.0f, 0.3f);
return PowerResult.ok();
}
@Override
public String getName() {
return "teleport";
}
@Override
public String displayText() {
return I18n.format("power.teleport", distance, (double) cooldown / 20d);
}
public enum TargetMode {
DEFAULT,
RAY_TRACING_SWEEP,
RAY_TRACING_EXACT,
RAY_TRACING_EXACT_SWEEP,
RAY_TRACING
}
}
| added some more triggers to power teleport
| src/main/java/think/rpgitems/power/impl/PowerTeleport.java | added some more triggers to power teleport | <ide><path>rc/main/java/think/rpgitems/power/impl/PowerTeleport.java
<ide> import org.bukkit.*;
<ide> import org.bukkit.block.Block;
<ide> import org.bukkit.entity.Player;
<add>import org.bukkit.event.Event;
<ide> import org.bukkit.event.entity.ProjectileHitEvent;
<ide> import org.bukkit.event.player.PlayerInteractEvent;
<add>import org.bukkit.event.player.PlayerToggleSneakEvent;
<add>import org.bukkit.event.player.PlayerToggleSprintEvent;
<ide> import org.bukkit.inventory.ItemStack;
<ide> import org.bukkit.util.BlockIterator;
<ide> import org.bukkit.util.BoundingBox;
<ide> */
<ide> @SuppressWarnings("WeakerAccess")
<ide> @PowerMeta(defaultTrigger = {"RIGHT_CLICK", "PROJECTILE_HIT"})
<del>public class PowerTeleport extends BasePower implements PowerRightClick, PowerProjectileHit {
<add>public class PowerTeleport extends BasePower implements PowerSneak, PowerLeftClick, PowerSprint, PowerRightClick, PowerProjectileHit {
<ide>
<ide> /**
<ide> * Maximum distance.
<ide>
<ide> @Override
<ide> public PowerResult<Void> rightClick(Player player, ItemStack stack, PlayerInteractEvent event) {
<add> return fire(player, stack);
<add> }
<add>
<add> @Override
<add> public PowerResult<Void> leftClick(Player player, ItemStack stack, PlayerInteractEvent event) {
<add> return fire(player, stack);
<add> }
<add>
<add> @Override
<add> public PowerResult<Void> sneak(Player player, ItemStack stack, PlayerToggleSneakEvent event) {
<add> return fire(player, stack);
<add> }
<add>
<add> @Override
<add> public PowerResult<Void> sprint(Player player, ItemStack stack, PlayerToggleSprintEvent event) {
<add> return fire(player, stack);
<add> }
<add>
<add>
<add> public PowerResult<Void> fire(Player player, ItemStack stack) {
<ide> if (!checkCooldown(this, player, cooldown, true, true)) return PowerResult.cd();
<ide> if (!getItem().consumeDurability(stack, cost)) return PowerResult.cost();
<ide> World world = player.getWorld(); |
|
JavaScript | mit | 6df5f1aa9a3a7c32f0f68f3088d4f5b06a482bf6 | 0 | tpoikela/battles,tpoikela/battles,tpoikela/battles,tpoikela/battles,tpoikela/battles | /* This file contains factory objects for creating different types
* of items. */
const RG = require('./rg');
const Random = require('./random');
const Placer = require('./placer');
const ObjectShell = require('./objectshellparser');
const RNG = Random.getRNG();
/* This object is used to randomize item properties during procedural
* generation.*/
const ItemRandomizer = function() {
/* Only public function. All logic is deferred to private functions.
* Adjusts the properties of given item, based also on maxValue.*/
this.adjustItem = (item, val) => {
const itemType = item.getType();
if (_adjustFunctions.hasOwnProperty(itemType)) {
_adjustFunctions[itemType](item, val);
}
};
/* Distr. of food weights.*/
const _foodWeights = RG.getFoodWeightDistr();
const _adjustFoodItem = food => {
const weight = RNG.getWeighted(_foodWeights);
food.setWeight(weight);
};
const _adjustGoldCoin = (gold, nLevel) => {
if (!RG.isNullOrUndef([nLevel])) {
const goldWeights = RG.getGoldCoinCountDistr(nLevel);
const count = RNG.getWeighted(goldWeights);
gold.setCount(parseInt(count, 10));
}
else {
RG.err('ItemRandomizer', '_adjustGoldCoin',
'nLevel is not defined.');
}
};
const _adjustMissile = missile => {
const count = RNG.getUniformInt(5, 15);
missile.setCount(count);
};
const _isCombatMod = val => val >= 0.0 && val <= 0.02;
const _isStatsMod = val => val >= 0.1 && val <= 0.12;
const _getRandStat = () => RNG.arrayGetRand(RG.STATS);
/* Adjust damage, attack, defense and value of a weapon. */
const _adjustWeapon = weapon => {
const randVal = RNG.getUniform();
if (_isCombatMod(randVal)) {
const bonus = RNG.getUniformInt(1, 5);
const type = RNG.getUniformInt(0, 4);
switch (type) {
case 0: // Fall through
case 1: {
weapon.setAttack(weapon.getAttack() + bonus);
break;
}
case 2: // Fall through
case 3: {
weapon.setDefense(weapon.getDefense() + bonus);
break;
}
case 4: {
weapon.setProtection(weapon.getProtection() + bonus);
break;
}
default: break;
}
RG.scaleItemValue('combat', bonus, weapon);
}
else if (_isStatsMod(randVal)) {
const bonus = RNG.getUniformInt(1, 3);
let stats = null;
if (weapon.has('Stats')) {
stats = weapon.get('Stats');
}
else {
stats = new RG.Component.Stats();
stats.clearValues();
weapon.add(stats);
}
const randStat = _getRandStat();
const getName = 'get' + randStat;
const setName = 'set' + randStat;
stats[setName](stats[getName]() + bonus);
RG.scaleItemValue('stats', bonus, weapon);
}
};
const _adjustArmour = armour => {
_adjustWeapon(armour); // The same function works fine for this
};
const _runeWeights = RG.getRuneChargeDistr();
const _adjustRune = rune => {
const charges = RNG.getWeighted(_runeWeights);
rune.setCharges(charges);
};
/* const _adjustMineral = mineral => {
};*/
/* LUT for functions to call on specific items.*/
const _adjustFunctions = {
food: _adjustFoodItem,
goldcoin: _adjustGoldCoin,
missile: _adjustMissile,
weapon: _adjustWeapon,
armour: _adjustArmour,
ammo: _adjustMissile,
rune: _adjustRune
// mineral: _adjustMineral
};
};
/* Factory object for creating items. */
const FactoryItem = function() {
this._itemRandomizer = new ItemRandomizer();
/* Called for random items. Adjusts some of their attributes randomly.*/
const _doItemSpecificAdjustments = (item, val) => {
this._itemRandomizer.adjustItem(item, val);
};
this.createItem = function(query) {
const parser = ObjectShell.getParser();
return parser.createRandomItem(query);
};
/* Adds N random items to the given level. Uses parser to generate the
* items. */
this.addNRandItems = (level, conf) => {
const items = this.generateItems(conf);
const parser = ObjectShell.getParser();
if (conf.food) {
const food = parser.createRandomItem({
func: item => item.type === 'food'
});
if (food) {
_doItemSpecificAdjustments(food, conf.maxValue);
items.push(food);
}
else {
RG.warn('FactoryItem', 'addNRandItems',
'Item.Food was not created properly.');
}
}
Placer.addPropsToFreeCells(level, items, RG.TYPE_ITEM);
return items.length;
};
this.generateItems = function(conf) {
const nItems = conf.itemsPerLevel || conf.nItems;
const items = [];
const parser = ObjectShell.getParser();
for (let j = 0; j < nItems; j++) {
const item = parser.createRandomItem({func: conf.func});
if (item) {
_doItemSpecificAdjustments(item, conf.maxValue);
items.push(item);
}
}
return items;
};
this.generateGold = function(conf) {
const nGold = conf.goldPerLevel || conf.nGold;
const parser = ObjectShell.getParser();
const goldItems = [];
for (let i = 0; i < nGold; i++) {
const gold = parser.createActualObj(RG.TYPE_ITEM,
RG.GOLD_COIN_NAME);
_doItemSpecificAdjustments(gold, conf.nLevel);
goldItems.push(gold);
}
return goldItems;
};
/* Adds a random number of gold coins to the level. */
this.addRandomGold = (level, parser, conf) => {
const goldItems = this.generateGold(conf);
Placer.addPropsToFreeCells(level, goldItems, RG.TYPE_ITEM);
};
/* Returns a shop item based on the configuration. */
this.getShopItem = (n, conf) => {
let item = null;
if (conf.shopFunc) {
if (typeof conf.shopFunc[n] === 'function') {
item = conf.parser.createRandomItem({
func: conf.shopFunc[n]
});
}
else {
RG.err('FactoryItem', 'createShop -> getShopItem',
'shopFunc must be a function.');
}
}
else if (Array.isArray(conf.shopType)) {
item = conf.parser.createRandomItem({
func: item => item.type === conf.shopType[n]
});
}
else if (typeof conf.shopType === 'string') {
item = conf.parser.createRandomItem({
func: item => item.type === conf.shopType
});
}
else { // Fallback, if no config
item = conf.parser.createRandomItem({
func: item => item.value <= 50 + n * 100
});
}
_doItemSpecificAdjustments(item, 50 + n * 100);
return item;
};
this.addItemsToCells = function(level, parser, cells, conf) {
if (!conf.maxValue) {
RG.err('FactoryItem', 'addItemsToCells',
'conf is missing maxValue');
}
const items = this.generateItems(conf);
Placer.addPropsToCells(level, cells, items, RG.TYPE_ITEM);
};
};
FactoryItem.addItemsToActor = function(actor, items) {
const parser = ObjectShell.getParser();
let createdItem = null;
items.forEach(item => {
if (typeof item === 'string') {
createdItem = parser.createItem(item);
}
else if (typeof item === 'object') {
createdItem = parser.createItem(item.name);
}
if (createdItem) {
actor.getInvEq().addItem(createdItem);
}
});
};
/* Given actor and gear type (mithril, ruby, permaice ...), tries to
* equip a full gear of items to the actor. */
FactoryItem.equipFullGearType = function(actor, type) {
const parser = ObjectShell.getParser();
const nameRegexp = new RegExp(type);
const items = parser.filterItems(item => (
item.type === 'armour' && nameRegexp.test(item.name)
));
return FactoryItem.equipItemsToActor(actor, items);
};
/* Equips one melee weapon of given type to the actor. */
FactoryItem.equipWeaponOfType = function(actor, type) {
const parser = ObjectShell.getParser();
const nameRegexp = new RegExp(type);
const items = parser.filterItems(item => (
item.type === 'weapon' && nameRegexp.test(item.name)
));
const oneWeapon = RNG.arrayGetRand(items);
return FactoryItem.equipItemsToActor(actor, [oneWeapon]);
};
/* Tries to equip the list of given items to actor. Each item can be a
* string or {name: 'xxx', count: 3} object. */
FactoryItem.equipItemsToActor = function(actor, items) {
const parser = ObjectShell.getParser();
let createdItem = null;
let ok = true;
items.forEach(item => {
if (typeof item === 'string') {
createdItem = parser.createItem(item);
}
else if (typeof item === 'object') {
createdItem = parser.createItem(item.name);
const itemCount = item.count || 1;
createdItem.setCount(itemCount);
}
if (createdItem) {
const count = createdItem.getCount();
actor.getInvEq().addItem(createdItem);
ok = ok && actor.getInvEq().equipNItems(createdItem, count);
}
});
return ok;
};
module.exports = {
FactoryItem,
ItemRandomizer
};
| client/src/factory.items.js | /* This file contains factory objects for creating different types
* of items. */
const RG = require('./rg');
const Random = require('./random');
const Placer = require('./placer');
const ObjectShell = require('./objectshellparser');
const RNG = Random.getRNG();
/* This object is used to randomize item properties during procedural
* generation.*/
const ItemRandomizer = function() {
/* Only public function. All logic is deferred to private functions.
* Adjusts the properties of given item, based also on maxValue.*/
this.adjustItem = (item, val) => {
const itemType = item.getType();
if (_adjustFunctions.hasOwnProperty(itemType)) {
_adjustFunctions[itemType](item, val);
}
};
/* Distr. of food weights.*/
const _foodWeights = RG.getFoodWeightDistr();
const _adjustFoodItem = food => {
const weight = RNG.getWeighted(_foodWeights);
food.setWeight(weight);
};
const _adjustGoldCoin = (gold, nLevel) => {
if (!RG.isNullOrUndef([nLevel])) {
const goldWeights = RG.getGoldCoinCountDistr(nLevel);
const count = RNG.getWeighted(goldWeights);
gold.setCount(parseInt(count, 10));
}
else {
RG.err('ItemRandomizer', '_adjustGoldCoin',
'nLevel is not defined.');
}
};
const _adjustMissile = missile => {
const count = RNG.getUniformInt(5, 15);
missile.setCount(count);
};
const _isCombatMod = val => val >= 0.0 && val <= 0.02;
const _isStatsMod = val => val >= 0.1 && val <= 0.12;
const _getRandStat = () => RNG.arrayGetRand(RG.STATS);
/* Adjust damage, attack, defense and value of a weapon. */
const _adjustWeapon = weapon => {
const randVal = RNG.getUniform();
if (_isCombatMod(randVal)) {
const bonus = RNG.getUniformInt(1, 5);
const type = RNG.getUniformInt(0, 4);
switch (type) {
case 0: // Fall through
case 1: {
weapon.setAttack(weapon.getAttack() + bonus);
break;
}
case 2: // Fall through
case 3: {
weapon.setDefense(weapon.getDefense() + bonus);
break;
}
case 4: {
weapon.setProtection(weapon.getProtection() + bonus);
break;
}
default: break;
}
RG.scaleItemValue('combat', bonus, weapon);
}
else if (_isStatsMod(randVal)) {
const bonus = RNG.getUniformInt(1, 3);
let stats = null;
if (weapon.has('Stats')) {
stats = weapon.get('Stats');
}
else {
stats = new RG.Component.Stats();
stats.clearValues();
weapon.add(stats);
}
const randStat = _getRandStat();
const getName = 'get' + randStat;
const setName = 'set' + randStat;
stats[setName](stats[getName]() + bonus);
RG.scaleItemValue('stats', bonus, weapon);
}
};
const _adjustArmour = armour => {
_adjustWeapon(armour); // The same function works fine for this
};
const _runeWeights = RG.getRuneChargeDistr();
const _adjustRune = rune => {
const charges = RNG.getWeighted(_runeWeights);
rune.setCharges(charges);
};
/* const _adjustMineral = mineral => {
};*/
/* LUT for functions to call on specific items.*/
const _adjustFunctions = {
food: _adjustFoodItem,
goldcoin: _adjustGoldCoin,
missile: _adjustMissile,
weapon: _adjustWeapon,
armour: _adjustArmour,
ammo: _adjustMissile,
rune: _adjustRune
// mineral: _adjustMineral
};
};
/* Factory object for creating items. */
const FactoryItem = function() {
this._itemRandomizer = new ItemRandomizer();
/* Called for random items. Adjusts some of their attributes randomly.*/
const _doItemSpecificAdjustments = (item, val) => {
this._itemRandomizer.adjustItem(item, val);
};
this.createItem = function(query) {
const parser = ObjectShell.getParser();
return parser.createRandomItem(query);
};
/* Adds N random items to the given level. Uses parser to generate the
* items. */
this.addNRandItems = (level, conf) => {
const items = this.generateItems(conf);
const parser = ObjectShell.getParser();
if (conf.food) {
const food = parser.createRandomItem({
func: item => item.type === 'food'
});
if (food) {
_doItemSpecificAdjustments(food, conf.maxValue);
items.push(food);
}
else {
RG.warn('FactoryItem', 'addNRandItems',
'Item.Food was not created properly.');
}
}
Placer.addPropsToFreeCells(level, items, RG.TYPE_ITEM);
return items.length;
};
this.generateItems = function(conf) {
const nItems = conf.itemsPerLevel || conf.nItems;
const items = [];
const parser = ObjectShell.getParser();
for (let j = 0; j < nItems; j++) {
const item = parser.createRandomItem({func: conf.func});
if (item) {
_doItemSpecificAdjustments(item, conf.maxValue);
items.push(item);
}
}
return items;
};
this.generateGold = function(conf) {
const nGold = conf.goldPerLevel || conf.nGold;
const parser = ObjectShell.getParser();
const goldItems = [];
for (let i = 0; i < nGold; i++) {
const gold = parser.createActualObj(RG.TYPE_ITEM,
RG.GOLD_COIN_NAME);
_doItemSpecificAdjustments(gold, conf.nLevel);
goldItems.push(gold);
}
return goldItems;
};
/* Adds a random number of gold coins to the level. */
this.addRandomGold = (level, parser, conf) => {
const goldItems = this.generateGold(conf);
Placer.addPropsToFreeCells(level, goldItems, RG.TYPE_ITEM);
};
/* Returns a shop item based on the configuration. */
this.getShopItem = (n, conf) => {
let item = null;
if (conf.shopFunc) {
if (typeof conf.shopFunc[n] === 'function') {
item = conf.parser.createRandomItem({
func: conf.shopFunc[n]
});
}
else {
RG.err('FactoryItem', 'createShop -> getShopItem',
'shopFunc must be a function.');
}
}
else if (Array.isArray(conf.shopType)) {
item = conf.parser.createRandomItem({
func: item => item.type === conf.shopType[n]
});
}
else if (typeof conf.shopType === 'string') {
item = conf.parser.createRandomItem({
func: item => item.type === conf.shopType
});
}
else { // Fallback, if no config
item = conf.parser.createRandomItem({
func: item => item.value <= 50 + n * 100
});
}
_doItemSpecificAdjustments(item, 50 + n * 100);
return item;
};
this.addItemsToCells = function(level, parser, cells, conf) {
if (!conf.maxValue) {
RG.err('FactoryItem', 'addItemsToCells',
'conf is missing maxValue');
}
const items = this.generateItems(conf);
Placer.addPropsToCells(level, cells, items, RG.TYPE_ITEM);
};
};
FactoryItem.addItemsToActor = function(actor, items) {
const parser = ObjectShell.getParser();
let createdItem = null;
items.forEach(item => {
if (typeof item === 'string') {
createdItem = parser.createItem(item);
}
else if (typeof item === 'object') {
createdItem = parser.createItem(item.name);
}
if (createdItem) {
actor.getInvEq().addItem(createdItem);
}
});
};
FactoryItem.equipItemsToActor = function(actor, items) {
const parser = ObjectShell.getParser();
let createdItem = null;
let ok = true;
items.forEach(item => {
if (typeof item === 'string') {
createdItem = parser.createItem(item);
}
else if (typeof item === 'object') {
createdItem = parser.createItem(item.name);
const itemCount = item.count || 1;
createdItem.setCount(itemCount);
}
if (createdItem) {
const count = createdItem.getCount();
actor.getInvEq().addItem(createdItem);
ok = ok && actor.getInvEq().equipNItems(createdItem, count);
}
});
return ok;
};
module.exports = {
FactoryItem,
ItemRandomizer
};
| Added two functions for equipping items.
| client/src/factory.items.js | Added two functions for equipping items. | <ide><path>lient/src/factory.items.js
<ide> });
<ide> };
<ide>
<add>/* Given actor and gear type (mithril, ruby, permaice ...), tries to
<add> * equip a full gear of items to the actor. */
<add>FactoryItem.equipFullGearType = function(actor, type) {
<add> const parser = ObjectShell.getParser();
<add> const nameRegexp = new RegExp(type);
<add> const items = parser.filterItems(item => (
<add> item.type === 'armour' && nameRegexp.test(item.name)
<add> ));
<add> return FactoryItem.equipItemsToActor(actor, items);
<add>};
<add>
<add>/* Equips one melee weapon of given type to the actor. */
<add>FactoryItem.equipWeaponOfType = function(actor, type) {
<add> const parser = ObjectShell.getParser();
<add> const nameRegexp = new RegExp(type);
<add> const items = parser.filterItems(item => (
<add> item.type === 'weapon' && nameRegexp.test(item.name)
<add> ));
<add> const oneWeapon = RNG.arrayGetRand(items);
<add> return FactoryItem.equipItemsToActor(actor, [oneWeapon]);
<add>};
<add>
<add>/* Tries to equip the list of given items to actor. Each item can be a
<add> * string or {name: 'xxx', count: 3} object. */
<ide> FactoryItem.equipItemsToActor = function(actor, items) {
<ide> const parser = ObjectShell.getParser();
<ide> let createdItem = null; |
|
Java | apache-2.0 | 1490e8a707d44a28c95d312c732f8ca9ed6b3200 | 0 | mparaz/spring-security,liuguohua/spring-security,zhaoqin102/spring-security,pkdevbox/spring-security,xingguang2013/spring-security,eddumelendez/spring-security,caiwenshu/spring-security,pwheel/spring-security,adairtaosy/spring-security,ollie314/spring-security,diegofernandes/spring-security,pwheel/spring-security,spring-projects/spring-security,rwinch/spring-security,Krasnyanskiy/spring-security,mrkingybc/spring-security,zshift/spring-security,dsyer/spring-security,zhaoqin102/spring-security,jgrandja/spring-security,panchenko/spring-security,spring-projects/spring-security,thomasdarimont/spring-security,mrkingybc/spring-security,jmnarloch/spring-security,olezhuravlev/spring-security,wkorando/spring-security,SanjayUser/SpringSecurityPro,tekul/spring-security,dsyer/spring-security,diegofernandes/spring-security,mparaz/spring-security,spring-projects/spring-security,ollie314/spring-security,tekul/spring-security,jmnarloch/spring-security,ajdinhedzic/spring-security,cyratech/spring-security,thomasdarimont/spring-security,raindev/spring-security,vitorgv/spring-security,djechelon/spring-security,zshift/spring-security,thomasdarimont/spring-security,pkdevbox/spring-security,forestqqqq/spring-security,hippostar/spring-security,SanjayUser/SpringSecurityPro,SanjayUser/SpringSecurityPro,zgscwjm/spring-security,yinhe402/spring-security,fhanik/spring-security,ajdinhedzic/spring-security,likaiwalkman/spring-security,mounb/spring-security,jgrandja/spring-security,vitorgv/spring-security,chinazhaoht/spring-security,yinhe402/spring-security,kazuki43zoo/spring-security,djechelon/spring-security,kazuki43zoo/spring-security,follow99/spring-security,mdeinum/spring-security,diegofernandes/spring-security,thomasdarimont/spring-security,ollie314/spring-security,zhaoqin102/spring-security,panchenko/spring-security,Peter32/spring-security,wilkinsona/spring-security,caiwenshu/spring-security,adairtaosy/spring-security,xingguang2013/spring-security,rwinch/spring-security,Krasnyanskiy/spring-security,jgrandja/spring-security,follow99/spring-security,wilkinsona/spring-security,MatthiasWinzeler/spring-security,Peter32/spring-security,mrkingybc/spring-security,follow99/spring-security,Peter32/spring-security,chinazhaoht/spring-security,zgscwjm/spring-security,tekul/spring-security,eddumelendez/spring-security,mparaz/spring-security,mdeinum/spring-security,cyratech/spring-security,MatthiasWinzeler/spring-security,eddumelendez/spring-security,chinazhaoht/spring-security,kazuki43zoo/spring-security,wilkinsona/spring-security,wilkinsona/spring-security,zgscwjm/spring-security,fhanik/spring-security,MatthiasWinzeler/spring-security,jgrandja/spring-security,rwinch/spring-security,ractive/spring-security,adairtaosy/spring-security,pkdevbox/spring-security,ajdinhedzic/spring-security,rwinch/spring-security,likaiwalkman/spring-security,forestqqqq/spring-security,pwheel/spring-security,fhanik/spring-security,justinedelson/spring-security,zshift/spring-security,djechelon/spring-security,driftman/spring-security,Xcorpio/spring-security,ollie314/spring-security,Krasnyanskiy/spring-security,xingguang2013/spring-security,eddumelendez/spring-security,jgrandja/spring-security,wkorando/spring-security,izeye/spring-security,justinedelson/spring-security,forestqqqq/spring-security,adairtaosy/spring-security,Peter32/spring-security,izeye/spring-security,thomasdarimont/spring-security,mounb/spring-security,liuguohua/spring-security,liuguohua/spring-security,chinazhaoht/spring-security,jgrandja/spring-security,izeye/spring-security,hippostar/spring-security,kazuki43zoo/spring-security,zhaoqin102/spring-security,spring-projects/spring-security,spring-projects/spring-security,ajdinhedzic/spring-security,liuguohua/spring-security,spring-projects/spring-security,SanjayUser/SpringSecurityPro,olezhuravlev/spring-security,djechelon/spring-security,olezhuravlev/spring-security,zshift/spring-security,Xcorpio/spring-security,ractive/spring-security,fhanik/spring-security,yinhe402/spring-security,rwinch/spring-security,driftman/spring-security,mounb/spring-security,zgscwjm/spring-security,SanjayUser/SpringSecurityPro,mounb/spring-security,xingguang2013/spring-security,justinedelson/spring-security,cyratech/spring-security,diegofernandes/spring-security,raindev/spring-security,ractive/spring-security,mrkingybc/spring-security,pwheel/spring-security,Xcorpio/spring-security,izeye/spring-security,caiwenshu/spring-security,vitorgv/spring-security,likaiwalkman/spring-security,jmnarloch/spring-security,hippostar/spring-security,driftman/spring-security,dsyer/spring-security,likaiwalkman/spring-security,forestqqqq/spring-security,dsyer/spring-security,djechelon/spring-security,panchenko/spring-security,dsyer/spring-security,tekul/spring-security,panchenko/spring-security,mdeinum/spring-security,mparaz/spring-security,Xcorpio/spring-security,spring-projects/spring-security,driftman/spring-security,ractive/spring-security,olezhuravlev/spring-security,eddumelendez/spring-security,follow99/spring-security,wkorando/spring-security,MatthiasWinzeler/spring-security,jmnarloch/spring-security,fhanik/spring-security,hippostar/spring-security,caiwenshu/spring-security,pkdevbox/spring-security,wkorando/spring-security,pwheel/spring-security,rwinch/spring-security,mdeinum/spring-security,olezhuravlev/spring-security,raindev/spring-security,vitorgv/spring-security,justinedelson/spring-security,cyratech/spring-security,raindev/spring-security,kazuki43zoo/spring-security,Krasnyanskiy/spring-security,fhanik/spring-security,yinhe402/spring-security | /* Copyright 2004 Acegi Technology Pty Limited
*
* 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 sample.contact;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.AuthenticationCredentialsNotFoundException;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.SecureContext;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Controller for secure index page.
*
* @author Ben Alex
* @version $Id$
*/
public class SecureIndexController implements Controller, InitializingBean {
//~ Instance fields ========================================================
private ContactManager contactManager;
//~ Methods ================================================================
public void setContactManager(ContactManager contact) {
this.contactManager = contact;
}
public ContactManager getContactManager() {
return contactManager;
}
public void afterPropertiesSet() throws Exception {
if (contactManager == null) {
throw new IllegalArgumentException(
"A ContactManager implementation is required");
}
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
SecureContext secureContext = ((SecureContext) ContextHolder.getContext());
if (null == secureContext) {
throw new AuthenticationCredentialsNotFoundException(
"Authentication credentials were not found in the " +
"SecureContext");
}
final Authentication currentUser = secureContext.getAuthentication();
boolean supervisor = false;
GrantedAuthority[] granted = currentUser.getAuthorities();
for (int i = 0; i < granted.length; i++) {
if (granted[i].getAuthority().equals("ROLE_SUPERVISOR")) {
supervisor = true;
}
}
Contact[] myContacts = contactManager.getAllByOwner(currentUser.getPrincipal()
.toString());
Map model = new HashMap();
model.put("contacts", myContacts);
model.put("supervisor", new Boolean(supervisor));
model.put("user", currentUser.getPrincipal().toString());
return new ModelAndView("index", "model", model);
}
}
| samples/contacts/src/main/java/sample/contact/SecureIndexController.java | /* Copyright 2004 Acegi Technology Pty Limited
*
* 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 sample.contact;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.SecureContext;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Controller for secure index page.
*
* @author Ben Alex
* @version $Id$
*/
public class SecureIndexController implements Controller, InitializingBean {
//~ Instance fields ========================================================
private ContactManager contactManager;
//~ Methods ================================================================
public void setContactManager(ContactManager contact) {
this.contactManager = contact;
}
public ContactManager getContactManager() {
return contactManager;
}
public void afterPropertiesSet() throws Exception {
if (contactManager == null) {
throw new IllegalArgumentException(
"A ContactManager implementation is required");
}
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Authentication currentUser = ((SecureContext) ContextHolder.getContext())
.getAuthentication();
boolean supervisor = false;
GrantedAuthority[] granted = currentUser.getAuthorities();
for (int i = 0; i < granted.length; i++) {
if (granted[i].getAuthority().equals("ROLE_SUPERVISOR")) {
supervisor = true;
}
}
Contact[] myContacts = contactManager.getAllByOwner(currentUser.getPrincipal()
.toString());
Map model = new HashMap();
model.put("contacts", myContacts);
model.put("supervisor", new Boolean(supervisor));
model.put("user", currentUser.getPrincipal().toString());
return new ModelAndView("index", "model", model);
}
}
| * samples/contacts/src/sample/contact/SecureIndexController.java:
Prevent a NullPointerException when no SecureContext can be found.
Instead, throw a real exception, explaining what's wrong.
| samples/contacts/src/main/java/sample/contact/SecureIndexController.java | * samples/contacts/src/sample/contact/SecureIndexController.java: Prevent a NullPointerException when no SecureContext can be found. Instead, throw a real exception, explaining what's wrong. | <ide><path>amples/contacts/src/main/java/sample/contact/SecureIndexController.java
<ide>
<ide> import net.sf.acegisecurity.Authentication;
<ide> import net.sf.acegisecurity.GrantedAuthority;
<add>import net.sf.acegisecurity.AuthenticationCredentialsNotFoundException;
<ide> import net.sf.acegisecurity.context.ContextHolder;
<ide> import net.sf.acegisecurity.context.SecureContext;
<ide>
<ide>
<ide> public ModelAndView handleRequest(HttpServletRequest request,
<ide> HttpServletResponse response) throws ServletException, IOException {
<del> Authentication currentUser = ((SecureContext) ContextHolder.getContext())
<del> .getAuthentication();
<add> SecureContext secureContext = ((SecureContext) ContextHolder.getContext());
<add> if (null == secureContext) {
<add> throw new AuthenticationCredentialsNotFoundException(
<add> "Authentication credentials were not found in the " +
<add> "SecureContext");
<add> }
<add>
<add> final Authentication currentUser = secureContext.getAuthentication();
<ide>
<ide> boolean supervisor = false;
<ide> GrantedAuthority[] granted = currentUser.getAuthorities(); |
|
Java | apache-2.0 | 5d2e6c10c40c725c8e068242da5f719a71505099 | 0 | apache/kylin,apache/incubator-kylin,apache/kylin,apache/kylin,apache/incubator-kylin,apache/incubator-kylin,apache/kylin,apache/incubator-kylin,apache/kylin,apache/kylin,apache/incubator-kylin,apache/incubator-kylin,apache/kylin | /*
* 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.kylin.engine.mr;
import java.io.IOException;
import java.util.List;
import org.apache.kylin.cube.CubeSegment;
import org.apache.kylin.engine.mr.common.BatchConstants;
import org.apache.kylin.engine.mr.common.HadoopShellExecutable;
import org.apache.kylin.engine.mr.common.MapReduceExecutable;
import org.apache.kylin.engine.mr.steps.CreateDictionaryJob;
import org.apache.kylin.engine.mr.steps.CubingExecutableUtil;
import org.apache.kylin.engine.mr.steps.FactDistinctColumnsJob;
import org.apache.kylin.engine.mr.steps.MergeDictionaryStep;
import org.apache.kylin.engine.mr.steps.UpdateCubeInfoAfterBuildStep;
import org.apache.kylin.engine.mr.steps.UpdateCubeInfoAfterMergeStep;
import org.apache.kylin.job.constant.ExecutableConstants;
import org.apache.kylin.job.engine.JobEngineConfig;
import com.google.common.base.Preconditions;
/**
* Hold reusable steps for builders.
*/
public class JobBuilderSupport {
final protected JobEngineConfig config;
final protected CubeSegment seg;
final protected String submitter;
final public static String LayeredCuboidFolderPrefix = "level_";
public JobBuilderSupport(CubeSegment seg, String submitter) {
Preconditions.checkNotNull(seg, "segment cannot be null");
this.config = new JobEngineConfig(seg.getConfig());
this.seg = seg;
this.submitter = submitter;
}
public MapReduceExecutable createFactDistinctColumnsStep(String jobId) {
return createFactDistinctColumnsStep(jobId, false);
}
public MapReduceExecutable createFactDistinctColumnsStepWithStats(String jobId) {
return createFactDistinctColumnsStep(jobId, true);
}
private MapReduceExecutable createFactDistinctColumnsStep(String jobId, boolean withStats) {
MapReduceExecutable result = new MapReduceExecutable();
result.setName(ExecutableConstants.STEP_NAME_FACT_DISTINCT_COLUMNS);
result.setMapReduceJobClass(FactDistinctColumnsJob.class);
StringBuilder cmd = new StringBuilder();
appendMapReduceParameters(cmd);
appendExecCmdParameters(cmd, BatchConstants.ARG_CUBE_NAME, seg.getRealization().getName());
appendExecCmdParameters(cmd, BatchConstants.ARG_OUTPUT, getFactDistinctColumnsPath(jobId));
appendExecCmdParameters(cmd, BatchConstants.ARG_SEGMENT_ID, seg.getUuid());
appendExecCmdParameters(cmd, BatchConstants.ARG_STATS_ENABLED, String.valueOf(withStats));
appendExecCmdParameters(cmd, BatchConstants.ARG_STATS_OUTPUT, getStatisticsPath(jobId));
appendExecCmdParameters(cmd, BatchConstants.ARG_STATS_SAMPLING_PERCENT, String.valueOf(config.getConfig().getCubingInMemSamplingPercent()));
appendExecCmdParameters(cmd, BatchConstants.ARG_JOB_NAME, "Kylin_Fact_Distinct_Columns_" + seg.getRealization().getName() + "_Step");
appendExecCmdParameters(cmd, BatchConstants.ARG_CUBING_JOB_ID, jobId);
result.setMapReduceParams(cmd.toString());
result.setCounterSaveAs(CubingJob.SOURCE_RECORD_COUNT + "," + CubingJob.SOURCE_SIZE_BYTES);
return result;
}
public HadoopShellExecutable createBuildDictionaryStep(String jobId) {
// base cuboid job
HadoopShellExecutable buildDictionaryStep = new HadoopShellExecutable();
buildDictionaryStep.setName(ExecutableConstants.STEP_NAME_BUILD_DICTIONARY);
StringBuilder cmd = new StringBuilder();
appendExecCmdParameters(cmd, BatchConstants.ARG_CUBE_NAME, seg.getRealization().getName());
appendExecCmdParameters(cmd, BatchConstants.ARG_SEGMENT_ID, seg.getUuid());
appendExecCmdParameters(cmd, BatchConstants.ARG_INPUT, getFactDistinctColumnsPath(jobId));
buildDictionaryStep.setJobParams(cmd.toString());
buildDictionaryStep.setJobClass(CreateDictionaryJob.class);
return buildDictionaryStep;
}
public UpdateCubeInfoAfterBuildStep createUpdateCubeInfoAfterBuildStep(String jobId) {
final UpdateCubeInfoAfterBuildStep result = new UpdateCubeInfoAfterBuildStep();
result.setName(ExecutableConstants.STEP_NAME_UPDATE_CUBE_INFO);
result.getParams().put(BatchConstants.CFG_OUTPUT_PATH, getFactDistinctColumnsPath(jobId));
CubingExecutableUtil.setCubeName(seg.getRealization().getName(), result.getParams());
CubingExecutableUtil.setSegmentId(seg.getUuid(), result.getParams());
CubingExecutableUtil.setCubingJobId(jobId, result.getParams());
return result;
}
public MergeDictionaryStep createMergeDictionaryStep(List<String> mergingSegmentIds) {
MergeDictionaryStep result = new MergeDictionaryStep();
result.setName(ExecutableConstants.STEP_NAME_MERGE_DICTIONARY);
CubingExecutableUtil.setCubeName(seg.getRealization().getName(), result.getParams());
CubingExecutableUtil.setSegmentId(seg.getUuid(), result.getParams());
CubingExecutableUtil.setMergingSegmentIds(mergingSegmentIds, result.getParams());
return result;
}
public UpdateCubeInfoAfterMergeStep createUpdateCubeInfoAfterMergeStep(List<String> mergingSegmentIds, String jobId) {
UpdateCubeInfoAfterMergeStep result = new UpdateCubeInfoAfterMergeStep();
result.setName(ExecutableConstants.STEP_NAME_UPDATE_CUBE_INFO);
CubingExecutableUtil.setCubeName(seg.getRealization().getName(), result.getParams());
CubingExecutableUtil.setSegmentId(seg.getUuid(), result.getParams());
CubingExecutableUtil.setCubingJobId(jobId, result.getParams());
CubingExecutableUtil.setMergingSegmentIds(mergingSegmentIds, result.getParams());
return result;
}
// ============================================================================
public String getJobWorkingDir(String jobId) {
return getJobWorkingDir(config, jobId);
}
public String getRealizationRootPath(String jobId) {
return getJobWorkingDir(jobId) + "/" + seg.getRealization().getName();
}
public String getCuboidRootPath(String jobId) {
return getRealizationRootPath(jobId) + "/cuboid/";
}
public String getCuboidRootPath(CubeSegment seg) {
return getCuboidRootPath(seg.getLastBuildJobID());
}
public String getSecondaryIndexPath(String jobId) {
return getRealizationRootPath(jobId) + "/secondary_index/";
}
public void appendMapReduceParameters(StringBuilder buf) {
appendMapReduceParameters(buf, JobEngineConfig.DEFAUL_JOB_CONF_SUFFIX);
}
public void appendMapReduceParameters(StringBuilder buf, String jobType) {
try {
String jobConf = config.getHadoopJobConfFilePath(jobType);
if (jobConf != null && jobConf.length() > 0) {
buf.append(" -conf ").append(jobConf);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String getFactDistinctColumnsPath(String jobId) {
return getRealizationRootPath(jobId) + "/fact_distinct_columns";
}
public String getStatisticsPath(String jobId) {
return getRealizationRootPath(jobId) + "/fact_distinct_columns/" + BatchConstants.CFG_OUTPUT_STATISTICS;
}
// ============================================================================
// static methods also shared by other job flow participant
// ----------------------------------------------------------------------------
public static String getJobWorkingDir(JobEngineConfig conf, String jobId) {
return getJobWorkingDir(conf.getHdfsWorkingDirectory(), jobId);
}
public static String getJobWorkingDir(String hdfsDir, String jobId) {
if (!hdfsDir.endsWith("/")) {
hdfsDir = hdfsDir + "/";
}
return hdfsDir + "kylin-" + jobId;
}
public static StringBuilder appendExecCmdParameters(StringBuilder buf, String paraName, String paraValue) {
return buf.append(" -").append(paraName).append(" ").append(paraValue);
}
public static String getCuboidOutputPathsByLevel(String cuboidRootPath, int level) {
if (level == 0) {
return cuboidRootPath + LayeredCuboidFolderPrefix + "base_cuboid";
} else {
return cuboidRootPath + LayeredCuboidFolderPrefix + level + "_cuboid";
}
}
}
| engine-mr/src/main/java/org/apache/kylin/engine/mr/JobBuilderSupport.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.kylin.engine.mr;
import java.io.IOException;
import java.util.List;
import org.apache.kylin.cube.CubeSegment;
import org.apache.kylin.engine.mr.common.BatchConstants;
import org.apache.kylin.engine.mr.common.HadoopShellExecutable;
import org.apache.kylin.engine.mr.common.MapReduceExecutable;
import org.apache.kylin.engine.mr.steps.CreateDictionaryJob;
import org.apache.kylin.engine.mr.steps.CubingExecutableUtil;
import org.apache.kylin.engine.mr.steps.FactDistinctColumnsJob;
import org.apache.kylin.engine.mr.steps.MergeDictionaryStep;
import org.apache.kylin.engine.mr.steps.UpdateCubeInfoAfterBuildStep;
import org.apache.kylin.engine.mr.steps.UpdateCubeInfoAfterMergeStep;
import org.apache.kylin.job.constant.ExecutableConstants;
import org.apache.kylin.job.engine.JobEngineConfig;
import com.google.common.base.Preconditions;
/**
* Hold reusable steps for builders.
*/
public class JobBuilderSupport {
final protected JobEngineConfig config;
final protected CubeSegment seg;
final protected String submitter;
public JobBuilderSupport(CubeSegment seg, String submitter) {
Preconditions.checkNotNull(seg, "segment cannot be null");
this.config = new JobEngineConfig(seg.getConfig());
this.seg = seg;
this.submitter = submitter;
}
public MapReduceExecutable createFactDistinctColumnsStep(String jobId) {
return createFactDistinctColumnsStep(jobId, false);
}
public MapReduceExecutable createFactDistinctColumnsStepWithStats(String jobId) {
return createFactDistinctColumnsStep(jobId, true);
}
private MapReduceExecutable createFactDistinctColumnsStep(String jobId, boolean withStats) {
MapReduceExecutable result = new MapReduceExecutable();
result.setName(ExecutableConstants.STEP_NAME_FACT_DISTINCT_COLUMNS);
result.setMapReduceJobClass(FactDistinctColumnsJob.class);
StringBuilder cmd = new StringBuilder();
appendMapReduceParameters(cmd);
appendExecCmdParameters(cmd, BatchConstants.ARG_CUBE_NAME, seg.getRealization().getName());
appendExecCmdParameters(cmd, BatchConstants.ARG_OUTPUT, getFactDistinctColumnsPath(jobId));
appendExecCmdParameters(cmd, BatchConstants.ARG_SEGMENT_ID, seg.getUuid());
appendExecCmdParameters(cmd, BatchConstants.ARG_STATS_ENABLED, String.valueOf(withStats));
appendExecCmdParameters(cmd, BatchConstants.ARG_STATS_OUTPUT, getStatisticsPath(jobId));
appendExecCmdParameters(cmd, BatchConstants.ARG_STATS_SAMPLING_PERCENT, String.valueOf(config.getConfig().getCubingInMemSamplingPercent()));
appendExecCmdParameters(cmd, BatchConstants.ARG_JOB_NAME, "Kylin_Fact_Distinct_Columns_" + seg.getRealization().getName() + "_Step");
appendExecCmdParameters(cmd, BatchConstants.ARG_CUBING_JOB_ID, jobId);
result.setMapReduceParams(cmd.toString());
result.setCounterSaveAs(CubingJob.SOURCE_RECORD_COUNT + "," + CubingJob.SOURCE_SIZE_BYTES);
return result;
}
public HadoopShellExecutable createBuildDictionaryStep(String jobId) {
// base cuboid job
HadoopShellExecutable buildDictionaryStep = new HadoopShellExecutable();
buildDictionaryStep.setName(ExecutableConstants.STEP_NAME_BUILD_DICTIONARY);
StringBuilder cmd = new StringBuilder();
appendExecCmdParameters(cmd, BatchConstants.ARG_CUBE_NAME, seg.getRealization().getName());
appendExecCmdParameters(cmd, BatchConstants.ARG_SEGMENT_ID, seg.getUuid());
appendExecCmdParameters(cmd, BatchConstants.ARG_INPUT, getFactDistinctColumnsPath(jobId));
buildDictionaryStep.setJobParams(cmd.toString());
buildDictionaryStep.setJobClass(CreateDictionaryJob.class);
return buildDictionaryStep;
}
public UpdateCubeInfoAfterBuildStep createUpdateCubeInfoAfterBuildStep(String jobId) {
final UpdateCubeInfoAfterBuildStep result = new UpdateCubeInfoAfterBuildStep();
result.setName(ExecutableConstants.STEP_NAME_UPDATE_CUBE_INFO);
result.getParams().put(BatchConstants.CFG_OUTPUT_PATH, getFactDistinctColumnsPath(jobId));
CubingExecutableUtil.setCubeName(seg.getRealization().getName(), result.getParams());
CubingExecutableUtil.setSegmentId(seg.getUuid(), result.getParams());
CubingExecutableUtil.setCubingJobId(jobId, result.getParams());
return result;
}
public MergeDictionaryStep createMergeDictionaryStep(List<String> mergingSegmentIds) {
MergeDictionaryStep result = new MergeDictionaryStep();
result.setName(ExecutableConstants.STEP_NAME_MERGE_DICTIONARY);
CubingExecutableUtil.setCubeName(seg.getRealization().getName(), result.getParams());
CubingExecutableUtil.setSegmentId(seg.getUuid(), result.getParams());
CubingExecutableUtil.setMergingSegmentIds(mergingSegmentIds, result.getParams());
return result;
}
public UpdateCubeInfoAfterMergeStep createUpdateCubeInfoAfterMergeStep(List<String> mergingSegmentIds, String jobId) {
UpdateCubeInfoAfterMergeStep result = new UpdateCubeInfoAfterMergeStep();
result.setName(ExecutableConstants.STEP_NAME_UPDATE_CUBE_INFO);
CubingExecutableUtil.setCubeName(seg.getRealization().getName(), result.getParams());
CubingExecutableUtil.setSegmentId(seg.getUuid(), result.getParams());
CubingExecutableUtil.setCubingJobId(jobId, result.getParams());
CubingExecutableUtil.setMergingSegmentIds(mergingSegmentIds, result.getParams());
return result;
}
// ============================================================================
public String getJobWorkingDir(String jobId) {
return getJobWorkingDir(config, jobId);
}
public String getRealizationRootPath(String jobId) {
return getJobWorkingDir(jobId) + "/" + seg.getRealization().getName();
}
public String getCuboidRootPath(String jobId) {
return getRealizationRootPath(jobId) + "/cuboid/";
}
public String getCuboidRootPath(CubeSegment seg) {
return getCuboidRootPath(seg.getLastBuildJobID());
}
public String getSecondaryIndexPath(String jobId) {
return getRealizationRootPath(jobId) + "/secondary_index/";
}
public void appendMapReduceParameters(StringBuilder buf) {
appendMapReduceParameters(buf, JobEngineConfig.DEFAUL_JOB_CONF_SUFFIX);
}
public void appendMapReduceParameters(StringBuilder buf, String jobType) {
try {
String jobConf = config.getHadoopJobConfFilePath(jobType);
if (jobConf != null && jobConf.length() > 0) {
buf.append(" -conf ").append(jobConf);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String getFactDistinctColumnsPath(String jobId) {
return getRealizationRootPath(jobId) + "/fact_distinct_columns";
}
public String getStatisticsPath(String jobId) {
return getRealizationRootPath(jobId) + "/fact_distinct_columns/" + BatchConstants.CFG_OUTPUT_STATISTICS;
}
// ============================================================================
// static methods also shared by other job flow participant
// ----------------------------------------------------------------------------
public static String getJobWorkingDir(JobEngineConfig conf, String jobId) {
return getJobWorkingDir(conf.getHdfsWorkingDirectory(), jobId);
}
public static String getJobWorkingDir(String hdfsDir, String jobId) {
if (!hdfsDir.endsWith("/")) {
hdfsDir = hdfsDir + "/";
}
return hdfsDir + "kylin-" + jobId;
}
public static StringBuilder appendExecCmdParameters(StringBuilder buf, String paraName, String paraValue) {
return buf.append(" -").append(paraName).append(" ").append(paraValue);
}
public static String getCuboidOutputPathsByLevel(String cuboidRootPath, int level) {
if (level == 0) {
return cuboidRootPath + "base_cuboid";
} else {
return cuboidRootPath + "level_" + level + "_cuboid";
}
}
}
| Minor, layer cuboid folder name convension
| engine-mr/src/main/java/org/apache/kylin/engine/mr/JobBuilderSupport.java | Minor, layer cuboid folder name convension | <ide><path>ngine-mr/src/main/java/org/apache/kylin/engine/mr/JobBuilderSupport.java
<ide> final protected CubeSegment seg;
<ide> final protected String submitter;
<ide>
<add> final public static String LayeredCuboidFolderPrefix = "level_";
<add>
<ide> public JobBuilderSupport(CubeSegment seg, String submitter) {
<ide> Preconditions.checkNotNull(seg, "segment cannot be null");
<ide> this.config = new JobEngineConfig(seg.getConfig());
<ide>
<ide> public static String getCuboidOutputPathsByLevel(String cuboidRootPath, int level) {
<ide> if (level == 0) {
<del> return cuboidRootPath + "base_cuboid";
<add> return cuboidRootPath + LayeredCuboidFolderPrefix + "base_cuboid";
<ide> } else {
<del> return cuboidRootPath + "level_" + level + "_cuboid";
<add> return cuboidRootPath + LayeredCuboidFolderPrefix + level + "_cuboid";
<ide> }
<ide> }
<ide> |
|
Java | mit | 1d919ad0ce5c8f6012ba450b1ee16d6894cfd109 | 0 | TimmyT123/android-chess,jcarolus/android-chess,jcarolus/android-chess,TimmyT123/android-chess,TimmyT123/android-chess | package jwtc.android.chess.ics;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.Vibrator;
import android.preference.PreferenceActivity;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.EditorInfo;
import android.widget.*;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.AdapterView.OnItemClickListener;
import com.google.android.gms.analytics.HitBuilders;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
import jwtc.android.chess.*;
public class ICSClient extends MyBaseActivity implements OnItemClickListener {
private TelnetSocket _socket;
private Thread _workerTelnet;
private String _server, _handle, _pwd, _prompt, _waitFor, _buffer, _ficsHandle, _ficsPwd,
_sFile, _FEN = "", _whiteRating, _blackRating, _whiteHandle, _blackHandle;
private int _port, _serverType, _TimeWarning, _gameStartSound, _iConsoleCharacterSize;
private boolean _bIsGuest, _bInICS, _bAutoSought, _bTimeWarning, _bEndGameDialog,
_gameStartFront, _bConsoleText;
private Button _butLogin;
private TextView _tvHeader, _tvConsole, _tvPlayConsole;
// public ICSChatDlg _dlgChat;
private EditText _editHandle, _editPwd, _editConsole;
private Spinner _spinnerHandles;
private ArrayAdapter<String> _adapterHandles;
private ArrayList<String> _arrayPasswords;
//private EditText _editPrompt;
private ListView _listChallenges, _listPlayers, _listGames, _listStored;
private ICSChessView _view;
protected ICSMatchDlg _dlgMatch;
private ICSConfirmDlg _dlgConfirm;
private ICSChatDlg _dlgChat;
private ICSGameOverDlg _dlgOver;
private StringBuilder PGN;
private ViewAnimator _viewAnimatorMain, _viewAnimatorLobby;
private ScrollView _scrollConsole, _scrollPlayConsole;
private Ringtone _ringNotification;
private TimeZone tz = TimeZone.getDefault();
// FICS
// Challenge: withca (----) GuestFHYH (----) unrated blitz 10 0
private Pattern _pattChallenge = Pattern.compile("Challenge\\: (\\w+) \\((.+)\\) (\\w+) \\((.+)\\) (rated |unrated )(standard |blitz |wild )(\\d+) (\\d+)( \\(adjourned\\))?.*");
// @TODO ===========================================================================================
// C Opponent On Type Str M ECO Date
// 1: W jwtc N [ sr 20 0] 39-39 W3 C44 Thu Nov 5, 12:41 PST 2009
// 1: B jwtc Y [ sr 7 12] 39-39 B3 B07 Sun Jun 2, 02:59 PDT 2013
private Pattern _pattStoredRow = Pattern.compile("[\\s]*(\\d+)\\: (W|B) (\\w+)[\\s]*(Y|N).+");
// =================================================================================================
// relay
// :262 GMTopalov GMCaruana * C78
// GuestNJVN (++++) seeking 5 0 unrated blitz ("play 104" to respond)
// GuestFXXP (++++) seeking 7 0 unrated blitz f ("play 27" to respond)
// Suffocate (++++) seeking 30 30 unrated standard [black] m ("play 29" to respond)
//Pattern _pattSeeking = Pattern.compile("(\\w+) \\((.+)\\) seeking (\\d+) (\\d+) (rated |unrated ?)(standard |blitz |lightning )(\\[white\\] |\\[black\\] )?(f |m )?\\(\"play (\\d+)\" to respond\\)");
private Pattern _pattSought, _pattGameRow;
private Pattern _pattChat = Pattern.compile("(\\w+)(\\(\\w+\\))? tells you\\: (.+)");
//1269.allko ++++.kaspalesweb(U)
private Pattern _pattPlayerRow = Pattern.compile("(\\s+)?(.{4})([\\.\\:\\^\\ ])(\\w+)(\\(\\w+\\))?");
private Pattern _pattEndGame = Pattern.compile("(\\w+) \\((\\w+)\\) vs. (\\w+) \\((\\w+)\\) --- \\w+ (\\w+\\s+\\d{1,2}, )\\w.*(\\d{4})\\s(\\w.+)\\," +
" initial time: (\\d{1,3}) minutes, increment: (\\d{1,3})(.|\\n)*\\{(.*)\\} (.*)");
private Matcher _matgame;
private ArrayList<HashMap<String, String>> _mapChallenges = new ArrayList<HashMap<String, String>>();
private ArrayList<HashMap<String, String>> _mapPlayers = new ArrayList<HashMap<String, String>>();
private ArrayList<HashMap<String, String>> _mapGames = new ArrayList<HashMap<String, String>>();
private ArrayList<HashMap<String, String>> _mapStored = new ArrayList<HashMap<String, String>>();
private AlternatingRowColorAdapter _adapterGames, _adapterPlayers, _adapterChallenges, _adapterStored;
public static final String TAG = "ICSClient";
protected static final int MSG_PARSE = 1;
protected static final int MSG_STOP_SESSION = 2;
protected static final int MSG_START_SESSION = 3;
protected static final int MSG_ERROR = 4;
protected static final int SERVER_FICS = 1;
protected static final int VIEW_MAIN_BOARD = 0;
protected static final int VIEW_MAIN_LOBBY = 1;
protected static final int VIEW_MAIN_NOT_CONNECTED = 2;
protected static final int VIEW_SUB_PLAYERS = 0;
protected static final int VIEW_SUB_GAMES = 1;
protected static final int VIEW_SUB_WELCOME = 2;
protected static final int VIEW_SUB_CHALLENGES = 3;
protected static final int VIEW_SUB_PROGRESS = 4;
protected static final int VIEW_SUB_LOGIN = 5;
protected static final int VIEW_SUB_CONSOLE = 6;
protected static final int VIEW_SUB_STORED = 7;
protected static final int DECREASE = 0;
MediaPlayer tickTock, chessPiecesFall;
static class InnerThreadHandler extends Handler {
WeakReference<ICSClient> _client;
InnerThreadHandler(ICSClient client) {
this._client = new WeakReference<ICSClient>(client);
}
@Override
public void handleMessage(Message msg) {
ICSClient client = _client.get();
if (client != null) {
switch (msg.what) {
case MSG_PARSE:
//parseBuffer(msg.getData().getString("buffer"));
client.parseBuffer();
break;
case MSG_STOP_SESSION:
client.stopSession(msg.getData().getString("buffer"));
client.trackEvent(TAG, "stopsession");
break;
case MSG_START_SESSION:
client.dateTimer();
client.switchToBoardView();
client.trackEvent(TAG, "startsession");
break;
}
super.handleMessage(msg);
}
}
}
// passes the incoming data from the socket worker thread for parsing
protected InnerThreadHandler m_threadHandler = new InnerThreadHandler(this);
static class InnerTimerHandler extends Handler {
WeakReference<ICSClient> _client;
InnerTimerHandler(ICSClient client) {
this._client = new WeakReference<ICSClient>(client);
}
@Override
public void handleMessage(Message msg) {
ICSClient client = _client.get();
if (client != null) {
if (client._bAutoSought) {
if (client._socket != null && client._workerTelnet != null && client._workerTelnet.isAlive() && client._socket.isConnected() &&
client._bInICS && client.get_view().isUserPlaying() == false) {
while (client._mapChallenges.size() > 0) {
client._mapChallenges.remove(0);
}
client._adapterChallenges.notifyDataSetChanged();
client.sendString("sought");
}
}
}
}
}
private Timer _timer = null;
protected InnerTimerHandler m_timerHandler = new InnerTimerHandler(this);
private Timer _timerDate = null;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int configOrientation = this.getResources().getConfiguration().orientation;
if(configOrientation == Configuration.ORIENTATION_LANDSCAPE) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
setContentView(R.layout.icsclient);
this.makeActionOverflowMenuShown();
// needs to be called first because of chess statics init
_view = new ICSChessView(this);
_view.init();
_dlgMatch = new ICSMatchDlg(this);
_dlgConfirm = new ICSConfirmDlg(this);
_dlgChat = new ICSChatDlg(this);
_dlgOver = new ICSGameOverDlg(this);
_handle = null;
_pwd = null;
_workerTelnet = null;
_socket = null;
_tvHeader = (TextView) findViewById(R.id.TextViewHeader);
//_dlgChat = new ICSChatDlg(this);
_bIsGuest = true;
_serverType = SERVER_FICS;
_bInICS = false;
_iConsoleCharacterSize = 10;
_bAutoSought = true;
_bTimeWarning = true;
_bEndGameDialog = true;
_adapterChallenges = new AlternatingRowColorAdapter(ICSClient.this, _mapChallenges, R.layout.ics_seek_row,
new String[]{"text_game", "text_name", "text_rating"}, new int[]{R.id.text_game, R.id.text_name, R.id.text_rating});
_listChallenges = (ListView) findViewById(R.id.ICSChallenges);
_listChallenges.setAdapter(_adapterChallenges);
_listChallenges.setOnItemClickListener(this);
_adapterPlayers = new AlternatingRowColorAdapter(ICSClient.this, _mapPlayers, R.layout.ics_player_row,
new String[]{"text_name", "text_rating"}, new int[]{R.id.text_name, R.id.text_rating});
_listPlayers = (ListView) findViewById(R.id.ICSPlayers);
_listPlayers.setAdapter(_adapterPlayers);
_listPlayers.setOnItemClickListener(this);
_adapterGames = new AlternatingRowColorAdapter(ICSClient.this, _mapGames, R.layout.ics_game_row,
new String[]{"text_name1", "text_name2", "text_rating1", "text_rating2"}, new int[]{R.id.text_name1, R.id.text_name2, R.id.text_rating1, R.id.text_rating2});
_listGames = (ListView) findViewById(R.id.ICSGames);
_listGames.setAdapter(_adapterGames);
_listGames.setOnItemClickListener(this);
_adapterStored = new AlternatingRowColorAdapter(ICSClient.this, _mapStored, R.layout.ics_stored_row,
new String[]{"nr_stored", "color_stored", "text_name_stored", "available_stored"}, new int[]{R.id.nr_stored, R.id.color_stored, R.id.text_name_stored, R.id.available_stored});
_listStored = (ListView) findViewById(R.id.ICSStored);
_listStored.setAdapter(_adapterStored);
_listStored.setOnItemClickListener(this);
_viewAnimatorMain = (ViewAnimator) findViewById(R.id.ViewAnimatorMain);
_viewAnimatorMain.setOutAnimation(this, R.anim.slide_left);
_viewAnimatorMain.setInAnimation(this, R.anim.slide_right);
_viewAnimatorLobby = (ViewAnimator) findViewById(R.id.ViewAnimatorLobby);
_viewAnimatorLobby.setOutAnimation(this, R.anim.slide_left);
_viewAnimatorLobby.setInAnimation(this, R.anim.slide_right);
_scrollConsole = (ScrollView) findViewById(R.id.ScrollICSConsole);
_scrollPlayConsole = (ScrollView) findViewById(R.id.ScrollPlayConsole);
tickTock = MediaPlayer.create(this, R.raw.ticktock);
chessPiecesFall = MediaPlayer.create(this, R.raw.chesspiecesfall);
/*
ImageButton butClose = (ImageButton)findViewById(R.id.ButtonBoardClose);
butClose.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
unsetBoard();
switchToWelcomeView();
}
});
*/
ImageButton butQuick = (ImageButton) findViewById(R.id.ButtonICSQuickCmd);
if (butQuick != null) {
butQuick.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//showMenu();
openOptionsMenu();
}
});
}
ImageButton butQuick2 = (ImageButton) findViewById(R.id.ButtonICSConsoleQuickCmd);
if (butQuick2 != null) { // crashes reported on this being null
butQuick2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//showMenu();
openOptionsMenu();
}
});
}
ImageButton butCloseConsole = (ImageButton) findViewById(R.id.ICSCloseConsole);
if (butCloseConsole != null) {
butCloseConsole.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (isConnected()) {
switchToBoardView();
} else {
finish();
}
}
});
}
//
ImageButton butChat = (ImageButton) findViewById(R.id.ButtonICSChat);
if (butChat != null) {
butChat.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//ICSChatDlg
_dlgChat.show();
_bConsoleText = true;
_dlgChat.prepare();
}
});
}
_editHandle = (EditText) findViewById(R.id.EditICSHandle);
_editPwd = (EditText) findViewById(R.id.EditICSPwd);
_spinnerHandles = (Spinner) findViewById(R.id.SpinnerLoginPresets);
_spinnerHandles.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
_editHandle.setText(_spinnerHandles.getSelectedItem().toString());
_editPwd.setText(_arrayPasswords.get(position));
if (_arrayPasswords.get(position).length() < 2) {
_editPwd.setText("");
}
Log.d(TAG, _spinnerHandles.getSelectedItem().toString());
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
Log.d(TAG, "nothing selected in spinner");
}
});
/////////////////////////
final Handler actionHandler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(ICSClient.this)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete " + _spinnerHandles.getSelectedItem().toString() + "?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String newData = _spinnerHandles.getSelectedItem().toString();
_adapterHandles.remove(newData);
_adapterHandles.notifyDataSetChanged();
_arrayPasswords.remove(_spinnerHandles.getSelectedItemPosition());
_editHandle.setText("");
_editPwd.setText("");
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
};
_spinnerHandles.setOnTouchListener(new View.OnTouchListener() { // simulate long press on spinner
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
actionHandler.postDelayed(runnable, 650);
} else if(event.getAction() == MotionEvent.ACTION_UP){
actionHandler.removeCallbacks(runnable);
}
return false;
}
});
/////////////////////
_butLogin = (Button) findViewById(R.id.ButICSLogin);
if (_butLogin != null) {
_butLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
startSession(_editHandle.getText().toString(), _editPwd.getText().toString());
}
});
}
_tvConsole = (TextView) findViewById(R.id.TextViewICSBoardConsole);
_tvPlayConsole = (TextView) findViewById(R.id.TextViewICSPlayConsole);
OnKeyListener okl = new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) ||
event.getAction() == EditorInfo.IME_ACTION_DONE
) {
// Perform action on key press
EditText et = (EditText) v;
String s = et.getText().toString();
_bConsoleText = true; // show text when user types to ICS
sendString(s + "\n");
et.setText("");
return true;
}
return false;
}
};
_editConsole = (EditText) findViewById(R.id.EditICSConsole);
if (_editConsole != null) {
_editConsole.setTextColor(getResources().getColor(android.R.color.white));
_editConsole.setSingleLine(true);
_editConsole.setOnKeyListener(okl);
}
EditText editBoard = (EditText) findViewById(R.id.EditICSBoard);
if (editBoard != null) {
editBoard.setSingleLine(true);
editBoard.setOnKeyListener(okl);
}
Button butReg = (Button) findViewById(R.id.ButICSRegister);
if (butReg != null) {
butReg.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try {
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://www.freechess.org/Register/index.html"));
startActivity(i);
} catch(Exception ex){
doToast("Could not go to registration page");
}
}
});
}
_ringNotification = null;
switchToLoginView();
Log.i("ICSClient", "onCreate");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, R.string.menu_prefs, Menu.NONE, R.string.menu_prefs);
menu.add(Menu.NONE, R.string.menu_flip, Menu.NONE, R.string.menu_flip);
menu.add(Menu.NONE, R.string.ics_menu_takeback, Menu.NONE, R.string.ics_menu_takeback);
menu.add(Menu.NONE, R.string.ics_menu_adjourn, Menu.NONE, R.string.ics_menu_adjourn);
menu.add(Menu.NONE, R.string.ics_menu_draw, Menu.NONE, R.string.ics_menu_draw);
menu.add(Menu.NONE, R.string.ics_menu_resign, Menu.NONE, R.string.ics_menu_resign);
menu.add(Menu.NONE, R.string.ics_menu_abort, Menu.NONE, R.string.ics_menu_abort);
menu.add(Menu.NONE, R.string.ics_menu_flag, Menu.NONE, R.string.ics_menu_flag);
menu.add(Menu.NONE, R.string.ics_menu_refresh, Menu.NONE, R.string.ics_menu_refresh);
menu.add(Menu.NONE, R.string.ics_menu_challenges, Menu.NONE, R.string.ics_menu_challenges);
menu.add(Menu.NONE, R.string.ics_menu_games, Menu.NONE, R.string.ics_menu_games);
menu.add(Menu.NONE, R.string.ics_menu_stored, Menu.NONE, R.string.ics_menu_stored);
menu.add(Menu.NONE, R.string.ics_menu_seek, Menu.NONE, R.string.ics_menu_seek);
menu.add(Menu.NONE, R.string.ics_menu_players, Menu.NONE, R.string.ics_menu_players);
menu.add(Menu.NONE, R.string.ics_menu_stop_puzzle, Menu.NONE, R.string.ics_menu_stop_puzzle);
menu.add(Menu.NONE, R.string.ics_menu_console, Menu.NONE, R.string.ics_menu_console);
menu.add("tell puzzlebot hint");
menu.add("forward");
menu.add("backward");
menu.add("unexamine");
menu.add("tell endgamebot hint");
menu.add("tell endgamebot move");
menu.add("tell endgamebot stop");
menu.add(Menu.NONE, R.string.ics_menu_unobserve, Menu.NONE, R.string.ics_menu_unobserve);
menu.add(Menu.NONE, R.string.menu_help, Menu.NONE, R.string.menu_help);
try {
SharedPreferences prefs = this.getPrefs();
JSONArray jArray = new JSONArray(prefs.getString("ics_custom_commands", CustomCommands.DEFAULT_COMMANDS));
for (int i = 0; i < jArray.length(); i++) {
try {
menu.add(jArray.getString(i));
} catch (JSONException e) {
}
}
} catch (JSONException e) {
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean isConnected = isConnected();
boolean isUserPlaying = get_view().isUserPlaying();
boolean isNotGuest = isConnected && (false == _handle.equals("guest"));
int viewMode = this.get_view()._viewMode;
menu.findItem(R.string.menu_flip).setVisible(isConnected && viewMode != ICSChessView.VIEW_NONE);
menu.findItem(R.string.ics_menu_takeback).setVisible(isConnected && isUserPlaying);
menu.findItem(R.string.ics_menu_adjourn).setVisible(isConnected && isUserPlaying && isNotGuest);
menu.findItem(R.string.ics_menu_draw).setVisible(isConnected && isUserPlaying);
menu.findItem(R.string.ics_menu_resign).setVisible(isConnected && isUserPlaying);
menu.findItem(R.string.ics_menu_abort).setVisible(isConnected && isUserPlaying);
menu.findItem(R.string.ics_menu_flag).setVisible(isConnected && isUserPlaying);
menu.findItem(R.string.ics_menu_refresh).setVisible(isConnected && isUserPlaying);
menu.findItem(R.string.ics_menu_challenges).setVisible(isConnected && viewMode == ICSChessView.VIEW_NONE);
menu.findItem(R.string.ics_menu_games).setVisible(isConnected && viewMode == ICSChessView.VIEW_NONE);
menu.findItem(R.string.ics_menu_stored).setVisible(isConnected && viewMode == ICSChessView.VIEW_NONE && isNotGuest);
menu.findItem(R.string.ics_menu_seek).setVisible(isConnected && viewMode == ICSChessView.VIEW_NONE);
menu.findItem(R.string.ics_menu_players).setVisible(isConnected && viewMode == ICSChessView.VIEW_NONE);
menu.findItem(R.string.ics_menu_stop_puzzle).setVisible(isConnected && viewMode == ICSChessView.VIEW_PUZZLE);
menu.findItem(R.string.ics_menu_unobserve).setVisible(isConnected && viewMode == ICSChessView.VIEW_WATCH);
menu.findItem(R.string.ics_menu_console).setVisible(isConnected);
for (int i = 0; i < menu.size(); i++) {
MenuItem item = menu.getItem(i);
String title = item.getTitle().toString();
if (title.equals("tell puzzlebot hint")) {
item.setVisible(isConnected && viewMode == ICSChessView.VIEW_PUZZLE);
} else if (title.equals("forward")) {
item.setVisible(isConnected && viewMode == ICSChessView.VIEW_EXAMINE);
} else if (title.equals("backward")) {
item.setVisible(isConnected && viewMode == ICSChessView.VIEW_EXAMINE);
} else if (title.equals("unexamine")) {
item.setVisible(isConnected && viewMode == ICSChessView.VIEW_EXAMINE);
} else if (title.equals("tell endgamebot hint")) {
item.setVisible(isConnected && viewMode == ICSChessView.VIEW_ENDGAME);
} else if (title.equals("tell endgamebot move")) {
item.setVisible(isConnected && viewMode == ICSChessView.VIEW_ENDGAME);
} else if (title.equals("tell endgamebot stop")) {
item.setVisible(isConnected && viewMode == ICSChessView.VIEW_ENDGAME);
}
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i;
switch (item.getItemId()) {
case R.string.menu_prefs:
i = new Intent();
i.setClass(ICSClient.this, ICSPrefs.class);
startActivity(i);
return true;
case R.string.menu_flip:
_view.flipBoard();
_view.paint();
sendString("refresh");
return true;
case R.string.ics_menu_refresh:
sendString("refresh");
return true;
case R.string.ics_menu_takeback:
sendString("takeback 2");
return true;
case R.string.ics_menu_resume:
sendString("resume");
return true;
case R.string.ics_menu_abort:
sendString("abort");
// game will stop by way of toast
return true;
case R.string.ics_menu_adjourn:
sendString("adjourn");
return true;
case R.string.ics_menu_draw:
sendString("draw");
return true;
case R.string.ics_menu_flag:
sendString("flag");
case R.string.ics_menu_resign:
sendString("resign");
return true;
case R.string.ics_menu_games:
// switchToLoadingView();
switchToGamesView();
sendString("games");
return true;
case R.string.ics_menu_stored:
switchToStoredView();
sendString("stored");
return true;
case R.string.ics_menu_challenges:
switchToChallengeView();
return true;
case R.string.ics_menu_seek:
_dlgMatch._rbSeek.performClick();
return true;
case R.string.menu_help:
i = new Intent();
i.setClass(ICSClient.this, HtmlActivity.class);
i.putExtra(HtmlActivity.HELP_MODE, "help_online");
startActivity(i);
return true;
case R.string.ics_menu_console:
switchToConsoleView();
return true;
case R.string.ics_menu_players:
sendString("who a");
switchToLoadingView();
return true;
case R.string.ics_menu_quit:
finish();
return true;
case R.string.ics_menu_stop_puzzle:
sendString("tell puzzlebot stop");
get_view().stopGame();
return true;
case R.string.ics_menu_unobserve:
sendString("unobserve");
get_view().stopGame();
return true;
case android.R.id.home:
confirmAbort();
return true;
}
sendString(item.getTitle().toString());
return true;
}
public void confirmAbort() {
Log.i("ICSClient", "confirmAbort");
if (isConnected()) {
if (_viewAnimatorMain.getDisplayedChild() == VIEW_MAIN_BOARD && get_view().isUserPlaying()) {
new AlertDialog.Builder(ICSClient.this)
.setTitle(ICSClient.this.getString(R.string.ics_menu_abort) + "?")
.setPositiveButton(getString(R.string.alert_yes),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
sendString("abort");
sendString("quit");
finish();
}
})
.setNegativeButton(getString(R.string.alert_no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
return;
}
}
finish();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
confirmAbort();
return true;
}
return super.onKeyDown(keyCode, event);
}
public void stopSession(String sReason) {
Log.e("stopSession", sReason);
if (isFinishing()) {
return;
}
new AlertDialog.Builder(ICSClient.this)
.setTitle(R.string.title_error)
.setMessage(sReason)
.setPositiveButton(R.string.alert_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
finish();
}
})
.show();
}
public void startSession(final String h, final String p) {
if (h == "") {
globalToast(getString(R.string.msg_ics_enter_handle));
return;
}
Log.i("ICSClient", "Setting servertype to FICS");
_serverType = SERVER_FICS;
_server = "freechess.org";
_port = 23;
_prompt = "fics% ";
_ficsHandle = h;
_ficsPwd = p;
_handle = _ficsHandle;
_pwd = _ficsPwd;
if (_handle != "guest" && _pwd == "") {
globalToast(getString(R.string.msg_ics_enter_password));
return;
}
// FICS
//209 1739 rahulso 15 10 unrated standard [white] 0-9999 m
//101 ++++ GuestYYLN 16 0 unrated standard 0-9999 mf
// 6 ++++ sdhisfh 2 0 unrated crazyhouse 0-9999
// 11 ++++ GuestFGMX 20 10 unrated standard 0-9999 f
// 7 ++++ Amhztb 10 90 unrated standard 0-9999 m
// 26 ++++ GuestFFHQ 7 0 unrated wild/3 [white] 0-9999
_pattSought = Pattern.compile("[\\s]*(\\d+)[\\s]+(\\d+|\\++|-+)[\\s]+([\\w\\(\\)]+)[\\s]+(\\d+)[\\s]+(\\d+)[\\s]+(rated|unrated?)[\\s]+([\\w/\\d]+?)[\\s]*(\\[white\\]|\\[black\\])?[\\s]*(\\d+)\\-(\\d+)[\\s]*([fm]+)?");
// " 09 09 | +++ handle() 09 09 wild/3
// FICS
// 93 2036 WFMKierzek 2229 FMKarl [ su120 0] 26:13 - 3:49 (22-22) W: 28
// 1 2 3 4 5 678 9
_pattGameRow = Pattern.compile("[\\s]*(\\d+) (\\d+) (\\w+)[\\s]+(\\d+) (\\w+)[\\s]+\\[ (s|b|l)(r|u)[\\s]*(\\d+)[\\s]*(\\d+)\\][\\s]*(\\d+):(\\d+)[\\s]*-[\\s]*(\\d+):(\\d+).+");
_butLogin.setEnabled(false);
switchToLoadingView();
_workerTelnet = new Thread(new Runnable() {
public void run() {
Message msg, msgStop;
Bundle bun;
msgStop = new Message();
msgStop.what = MSG_STOP_SESSION;
_bIsGuest = _handle.equals("guest");
try {
_socket = new TelnetSocket(_server, _port);
} catch (Exception ex) {
_socket = null;
bun = new Bundle();
bun.putString("buffer", getString(R.string.ics_error_connection));
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
try {
// do login
String data = "";
String buf = _socket.readString();
while (buf != null && !isFinishing()) {
data += buf;
if (data.indexOf("login: ") > 0)
break;
//Log.i("startSession 0", "Fetching until 'login:'");
buf = _socket.readString();
}
if (data.length() == 0) {
bun = new Bundle();
bun.putString("buffer", "No response from server after connection...");
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
//Log.i("startSession 1", "First response: " + data);
if (data.indexOf("login: ") == -1) {
bun = new Bundle();
bun.putString("buffer", "Unexpected response from server after connection...");
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
Log.i("startSession 1", "Logging in with " + _handle);
sendString(_handle);
int iPos, iPos2;
data = "";
buf = _socket.readString();
while (buf != null) {
data += buf;
if (data.indexOf("\":") > 0 &&
(data.indexOf("Press return to enter the server as") > 0 ||
data.indexOf("Logging you in as") > 0) ||
data.indexOf("password: ") > 0 || data.indexOf("login:") > 0
)
break;
Log.i("startSession debug", "wait: " + data);
buf = _socket.readString();
}
if (data.length() == 0) {
bun = new Bundle();
bun.putString("buffer", "No response from server after setting login handle...");
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
// just remove all newlines from the string for better regex matching
data = data.replaceAll("[\r\n\0]", "");
Log.i("startSession 2", "After handle: " + data);
iPos = data.indexOf("Press return to enter the server as \"");
iPos2 = data.indexOf("Logging you in as \"");
//iPos3 = data.indexOf("If it is yours, type the password");
if (iPos >= 0) {
data = data.trim();
Log.i("startSession 2.1", "Guest log in v1");
// Press return to enter the server as
Pattern patt = Pattern.compile("Press return to enter the server as \"(\\w+)\":");
Matcher match = patt.matcher(data);
if (match.find()) {
_handle = match.group(1);
sendString("");
} else {
bun = new Bundle();
bun.putString("buffer", "Could not process response after setting login handle...(1)");
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
} else if (iPos2 >= 0) {
Log.i("startSession 2.1", "Guest log in v2");
Pattern patt = Pattern.compile("Logging you in as \"(\\w+)\"");
Matcher match = patt.matcher(data);
if (match.find()) {
_handle = match.group(1);
} else {
bun = new Bundle();
bun.putString("buffer", "Could not process response after setting login handle...(2)");
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
} else if (data.indexOf("password: ") > 0) {
sendString(_pwd);
} else {
bun = new Bundle();
bun.putString("buffer", "username error: " + data);
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
data = "";
buf = _socket.readString();
while (buf != null) {
data += buf;
if (data.length() > 20)
break;
buf = _socket.readString();
}
Log.i("startSession 3", "Response after password: " + data);
if (data == null || data.length() == 0) {
bun = new Bundle();
bun.putString("buffer", "No response from server while logging in...");
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
if (data.indexOf("**** Starting ") == -1 && data.indexOf("****************") == -1) {
bun = new Bundle();
bun.putString("buffer", "password error: " + data);
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
_bInICS = true;
sendString("style 12");
sendString("-channel 4"); // guest
sendString("-channel 53"); // guest chat
sendString("set kibitz 1"); // for puzzlebot
sendString("set tzone " + tz.getDisplayName(false, TimeZone.SHORT)); // sets timezone
// sendMessage("set interface "+ getPreferences().getString(APP_NAME));
Log.i("ICSClient", " == HANDLE " + _handle);
// _handle
msg = new Message();
msg.what = MSG_START_SESSION;
m_threadHandler.sendMessage(msg);
//
String buffer = "";
_waitFor = _prompt;
buffer = "";
while (_socket != null && _socket.isConnected()) {
data = _socket.readString();
if (data != null && data.length() > 0) {
//Log.i("WorkerTelnet = ", data);
buffer += data;
if (buffer.endsWith(_waitFor)) {
_buffer = buffer;
msg = new Message();
msg.what = MSG_PARSE;
bun = new Bundle();
//bun.putString("buffer", buffer);
//msg.setData(bun);
m_threadHandler.sendMessage(msg);
buffer = "";
}
}
}
} catch (Exception ex) {
bun = new Bundle();
bun.putString("buffer", getString(R.string.ics_error_connection));
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
Log.e("WorkerTelnet", ex.toString());
}
_bInICS = false;
Log.i("WorkerTelnet", "stopped");
finish();
}
});
_workerTelnet.start();
}
private void parseBuffer() {
try {
//Log.i("parseBuffer", "[" + buffer + "]");
String sRaw = "", sEnd = "", sBeg = "";
Matcher match;
//////////////////////////////////////////////////////////////////////////////////////////////
String[] lines;
if (_serverType == SERVER_FICS) {
lines = _buffer.split("\n\r");
} else {
lines = _buffer.split("\r\n");
}
//Log.i("WorkerTelnet", "looking within STATUS_ONLINE");
// 680 players displayed (of 680). (*) indicates system administrator.
// result for who
if (lines.length > 3 && _buffer.indexOf("players displayed (of ") > 0 && _buffer.indexOf("indicates system administrator.") > 0) {
_mapPlayers.clear();
for (int i = 0; i < lines.length - 2; i++) {
match = _pattPlayerRow.matcher(lines[i]);
while (match.find()) {
String name = match.group(4);
if (name != null && match.group(2) != null) {
String code = match.group(5);
if (code == null) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("text_name", name);
item.put("text_rating", match.group(2));
_mapPlayers.add(item);
} else {
if (code == "(U)" || code == "(FM)" || code == "(GM)" || code == "(IM)" || code == "(WIM)" || code == "(WGM)") {
name += code;
HashMap<String, String> item = new HashMap<String, String>();
item.put("text_name", name);
item.put("text_rating", match.group(2));
_mapPlayers.add(item);
}
}
}
}
}
switchToPlayersView();
Collections.sort(_mapPlayers, new ComparatorHashRating());
_adapterPlayers.notifyDataSetChanged();
}
//////////////////////////////////////////////////////////////////////////////////////////////
// result for stored
/*
else if(lines.length > 3 && _buffer.indexOf("Stored games for " + _handle + ":") > 0){
//_pattStoredRow
}*/
//////////////////////////////////////////////////////////////////////////////////////////////
// single line stuff
else {
String line;
for (int i = 0; i < lines.length; i++) {
line = lines[i].replace(_prompt, "");
// lines can still contain prompt!
// _prompt
//////////////////////////////////////////////////////////////
if (line.contains("Game") || line.contains("Creating:") || line.contains("Issuing:") || line.contains("Challenge:")){
// 1 2 3 4 5 6 7 8
//Creating: bunnyhopone (++++) mardukedog (++++) unrated blitz 5 5
Pattern _pattGameInfo1 = Pattern.compile("\\{?\\w+\\s?\\d+?: (\\w+) \\((.{3,4})\\) (\\w+) \\((.{3,4})\\) (\\w+) (\\w+) (\\d+) (\\d+)");
Pattern _pattGameInfo2 = Pattern.compile("\\w+: (\\w+) \\((.{3,4})\\) (\\w+) \\((.{3,4})\\) (\\w+) (\\w+) (\\d+) (\\d+)");
Pattern _pattGameInfo3 = Pattern.compile("\\{\\w+\\s(\\d+) \\((\\w+) vs. (\\w+)\\) (.*)\\} (.*)");
Matcher mat = _pattGameInfo1.matcher(line);
Matcher mat2 = _pattGameInfo2.matcher(line);
Matcher mat3 = _pattGameInfo3.matcher(line);
if (mat.matches() || mat2.matches()){ //mat and mat2 are the beginning game info
_whiteHandle = mat.matches() ? mat.group(1) : mat2.group(1);
_whiteRating = mat.matches() ? mat.group(2) : mat2.group(2);
if (_whiteRating.equals("++++")){
_whiteRating = "UNR";
}
_blackHandle = mat.matches() ? mat.group(3) : mat2.group(3);
_blackRating = mat.matches() ? mat.group(4) : mat2.group(4);
if (_blackRating.equals("++++")){
_blackRating = "UNR";
}
}
if (mat3.matches()){ // mat3 is the endgame result
sendString("oldmoves " + _whiteHandle); // send moves at end of game
Log.d(TAG, "oldmoves " + _whiteHandle);
}
}
// board representation
if (line.indexOf("<12> ") >= 0) {
// this can be multiple lines!
String[] gameLines = line.split("<12> ");
if(_FEN.isEmpty() && gameLines[1].contains("none (0:00) none")) {
_FEN = gameLines[1]; // get first gameLine - contains FEN setup
}
for (int j = 0; j < gameLines.length; j++) {
// at least 65 chars
if (gameLines[j].length() > 65) {
//if(get_view().preParseGame(gameLines[j])){
if (get_view().parseGame(gameLines[j], _handle)) {
switchToBoardView();
} else {
//gameToast("There was a problem parsing the response of the server.", false);
Log.w("parseBuffer", "Could not parse game response");
addConsoleText("Could not parse game response");
}
//}
}
}
}
///////////////////////////////////////////////////////////////
// Challenge: jwtc (++++) jewithca (++++) unrated blitz 5 0.
else if (line.indexOf("Challenge:") >= 0) {
Log.i("parseBuffer", "parsing challenge " + line);
match = _pattChallenge.matcher(line);
if (match.matches()) {
String opponent, rating;
if (match.group(1).equals(_handle)) {
opponent = match.group(3);
rating = match.group(4);
} else {
opponent = match.group(1);
rating = match.group(2);
}
//Log.i("parseBuffer", "matched challenge");
// ("adjourned", match.group(9) != null);
new AlertDialog.Builder(ICSClient.this)
.setTitle(ICSClient.this.getString(R.string.title_challenge))
.setMessage(opponent +
" [" + rating +
"]\nchallenges you for a " + match.group(7) + " min.+" + match.group(8) + "s " + match.group(5) + " " + match.group(6) + ".\nDo you wish to accept?")
.setPositiveButton(getString(R.string.alert_yes),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
sendString("accept");
dialog.dismiss();
}
})
.setNegativeButton(getString(R.string.alert_no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
}
}
//////////////////////////////////////////////////////////////
// seek no longer available
else if (line.equals("That seek is not available.")) {
gameToast("That seek is not available", false);
}
/////////////////////////////////////////////////////////////////
// game created
else if (line.indexOf("{Game ") >= 0 && (line.indexOf(" Creating ") > 0 || line.indexOf(" Continuing ") > 0)) {
Pattern p = Pattern.compile("\\{Game (\\d+) .*");
Matcher m = p.matcher(line);
if (m.matches()) {
get_view().setGameNum(Integer.parseInt(m.group(1)));
get_view().setViewMode(ICSChessView.VIEW_PLAY);
switchToBoardView();
}
} else if (line.indexOf("Creating: ") >= 0 && line.indexOf("(adjourned)") >= 0) {
//Creating: jcarolus (----) jwtc (----) unrated blitz 5 0 (adjourned)
get_view().setViewMode(ICSChessView.VIEW_PLAY);
switchToBoardView();
gameToast("Resuming adjourned game", false);
}
//////////////////////////////////////////////////////////////
else if (line.indexOf("Illegal move (") == 0) {
gameToast("Illegal move", false);
}
//////////////////////////////////////////////////////////////
// abort
else if (get_view().isUserPlaying() && line.indexOf(get_view().getOpponent() + " would like to abort the game") != -1) { // todo add opponent in match
confirmShow(getString(R.string.title_offers_abort), getString(R.string.ics_offers_abort), "abort");
} else if (get_view().isUserPlaying() && line.indexOf("Game aborted by mutual agreement}") >= 0) {
gameToast("Game aborted by mutual agreement", true);
get_view().setViewMode(ICSChessView.VIEW_NONE);
}
//////////////////////////////////////////////////////////////
// take back
else if (get_view().isUserPlaying() && line.indexOf(get_view().getOpponent() + " would like to take back ") != -1) { //
confirmShow(getString(R.string.title_offers_takeback), getString(R.string.ics_offers_takeback), "accept");
}
//////////////////////////////////////////////////////////////
// aborted/adjouned
else if (line.indexOf("{Game " /*+ get_view().getGameNum()*/) >= 0 && line.indexOf("} *") > 0) {
String text = getString(R.string.ics_game_over);
gameToast(text, true);
get_view().setViewMode(ICSChessView.VIEW_NONE);
}
//////////////////////////////////////////////////////////////
// game over
else if (line.contains("{Game ") && (line.contains("} 1-0") || line.contains("} 0-1") || line.contains("} 1/2-1/2"))) {
String text = "";
text = line.substring(line.indexOf(")") + 2, line.indexOf("}")); // gets name and state of name
if (line.contains("} 1-0") || line.contains("} 0-1")) {
if (line.indexOf(" resigns} ") > 0) { // make translation friendly
text = text.replace("resigns", getString(R.string.state_resigned));
} else if (line.indexOf("checkmated") > 0) {
text = text.replace("checkmated", getString(R.string.state_mate));
} else if (line.indexOf("forfeits on time") > 0) {
text = text.replace("forfeits on time", getString(R.string.state_time));
} else {
text = getString(R.string.ics_game_over);
}
}
else if (line.contains("} 1/2-1/2")){ // draw
gameToast(String.format(getString(R.string.ics_game_over_format), getString(R.string.state_draw)), true);
}
gameToast(String.format(getString(R.string.ics_game_over_format), text), true);
get_view().setViewMode(ICSChessView.VIEW_NONE);
}
//////////////////////////////////////////////////////////////
// draw / abort / todo:adjourn request sent
else if (line.equals("Draw request sent.") || line.equals("Abort request sent.") || line.equals("Takeback request sent.")) {
gameToast(getString(R.string.ics_request_sent), false);
} else if (get_view().isUserPlaying() && line.indexOf(get_view().getOpponent() + " offers you a draw.") >= 0) {
confirmShow(getString(R.string.title_offers_draw), getString(R.string.ics_offers_draw), "draw");
} else if (get_view().isUserPlaying() && line.indexOf(get_view().getOpponent() + " would like to adjourn the game; type \"adjourn\" to accept.") >= 0) {
confirmShow(getString(R.string.title_offers_adjourn), getString(R.string.ics_offers_adjourn), "adjourn");
}
/////////////////////////////////////////////////////////////
// chat
else if (line.indexOf(" tells you: ") > 0) {
match = _pattChat.matcher(line);
if (match.matches()) {
//globalToast(String.format(getString(R.string.ics_tells_you), match.group(1), match.group(3)));
String s = String.format(getString(R.string.ics_tells_you), match.group(1), match.group(3));
while (i + 2 < lines.length && lines[i + 1].startsWith("\\")) {
i++;
s += line.replace("\\", "");
}
addConsoleText(s);
}
}
// observe status
else if (line.indexOf("You are now observing game") >= 0) {
_FEN = ""; // reset in case last watched game wasn't finished
get_view().setViewMode(ICSChessView.VIEW_WATCH);
//gameToast("Observing a game", false);
}
// stop observing
else if (line.indexOf("Removing game") >= 0 && line.indexOf("from observation list") > 0 || line.indexOf("You are no longer examining game") >= 0) {
//gameToast("No longer observing the game", true);
get_view().setViewMode(ICSChessView.VIEW_NONE);
}
// examine
else if (line.indexOf("puzzlebot has made you an examiner of game") >= 0) {
get_view().setViewMode(ICSChessView.VIEW_PUZZLE);
gameToast("Puzzle started", false);
}
// stop problem
else if (line.indexOf("Your current problem has been stopped") >= 0) {
get_view().setViewMode(ICSChessView.VIEW_NONE);
gameToast("Puzzle stopped", true);
}
/////////////////////////////////////////////////////////////
// game talk
else if (line.indexOf("[" + get_view().getGameNum() + "] says: ") > 0) {
String s = line;
while (i + 2 < lines.length && lines[i + 1].startsWith("\\")) {
i++;
s += line.replace("\\", "");
}
addConsoleText(s);
}
//////////////////////////////////////////////////////////////
// TODO what is this
else if (line.indexOf("-->") == 0) {
// globalToast(line);
} else if (line.indexOf("kibitzes:") > 0) {
String s = line.replace("kibitzes:", "");
while (i + 2 < lines.length && lines[i + 1].startsWith("\\")) {
i++;
s += line.replace("\\", "");
}
addConsoleText(s);
}
/////////////////////////////////////////////////////////////////
// result of sought
else if ((false == get_view().isUserPlaying()) && _pattSought.matcher(line).matches()) {
match = _pattSought.matcher(line);
if (match.matches()) {
//Log.i("PATSOUGHT", "groupCount " + match.groupCount());
if (match.groupCount() > 7) {
String s, type, rated;
if (_serverType == SERVER_FICS) {
// 1 2 3 4 5 6 7 8
// 209 1739 rahulso 15 10 unrated standard [white] 0-9999 m
s = String.format("%2dm+%2ds", Integer.parseInt(match.group(4)), Integer.parseInt(match.group(5)));
type = match.group(7);
rated = match.group(6);
} else {
// 1 2 3 4 5 6 7 8
// 5 1111 SlowFlo(C) standard 30 30 rated white 0-1700 mf
s = String.format("%2dm+%2ds", Integer.parseInt(match.group(5)), Integer.parseInt(match.group(6)));
type = match.group(4);
rated = match.group(7);
}
//_adapter.insert(s + " " + b.getString("type") + " " + b.getString("opponent") + "[" + b.getString("rating") + "]", 0);
HashMap<String, String> item = new HashMap<String, String>();
if (type.indexOf("blitz") >= 0 || type.indexOf("standard") >= 0) {
if (type.indexOf("standard") >= 0)
type = "";
item.put("text_game", s + " " + rated + " " + type);
item.put("play", match.group(1));
item.put("text_name", match.group(3));
item.put("text_rating", match.group(2));
_mapChallenges.add(0, item);
_adapterChallenges.notifyDataSetChanged();
}
//switchToChallengeView();
} else {
Log.w("ICSClient", "pattSought match, but groupcount = " + match.groupCount());
}
}
}
// skip stuff
else if (line.indexOf("seeking") > 0 && line.indexOf("to respond") > 0) {
// skip seeking stuff, is handled via 'sought' command
//Log.i("ICSClient", "Skip seeking");
} else if (line.indexOf("ads displayed.") > 0) {
//Log.i("ICSClient", "Skip ads displayed");
}
//////////////////////////////////////////////////////////////////////////////////////////////
// result for games
else if ((false == get_view().isUserPlaying()) && _pattGameRow.matcher(line).matches()) {
//Log.i("ICSClient", "GAMEROW match");
match = _pattGameRow.matcher(line);
if (match.matches()) {
HashMap<String, String> item = new HashMap<String, String>();
// 93 2036 WFMKierzek 2229 FMKarl [ su120 0] 26:13 - 3:49 (22-22) W: 28
item.put("nr", match.group(1));
item.put("text_rating1", match.group(2));
item.put("text_name1", match.group(3));
item.put("text_rating2", match.group(4));
item.put("text_name2", match.group(5));
item.put("text_type", match.group(6).toUpperCase() + match.group(7).toUpperCase());
item.put("text_time1", match.group(10) + ":" + match.group(11));
item.put("text_time2", match.group(12) + ":" + match.group(13));
_mapGames.add(0, item);
_adapterGames.notifyDataSetChanged();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// result for stored games
else if ((false == get_view().isUserPlaying()) && _pattStoredRow.matcher(line).matches()) {
//Log.i(TAG, "stored row match");
match = _pattStoredRow.matcher(line);
if (match.matches()) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("nr_stored", match.group(1));
item.put("color_stored", match.group(2));
item.put("text_name_stored", match.group(3));
item.put("available_stored", match.group(4).equals("Y") ? "*" : "");
_mapStored.add(item);
_adapterStored.notifyDataSetChanged();
}
}
//////////////////////////////////////////////////////////////
// shouts, tshouts etc...
// any other data we haven't matched, put it on prompt
else if (line.length() > 0) {
Log.i("ICSClient", "lines[" + i + "] " + line);
//Log.i("ICSClient", "lines[" + i + "][last] " + (int)(line.charAt(line.length()-1)));
sRaw += "\n" + line;
}
} // for line
//////////////////////////////////////////////////////////////
if (sRaw.length() > 0) {
sRaw = sRaw.replace(new Character((char) 7).toString(), "").replace("\\", "").replace("\t", "").replace(_prompt, "\n").trim();
sRaw = sRaw.replaceAll("[\n]{2,}", "\n");
if (sRaw.length() > 0) {
addConsoleText(sRaw);
}
if (_bEndGameDialog){
sEnd += sRaw;
//Log.d(TAG, "sEnd ->" + sEnd);
_matgame = _pattEndGame.matcher(sEnd);
if(_matgame.matches()){
sEnd = sEnd.trim().replaceAll(" +", " ");
sEnd = sEnd.replaceAll("\\{.*\\}", "");
String event = sEnd.substring(sEnd.indexOf("\n"), sEnd.indexOf(", initial"));
event = event.replace("\n", "");
String site = "FICS";
String timeControl = sEnd.substring(sEnd.indexOf("time:")+6, sEnd.indexOf(".", sEnd.indexOf("time:")));
String _FEN1, _FEN2;
sBeg = sEnd.substring(sEnd.indexOf("1."), sEnd.length());
sBeg = sBeg.replaceAll("\\s*\\([^\\)]*\\)\\s*", " "); // gets rid of timestamp and parentheses
PGN = new StringBuilder("");
PGN.append("[Event \"" + event + "\"]\n");
PGN.append("[Site \"" + site + "\"]\n");
PGN.append("[Date \"" + _matgame.group(5) + _matgame.group(6) + "\"]\n");
PGN.append("[White \"" + _matgame.group(1) + "\"]\n");
PGN.append("[Black \"" + _matgame.group(3) + "\"]\n");
PGN.append("[Result \"" + _matgame.group(12) + "\"]\n");
PGN.append("[WhiteElo \"" + _matgame.group(2) + "\"]\n");
PGN.append("[BlackElo \"" + _matgame.group(4) + "\"]\n");
PGN.append("[TimeControl \"" + timeControl + "\"]\n");
if(!_FEN.equals("")) { // As for now, used for Chess960 FEN.
_FEN1 = _FEN.substring(0, _FEN.indexOf(" "));
_FEN2 = _FEN.substring(_FEN.indexOf("P") + 9, _FEN.indexOf("W") - 1);
if (!_FEN1.equals("rnbqkbnr") || !_FEN2.equals("RNBQKBNR")) {
PGN.append("[FEN \"" + _FEN1 + "/pppppppp/8/8/8/8/PPPPPPPP/" + _FEN2 + " w KQkq - 0 1" + "\"]\n");
}
_FEN = ""; // reset to capture starting FEN for next game
}
PGN.append(sBeg + "\n\n");
saveGameSDCard();
_dlgOver.updateGRtext(_matgame.group(11)); // game result message sent to dialog
_dlgOver.setWasPlaying(get_view().getOpponent().length() > 0);
_dlgOver.show();
//_dlgOver.prepare();
}
}
}
} // single line stuff
} catch (Exception ex) {
Log.e("WorkerTelnet", ex.toString());
}
}
public void copyToClipBoard() {
try {
ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
cm.setText(PGN.toString());
doToast(getString(R.string.ics_copy_clipboard));
} catch (Exception e) {
doToast(getString(R.string.err_copy_clipboard));
Log.e("ex", e.toString());
}
}
public void saveGameSDCard(){
try{
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
_sFile = Environment.getExternalStorageDirectory() + "/chessgamesonline.pgn";
FileOutputStream fos;
fos = new FileOutputStream(_sFile, true);
fos.write(PGN.toString().getBytes());
fos.flush();
fos.close();
doToast(getString(R.string.ics_save_game));
} else {
doToast(getString(R.string.err_sd_not_mounted));
}
} catch (Exception e) {
doToast(getString(R.string.err_saving_game));
Log.e("ex", e.toString());
}
}
public void SendToApp(){
try {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "chess pgn");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + _sFile));
sendIntent.setType("application/x-chess-pgn");
startActivity(sendIntent);
} catch (Exception e) {
doToast(getString(R.string.err_send_email));
Log.e("ex", e.toString());
}
}
public void addConsoleText(final String s) {
_tvConsole.setTypeface(Typeface.MONOSPACE); // Monospace gives each character the same width
_tvPlayConsole.setTypeface(Typeface.MONOSPACE);
_tvConsole.setTextSize(_iConsoleCharacterSize); // sets console text size
_tvPlayConsole.setTextSize(_iConsoleCharacterSize);
final String s2 = _tvConsole.getText() + "\n\n" + s;
if (s2.length() > 8192) {
_tvConsole.setText(s2.substring(s2.length() - 4096));
} else {
_tvConsole.append("\n\n" + s);
}
final String s3 = _tvPlayConsole.getText() + "\n\n" + s;
if(s3.length() > 1024){
_tvPlayConsole.setText(s3.substring(s3.length() - 512));
} else {
_tvPlayConsole.append("\n\n" + s);
}
_scrollPlayConsole.post(new Runnable() {
public void run() {
_scrollPlayConsole.fullScroll(HorizontalScrollView.FOCUS_DOWN);
}
});
}
private void confirmShow(String title, String text, String sendstring) {
_dlgConfirm.setSendString(sendstring);
_dlgConfirm.setText(title, text);
_dlgConfirm.show();
}
public void gameToast(final String text, final boolean stop) {
if (stop) {
get_view().stopGame();
}
Toast t = Toast.makeText(this, text, Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
}
private void globalToast(final String text) {
Toast t = Toast.makeText(this, text, Toast.LENGTH_LONG);
t.setGravity(Gravity.BOTTOM, 0, 0);
t.show();
}
@Override
protected void onResume() {
SharedPreferences prefs = this.getPrefs();
ChessImageView._colorScheme = prefs.getInt("ColorScheme", 0);
_view.setConfirmMove(prefs.getBoolean("ICSConfirmMove", false));
_ficsHandle = prefs.getString("ics_handle", null);
_ficsPwd = prefs.getString("ics_password", null);
_iConsoleCharacterSize = Integer.parseInt(prefs.getString("ICSConsoleCharacterSize", "10"));
_bAutoSought = prefs.getBoolean("ICSAutoSought", true);
_bTimeWarning = prefs.getBoolean("ICSTimeWarning", true);
_TimeWarning = Integer.parseInt(prefs.getString("ICSTimeWarningsecs", "10"));
_bEndGameDialog = prefs.getBoolean("ICSEndGameDialog", true);
_gameStartSound = Integer.parseInt(prefs.getString("ICSGameStartSound", "1"));
_gameStartFront = prefs.getBoolean("ICSGameStartBringToFront", true);
/////////////////////////////////////////////
_adapterHandles = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
_arrayPasswords = new ArrayList<String>();
if(_ficsHandle != null) {
_adapterHandles.add(_ficsHandle);
_arrayPasswords.add(_ficsPwd);
}
try {
JSONArray jArray = new JSONArray(prefs.getString("ics_handle_array", "guest"));
JSONArray jArrayPasswords = new JSONArray(prefs.getString("ics_password_array", ""));
for(int i = 0; i < jArray.length(); i++){
_adapterHandles.add(jArray.getString(i));
_arrayPasswords.add(jArrayPasswords.getString(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int t= 0;
boolean g = false;
for (int i = 0; i < _adapterHandles.getCount(); i++) {
String x = _adapterHandles.getItem(i).toString();
if (x.equals(_ficsHandle)) {
t++;
}
if (x.equals("guest")){
g = true; // flag to check if guest is in the spinner
}
}
if (t > 1) { // work around for remove - delete every occurrence and add latest - this will add latest password
while (t > 0) {
_adapterHandles.remove(_ficsHandle);
_arrayPasswords.remove(_adapterHandles.getPosition(_ficsHandle)+1);
t--;
}
_adapterHandles.add(_ficsHandle);
_arrayPasswords.add(_ficsPwd);
}
if (g==false){
_adapterHandles.add("guest"); // if no guest then add guest
_arrayPasswords.add(" ");
}
_spinnerHandles.setAdapter(_adapterHandles);
_spinnerHandles.setSelection(_adapterHandles.getPosition(_ficsHandle));
/////////////////////////////////////////////////////////////////
if (_ficsHandle == null) {
_ficsHandle = "guest";
_ficsPwd = "";
}
String sTmp = prefs.getString("NotificationUri", null);
if (sTmp == null) {
_ringNotification = null;
} else {
Uri tmpUri = Uri.parse(sTmp);
_ringNotification = RingtoneManager.getRingtone(this, tmpUri);
}
//if(true)return;
if (isConnected()) {
switchToBoardView();
} else {
Log.i("onResume", "socket " + (_socket == null) + " worker " + (_workerTelnet == null));
_editHandle.setText(_ficsHandle);
_editPwd.setText(_ficsPwd);
if (_ficsPwd.length() < 2){
_editPwd.setText("");
}
/////////////////////////////////////////////////////
// DEBUG
//switchToBoardView();
/////////////////////////////////////////////////////
// real
switchToLoginView();
}
//rescheduleTimer();
super.onResume();
}
public String get_ficsHandle(){
return _ficsHandle;
}
public boolean is_bTimeWarning() {
return _bTimeWarning;
}
public int get_TimeWarning() {
return _TimeWarning;
}
public int get_gameStartSound(){
return _gameStartSound;
}
public String get_whiteRating(){
return _whiteRating == null ? "" : _whiteRating;
}
public String get_blackRating(){
return _blackRating == null ? "" : _blackRating;
}
public boolean isConnected() {
if (_socket == null || _workerTelnet == null || (false == _workerTelnet.isAlive()) || (false == _bInICS) || (false == _socket.isConnected())) {
return false;
}
return true;
}
public void bringAPPtoFront(){
if (_gameStartFront) {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasklist = am.getRunningTasks(10); // Number of tasks you want to get
if (!tasklist.isEmpty()) {
int nSize = tasklist.size();
for (int i = 0; i < nSize; i++) {
ActivityManager.RunningTaskInfo taskinfo = tasklist.get(i);
if (taskinfo.topActivity.getPackageName().equals("jwtc.android.chess")) {
am.moveTaskToFront(taskinfo.id, 2);
}
}
}
}
}
@Override
protected void onPause() {
// lock screen orientation?
//setRequestedOrientation(this.getResources().getConfiguration().orientation);
////////////////////////////////////////////////////////////
SharedPreferences.Editor editor = this.getPrefs().edit();
if (_bIsGuest) {
_handle = "guest";
}
editor.putString("ics_handle", _ficsHandle);
editor.putString("ics_password", _ficsPwd);
JSONArray jArray = new JSONArray();
JSONArray jArrayPasswords = new JSONArray();
for(int i = 0; i < _adapterHandles.getCount(); i++){
jArray.put(_adapterHandles.getItem(i));
jArrayPasswords.put(_arrayPasswords.get(i));
}
editor.putString("ics_handle_array", jArray.toString());
editor.putString("ics_password_array", jArrayPasswords.toString());
editor.commit();
super.onPause();
}
@Override
protected void onStart() {
Log.i("ICSClient", "onStart");
super.onStart();
}
@Override
protected void onStop() {
Log.i("ICSClient", "onStop");
super.onStop();
}
@Override
protected void onDestroy() {
Log.i("ICSClient", "onDestroy");
_workerTelnet = null;
disconnect();
tickTock.release(); // clear MediaPlayer resources
chessPiecesFall.release();
super.onDestroy();
}
public void rescheduleTimer() {
_timer = new Timer(true);
_timer.schedule(new TimerTask() {
@Override
public void run() {
m_timerHandler.sendMessage(new Message());
}
}, 200, 5000);
}
public void cancelTimer() {
if (_timer != null) {
_timer.cancel();
}
}
public void dateTimer(){
if(_timerDate == null) {
_timerDate = new Timer(true);
_timerDate.schedule(new TimerTask() {
@Override
public void run() {
dateHandler.sendEmptyMessage(0); // sends date string to prevent disconnection
}
}, 60000, 60000);
}
}
public void cancelDateTimer(){
if(_timerDate != null) {
_timerDate.cancel();
_timerDate = null;
}
}
Handler dateHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
sendString("date");
}
};
public void disconnect() {
if (_socket != null) {
try {
_socket.close();
} catch (Exception ex) {
}
_socket = null;
Log.d(TAG, "disconnect method");
}
cancelDateTimer();
}
public void sendString(String s) {
if (_bConsoleText){ // allows user ICS console text only
addConsoleText(s);
_bConsoleText = false;
}
if (_socket == null || _socket.sendString(s + "\n") == false) {
switch (get_gameStartSound()) {
case 0:
break;
case 1:
soundChessPiecesFall();
vibration(DECREASE);
break;
case 2:
soundChessPiecesFall();
break;
case 3:
vibration(DECREASE);
break;
default:
Log.e(TAG, "get_gameStartSound error");
}
//gameToast(getString(R.string.ics_disconnected), false);
try {
bringAPPtoFront();
cancelDateTimer();
new AlertDialog.Builder(ICSClient.this)
.setTitle(R.string.title_error)
.setMessage("Connection to server is broken.")
.setPositiveButton(getString(R.string.alert_ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
finish();
}
})
.show();
} catch(Exception ex){
Log.e(TAG, ex.toString());
}
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if (arg0 == _listChallenges) {
if (_mapChallenges.size() > arg2) {
HashMap<String, String> m = _mapChallenges.get(arg2);
Log.i("onItemClick", "item " + m.get("play"));
sendString("play " + m.get("play"));
}
} else if (arg0 == _listPlayers) {
if (_mapPlayers.size() > arg2) {
HashMap<String, String> m = _mapPlayers.get(arg2);
Log.i("onItemClick", "item " + m.get("text_name"));
_dlgMatch.setPlayer(m.get("text_name").toString());
_dlgMatch.show();
}
} else if (arg0 == _listGames) {
if (_mapGames.size() > arg2) {
HashMap<String, String> m = _mapGames.get(arg2);
Log.i("onItemClick", "item " + m.get("text_name1"));
sendString("observe " + m.get("text_name1"));
sendString("refresh");
get_view().setViewMode(ICSChessView.VIEW_WATCH);
get_view().setGameNum(Integer.parseInt((String) m.get("nr")));
switchToBoardView();
}
} else if (arg0 == _listStored) {
if (_mapStored.size() > arg2) {
HashMap<String, String> m = _mapStored.get(arg2);
Log.i("onItemClick", "item " + m.get("text_name_stored"));
sendString("match " + m.get("text_name_stored"));
switchToBoardView();
}
}
}
public void switchToBoardView() {
cancelTimer();
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_BOARD)
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_BOARD);
}
/*
public void switchToLobbyView(){
if(_viewAnimatorMain.getDisplayedChild() != 0)
_viewAnimatorMain.setDisplayedChild(0);
}
public void switchToWelcomeView(){
_tvHeader.setText(String.format(getString(R.string.ics_welcome_format), _handle));
if(_viewAnimatorMain.getDisplayedChild() != 0)
_viewAnimatorMain.setDisplayedChild(0);
_viewAnimatorLobby.setDisplayedChild(2);
}
*/
public void switchToChallengeView() {
rescheduleTimer();
_tvHeader.setText(R.string.ics_menu_challenges);
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_LOBBY)
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_LOBBY);
_viewAnimatorLobby.setDisplayedChild(VIEW_SUB_CHALLENGES);
}
public void switchToPlayersView() {
cancelTimer();
_tvHeader.setText(R.string.ics_menu_players);
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_LOBBY)
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_LOBBY);
_viewAnimatorLobby.setDisplayedChild(VIEW_SUB_PLAYERS);
}
public void switchToGamesView() {
cancelTimer();
_mapGames.clear();
_adapterGames.notifyDataSetChanged();
_tvHeader.setText(R.string.ics_menu_games);
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_LOBBY)
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_LOBBY);
_viewAnimatorLobby.setDisplayedChild(VIEW_SUB_GAMES);
}
public void switchToStoredView() {
cancelTimer();
_mapStored.clear();
_adapterStored.notifyDataSetChanged();
_tvHeader.setText(R.string.ics_menu_stored);
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_LOBBY)
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_LOBBY);
_viewAnimatorLobby.setDisplayedChild(VIEW_SUB_STORED);
}
public void switchToLoadingView() {
cancelTimer();
_tvHeader.setText(R.string.title_loading);
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_LOBBY) {
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_LOBBY);
}
_viewAnimatorLobby.setDisplayedChild(VIEW_SUB_PROGRESS);
}
public void switchToLoginView() {
cancelTimer();
_butLogin.setEnabled(true);
_tvHeader.setText("Login");
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_LOBBY) {
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_LOBBY);
}
_viewAnimatorLobby.setDisplayedChild(VIEW_SUB_LOGIN);
}
public void switchToConsoleView() {
cancelTimer();
_tvHeader.setText("Console");
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_LOBBY) {
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_LOBBY);
}
_viewAnimatorLobby.setDisplayedChild(VIEW_SUB_CONSOLE);
_scrollConsole.post(new Runnable() {
public void run() {
_scrollConsole.fullScroll(HorizontalScrollView.FOCUS_DOWN);
}
});
}
public ICSChessView get_view() {
return _view;
}
public void soundNotification() {
if (_ringNotification != null) {
_ringNotification.play();
}
}
public void soundTickTock(){
tickTock.start();
}
public void soundChessPiecesFall(){
try {
chessPiecesFall.start();
} catch(Exception ex){
Log.e(TAG, ex.toString());
}
}
public void vibration(int seq){
try {
int v1, v2;
if(seq == 1){
v1 = 200; // increase
v2 = 500;
}else {
v1 = 500; // decrease
v2 = 200;
}
long[] pattern = {500, v1, 100, v2};
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(pattern, -1);
} catch (Exception e) {
Log.e(TAG, "vibrator process error", e);
}
}
public class ComparatorHashName implements java.util.Comparator<HashMap<String, String>> {
public int compare(HashMap<String, String> a, HashMap<String, String> b) {
return ((String) ((HashMap<String, String>) a).get("text_name")).compareToIgnoreCase(((String) ((HashMap<String, String>) b).get("text_name")));
}
}
public class ComparatorHashRating implements java.util.Comparator<HashMap<String, String>> {
public int compare(HashMap<String, String> a, HashMap<String, String> b) {
return -1 * ((String) ((HashMap<String, String>) a).get("text_rating")).compareToIgnoreCase(((String) ((HashMap<String, String>) b).get("text_rating")));
}
}
private class AlternatingRowColorAdapter extends SimpleAdapter {
public AlternatingRowColorAdapter(Context context, List<HashMap<String, String>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
view.setBackgroundColor(position % 2 == 0 ? 0x55888888 : 0x55666666);
return view;
}
}
}
| app/src/main/java/jwtc/android/chess/ics/ICSClient.java | package jwtc.android.chess.ics;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.Vibrator;
import android.preference.PreferenceActivity;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.EditorInfo;
import android.widget.*;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.AdapterView.OnItemClickListener;
import com.google.android.gms.analytics.HitBuilders;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
import jwtc.android.chess.*;
public class ICSClient extends MyBaseActivity implements OnItemClickListener {
private TelnetSocket _socket;
private Thread _workerTelnet;
private String _server, _handle, _pwd, _prompt, _waitFor, _buffer, _ficsHandle, _ficsPwd,
_sFile, _FEN = "", _whiteRating, _blackRating, _whiteHandle, _blackHandle;
private int _port, _serverType, _TimeWarning, _gameStartSound, _iConsoleCharacterSize;
private boolean _bIsGuest, _bInICS, _bAutoSought, _bTimeWarning, _bEndGameDialog,
_gameStartFront, _bConsoleText;
private Button _butLogin;
private TextView _tvHeader, _tvConsole, _tvPlayConsole;
// public ICSChatDlg _dlgChat;
private EditText _editHandle, _editPwd, _editConsole;
private Spinner _spinnerHandles;
private ArrayAdapter<String> _adapterHandles;
private ArrayList<String> _arrayPasswords;
//private EditText _editPrompt;
private ListView _listChallenges, _listPlayers, _listGames, _listStored;
private ICSChessView _view;
protected ICSMatchDlg _dlgMatch;
private ICSConfirmDlg _dlgConfirm;
private ICSChatDlg _dlgChat;
private ICSGameOverDlg _dlgOver;
private StringBuilder PGN;
private ViewAnimator _viewAnimatorMain, _viewAnimatorLobby;
private ScrollView _scrollConsole, _scrollPlayConsole;
private Ringtone _ringNotification;
private TimeZone tz = TimeZone.getDefault();
// FICS
// Challenge: withca (----) GuestFHYH (----) unrated blitz 10 0
private Pattern _pattChallenge = Pattern.compile("Challenge\\: (\\w+) \\((.+)\\) (\\w+) \\((.+)\\) (rated |unrated )(standard |blitz |wild )(\\d+) (\\d+)( \\(adjourned\\))?.*");
// @TODO ===========================================================================================
// C Opponent On Type Str M ECO Date
// 1: W jwtc N [ sr 20 0] 39-39 W3 C44 Thu Nov 5, 12:41 PST 2009
// 1: B jwtc Y [ sr 7 12] 39-39 B3 B07 Sun Jun 2, 02:59 PDT 2013
private Pattern _pattStoredRow = Pattern.compile("[\\s]*(\\d+)\\: (W|B) (\\w+)[\\s]*(Y|N).+");
// =================================================================================================
// relay
// :262 GMTopalov GMCaruana * C78
// GuestNJVN (++++) seeking 5 0 unrated blitz ("play 104" to respond)
// GuestFXXP (++++) seeking 7 0 unrated blitz f ("play 27" to respond)
// Suffocate (++++) seeking 30 30 unrated standard [black] m ("play 29" to respond)
//Pattern _pattSeeking = Pattern.compile("(\\w+) \\((.+)\\) seeking (\\d+) (\\d+) (rated |unrated ?)(standard |blitz |lightning )(\\[white\\] |\\[black\\] )?(f |m )?\\(\"play (\\d+)\" to respond\\)");
private Pattern _pattSought, _pattGameRow;
private Pattern _pattChat = Pattern.compile("(\\w+)(\\(\\w+\\))? tells you\\: (.+)");
//1269.allko ++++.kaspalesweb(U)
private Pattern _pattPlayerRow = Pattern.compile("(\\s+)?(.{4})([\\.\\:\\^\\ ])(\\w+)(\\(\\w+\\))?");
private Pattern _pattEndGame = Pattern.compile("(\\w+) \\((\\w+)\\) vs. (\\w+) \\((\\w+)\\) --- \\w+ (\\w+\\s+\\d{1,2}, )\\w.*(\\d{4})\\s(\\w.+)\\," +
" initial time: (\\d{1,3}) minutes, increment: (\\d{1,3})(.|\\n)*\\{(.*)\\} (.*)");
private Matcher _matgame;
private ArrayList<HashMap<String, String>> _mapChallenges = new ArrayList<HashMap<String, String>>();
private ArrayList<HashMap<String, String>> _mapPlayers = new ArrayList<HashMap<String, String>>();
private ArrayList<HashMap<String, String>> _mapGames = new ArrayList<HashMap<String, String>>();
private ArrayList<HashMap<String, String>> _mapStored = new ArrayList<HashMap<String, String>>();
private AlternatingRowColorAdapter _adapterGames, _adapterPlayers, _adapterChallenges, _adapterStored;
public static final String TAG = "ICSClient";
protected static final int MSG_PARSE = 1;
protected static final int MSG_STOP_SESSION = 2;
protected static final int MSG_START_SESSION = 3;
protected static final int MSG_ERROR = 4;
protected static final int SERVER_FICS = 1;
protected static final int VIEW_MAIN_BOARD = 0;
protected static final int VIEW_MAIN_LOBBY = 1;
protected static final int VIEW_MAIN_NOT_CONNECTED = 2;
protected static final int VIEW_SUB_PLAYERS = 0;
protected static final int VIEW_SUB_GAMES = 1;
protected static final int VIEW_SUB_WELCOME = 2;
protected static final int VIEW_SUB_CHALLENGES = 3;
protected static final int VIEW_SUB_PROGRESS = 4;
protected static final int VIEW_SUB_LOGIN = 5;
protected static final int VIEW_SUB_CONSOLE = 6;
protected static final int VIEW_SUB_STORED = 7;
protected static final int DECREASE = 0;
MediaPlayer tickTock, chessPiecesFall;
static class InnerThreadHandler extends Handler {
WeakReference<ICSClient> _client;
InnerThreadHandler(ICSClient client) {
this._client = new WeakReference<ICSClient>(client);
}
@Override
public void handleMessage(Message msg) {
ICSClient client = _client.get();
if (client != null) {
switch (msg.what) {
case MSG_PARSE:
//parseBuffer(msg.getData().getString("buffer"));
client.parseBuffer();
break;
case MSG_STOP_SESSION:
client.stopSession(msg.getData().getString("buffer"));
client.trackEvent(TAG, "stopsession");
break;
case MSG_START_SESSION:
client.dateTimer();
client.switchToBoardView();
client.trackEvent(TAG, "startsession");
break;
}
super.handleMessage(msg);
}
}
}
// passes the incoming data from the socket worker thread for parsing
protected InnerThreadHandler m_threadHandler = new InnerThreadHandler(this);
static class InnerTimerHandler extends Handler {
WeakReference<ICSClient> _client;
InnerTimerHandler(ICSClient client) {
this._client = new WeakReference<ICSClient>(client);
}
@Override
public void handleMessage(Message msg) {
ICSClient client = _client.get();
if (client != null) {
if (client._bAutoSought) {
if (client._socket != null && client._workerTelnet != null && client._workerTelnet.isAlive() && client._socket.isConnected() &&
client._bInICS && client.get_view().isUserPlaying() == false) {
while (client._mapChallenges.size() > 0) {
client._mapChallenges.remove(0);
}
client._adapterChallenges.notifyDataSetChanged();
client.sendString("sought");
}
}
}
}
}
private Timer _timer = null;
protected InnerTimerHandler m_timerHandler = new InnerTimerHandler(this);
private Timer _timerDate = null;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int configOrientation = this.getResources().getConfiguration().orientation;
if(configOrientation == Configuration.ORIENTATION_LANDSCAPE) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
setContentView(R.layout.icsclient);
this.makeActionOverflowMenuShown();
// needs to be called first because of chess statics init
_view = new ICSChessView(this);
_view.init();
_dlgMatch = new ICSMatchDlg(this);
_dlgConfirm = new ICSConfirmDlg(this);
_dlgChat = new ICSChatDlg(this);
_dlgOver = new ICSGameOverDlg(this);
_handle = null;
_pwd = null;
_workerTelnet = null;
_socket = null;
_tvHeader = (TextView) findViewById(R.id.TextViewHeader);
//_dlgChat = new ICSChatDlg(this);
_bIsGuest = true;
_serverType = SERVER_FICS;
_bInICS = false;
_iConsoleCharacterSize = 10;
_bAutoSought = true;
_bTimeWarning = true;
_bEndGameDialog = true;
_adapterChallenges = new AlternatingRowColorAdapter(ICSClient.this, _mapChallenges, R.layout.ics_seek_row,
new String[]{"text_game", "text_name", "text_rating"}, new int[]{R.id.text_game, R.id.text_name, R.id.text_rating});
_listChallenges = (ListView) findViewById(R.id.ICSChallenges);
_listChallenges.setAdapter(_adapterChallenges);
_listChallenges.setOnItemClickListener(this);
_adapterPlayers = new AlternatingRowColorAdapter(ICSClient.this, _mapPlayers, R.layout.ics_player_row,
new String[]{"text_name", "text_rating"}, new int[]{R.id.text_name, R.id.text_rating});
_listPlayers = (ListView) findViewById(R.id.ICSPlayers);
_listPlayers.setAdapter(_adapterPlayers);
_listPlayers.setOnItemClickListener(this);
_adapterGames = new AlternatingRowColorAdapter(ICSClient.this, _mapGames, R.layout.ics_game_row,
new String[]{"text_name1", "text_name2", "text_rating1", "text_rating2"}, new int[]{R.id.text_name1, R.id.text_name2, R.id.text_rating1, R.id.text_rating2});
_listGames = (ListView) findViewById(R.id.ICSGames);
_listGames.setAdapter(_adapterGames);
_listGames.setOnItemClickListener(this);
_adapterStored = new AlternatingRowColorAdapter(ICSClient.this, _mapStored, R.layout.ics_stored_row,
new String[]{"nr_stored", "color_stored", "text_name_stored", "available_stored"}, new int[]{R.id.nr_stored, R.id.color_stored, R.id.text_name_stored, R.id.available_stored});
_listStored = (ListView) findViewById(R.id.ICSStored);
_listStored.setAdapter(_adapterStored);
_listStored.setOnItemClickListener(this);
_viewAnimatorMain = (ViewAnimator) findViewById(R.id.ViewAnimatorMain);
_viewAnimatorMain.setOutAnimation(this, R.anim.slide_left);
_viewAnimatorMain.setInAnimation(this, R.anim.slide_right);
_viewAnimatorLobby = (ViewAnimator) findViewById(R.id.ViewAnimatorLobby);
_viewAnimatorLobby.setOutAnimation(this, R.anim.slide_left);
_viewAnimatorLobby.setInAnimation(this, R.anim.slide_right);
_scrollConsole = (ScrollView) findViewById(R.id.ScrollICSConsole);
_scrollPlayConsole = (ScrollView) findViewById(R.id.ScrollPlayConsole);
tickTock = MediaPlayer.create(this, R.raw.ticktock);
chessPiecesFall = MediaPlayer.create(this, R.raw.chesspiecesfall);
/*
ImageButton butClose = (ImageButton)findViewById(R.id.ButtonBoardClose);
butClose.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
unsetBoard();
switchToWelcomeView();
}
});
*/
ImageButton butQuick = (ImageButton) findViewById(R.id.ButtonICSQuickCmd);
if (butQuick != null) {
butQuick.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//showMenu();
openOptionsMenu();
}
});
}
ImageButton butQuick2 = (ImageButton) findViewById(R.id.ButtonICSConsoleQuickCmd);
if (butQuick2 != null) { // crashes reported on this being null
butQuick2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//showMenu();
openOptionsMenu();
}
});
}
ImageButton butCloseConsole = (ImageButton) findViewById(R.id.ICSCloseConsole);
if (butCloseConsole != null) {
butCloseConsole.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (isConnected()) {
switchToBoardView();
} else {
finish();
}
}
});
}
//
ImageButton butChat = (ImageButton) findViewById(R.id.ButtonICSChat);
if (butChat != null) {
butChat.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//ICSChatDlg
_dlgChat.show();
_bConsoleText = true;
_dlgChat.prepare();
}
});
}
_editHandle = (EditText) findViewById(R.id.EditICSHandle);
_editPwd = (EditText) findViewById(R.id.EditICSPwd);
_spinnerHandles = (Spinner) findViewById(R.id.SpinnerLoginPresets);
_spinnerHandles.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
_editHandle.setText(_spinnerHandles.getSelectedItem().toString());
_editPwd.setText(_arrayPasswords.get(position));
if (_arrayPasswords.get(position).length() < 2) {
_editPwd.setText("");
}
Log.d(TAG, _spinnerHandles.getSelectedItem().toString());
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
Log.d(TAG, "nothing selected in spinner");
}
});
/////////////////////////
final Handler actionHandler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(ICSClient.this)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete " + _spinnerHandles.getSelectedItem().toString() + "?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String newData = _spinnerHandles.getSelectedItem().toString();
_adapterHandles.remove(newData);
_adapterHandles.notifyDataSetChanged();
_arrayPasswords.remove(_spinnerHandles.getSelectedItemPosition());
_editHandle.setText("");
_editPwd.setText("");
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
};
_spinnerHandles.setOnTouchListener(new View.OnTouchListener() { // simulate long press on spinner
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
actionHandler.postDelayed(runnable, 650);
} else if(event.getAction() == MotionEvent.ACTION_UP){
actionHandler.removeCallbacks(runnable);
}
return false;
}
});
/////////////////////
_butLogin = (Button) findViewById(R.id.ButICSLogin);
if (_butLogin != null) {
_butLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
startSession(_editHandle.getText().toString(), _editPwd.getText().toString());
}
});
}
_tvConsole = (TextView) findViewById(R.id.TextViewICSBoardConsole);
_tvPlayConsole = (TextView) findViewById(R.id.TextViewICSPlayConsole);
OnKeyListener okl = new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) ||
event.getAction() == EditorInfo.IME_ACTION_DONE
) {
// Perform action on key press
EditText et = (EditText) v;
String s = et.getText().toString();
_bConsoleText = true; // show text when user types to ICS
sendString(s + "\n");
et.setText("");
return true;
}
return false;
}
};
_editConsole = (EditText) findViewById(R.id.EditICSConsole);
if (_editConsole != null) {
_editConsole.setTextColor(getResources().getColor(android.R.color.white));
_editConsole.setSingleLine(true);
_editConsole.setOnKeyListener(okl);
}
EditText editBoard = (EditText) findViewById(R.id.EditICSBoard);
if (editBoard != null) {
editBoard.setSingleLine(true);
editBoard.setOnKeyListener(okl);
}
Button butReg = (Button) findViewById(R.id.ButICSRegister);
if (butReg != null) {
butReg.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try {
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://www.freechess.org/Register/index.html"));
startActivity(i);
} catch(Exception ex){
doToast("Could not go to registration page");
}
}
});
}
_ringNotification = null;
switchToLoginView();
Log.i("ICSClient", "onCreate");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, R.string.menu_prefs, Menu.NONE, R.string.menu_prefs);
menu.add(Menu.NONE, R.string.menu_flip, Menu.NONE, R.string.menu_flip);
menu.add(Menu.NONE, R.string.ics_menu_takeback, Menu.NONE, R.string.ics_menu_takeback);
menu.add(Menu.NONE, R.string.ics_menu_adjourn, Menu.NONE, R.string.ics_menu_adjourn);
menu.add(Menu.NONE, R.string.ics_menu_draw, Menu.NONE, R.string.ics_menu_draw);
menu.add(Menu.NONE, R.string.ics_menu_resign, Menu.NONE, R.string.ics_menu_resign);
menu.add(Menu.NONE, R.string.ics_menu_abort, Menu.NONE, R.string.ics_menu_abort);
menu.add(Menu.NONE, R.string.ics_menu_flag, Menu.NONE, R.string.ics_menu_flag);
menu.add(Menu.NONE, R.string.ics_menu_refresh, Menu.NONE, R.string.ics_menu_refresh);
menu.add(Menu.NONE, R.string.ics_menu_challenges, Menu.NONE, R.string.ics_menu_challenges);
menu.add(Menu.NONE, R.string.ics_menu_games, Menu.NONE, R.string.ics_menu_games);
menu.add(Menu.NONE, R.string.ics_menu_stored, Menu.NONE, R.string.ics_menu_stored);
menu.add(Menu.NONE, R.string.ics_menu_seek, Menu.NONE, R.string.ics_menu_seek);
menu.add(Menu.NONE, R.string.ics_menu_players, Menu.NONE, R.string.ics_menu_players);
menu.add(Menu.NONE, R.string.ics_menu_stop_puzzle, Menu.NONE, R.string.ics_menu_stop_puzzle);
menu.add(Menu.NONE, R.string.ics_menu_console, Menu.NONE, R.string.ics_menu_console);
menu.add("tell puzzlebot hint");
menu.add("forward");
menu.add("backward");
menu.add("unexamine");
menu.add("tell endgamebot hint");
menu.add("tell endgamebot move");
menu.add("tell endgamebot stop");
menu.add(Menu.NONE, R.string.ics_menu_unobserve, Menu.NONE, R.string.ics_menu_unobserve);
menu.add(Menu.NONE, R.string.menu_help, Menu.NONE, R.string.menu_help);
try {
SharedPreferences prefs = this.getPrefs();
JSONArray jArray = new JSONArray(prefs.getString("ics_custom_commands", CustomCommands.DEFAULT_COMMANDS));
for (int i = 0; i < jArray.length(); i++) {
try {
menu.add(jArray.getString(i));
} catch (JSONException e) {
}
}
} catch (JSONException e) {
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean isConnected = isConnected();
boolean isUserPlaying = get_view().isUserPlaying();
boolean isNotGuest = isConnected && (false == _handle.equals("guest"));
int viewMode = this.get_view()._viewMode;
menu.findItem(R.string.menu_flip).setVisible(isConnected && viewMode != ICSChessView.VIEW_NONE);
menu.findItem(R.string.ics_menu_takeback).setVisible(isConnected && isUserPlaying);
menu.findItem(R.string.ics_menu_adjourn).setVisible(isConnected && isUserPlaying && isNotGuest);
menu.findItem(R.string.ics_menu_draw).setVisible(isConnected && isUserPlaying);
menu.findItem(R.string.ics_menu_resign).setVisible(isConnected && isUserPlaying);
menu.findItem(R.string.ics_menu_abort).setVisible(isConnected && isUserPlaying);
menu.findItem(R.string.ics_menu_flag).setVisible(isConnected && isUserPlaying);
menu.findItem(R.string.ics_menu_refresh).setVisible(isConnected && isUserPlaying);
menu.findItem(R.string.ics_menu_challenges).setVisible(isConnected && viewMode == ICSChessView.VIEW_NONE);
menu.findItem(R.string.ics_menu_games).setVisible(isConnected && viewMode == ICSChessView.VIEW_NONE);
menu.findItem(R.string.ics_menu_stored).setVisible(isConnected && viewMode == ICSChessView.VIEW_NONE && isNotGuest);
menu.findItem(R.string.ics_menu_seek).setVisible(isConnected && viewMode == ICSChessView.VIEW_NONE);
menu.findItem(R.string.ics_menu_players).setVisible(isConnected && viewMode == ICSChessView.VIEW_NONE);
menu.findItem(R.string.ics_menu_stop_puzzle).setVisible(isConnected && viewMode == ICSChessView.VIEW_PUZZLE);
menu.findItem(R.string.ics_menu_unobserve).setVisible(isConnected && viewMode == ICSChessView.VIEW_WATCH);
menu.findItem(R.string.ics_menu_console).setVisible(isConnected);
for (int i = 0; i < menu.size(); i++) {
MenuItem item = menu.getItem(i);
String title = item.getTitle().toString();
if (title.equals("tell puzzlebot hint")) {
item.setVisible(isConnected && viewMode == ICSChessView.VIEW_PUZZLE);
} else if (title.equals("forward")) {
item.setVisible(isConnected && viewMode == ICSChessView.VIEW_EXAMINE);
} else if (title.equals("backward")) {
item.setVisible(isConnected && viewMode == ICSChessView.VIEW_EXAMINE);
} else if (title.equals("unexamine")) {
item.setVisible(isConnected && viewMode == ICSChessView.VIEW_EXAMINE);
} else if (title.equals("tell endgamebot hint")) {
item.setVisible(isConnected && viewMode == ICSChessView.VIEW_ENDGAME);
} else if (title.equals("tell endgamebot move")) {
item.setVisible(isConnected && viewMode == ICSChessView.VIEW_ENDGAME);
} else if (title.equals("tell endgamebot stop")) {
item.setVisible(isConnected && viewMode == ICSChessView.VIEW_ENDGAME);
}
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i;
switch (item.getItemId()) {
case R.string.menu_prefs:
i = new Intent();
i.setClass(ICSClient.this, ICSPrefs.class);
startActivity(i);
return true;
case R.string.menu_flip:
_view.flipBoard();
_view.paint();
sendString("refresh");
return true;
case R.string.ics_menu_refresh:
sendString("refresh");
return true;
case R.string.ics_menu_takeback:
sendString("takeback 2");
return true;
case R.string.ics_menu_resume:
sendString("resume");
return true;
case R.string.ics_menu_abort:
sendString("abort");
get_view().stopGame();
return true;
case R.string.ics_menu_adjourn:
sendString("adjourn");
return true;
case R.string.ics_menu_draw:
sendString("draw");
return true;
case R.string.ics_menu_flag:
sendString("flag");
case R.string.ics_menu_resign:
sendString("resign");
return true;
case R.string.ics_menu_games:
// switchToLoadingView();
switchToGamesView();
sendString("games");
return true;
case R.string.ics_menu_stored:
switchToStoredView();
sendString("stored");
return true;
case R.string.ics_menu_challenges:
switchToChallengeView();
return true;
case R.string.ics_menu_seek:
_dlgMatch._rbSeek.performClick();
return true;
case R.string.menu_help:
i = new Intent();
i.setClass(ICSClient.this, HtmlActivity.class);
i.putExtra(HtmlActivity.HELP_MODE, "help_online");
startActivity(i);
return true;
case R.string.ics_menu_console:
switchToConsoleView();
return true;
case R.string.ics_menu_players:
sendString("who a");
switchToLoadingView();
return true;
case R.string.ics_menu_quit:
finish();
return true;
case R.string.ics_menu_stop_puzzle:
sendString("tell puzzlebot stop");
get_view().stopGame();
return true;
case R.string.ics_menu_unobserve:
sendString("unobserve");
get_view().stopGame();
return true;
case android.R.id.home:
confirmAbort();
return true;
}
sendString(item.getTitle().toString());
return true;
}
public void confirmAbort() {
Log.i("ICSClient", "confirmAbort");
if (isConnected()) {
if (_viewAnimatorMain.getDisplayedChild() == VIEW_MAIN_BOARD && get_view().isUserPlaying()) {
new AlertDialog.Builder(ICSClient.this)
.setTitle(ICSClient.this.getString(R.string.ics_menu_abort) + "?")
.setPositiveButton(getString(R.string.alert_yes),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
sendString("abort");
sendString("quit");
finish();
}
})
.setNegativeButton(getString(R.string.alert_no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
return;
}
}
finish();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
confirmAbort();
return true;
}
return super.onKeyDown(keyCode, event);
}
public void stopSession(String sReason) {
Log.e("stopSession", sReason);
if (isFinishing()) {
return;
}
new AlertDialog.Builder(ICSClient.this)
.setTitle(R.string.title_error)
.setMessage(sReason)
.setPositiveButton(R.string.alert_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
finish();
}
})
.show();
}
public void startSession(final String h, final String p) {
if (h == "") {
globalToast(getString(R.string.msg_ics_enter_handle));
return;
}
Log.i("ICSClient", "Setting servertype to FICS");
_serverType = SERVER_FICS;
_server = "freechess.org";
_port = 23;
_prompt = "fics% ";
_ficsHandle = h;
_ficsPwd = p;
_handle = _ficsHandle;
_pwd = _ficsPwd;
if (_handle != "guest" && _pwd == "") {
globalToast(getString(R.string.msg_ics_enter_password));
return;
}
// FICS
//209 1739 rahulso 15 10 unrated standard [white] 0-9999 m
//101 ++++ GuestYYLN 16 0 unrated standard 0-9999 mf
// 6 ++++ sdhisfh 2 0 unrated crazyhouse 0-9999
// 11 ++++ GuestFGMX 20 10 unrated standard 0-9999 f
// 7 ++++ Amhztb 10 90 unrated standard 0-9999 m
// 26 ++++ GuestFFHQ 7 0 unrated wild/3 [white] 0-9999
_pattSought = Pattern.compile("[\\s]*(\\d+)[\\s]+(\\d+|\\++|-+)[\\s]+([\\w\\(\\)]+)[\\s]+(\\d+)[\\s]+(\\d+)[\\s]+(rated|unrated?)[\\s]+([\\w/\\d]+?)[\\s]*(\\[white\\]|\\[black\\])?[\\s]*(\\d+)\\-(\\d+)[\\s]*([fm]+)?");
// " 09 09 | +++ handle() 09 09 wild/3
// FICS
// 93 2036 WFMKierzek 2229 FMKarl [ su120 0] 26:13 - 3:49 (22-22) W: 28
// 1 2 3 4 5 678 9
_pattGameRow = Pattern.compile("[\\s]*(\\d+) (\\d+) (\\w+)[\\s]+(\\d+) (\\w+)[\\s]+\\[ (s|b|l)(r|u)[\\s]*(\\d+)[\\s]*(\\d+)\\][\\s]*(\\d+):(\\d+)[\\s]*-[\\s]*(\\d+):(\\d+).+");
_butLogin.setEnabled(false);
switchToLoadingView();
_workerTelnet = new Thread(new Runnable() {
public void run() {
Message msg, msgStop;
Bundle bun;
msgStop = new Message();
msgStop.what = MSG_STOP_SESSION;
_bIsGuest = _handle.equals("guest");
try {
_socket = new TelnetSocket(_server, _port);
} catch (Exception ex) {
_socket = null;
bun = new Bundle();
bun.putString("buffer", getString(R.string.ics_error_connection));
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
try {
// do login
String data = "";
String buf = _socket.readString();
while (buf != null && !isFinishing()) {
data += buf;
if (data.indexOf("login: ") > 0)
break;
//Log.i("startSession 0", "Fetching until 'login:'");
buf = _socket.readString();
}
if (data.length() == 0) {
bun = new Bundle();
bun.putString("buffer", "No response from server after connection...");
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
//Log.i("startSession 1", "First response: " + data);
if (data.indexOf("login: ") == -1) {
bun = new Bundle();
bun.putString("buffer", "Unexpected response from server after connection...");
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
Log.i("startSession 1", "Logging in with " + _handle);
sendString(_handle);
int iPos, iPos2;
data = "";
buf = _socket.readString();
while (buf != null) {
data += buf;
if (data.indexOf("\":") > 0 &&
(data.indexOf("Press return to enter the server as") > 0 ||
data.indexOf("Logging you in as") > 0) ||
data.indexOf("password: ") > 0 || data.indexOf("login:") > 0
)
break;
Log.i("startSession debug", "wait: " + data);
buf = _socket.readString();
}
if (data.length() == 0) {
bun = new Bundle();
bun.putString("buffer", "No response from server after setting login handle...");
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
// just remove all newlines from the string for better regex matching
data = data.replaceAll("[\r\n\0]", "");
Log.i("startSession 2", "After handle: " + data);
iPos = data.indexOf("Press return to enter the server as \"");
iPos2 = data.indexOf("Logging you in as \"");
//iPos3 = data.indexOf("If it is yours, type the password");
if (iPos >= 0) {
data = data.trim();
Log.i("startSession 2.1", "Guest log in v1");
// Press return to enter the server as
Pattern patt = Pattern.compile("Press return to enter the server as \"(\\w+)\":");
Matcher match = patt.matcher(data);
if (match.find()) {
_handle = match.group(1);
sendString("");
} else {
bun = new Bundle();
bun.putString("buffer", "Could not process response after setting login handle...(1)");
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
} else if (iPos2 >= 0) {
Log.i("startSession 2.1", "Guest log in v2");
Pattern patt = Pattern.compile("Logging you in as \"(\\w+)\"");
Matcher match = patt.matcher(data);
if (match.find()) {
_handle = match.group(1);
} else {
bun = new Bundle();
bun.putString("buffer", "Could not process response after setting login handle...(2)");
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
} else if (data.indexOf("password: ") > 0) {
sendString(_pwd);
} else {
bun = new Bundle();
bun.putString("buffer", "username error: " + data);
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
data = "";
buf = _socket.readString();
while (buf != null) {
data += buf;
if (data.length() > 20)
break;
buf = _socket.readString();
}
Log.i("startSession 3", "Response after password: " + data);
if (data == null || data.length() == 0) {
bun = new Bundle();
bun.putString("buffer", "No response from server while logging in...");
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
if (data.indexOf("**** Starting ") == -1 && data.indexOf("****************") == -1) {
bun = new Bundle();
bun.putString("buffer", "password error: " + data);
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
return;
}
_bInICS = true;
sendString("style 12");
sendString("-channel 4"); // guest
sendString("-channel 53"); // guest chat
sendString("set kibitz 1"); // for puzzlebot
sendString("set tzone " + tz.getDisplayName(false, TimeZone.SHORT)); // sets timezone
// sendMessage("set interface "+ getPreferences().getString(APP_NAME));
Log.i("ICSClient", " == HANDLE " + _handle);
// _handle
msg = new Message();
msg.what = MSG_START_SESSION;
m_threadHandler.sendMessage(msg);
//
String buffer = "";
_waitFor = _prompt;
buffer = "";
while (_socket != null && _socket.isConnected()) {
data = _socket.readString();
if (data != null && data.length() > 0) {
//Log.i("WorkerTelnet = ", data);
buffer += data;
if (buffer.endsWith(_waitFor)) {
_buffer = buffer;
msg = new Message();
msg.what = MSG_PARSE;
bun = new Bundle();
//bun.putString("buffer", buffer);
//msg.setData(bun);
m_threadHandler.sendMessage(msg);
buffer = "";
}
}
}
} catch (Exception ex) {
bun = new Bundle();
bun.putString("buffer", getString(R.string.ics_error_connection));
msgStop.setData(bun);
m_threadHandler.sendMessage(msgStop);
Log.e("WorkerTelnet", ex.toString());
}
_bInICS = false;
Log.i("WorkerTelnet", "stopped");
finish();
}
});
_workerTelnet.start();
}
private void parseBuffer() {
try {
//Log.i("parseBuffer", "[" + buffer + "]");
String sRaw = "", sEnd = "", sBeg = "";
Matcher match;
//////////////////////////////////////////////////////////////////////////////////////////////
String[] lines;
if (_serverType == SERVER_FICS) {
lines = _buffer.split("\n\r");
} else {
lines = _buffer.split("\r\n");
}
//Log.i("WorkerTelnet", "looking within STATUS_ONLINE");
// 680 players displayed (of 680). (*) indicates system administrator.
// result for who
if (lines.length > 3 && _buffer.indexOf("players displayed (of ") > 0 && _buffer.indexOf("indicates system administrator.") > 0) {
_mapPlayers.clear();
for (int i = 0; i < lines.length - 2; i++) {
match = _pattPlayerRow.matcher(lines[i]);
while (match.find()) {
String name = match.group(4);
if (name != null && match.group(2) != null) {
String code = match.group(5);
if (code == null) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("text_name", name);
item.put("text_rating", match.group(2));
_mapPlayers.add(item);
} else {
if (code == "(U)" || code == "(FM)" || code == "(GM)" || code == "(IM)" || code == "(WIM)" || code == "(WGM)") {
name += code;
HashMap<String, String> item = new HashMap<String, String>();
item.put("text_name", name);
item.put("text_rating", match.group(2));
_mapPlayers.add(item);
}
}
}
}
}
switchToPlayersView();
Collections.sort(_mapPlayers, new ComparatorHashRating());
_adapterPlayers.notifyDataSetChanged();
}
//////////////////////////////////////////////////////////////////////////////////////////////
// result for stored
/*
else if(lines.length > 3 && _buffer.indexOf("Stored games for " + _handle + ":") > 0){
//_pattStoredRow
}*/
//////////////////////////////////////////////////////////////////////////////////////////////
// single line stuff
else {
String line;
for (int i = 0; i < lines.length; i++) {
line = lines[i].replace(_prompt, "");
// lines can still contain prompt!
// _prompt
//////////////////////////////////////////////////////////////
if (line.contains("Game") || line.contains("Creating:") || line.contains("Issuing:") || line.contains("Challenge:")){
// 1 2 3 4 5 6 7 8
//Creating: bunnyhopone (++++) mardukedog (++++) unrated blitz 5 5
Pattern _pattGameInfo1 = Pattern.compile("\\{?\\w+\\s?\\d+?: (\\w+) \\((.{3,4})\\) (\\w+) \\((.{3,4})\\) (\\w+) (\\w+) (\\d+) (\\d+)");
Pattern _pattGameInfo2 = Pattern.compile("\\w+: (\\w+) \\((.{3,4})\\) (\\w+) \\((.{3,4})\\) (\\w+) (\\w+) (\\d+) (\\d+)");
Pattern _pattGameInfo3 = Pattern.compile("\\{\\w+\\s(\\d+) \\((\\w+) vs. (\\w+)\\) (.*)\\} (.*)");
Matcher mat = _pattGameInfo1.matcher(line);
Matcher mat2 = _pattGameInfo2.matcher(line);
Matcher mat3 = _pattGameInfo3.matcher(line);
if (mat.matches() || mat2.matches()){ //mat and mat2 are the beginning game info
_whiteHandle = mat.matches() ? mat.group(1) : mat2.group(1);
_whiteRating = mat.matches() ? mat.group(2) : mat2.group(2);
if (_whiteRating.equals("++++")){
_whiteRating = "UNR";
}
_blackHandle = mat.matches() ? mat.group(3) : mat2.group(3);
_blackRating = mat.matches() ? mat.group(4) : mat2.group(4);
if (_blackRating.equals("++++")){
_blackRating = "UNR";
}
}
if (mat3.matches()){ // mat3 is the endgame result
sendString("oldmoves " + _whiteHandle); // send moves at end of game
Log.d(TAG, "oldmoves " + _whiteHandle);
}
}
// board representation
if (line.indexOf("<12> ") >= 0) {
// this can be multiple lines!
String[] gameLines = line.split("<12> ");
if(_FEN.isEmpty() && gameLines[1].contains("none (0:00) none")) {
_FEN = gameLines[1]; // get first gameLine - contains FEN setup
}
for (int j = 0; j < gameLines.length; j++) {
// at least 65 chars
if (gameLines[j].length() > 65) {
//if(get_view().preParseGame(gameLines[j])){
if (get_view().parseGame(gameLines[j], _handle)) {
switchToBoardView();
} else {
//gameToast("There was a problem parsing the response of the server.", false);
Log.w("parseBuffer", "Could not parse game response");
addConsoleText("Could not parse game response");
}
//}
}
}
}
///////////////////////////////////////////////////////////////
// Challenge: jwtc (++++) jewithca (++++) unrated blitz 5 0.
else if (line.indexOf("Challenge:") >= 0) {
Log.i("parseBuffer", "parsing challenge " + line);
match = _pattChallenge.matcher(line);
if (match.matches()) {
String opponent, rating;
if (match.group(1).equals(_handle)) {
opponent = match.group(3);
rating = match.group(4);
} else {
opponent = match.group(1);
rating = match.group(2);
}
//Log.i("parseBuffer", "matched challenge");
// ("adjourned", match.group(9) != null);
new AlertDialog.Builder(ICSClient.this)
.setTitle(ICSClient.this.getString(R.string.title_challenge))
.setMessage(opponent +
" [" + rating +
"]\nchallenges you for a " + match.group(7) + " min.+" + match.group(8) + "s " + match.group(5) + " " + match.group(6) + ".\nDo you wish to accept?")
.setPositiveButton(getString(R.string.alert_yes),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
sendString("accept");
dialog.dismiss();
}
})
.setNegativeButton(getString(R.string.alert_no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
}
}
//////////////////////////////////////////////////////////////
// seek no longer available
else if (line.equals("That seek is not available.")) {
gameToast("That seek is not available", false);
}
/////////////////////////////////////////////////////////////////
// game created
else if (line.indexOf("{Game ") >= 0 && (line.indexOf(" Creating ") > 0 || line.indexOf(" Continuing ") > 0)) {
Pattern p = Pattern.compile("\\{Game (\\d+) .*");
Matcher m = p.matcher(line);
if (m.matches()) {
get_view().setGameNum(Integer.parseInt(m.group(1)));
get_view().setViewMode(ICSChessView.VIEW_PLAY);
switchToBoardView();
}
} else if (line.indexOf("Creating: ") >= 0 && line.indexOf("(adjourned)") >= 0) {
//Creating: jcarolus (----) jwtc (----) unrated blitz 5 0 (adjourned)
get_view().setViewMode(ICSChessView.VIEW_PLAY);
switchToBoardView();
gameToast("Resuming adjourned game", false);
}
//////////////////////////////////////////////////////////////
else if (line.indexOf("Illegal move (") == 0) {
gameToast("Illegal move", false);
}
//////////////////////////////////////////////////////////////
// abort
else if (get_view().isUserPlaying() && line.indexOf(get_view().getOpponent() + " would like to abort the game") != -1) { // todo add opponent in match
confirmShow(getString(R.string.title_offers_abort), getString(R.string.ics_offers_abort), "abort");
} else if (get_view().isUserPlaying() && line.indexOf("Game aborted by mutual agreement}") >= 0) {
gameToast("Game aborted by mutual agreement", true);
get_view().setViewMode(ICSChessView.VIEW_NONE);
}
//////////////////////////////////////////////////////////////
// take back
else if (get_view().isUserPlaying() && line.indexOf(get_view().getOpponent() + " would like to take back ") != -1) { //
confirmShow(getString(R.string.title_offers_takeback), getString(R.string.ics_offers_takeback), "accept");
}
//////////////////////////////////////////////////////////////
// aborted/adjouned
else if (line.indexOf("{Game " /*+ get_view().getGameNum()*/) >= 0 && line.indexOf("} *") > 0) {
String text = getString(R.string.ics_game_over);
gameToast(text, true);
get_view().setViewMode(ICSChessView.VIEW_NONE);
}
//////////////////////////////////////////////////////////////
// game over
else if (line.contains("{Game ") && (line.contains("} 1-0") || line.contains("} 0-1") || line.contains("} 1/2-1/2"))) {
String text = "";
text = line.substring(line.indexOf(")") + 2, line.indexOf("}")); // gets name and state of name
if (line.contains("} 1-0") || line.contains("} 0-1")) {
if (line.indexOf(" resigns} ") > 0) { // make translation friendly
text = text.replace("resigns", getString(R.string.state_resigned));
} else if (line.indexOf("checkmated") > 0) {
text = text.replace("checkmated", getString(R.string.state_mate));
} else if (line.indexOf("forfeits on time") > 0) {
text = text.replace("forfeits on time", getString(R.string.state_time));
} else {
text = getString(R.string.ics_game_over);
}
}
else if (line.contains("} 1/2-1/2")){ // draw
gameToast(String.format(getString(R.string.ics_game_over_format), getString(R.string.state_draw)), true);
}
gameToast(String.format(getString(R.string.ics_game_over_format), text), true);
get_view().setViewMode(ICSChessView.VIEW_NONE);
}
//////////////////////////////////////////////////////////////
// draw / abort / todo:adjourn request sent
else if (line.equals("Draw request sent.") || line.equals("Abort request sent.") || line.equals("Takeback request sent.")) {
gameToast(getString(R.string.ics_request_sent), false);
} else if (get_view().isUserPlaying() && line.indexOf(get_view().getOpponent() + " offers you a draw.") >= 0) {
confirmShow(getString(R.string.title_offers_draw), getString(R.string.ics_offers_draw), "draw");
} else if (get_view().isUserPlaying() && line.indexOf(get_view().getOpponent() + " would like to adjourn the game; type \"adjourn\" to accept.") >= 0) {
confirmShow(getString(R.string.title_offers_adjourn), getString(R.string.ics_offers_adjourn), "adjourn");
}
/////////////////////////////////////////////////////////////
// chat
else if (line.indexOf(" tells you: ") > 0) {
match = _pattChat.matcher(line);
if (match.matches()) {
//globalToast(String.format(getString(R.string.ics_tells_you), match.group(1), match.group(3)));
String s = String.format(getString(R.string.ics_tells_you), match.group(1), match.group(3));
while (i + 2 < lines.length && lines[i + 1].startsWith("\\")) {
i++;
s += line.replace("\\", "");
}
addConsoleText(s);
}
}
// observe status
else if (line.indexOf("You are now observing game") >= 0) {
_FEN = ""; // reset in case last watched game wasn't finished
get_view().setViewMode(ICSChessView.VIEW_WATCH);
//gameToast("Observing a game", false);
}
// stop observing
else if (line.indexOf("Removing game") >= 0 && line.indexOf("from observation list") > 0 || line.indexOf("You are no longer examining game") >= 0) {
//gameToast("No longer observing the game", true);
get_view().setViewMode(ICSChessView.VIEW_NONE);
}
// examine
else if (line.indexOf("puzzlebot has made you an examiner of game") >= 0) {
get_view().setViewMode(ICSChessView.VIEW_PUZZLE);
gameToast("Puzzle started", false);
}
// stop problem
else if (line.indexOf("Your current problem has been stopped") >= 0) {
get_view().setViewMode(ICSChessView.VIEW_NONE);
gameToast("Puzzle stopped", true);
}
/////////////////////////////////////////////////////////////
// game talk
else if (line.indexOf("[" + get_view().getGameNum() + "] says: ") > 0) {
String s = line;
while (i + 2 < lines.length && lines[i + 1].startsWith("\\")) {
i++;
s += line.replace("\\", "");
}
addConsoleText(s);
}
//////////////////////////////////////////////////////////////
// TODO what is this
else if (line.indexOf("-->") == 0) {
// globalToast(line);
} else if (line.indexOf("kibitzes:") > 0) {
String s = line.replace("kibitzes:", "");
while (i + 2 < lines.length && lines[i + 1].startsWith("\\")) {
i++;
s += line.replace("\\", "");
}
addConsoleText(s);
}
/////////////////////////////////////////////////////////////////
// result of sought
else if ((false == get_view().isUserPlaying()) && _pattSought.matcher(line).matches()) {
match = _pattSought.matcher(line);
if (match.matches()) {
//Log.i("PATSOUGHT", "groupCount " + match.groupCount());
if (match.groupCount() > 7) {
String s, type, rated;
if (_serverType == SERVER_FICS) {
// 1 2 3 4 5 6 7 8
// 209 1739 rahulso 15 10 unrated standard [white] 0-9999 m
s = String.format("%2dm+%2ds", Integer.parseInt(match.group(4)), Integer.parseInt(match.group(5)));
type = match.group(7);
rated = match.group(6);
} else {
// 1 2 3 4 5 6 7 8
// 5 1111 SlowFlo(C) standard 30 30 rated white 0-1700 mf
s = String.format("%2dm+%2ds", Integer.parseInt(match.group(5)), Integer.parseInt(match.group(6)));
type = match.group(4);
rated = match.group(7);
}
//_adapter.insert(s + " " + b.getString("type") + " " + b.getString("opponent") + "[" + b.getString("rating") + "]", 0);
HashMap<String, String> item = new HashMap<String, String>();
if (type.indexOf("blitz") >= 0 || type.indexOf("standard") >= 0) {
if (type.indexOf("standard") >= 0)
type = "";
item.put("text_game", s + " " + rated + " " + type);
item.put("play", match.group(1));
item.put("text_name", match.group(3));
item.put("text_rating", match.group(2));
_mapChallenges.add(0, item);
_adapterChallenges.notifyDataSetChanged();
}
//switchToChallengeView();
} else {
Log.w("ICSClient", "pattSought match, but groupcount = " + match.groupCount());
}
}
}
// skip stuff
else if (line.indexOf("seeking") > 0 && line.indexOf("to respond") > 0) {
// skip seeking stuff, is handled via 'sought' command
//Log.i("ICSClient", "Skip seeking");
} else if (line.indexOf("ads displayed.") > 0) {
//Log.i("ICSClient", "Skip ads displayed");
}
//////////////////////////////////////////////////////////////////////////////////////////////
// result for games
else if ((false == get_view().isUserPlaying()) && _pattGameRow.matcher(line).matches()) {
//Log.i("ICSClient", "GAMEROW match");
match = _pattGameRow.matcher(line);
if (match.matches()) {
HashMap<String, String> item = new HashMap<String, String>();
// 93 2036 WFMKierzek 2229 FMKarl [ su120 0] 26:13 - 3:49 (22-22) W: 28
item.put("nr", match.group(1));
item.put("text_rating1", match.group(2));
item.put("text_name1", match.group(3));
item.put("text_rating2", match.group(4));
item.put("text_name2", match.group(5));
item.put("text_type", match.group(6).toUpperCase() + match.group(7).toUpperCase());
item.put("text_time1", match.group(10) + ":" + match.group(11));
item.put("text_time2", match.group(12) + ":" + match.group(13));
_mapGames.add(0, item);
_adapterGames.notifyDataSetChanged();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// result for stored games
else if ((false == get_view().isUserPlaying()) && _pattStoredRow.matcher(line).matches()) {
//Log.i(TAG, "stored row match");
match = _pattStoredRow.matcher(line);
if (match.matches()) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("nr_stored", match.group(1));
item.put("color_stored", match.group(2));
item.put("text_name_stored", match.group(3));
item.put("available_stored", match.group(4).equals("Y") ? "*" : "");
_mapStored.add(item);
_adapterStored.notifyDataSetChanged();
}
}
//////////////////////////////////////////////////////////////
// shouts, tshouts etc...
// any other data we haven't matched, put it on prompt
else if (line.length() > 0) {
Log.i("ICSClient", "lines[" + i + "] " + line);
//Log.i("ICSClient", "lines[" + i + "][last] " + (int)(line.charAt(line.length()-1)));
sRaw += "\n" + line;
}
} // for line
//////////////////////////////////////////////////////////////
if (sRaw.length() > 0) {
sRaw = sRaw.replace(new Character((char) 7).toString(), "").replace("\\", "").replace("\t", "").replace(_prompt, "\n").trim();
sRaw = sRaw.replaceAll("[\n]{2,}", "\n");
if (sRaw.length() > 0) {
addConsoleText(sRaw);
}
if (_bEndGameDialog){
sEnd += sRaw;
//Log.d(TAG, "sEnd ->" + sEnd);
_matgame = _pattEndGame.matcher(sEnd);
if(_matgame.matches()){
sEnd = sEnd.trim().replaceAll(" +", " ");
sEnd = sEnd.replaceAll("\\{.*\\}", "");
String event = sEnd.substring(sEnd.indexOf("\n"), sEnd.indexOf(", initial"));
event = event.replace("\n", "");
String site = "FICS";
String timeControl = sEnd.substring(sEnd.indexOf("time:")+6, sEnd.indexOf(".", sEnd.indexOf("time:")));
String _FEN1, _FEN2;
sBeg = sEnd.substring(sEnd.indexOf("1."), sEnd.length());
sBeg = sBeg.replaceAll("\\s*\\([^\\)]*\\)\\s*", " "); // gets rid of timestamp and parentheses
PGN = new StringBuilder("");
PGN.append("[Event \"" + event + "\"]\n");
PGN.append("[Site \"" + site + "\"]\n");
PGN.append("[Date \"" + _matgame.group(5) + _matgame.group(6) + "\"]\n");
PGN.append("[White \"" + _matgame.group(1) + "\"]\n");
PGN.append("[Black \"" + _matgame.group(3) + "\"]\n");
PGN.append("[Result \"" + _matgame.group(12) + "\"]\n");
PGN.append("[WhiteElo \"" + _matgame.group(2) + "\"]\n");
PGN.append("[BlackElo \"" + _matgame.group(4) + "\"]\n");
PGN.append("[TimeControl \"" + timeControl + "\"]\n");
if(!_FEN.equals("")) { // As for now, used for Chess960 FEN.
_FEN1 = _FEN.substring(0, _FEN.indexOf(" "));
_FEN2 = _FEN.substring(_FEN.indexOf("P") + 9, _FEN.indexOf("W") - 1);
if (!_FEN1.equals("rnbqkbnr") || !_FEN2.equals("RNBQKBNR")) {
PGN.append("[FEN \"" + _FEN1 + "/pppppppp/8/8/8/8/PPPPPPPP/" + _FEN2 + " w KQkq - 0 1" + "\"]\n");
}
_FEN = ""; // reset to capture starting FEN for next game
}
PGN.append(sBeg + "\n\n");
saveGameSDCard();
_dlgOver.updateGRtext(_matgame.group(11)); // game result message sent to dialog
_dlgOver.setWasPlaying(get_view().getOpponent().length() > 0);
_dlgOver.show();
//_dlgOver.prepare();
}
}
}
} // single line stuff
} catch (Exception ex) {
Log.e("WorkerTelnet", ex.toString());
}
}
public void copyToClipBoard() {
try {
ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
cm.setText(PGN.toString());
doToast(getString(R.string.ics_copy_clipboard));
} catch (Exception e) {
doToast(getString(R.string.err_copy_clipboard));
Log.e("ex", e.toString());
}
}
public void saveGameSDCard(){
try{
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
_sFile = Environment.getExternalStorageDirectory() + "/chessgamesonline.pgn";
FileOutputStream fos;
fos = new FileOutputStream(_sFile, true);
fos.write(PGN.toString().getBytes());
fos.flush();
fos.close();
doToast(getString(R.string.ics_save_game));
} else {
doToast(getString(R.string.err_sd_not_mounted));
}
} catch (Exception e) {
doToast(getString(R.string.err_saving_game));
Log.e("ex", e.toString());
}
}
public void SendToApp(){
try {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "chess pgn");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + _sFile));
sendIntent.setType("application/x-chess-pgn");
startActivity(sendIntent);
} catch (Exception e) {
doToast(getString(R.string.err_send_email));
Log.e("ex", e.toString());
}
}
public void addConsoleText(final String s) {
_tvConsole.setTypeface(Typeface.MONOSPACE); // Monospace gives each character the same width
_tvPlayConsole.setTypeface(Typeface.MONOSPACE);
_tvConsole.setTextSize(_iConsoleCharacterSize); // sets console text size
_tvPlayConsole.setTextSize(_iConsoleCharacterSize);
final String s2 = _tvConsole.getText() + "\n\n" + s;
if (s2.length() > 8192) {
_tvConsole.setText(s2.substring(s2.length() - 4096));
} else {
_tvConsole.append("\n\n" + s);
}
final String s3 = _tvPlayConsole.getText() + "\n\n" + s;
if(s3.length() > 1024){
_tvPlayConsole.setText(s3.substring(s3.length() - 512));
} else {
_tvPlayConsole.append("\n\n" + s);
}
_scrollPlayConsole.post(new Runnable() {
public void run() {
_scrollPlayConsole.fullScroll(HorizontalScrollView.FOCUS_DOWN);
}
});
}
private void confirmShow(String title, String text, String sendstring) {
_dlgConfirm.setSendString(sendstring);
_dlgConfirm.setText(title, text);
_dlgConfirm.show();
}
public void gameToast(final String text, final boolean stop) {
if (stop) {
get_view().stopGame();
}
Toast t = Toast.makeText(this, text, Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
}
private void globalToast(final String text) {
Toast t = Toast.makeText(this, text, Toast.LENGTH_LONG);
t.setGravity(Gravity.BOTTOM, 0, 0);
t.show();
}
@Override
protected void onResume() {
SharedPreferences prefs = this.getPrefs();
ChessImageView._colorScheme = prefs.getInt("ColorScheme", 0);
_view.setConfirmMove(prefs.getBoolean("ICSConfirmMove", false));
_ficsHandle = prefs.getString("ics_handle", null);
_ficsPwd = prefs.getString("ics_password", null);
_iConsoleCharacterSize = Integer.parseInt(prefs.getString("ICSConsoleCharacterSize", "10"));
_bAutoSought = prefs.getBoolean("ICSAutoSought", true);
_bTimeWarning = prefs.getBoolean("ICSTimeWarning", true);
_TimeWarning = Integer.parseInt(prefs.getString("ICSTimeWarningsecs", "10"));
_bEndGameDialog = prefs.getBoolean("ICSEndGameDialog", true);
_gameStartSound = Integer.parseInt(prefs.getString("ICSGameStartSound", "1"));
_gameStartFront = prefs.getBoolean("ICSGameStartBringToFront", true);
/////////////////////////////////////////////
_adapterHandles = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
_arrayPasswords = new ArrayList<String>();
if(_ficsHandle != null) {
_adapterHandles.add(_ficsHandle);
_arrayPasswords.add(_ficsPwd);
}
try {
JSONArray jArray = new JSONArray(prefs.getString("ics_handle_array", "guest"));
JSONArray jArrayPasswords = new JSONArray(prefs.getString("ics_password_array", ""));
for(int i = 0; i < jArray.length(); i++){
_adapterHandles.add(jArray.getString(i));
_arrayPasswords.add(jArrayPasswords.getString(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int t= 0;
boolean g = false;
for (int i = 0; i < _adapterHandles.getCount(); i++) {
String x = _adapterHandles.getItem(i).toString();
if (x.equals(_ficsHandle)) {
t++;
}
if (x.equals("guest")){
g = true; // flag to check if guest is in the spinner
}
}
if (t > 1) { // work around for remove - delete every occurrence and add latest - this will add latest password
while (t > 0) {
_adapterHandles.remove(_ficsHandle);
_arrayPasswords.remove(_adapterHandles.getPosition(_ficsHandle)+1);
t--;
}
_adapterHandles.add(_ficsHandle);
_arrayPasswords.add(_ficsPwd);
}
if (g==false){
_adapterHandles.add("guest"); // if no guest then add guest
_arrayPasswords.add(" ");
}
_spinnerHandles.setAdapter(_adapterHandles);
_spinnerHandles.setSelection(_adapterHandles.getPosition(_ficsHandle));
/////////////////////////////////////////////////////////////////
if (_ficsHandle == null) {
_ficsHandle = "guest";
_ficsPwd = "";
}
String sTmp = prefs.getString("NotificationUri", null);
if (sTmp == null) {
_ringNotification = null;
} else {
Uri tmpUri = Uri.parse(sTmp);
_ringNotification = RingtoneManager.getRingtone(this, tmpUri);
}
//if(true)return;
if (isConnected()) {
switchToBoardView();
} else {
Log.i("onResume", "socket " + (_socket == null) + " worker " + (_workerTelnet == null));
_editHandle.setText(_ficsHandle);
_editPwd.setText(_ficsPwd);
if (_ficsPwd.length() < 2){
_editPwd.setText("");
}
/////////////////////////////////////////////////////
// DEBUG
//switchToBoardView();
/////////////////////////////////////////////////////
// real
switchToLoginView();
}
//rescheduleTimer();
super.onResume();
}
public String get_ficsHandle(){
return _ficsHandle;
}
public boolean is_bTimeWarning() {
return _bTimeWarning;
}
public int get_TimeWarning() {
return _TimeWarning;
}
public int get_gameStartSound(){
return _gameStartSound;
}
public String get_whiteRating(){
return _whiteRating == null ? "" : _whiteRating;
}
public String get_blackRating(){
return _blackRating == null ? "" : _blackRating;
}
public boolean isConnected() {
if (_socket == null || _workerTelnet == null || (false == _workerTelnet.isAlive()) || (false == _bInICS) || (false == _socket.isConnected())) {
return false;
}
return true;
}
public void bringAPPtoFront(){
if (_gameStartFront) {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasklist = am.getRunningTasks(10); // Number of tasks you want to get
if (!tasklist.isEmpty()) {
int nSize = tasklist.size();
for (int i = 0; i < nSize; i++) {
ActivityManager.RunningTaskInfo taskinfo = tasklist.get(i);
if (taskinfo.topActivity.getPackageName().equals("jwtc.android.chess")) {
am.moveTaskToFront(taskinfo.id, 2);
}
}
}
}
}
@Override
protected void onPause() {
// lock screen orientation?
//setRequestedOrientation(this.getResources().getConfiguration().orientation);
////////////////////////////////////////////////////////////
SharedPreferences.Editor editor = this.getPrefs().edit();
if (_bIsGuest) {
_handle = "guest";
}
editor.putString("ics_handle", _ficsHandle);
editor.putString("ics_password", _ficsPwd);
JSONArray jArray = new JSONArray();
JSONArray jArrayPasswords = new JSONArray();
for(int i = 0; i < _adapterHandles.getCount(); i++){
jArray.put(_adapterHandles.getItem(i));
jArrayPasswords.put(_arrayPasswords.get(i));
}
editor.putString("ics_handle_array", jArray.toString());
editor.putString("ics_password_array", jArrayPasswords.toString());
editor.commit();
super.onPause();
}
@Override
protected void onStart() {
Log.i("ICSClient", "onStart");
super.onStart();
}
@Override
protected void onStop() {
Log.i("ICSClient", "onStop");
super.onStop();
}
@Override
protected void onDestroy() {
Log.i("ICSClient", "onDestroy");
_workerTelnet = null;
disconnect();
tickTock.release(); // clear MediaPlayer resources
chessPiecesFall.release();
super.onDestroy();
}
public void rescheduleTimer() {
_timer = new Timer(true);
_timer.schedule(new TimerTask() {
@Override
public void run() {
m_timerHandler.sendMessage(new Message());
}
}, 200, 5000);
}
public void cancelTimer() {
if (_timer != null) {
_timer.cancel();
}
}
public void dateTimer(){
if(_timerDate == null) {
_timerDate = new Timer(true);
_timerDate.schedule(new TimerTask() {
@Override
public void run() {
dateHandler.sendEmptyMessage(0); // sends date string to prevent disconnection
}
}, 60000, 60000);
}
}
public void cancelDateTimer(){
if(_timerDate != null) {
_timerDate.cancel();
_timerDate = null;
}
}
Handler dateHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
sendString("date");
}
};
public void disconnect() {
if (_socket != null) {
try {
_socket.close();
} catch (Exception ex) {
}
_socket = null;
Log.d(TAG, "disconnect method");
}
cancelDateTimer();
}
public void sendString(String s) {
if (_bConsoleText){ // allows user ICS console text only
addConsoleText(s);
_bConsoleText = false;
}
if (_socket == null || _socket.sendString(s + "\n") == false) {
switch (get_gameStartSound()) {
case 0:
break;
case 1:
soundChessPiecesFall();
vibration(DECREASE);
break;
case 2:
soundChessPiecesFall();
break;
case 3:
vibration(DECREASE);
break;
default:
Log.e(TAG, "get_gameStartSound error");
}
//gameToast(getString(R.string.ics_disconnected), false);
try {
bringAPPtoFront();
cancelDateTimer();
new AlertDialog.Builder(ICSClient.this)
.setTitle(R.string.title_error)
.setMessage("Connection to server is broken.")
.setPositiveButton(getString(R.string.alert_ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
finish();
}
})
.show();
} catch(Exception ex){
Log.e(TAG, ex.toString());
}
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if (arg0 == _listChallenges) {
if (_mapChallenges.size() > arg2) {
HashMap<String, String> m = _mapChallenges.get(arg2);
Log.i("onItemClick", "item " + m.get("play"));
sendString("play " + m.get("play"));
}
} else if (arg0 == _listPlayers) {
if (_mapPlayers.size() > arg2) {
HashMap<String, String> m = _mapPlayers.get(arg2);
Log.i("onItemClick", "item " + m.get("text_name"));
_dlgMatch.setPlayer(m.get("text_name").toString());
_dlgMatch.show();
}
} else if (arg0 == _listGames) {
if (_mapGames.size() > arg2) {
HashMap<String, String> m = _mapGames.get(arg2);
Log.i("onItemClick", "item " + m.get("text_name1"));
sendString("observe " + m.get("text_name1"));
sendString("refresh");
get_view().setViewMode(ICSChessView.VIEW_WATCH);
get_view().setGameNum(Integer.parseInt((String) m.get("nr")));
switchToBoardView();
}
} else if (arg0 == _listStored) {
if (_mapStored.size() > arg2) {
HashMap<String, String> m = _mapStored.get(arg2);
Log.i("onItemClick", "item " + m.get("text_name_stored"));
sendString("match " + m.get("text_name_stored"));
switchToBoardView();
}
}
}
public void switchToBoardView() {
cancelTimer();
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_BOARD)
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_BOARD);
}
/*
public void switchToLobbyView(){
if(_viewAnimatorMain.getDisplayedChild() != 0)
_viewAnimatorMain.setDisplayedChild(0);
}
public void switchToWelcomeView(){
_tvHeader.setText(String.format(getString(R.string.ics_welcome_format), _handle));
if(_viewAnimatorMain.getDisplayedChild() != 0)
_viewAnimatorMain.setDisplayedChild(0);
_viewAnimatorLobby.setDisplayedChild(2);
}
*/
public void switchToChallengeView() {
rescheduleTimer();
_tvHeader.setText(R.string.ics_menu_challenges);
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_LOBBY)
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_LOBBY);
_viewAnimatorLobby.setDisplayedChild(VIEW_SUB_CHALLENGES);
}
public void switchToPlayersView() {
cancelTimer();
_tvHeader.setText(R.string.ics_menu_players);
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_LOBBY)
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_LOBBY);
_viewAnimatorLobby.setDisplayedChild(VIEW_SUB_PLAYERS);
}
public void switchToGamesView() {
cancelTimer();
_mapGames.clear();
_adapterGames.notifyDataSetChanged();
_tvHeader.setText(R.string.ics_menu_games);
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_LOBBY)
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_LOBBY);
_viewAnimatorLobby.setDisplayedChild(VIEW_SUB_GAMES);
}
public void switchToStoredView() {
cancelTimer();
_mapStored.clear();
_adapterStored.notifyDataSetChanged();
_tvHeader.setText(R.string.ics_menu_stored);
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_LOBBY)
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_LOBBY);
_viewAnimatorLobby.setDisplayedChild(VIEW_SUB_STORED);
}
public void switchToLoadingView() {
cancelTimer();
_tvHeader.setText(R.string.title_loading);
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_LOBBY) {
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_LOBBY);
}
_viewAnimatorLobby.setDisplayedChild(VIEW_SUB_PROGRESS);
}
public void switchToLoginView() {
cancelTimer();
_butLogin.setEnabled(true);
_tvHeader.setText("Login");
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_LOBBY) {
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_LOBBY);
}
_viewAnimatorLobby.setDisplayedChild(VIEW_SUB_LOGIN);
}
public void switchToConsoleView() {
cancelTimer();
_tvHeader.setText("Console");
if (_viewAnimatorMain.getDisplayedChild() != VIEW_MAIN_LOBBY) {
_viewAnimatorMain.setDisplayedChild(VIEW_MAIN_LOBBY);
}
_viewAnimatorLobby.setDisplayedChild(VIEW_SUB_CONSOLE);
_scrollConsole.post(new Runnable() {
public void run() {
_scrollConsole.fullScroll(HorizontalScrollView.FOCUS_DOWN);
}
});
}
public ICSChessView get_view() {
return _view;
}
public void soundNotification() {
if (_ringNotification != null) {
_ringNotification.play();
}
}
public void soundTickTock(){
tickTock.start();
}
public void soundChessPiecesFall(){
try {
chessPiecesFall.start();
} catch(Exception ex){
Log.e(TAG, ex.toString());
}
}
public void vibration(int seq){
try {
int v1, v2;
if(seq == 1){
v1 = 200; // increase
v2 = 500;
}else {
v1 = 500; // decrease
v2 = 200;
}
long[] pattern = {500, v1, 100, v2};
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(pattern, -1);
} catch (Exception e) {
Log.e(TAG, "vibrator process error", e);
}
}
public class ComparatorHashName implements java.util.Comparator<HashMap<String, String>> {
public int compare(HashMap<String, String> a, HashMap<String, String> b) {
return ((String) ((HashMap<String, String>) a).get("text_name")).compareToIgnoreCase(((String) ((HashMap<String, String>) b).get("text_name")));
}
}
public class ComparatorHashRating implements java.util.Comparator<HashMap<String, String>> {
public int compare(HashMap<String, String> a, HashMap<String, String> b) {
return -1 * ((String) ((HashMap<String, String>) a).get("text_rating")).compareToIgnoreCase(((String) ((HashMap<String, String>) b).get("text_rating")));
}
}
private class AlternatingRowColorAdapter extends SimpleAdapter {
public AlternatingRowColorAdapter(Context context, List<HashMap<String, String>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
view.setBackgroundColor(position % 2 == 0 ? 0x55888888 : 0x55666666);
return view;
}
}
}
| removed game stop when abort request was offered
| app/src/main/java/jwtc/android/chess/ics/ICSClient.java | removed game stop when abort request was offered | <ide><path>pp/src/main/java/jwtc/android/chess/ics/ICSClient.java
<ide> return true;
<ide> case R.string.ics_menu_abort:
<ide> sendString("abort");
<del> get_view().stopGame();
<add> // game will stop by way of toast
<ide> return true;
<ide> case R.string.ics_menu_adjourn:
<ide> sendString("adjourn"); |
|
Java | mit | a89f82d5b8dde3d3af25b2ff054aa1447ee828d0 | 0 | Alex1304/ultimategdbot,Alex1304/ultimategdbot | package com.github.alex1304.ultimategdbot.utils;
import java.util.HashMap;
import java.util.Map;
import com.github.alex1304.jdash.component.GDLevel;
import com.github.alex1304.jdash.component.GDLevelPreview;
import com.github.alex1304.jdash.component.GDSong;
import sx.blah.discord.api.internal.json.objects.EmbedObject;
import sx.blah.discord.util.EmbedBuilder;
/**
* Provides utility methods for Geometry Dash related features of the bot
*
* @author Alex1304
*/
public class GDUtils {
public static Map<String, String> difficultyIconByName = new HashMap<>();
public static Map<Integer, String> formatGameVersion = new HashMap<>();
static {
difficultyIconByName.put("6-harder-featured", "https://i.imgur.com/b7J4AXi.png");
difficultyIconByName.put("0-insane-epic", "https://i.imgur.com/GdS2f8f.png");
difficultyIconByName.put("0-harder", "https://i.imgur.com/5lT74Xj.png");
difficultyIconByName.put("4-hard-epic", "https://i.imgur.com/toyo1Cd.png");
difficultyIconByName.put("4-hard", "https://i.imgur.com/XnUynAa.png");
difficultyIconByName.put("6-harder", "https://i.imgur.com/e499HCB.png");
difficultyIconByName.put("5-hard-epic", "https://i.imgur.com/W11eyJ9.png");
difficultyIconByName.put("6-harder-epic", "https://i.imgur.com/9x1ddvD.png");
difficultyIconByName.put("5-hard", "https://i.imgur.com/Odx0nAT.png");
difficultyIconByName.put("1-auto-featured", "https://i.imgur.com/DplWGja.png");
difficultyIconByName.put("5-hard-featured", "https://i.imgur.com/HiyX5DD.png");
difficultyIconByName.put("8-insane-featured", "https://i.imgur.com/PYJ5T0x.png");
difficultyIconByName.put("0-auto-featured", "https://i.imgur.com/eMwuWmx.png");
difficultyIconByName.put("8-insane", "https://i.imgur.com/RDVJDaO.png");
difficultyIconByName.put("7-harder-epic", "https://i.imgur.com/X3N5sm1.png");
difficultyIconByName.put("0-normal-epic", "https://i.imgur.com/VyV8II6.png");
difficultyIconByName.put("0-demon-hard-featured", "https://i.imgur.com/lVdup3A.png");
difficultyIconByName.put("8-insane-epic", "https://i.imgur.com/N2pjW2W.png");
difficultyIconByName.put("3-normal-epic", "https://i.imgur.com/S3PhlDs.png");
difficultyIconByName.put("0-normal-featured", "https://i.imgur.com/Q1MYgu4.png");
difficultyIconByName.put("2-easy", "https://i.imgur.com/yG1U6RP.png");
difficultyIconByName.put("0-hard-featured", "https://i.imgur.com/8DeaxfL.png");
difficultyIconByName.put("0-demon-hard-epic", "https://i.imgur.com/xLFubIn.png");
difficultyIconByName.put("1-auto", "https://i.imgur.com/Fws2s3b.png");
difficultyIconByName.put("0-demon-hard", "https://i.imgur.com/WhrTo7w.png");
difficultyIconByName.put("0-easy", "https://i.imgur.com/kWHZa5d.png");
difficultyIconByName.put("2-easy-featured", "https://i.imgur.com/Kyjevk1.png");
difficultyIconByName.put("0-insane-featured", "https://i.imgur.com/t8JmuIw.png");
difficultyIconByName.put("0-hard", "https://i.imgur.com/YV4Afz2.png");
difficultyIconByName.put("0-na", "https://i.imgur.com/T3YfK5d.png");
difficultyIconByName.put("7-harder", "https://i.imgur.com/dJoUDUk.png");
difficultyIconByName.put("0-na-featured", "https://i.imgur.com/C4oMYGU.png");
difficultyIconByName.put("3-normal", "https://i.imgur.com/cx8tv98.png");
difficultyIconByName.put("0-harder-featured", "https://i.imgur.com/n5kA2Tv.png");
difficultyIconByName.put("0-harder-epic", "https://i.imgur.com/Y7bgUu9.png");
difficultyIconByName.put("0-na-epic", "https://i.imgur.com/hDBDGzX.png");
difficultyIconByName.put("1-auto-epic", "https://i.imgur.com/uzYx91v.png");
difficultyIconByName.put("0-easy-featured", "https://i.imgur.com/5p9eTaR.png");
difficultyIconByName.put("0-easy-epic", "https://i.imgur.com/k2lJftM.png");
difficultyIconByName.put("0-hard-epic", "https://i.imgur.com/SqnA9kJ.png");
difficultyIconByName.put("3-normal-featured", "https://i.imgur.com/1v3p1A8.png");
difficultyIconByName.put("0-normal", "https://i.imgur.com/zURUazz.png");
difficultyIconByName.put("6-harder-featured", "https://i.imgur.com/b7J4AXi.png");
difficultyIconByName.put("2-easy-epic", "https://i.imgur.com/wl575nH.png");
difficultyIconByName.put("7-harder-featured", "https://i.imgur.com/v50cZBZ.png");
difficultyIconByName.put("0-auto", "https://i.imgur.com/7xI8EOp.png");
difficultyIconByName.put("0-insane", "https://i.imgur.com/PeOvWuq.png");
difficultyIconByName.put("4-hard-featured", "https://i.imgur.com/VW4yufj.png");
difficultyIconByName.put("0-auto-epic", "https://i.imgur.com/QuRBnpB.png");
difficultyIconByName.put("10-demon-hard", "https://i.imgur.com/jLBD7cO.png");
difficultyIconByName.put("9-insane-featured", "https://i.imgur.com/byhPbgR.png");
difficultyIconByName.put("10-demon-hard-featured", "https://i.imgur.com/7deDmTQ.png");
difficultyIconByName.put("10-demon-hard-epic", "https://i.imgur.com/xtrTl4r.png");
difficultyIconByName.put("9-insane", "https://i.imgur.com/5VA2qDb.png");
difficultyIconByName.put("9-insane-epic", "https://i.imgur.com/qmfey5L.png");
// Demon difficulties
difficultyIconByName.put("0-demon-medium-epic", "https://i.imgur.com/eEEzM6I.png");
difficultyIconByName.put("10-demon-medium-epic", "https://i.imgur.com/ghco42q.png");
difficultyIconByName.put("10-demon-insane", "https://i.imgur.com/nLZqoyQ.png");
difficultyIconByName.put("0-demon-extreme-epic", "https://i.imgur.com/p250YUh.png");
difficultyIconByName.put("0-demon-easy-featured", "https://i.imgur.com/r2WNVw0.png");
difficultyIconByName.put("10-demon-easy", "https://i.imgur.com/0zM0VuT.png");
difficultyIconByName.put("10-demon-medium", "https://i.imgur.com/lvpPepA.png");
difficultyIconByName.put("10-demon-insane-epic", "https://i.imgur.com/2BWY8pO.png");
difficultyIconByName.put("10-demon-medium-featured", "https://i.imgur.com/kkAZv5O.png");
difficultyIconByName.put("0-demon-extreme-featured", "https://i.imgur.com/4MMF8uE.png");
difficultyIconByName.put("0-demon-extreme", "https://i.imgur.com/v74cX5I.png");
difficultyIconByName.put("0-demon-medium", "https://i.imgur.com/H3Swqhy.png");
difficultyIconByName.put("0-demon-medium-featured", "https://i.imgur.com/IaeyGY4.png");
difficultyIconByName.put("0-demon-insane", "https://i.imgur.com/fNC1iFH.png");
difficultyIconByName.put("0-demon-easy-epic", "https://i.imgur.com/idesUcS.png");
difficultyIconByName.put("10-demon-easy-epic", "https://i.imgur.com/wUGOGJ7.png");
difficultyIconByName.put("10-demon-insane-featured", "https://i.imgur.com/RWqIpYL.png");
difficultyIconByName.put("10-demon-easy-featured", "https://i.imgur.com/fFq5lbN.png");
difficultyIconByName.put("0-demon-insane-featured", "https://i.imgur.com/1MpbSRR.png");
difficultyIconByName.put("0-demon-insane-epic", "https://i.imgur.com/ArGfdeh.png");
difficultyIconByName.put("10-demon-extreme", "https://i.imgur.com/DEr1HoM.png");
difficultyIconByName.put("0-demon-easy", "https://i.imgur.com/45GaxRN.png");
difficultyIconByName.put("10-demon-extreme-epic", "https://i.imgur.com/gFndlkZ.png");
difficultyIconByName.put("10-demon-extreme-featured", "https://i.imgur.com/xat5en2.png");
formatGameVersion.put(10, "1.7");
formatGameVersion.put(11, "1.8");
}
/**
* Builds an embed for the specified Geometry Dash level
*
* @param authorName
* - authorName field of the embed
* @param authorIcon
* - authorIcon field of the embed
* @param lvl
* - the level to convert to embed
* @return an EmbedObject representing the embedded level
*/
public static EmbedObject buildEmbedForGDLevel(String authorName, String authorIcon, GDLevelPreview lp, GDLevel lvl) {
EmbedBuilder eb = new EmbedBuilder();
eb.withAuthorName(authorName);
eb.withAuthorIcon(authorIcon);
eb.withThumbnail(getDifficultyImageForLevel(lvl));
eb.appendField(Emojis.PLAY + " __" + lvl.getName() + "__ by " + lp.getCreatorName() + "",
"**Description:** " + (lvl.getDescription().isEmpty() ? "*(No description provided)*" : BotUtils.escapeMarkdown(lvl.getDescription())), true);
eb.appendField("Coins: " + coinsToEmoji(lvl.getCoinCount(), lvl.hasCoinsVerified(), false),
Emojis.DOWNLOADS + " " + lvl.getDownloads() + "\t\t"
+ (lvl.getLikes() < 0 ? Emojis.DISLIKE + " " : Emojis.LIKE + " ") + lvl.getLikes() + "\t\t"
+ Emojis.LENGTH + " " + lvl.getLength().toString().toUpperCase(),
false);
String pass = "";
if (lvl.getPass() == -2)
pass = "Yes, no passcode required";
else if (lvl.getPass() == -1)
pass = "No";
else {
StringBuffer passStr = new StringBuffer(String.valueOf(lvl.getPass()));
passStr.deleteCharAt(0);
pass = "Yes, " + Emojis.LOCK + " passcode: " + String.format("%06d", Integer.parseInt(passStr.toString()));
}
String objCount = "**Object count:** ";
if (lvl.getObjectCount() > 0 || lvl.getLevelVersion() >= 21) {
if (lvl.getObjectCount() == 65535)
objCount += "More than ";
objCount += lvl.getObjectCount();
if (lvl.getObjectCount() > 40000)
objCount += " " + Emojis.OBJECT_OVERFLOW + " **This level may lag on low end devices**";
} else
objCount += "_Info unavailable for levels playable in GD 2.0 or older_";
objCount += "\n";
eb.appendField(":musical_note: " + formatSongPrimaryMetadata(lp.getSong()),
formatSongSecondaryMetadata(lp.getSong()) + "\n\n"
+ "**Level ID:** " + lvl.getId() + "\n"
+ "**Level version:** " + lvl.getLevelVersion() + "\n"
+ "**Minimum GD version required to play this level:** " + formatGameVersion(lvl.getGameVersion()) + "\n"
+ "**Uploaded:** " + lvl.getUploadTimestamp() + " ago\n"
+ "**Last Updated:** " + lvl.getLastUpdatedTimestamp() + " ago\n"
+ "**Copyable:** " + pass + "\n"
+ objCount
+ (lvl.getOriginalLevelID() > 0 ? Emojis.COPY + " This level is a copy of " + lvl.getOriginalLevelID() + "\n" : "") + "\n"
+ (lvl.getFeaturedScore() > 0 ? Emojis.ICON_NA_FEATURED + " This level has been placed in the Featured section with a score of **"
+ lvl.getFeaturedScore() + "** (the higher this score is, the higher it's placed in the Featured section)\n" : ""), false);
return eb.build();
}
/**
* Builds a string of emojis according to the coin count and their verified status
*
* @param n - the coin count
* @param verified - verified status of the coins
* @param shorten - short or long version of the string
* @return
*/
public static String coinsToEmoji(int n, boolean verified, boolean shorten) {
String emoji = "" + (verified ? Emojis.USER_COIN : Emojis.USER_COIN_UNVERIFIED);
StringBuffer output = new StringBuffer();
if (shorten) {
if (n <= 0)
return "";
output.append(emoji);
output.append(" x");
output.append(n);
} else {
if (n <= 0)
return "None";
for (int i = 1 ; i <= n && i <= 3 ; i++) {
output.append(emoji);
output.append(" ");
}
}
return output.toString();
}
private static String getDifficultyImageForLevel(GDLevel lvl) {
String difficulty = "";
difficulty += lvl.getStars() + "-";
if (lvl.isDemon())
difficulty += "demon-" + lvl.getDemonDifficulty().toString().toLowerCase();
else if (lvl.isAuto())
difficulty += "auto";
else
difficulty += lvl.getDifficulty().toString().toLowerCase();
if (lvl.isEpic())
difficulty += "-epic";
else if (lvl.getFeaturedScore() > 0)
difficulty += "-featured";
return difficultyIconByName.get(difficulty);
}
/**
* Adds a dot before the last difit of the version number. For example, 20
* will become 2.0, etc.
*
* @param v
* - the int representing the version
* @return String - the formatted version
*/
public static String formatGameVersion(int v) {
if (v < 10)
return "<1.6";
if (formatGameVersion.containsKey(v))
return formatGameVersion.get(v);
String vStr = String.format("%02d", v);
if (vStr.length() <= 1)
return vStr;
return vStr.substring(0, vStr.length() - 1) + "." + vStr.charAt(vStr.length() - 1);
}
/**
* Formats song primary metadata (title + author) to a human-readable format
*
* @param song - the song
* @return String
*/
public static String formatSongPrimaryMetadata(GDSong song) {
return "__" + song.getSongTitle() + "__ by " + song.getSongAuthorName();
}
/**
* Formats song secondary metadata (ID + size + download link) to a human-readable format
*
* @param song - the song
* @return String
*/
public static String formatSongSecondaryMetadata(GDSong song) {
return song.isCustom() ? ("SongID: " + song.getSongID() + " - Size: " + song.getSongSize() + "MB\n"
+ Emojis.PLAY + " [Play on Newgrounds](https://www.newgrounds.com/audio/listen/" + song.getSongID() + ")\n"
+ Emojis.DOWNLOAD_SONG + " [Download MP3](" + song.getDownloadURL() + ")") : "Geometry Dash native audio track";
}
/**
* Returns the appropriate emoji for the difficulty of the given level
*
* @param lp - the level
* @return String
*/
public static String difficultyToEmoji(GDLevelPreview lvl) {
String difficulty = "icon_";
if (lvl.isDemon())
difficulty += "demon_" + lvl.getDemonDifficulty().toString();
else if (lvl.isAuto())
difficulty += "auto";
else
difficulty += lvl.getDifficulty().toString();
if (lvl.isEpic())
difficulty += "_epic";
else if (lvl.getFeaturedScore() > 0)
difficulty += "_featured";
String output = Emojis.valueOf(difficulty.toUpperCase()).toString();
if (lvl.getStars() > 0)
output += Emojis.STAR + " x" + lvl.getStars();
return output;
}
}
| src/main/java/com/github/alex1304/ultimategdbot/utils/GDUtils.java | package com.github.alex1304.ultimategdbot.utils;
import java.util.HashMap;
import java.util.Map;
import com.github.alex1304.jdash.component.GDLevel;
import com.github.alex1304.jdash.component.GDLevelPreview;
import com.github.alex1304.jdash.component.GDSong;
import sx.blah.discord.api.internal.json.objects.EmbedObject;
import sx.blah.discord.util.EmbedBuilder;
/**
* Provides utility methods for Geometry Dash related features of the bot
*
* @author Alex1304
*/
public class GDUtils {
public static Map<String, String> difficultyIconByName = new HashMap<>();
public static Map<Integer, String> formatGameVersion = new HashMap<>();
static {
difficultyIconByName.put("6-harder-featured", "https://i.imgur.com/b7J4AXi.png");
difficultyIconByName.put("0-insane-epic", "https://i.imgur.com/GdS2f8f.png");
difficultyIconByName.put("0-harder", "https://i.imgur.com/5lT74Xj.png");
difficultyIconByName.put("4-hard-epic", "https://i.imgur.com/toyo1Cd.png");
difficultyIconByName.put("4-hard", "https://i.imgur.com/XnUynAa.png");
difficultyIconByName.put("6-harder", "https://i.imgur.com/e499HCB.png");
difficultyIconByName.put("5-hard-epic", "https://i.imgur.com/W11eyJ9.png");
difficultyIconByName.put("6-harder-epic", "https://i.imgur.com/9x1ddvD.png");
difficultyIconByName.put("5-hard", "https://i.imgur.com/Odx0nAT.png");
difficultyIconByName.put("1-auto-featured", "https://i.imgur.com/DplWGja.png");
difficultyIconByName.put("5-hard-featured", "https://i.imgur.com/HiyX5DD.png");
difficultyIconByName.put("8-insane-featured", "https://i.imgur.com/PYJ5T0x.png");
difficultyIconByName.put("0-auto-featured", "https://i.imgur.com/eMwuWmx.png");
difficultyIconByName.put("8-insane", "https://i.imgur.com/RDVJDaO.png");
difficultyIconByName.put("7-harder-epic", "https://i.imgur.com/X3N5sm1.png");
difficultyIconByName.put("0-normal-epic", "https://i.imgur.com/VyV8II6.png");
difficultyIconByName.put("0-demon-hard-featured", "https://i.imgur.com/lVdup3A.png");
difficultyIconByName.put("8-insane-epic", "https://i.imgur.com/N2pjW2W.png");
difficultyIconByName.put("3-normal-epic", "https://i.imgur.com/S3PhlDs.png");
difficultyIconByName.put("0-normal-featured", "https://i.imgur.com/Q1MYgu4.png");
difficultyIconByName.put("2-easy", "https://i.imgur.com/yG1U6RP.png");
difficultyIconByName.put("0-hard-featured", "https://i.imgur.com/8DeaxfL.png");
difficultyIconByName.put("0-demon-hard-epic", "https://i.imgur.com/xLFubIn.png");
difficultyIconByName.put("1-auto", "https://i.imgur.com/Fws2s3b.png");
difficultyIconByName.put("0-demon-hard", "https://i.imgur.com/WhrTo7w.png");
difficultyIconByName.put("0-easy", "https://i.imgur.com/kWHZa5d.png");
difficultyIconByName.put("2-easy-featured", "https://i.imgur.com/Kyjevk1.png");
difficultyIconByName.put("0-insane-featured", "https://i.imgur.com/t8JmuIw.png");
difficultyIconByName.put("0-hard", "https://i.imgur.com/YV4Afz2.png");
difficultyIconByName.put("0-na", "https://i.imgur.com/T3YfK5d.png");
difficultyIconByName.put("7-harder", "https://i.imgur.com/dJoUDUk.png");
difficultyIconByName.put("0-na-featured", "https://i.imgur.com/C4oMYGU.png");
difficultyIconByName.put("3-normal", "https://i.imgur.com/cx8tv98.png");
difficultyIconByName.put("0-harder-featured", "https://i.imgur.com/n5kA2Tv.png");
difficultyIconByName.put("0-harder-epic", "https://i.imgur.com/Y7bgUu9.png");
difficultyIconByName.put("0-na-epic", "https://i.imgur.com/hDBDGzX.png");
difficultyIconByName.put("1-auto-epic", "https://i.imgur.com/uzYx91v.png");
difficultyIconByName.put("0-easy-featured", "https://i.imgur.com/5p9eTaR.png");
difficultyIconByName.put("0-easy-epic", "https://i.imgur.com/k2lJftM.png");
difficultyIconByName.put("0-hard-epic", "https://i.imgur.com/SqnA9kJ.png");
difficultyIconByName.put("3-normal-featured", "https://i.imgur.com/1v3p1A8.png");
difficultyIconByName.put("0-normal", "https://i.imgur.com/zURUazz.png");
difficultyIconByName.put("6-harder-featured", "https://i.imgur.com/b7J4AXi.png");
difficultyIconByName.put("2-easy-epic", "https://i.imgur.com/wl575nH.png");
difficultyIconByName.put("7-harder-featured", "https://i.imgur.com/v50cZBZ.png");
difficultyIconByName.put("0-auto", "https://i.imgur.com/7xI8EOp.png");
difficultyIconByName.put("0-insane", "https://i.imgur.com/PeOvWuq.png");
difficultyIconByName.put("4-hard-featured", "https://i.imgur.com/VW4yufj.png");
difficultyIconByName.put("0-auto-epic", "https://i.imgur.com/QuRBnpB.png");
difficultyIconByName.put("10-demon-hard", "https://i.imgur.com/jLBD7cO.png");
difficultyIconByName.put("9-insane-featured", "https://i.imgur.com/byhPbgR.png");
difficultyIconByName.put("10-demon-hard-featured", "https://i.imgur.com/7deDmTQ.png");
difficultyIconByName.put("10-demon-hard-epic", "https://i.imgur.com/xtrTl4r.png");
difficultyIconByName.put("9-insane", "https://i.imgur.com/5VA2qDb.png");
difficultyIconByName.put("9-insane-epic", "https://i.imgur.com/qmfey5L.png");
// Demon difficulties
difficultyIconByName.put("0-demon-medium-epic", "https://i.imgur.com/eEEzM6I.png");
difficultyIconByName.put("10-demon-medium-epic", "https://i.imgur.com/ghco42q.png");
difficultyIconByName.put("10-demon-insane", "https://i.imgur.com/nLZqoyQ.png");
difficultyIconByName.put("0-demon-extreme-epic", "https://i.imgur.com/p250YUh.png");
difficultyIconByName.put("0-demon-easy-featured", "https://i.imgur.com/r2WNVw0.png");
difficultyIconByName.put("10-demon-easy", "https://i.imgur.com/0zM0VuT.png");
difficultyIconByName.put("10-demon-medium", "https://i.imgur.com/lvpPepA.png");
difficultyIconByName.put("10-demon-insane-epic", "https://i.imgur.com/2BWY8pO.png");
difficultyIconByName.put("10-demon-medium-featured", "https://i.imgur.com/kkAZv5O.png");
difficultyIconByName.put("0-demon-extreme-featured", "https://i.imgur.com/4MMF8uE.png");
difficultyIconByName.put("0-demon-extreme", "https://i.imgur.com/v74cX5I.png");
difficultyIconByName.put("0-demon-medium", "https://i.imgur.com/H3Swqhy.png");
difficultyIconByName.put("0-demon-medium-featured", "https://i.imgur.com/IaeyGY4.png");
difficultyIconByName.put("0-demon-insane", "https://i.imgur.com/fNC1iFH.png");
difficultyIconByName.put("0-demon-easy-epic", "https://i.imgur.com/idesUcS.png");
difficultyIconByName.put("10-demon-easy-epic", "https://i.imgur.com/wUGOGJ7.png");
difficultyIconByName.put("10-demon-insane-featured", "https://i.imgur.com/RWqIpYL.png");
difficultyIconByName.put("10-demon-easy-featured", "https://i.imgur.com/fFq5lbN.png");
difficultyIconByName.put("0-demon-insane-featured", "https://i.imgur.com/1MpbSRR.png");
difficultyIconByName.put("0-demon-insane-epic", "https://i.imgur.com/ArGfdeh.png");
difficultyIconByName.put("10-demon-extreme", "https://i.imgur.com/DEr1HoM.png");
difficultyIconByName.put("0-demon-easy", "https://i.imgur.com/45GaxRN.png");
difficultyIconByName.put("10-demon-extreme-epic", "https://i.imgur.com/gFndlkZ.png");
difficultyIconByName.put("10-demon-extreme-featured", "https://i.imgur.com/xat5en2.png");
formatGameVersion.put(10, "1.7");
formatGameVersion.put(11, "1.8");
}
/**
* Builds an embed for the specified Geometry Dash level
*
* @param authorName
* - authorName field of the embed
* @param authorIcon
* - authorIcon field of the embed
* @param lvl
* - the level to convert to embed
* @return an EmbedObject representing the embedded level
*/
public static EmbedObject buildEmbedForGDLevel(String authorName, String authorIcon, GDLevelPreview lp, GDLevel lvl) {
EmbedBuilder eb = new EmbedBuilder();
eb.withAuthorName(authorName);
eb.withAuthorIcon(authorIcon);
eb.withThumbnail(getDifficultyImageForLevel(lvl));
eb.appendField(Emojis.PLAY + " __" + lvl.getName() + "__ by " + lp.getCreatorName() + "",
"**Description:** " + (lvl.getDescription().isEmpty() ? "*(No description provided)*" : BotUtils.escapeMarkdown(lvl.getDescription())), true);
eb.appendField("Coins: " + coinsToEmoji(lvl.getCoinCount(), lvl.hasCoinsVerified(), false),
Emojis.DOWNLOADS + " " + lvl.getDownloads() + "\t\t"
+ (lvl.getLikes() < 0 ? Emojis.DISLIKE + " " : Emojis.LIKE + " ") + lvl.getLikes() + "\t\t"
+ Emojis.LENGTH + " " + lvl.getLength().toString().toUpperCase(),
false);
String pass = "";
if (lvl.getPass() == -2)
pass = "Yes, no passcode required";
else if (lvl.getPass() == -1)
pass = "No";
else {
StringBuffer passStr = new StringBuffer(String.valueOf(lvl.getPass()));
passStr.deleteCharAt(0);
pass = "Yes, " + Emojis.LOCK + " passcode: " + String.format("%06d", Integer.parseInt(passStr.toString()));
}
String objCount = "**Object count:** ";
if (lvl.getObjectCount() > 0 || lvl.getLevelVersion() >= 21) {
if (lvl.getObjectCount() == 65535)
objCount += "More than ";
objCount += lvl.getObjectCount();
if (lvl.getObjectCount() > 40000)
objCount += " " + Emojis.OBJECT_OVERFLOW + " **This level may lag on low end devices**";
} else
objCount += "_Info unavailable for levels playable in GD 2.0 or older_";
objCount += "\n";
eb.appendField(":musical_note: " + formatSongPrimaryMetadata(lp.getSong()),
formatSongSecondaryMetadata(lp.getSong()) + "\n\n"
+ "**Level ID:** " + lvl.getId() + "\n"
+ "**Level version:** " + lvl.getLevelVersion() + "\n"
+ "**Minimum GD version required to play this level:** " + formatGameVersion(lvl.getGameVersion()) + "\n"
+ "**Uploaded:** " + lvl.getUploadTimestamp() + " ago\n"
+ "**Last Updated:** " + lvl.getLastUpdatedTimestamp() + " ago\n"
+ "**Copyable:** " + pass + "\n"
+ objCount
+ (lvl.getOriginalLevelID() > 0 ? Emojis.COPY + " This level is a copy of " + lvl.getOriginalLevelID() + "\n" : "") + "\n"
+ (lvl.getFeaturedScore() > 0 ? Emojis.ICON_NA_FEATURED + " This level has been placed in the Featured section with a score of **"
+ lvl.getFeaturedScore() + "** (the higher this score is, the higher it's placed in the Featured section)\n" : ""), false);
return eb.build();
}
/**
* Builds a string of emojis according to the coin count and their verified status
*
* @param n - the coin count
* @param verified - verified status of the coins
* @param shorten - short or long version of the string
* @return
*/
public static String coinsToEmoji(int n, boolean verified, boolean shorten) {
String emoji = "" + (verified ? Emojis.USER_COIN : Emojis.USER_COIN_UNVERIFIED);
StringBuffer output = new StringBuffer();
if (shorten) {
if (n <= 0)
return "";
output.append(emoji);
output.append(" x");
output.append(n);
} else {
if (n <= 0)
return "None";
for (int i = 1 ; i <= n && i <= 3 ; i++) {
output.append(emoji);
output.append(" ");
}
}
return output.toString();
}
private static String getDifficultyImageForLevel(GDLevel lvl) {
String difficulty = "";
difficulty += lvl.getStars() + "-";
if (lvl.isDemon())
difficulty += "demon-" + lvl.getDemonDifficulty().toString().toLowerCase();
else if (lvl.isAuto())
difficulty += "auto";
else
difficulty += lvl.getDifficulty().toString().toLowerCase();
if (lvl.isEpic())
difficulty += "-epic";
else if (lvl.getFeaturedScore() > 0)
difficulty += "-featured";
return difficultyIconByName.get(difficulty);
}
/**
* Adds a dot before the last difit of the version number. For example, 20
* will become 2.0, etc.
*
* @param v
* - the int representing the version
* @return String - the formatted version
*/
public static String formatGameVersion(int v) {
if (v < 10)
return "<1.6";
if (formatGameVersion.containsKey(v))
return formatGameVersion.get(v);
String vStr = String.format("%02d", v);
if (vStr.length() <= 1)
return vStr;
return vStr.substring(0, vStr.length() - 1) + "." + vStr.charAt(vStr.length() - 1);
}
/**
* Formats song primary metadata (title + author) to a human-readable format
*
* @param song - the song
* @return String
*/
public static String formatSongPrimaryMetadata(GDSong song) {
return "__" + song.getSongTitle() + "__ by " + song.getSongAuthorName();
}
/**
* Formats song secondary metadata (ID + size + download link) to a human-readable format
*
* @param song - the song
* @return String
*/
public static String formatSongSecondaryMetadata(GDSong song) {
return song.isCustom() ? ("SongID: " + song.getSongID() + " - Size: " + song.getSongSize() + "MB\n"
+ Emojis.PLAY + " [Play on Newgrounds](https://www.newgrounds.com/audio/listen/" + song.getSongID() + ")\n"
+ Emojis.DOWNLOAD_SONG + " [Download](" + song.getDownloadURL() + ")") : "Geometry Dash native audio track";
}
/**
* Returns the appropriate emoji for the difficulty of the given level
*
* @param lp - the level
* @return String
*/
public static String difficultyToEmoji(GDLevelPreview lvl) {
String difficulty = "icon_";
if (lvl.isDemon())
difficulty += "demon_" + lvl.getDemonDifficulty().toString();
else if (lvl.isAuto())
difficulty += "auto";
else
difficulty += lvl.getDifficulty().toString();
if (lvl.isEpic())
difficulty += "_epic";
else if (lvl.getFeaturedScore() > 0)
difficulty += "_featured";
String output = Emojis.valueOf(difficulty.toUpperCase()).toString();
if (lvl.getStars() > 0)
output += Emojis.STAR + " x" + lvl.getStars();
return output;
}
}
| Rewording Download to Download MP3
| src/main/java/com/github/alex1304/ultimategdbot/utils/GDUtils.java | Rewording Download to Download MP3 | <ide><path>rc/main/java/com/github/alex1304/ultimategdbot/utils/GDUtils.java
<ide> public static String formatSongSecondaryMetadata(GDSong song) {
<ide> return song.isCustom() ? ("SongID: " + song.getSongID() + " - Size: " + song.getSongSize() + "MB\n"
<ide> + Emojis.PLAY + " [Play on Newgrounds](https://www.newgrounds.com/audio/listen/" + song.getSongID() + ")\n"
<del> + Emojis.DOWNLOAD_SONG + " [Download](" + song.getDownloadURL() + ")") : "Geometry Dash native audio track";
<add> + Emojis.DOWNLOAD_SONG + " [Download MP3](" + song.getDownloadURL() + ")") : "Geometry Dash native audio track";
<ide> }
<ide>
<ide> /** |
|
JavaScript | mit | 26b672a7fcb98475ce2aea5b9d04b42733654c45 | 0 | ongr-io/ongr-sandbox,ongr-io/ongr-sandbox,ongr-io/Demo,ongr-io/Demo,ongr-io/demo.ongr.io,ongr-io/Demo,ongr-io/demo.ongr.io,ongr-io/demo.ongr.io,ongr-io/ongr-sandbox | /*
* This file is part of the ONGR package.
*
* (c) NFQ Technologies UAB <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
(function ($) {
var topbarDropdown = '.topbar-dropdown-content';
var navbarDropdown = '.navbar-dropdown-content';
$('.topbar-dropdown')
.mouseenter(function() {
$(this).addClass('opened');
$(this).find(topbarDropdown).slideDown('fast');
})
.mouseleave(function() {
$(this).removeClass('opened');
$(this).find(topbarDropdown).slideUp('fast');
});
$('.navbar-dropdown')
.mouseenter(function() {
$(this).addClass('opened');
$(this).find(navbarDropdown).fadeIn('fast');
})
.mouseleave(function() {
$(this).removeClass('opened');
$(this).find(navbarDropdown).fadeOut('fast');
});
$('.js-footer-dropdown-trigger').click(function() {
var trigger = $(this);
if ($(this).hasClass('opened')) {
$(this).next().slideUp('fast', function() {
trigger.removeClass('opened');
});
} else {
trigger.addClass('opened');
$(this).next().slideDown('fast');
}
});
$('.page-header-search-inp').click(function(e) {
$(this).parent().width('300px');
e.stopPropagation();
});
$(document).click(function() {
$('.page-header-search-inp').parent().width('200px');
});
$('.page-header-search-btn').click(function(e) {
e.stopPropagation();
$(this).parent().submit();
});
$('.page-header-cart-close').click(function(e) {
e.preventDefault();
$(this).parents().find(topbarDropdown).slideUp('fast');
});
})(jQuery);
| src/ONGR/DemoBundle/Resources/public/scripts/main.js | /*
* This file is part of the ONGR package.
*
* (c) NFQ Technologies UAB <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
(function ($) {
var topbarDropdown = '.topbar-dropdown-content';
$('.topbar-dropdown')
.mouseenter(function() {
$(this).addClass('opened');
$(this).find(topbarDropdown).slideDown('fast');
})
.mouseleave(function() {
$(this).removeClass('opened');
$(this).find(topbarDropdown).slideUp('fast');
});
$('.js-footer-dropdown-trigger').click(function() {
var trigger = $(this);
if ($(this).hasClass('opened')) {
$(this).next().slideUp('fast', function() {
trigger.removeClass('opened');
});
} else {
trigger.addClass('opened');
$(this).next().slideDown('fast');
}
});
$('.page-header-search-inp').click(function(e) {
$(this).parent().width('300px');
e.stopPropagation();
});
$(document).click(function() {
$('.page-header-search-inp').parent().width('200px');
});
$('.page-header-search-btn').click(function(e) {
e.stopPropagation();
$(this).parent().submit();
});
$('.page-header-cart-close').click(function(e) {
e.preventDefault();
$(this).parents().find(topbarDropdown).slideUp('fast');
});
})(jQuery);
| navbar dropdown js added
| src/ONGR/DemoBundle/Resources/public/scripts/main.js | navbar dropdown js added | <ide><path>rc/ONGR/DemoBundle/Resources/public/scripts/main.js
<ide>
<ide> (function ($) {
<ide> var topbarDropdown = '.topbar-dropdown-content';
<add> var navbarDropdown = '.navbar-dropdown-content';
<ide>
<ide> $('.topbar-dropdown')
<ide> .mouseenter(function() {
<ide> .mouseleave(function() {
<ide> $(this).removeClass('opened');
<ide> $(this).find(topbarDropdown).slideUp('fast');
<add> });
<add>
<add> $('.navbar-dropdown')
<add> .mouseenter(function() {
<add> $(this).addClass('opened');
<add> $(this).find(navbarDropdown).fadeIn('fast');
<add> })
<add> .mouseleave(function() {
<add> $(this).removeClass('opened');
<add> $(this).find(navbarDropdown).fadeOut('fast');
<ide> });
<ide>
<ide> $('.js-footer-dropdown-trigger').click(function() { |
|
Java | apache-2.0 | ac73f38d3d74789a6e369416edf982b31553f696 | 0 | rgodfrey/activemq-artemis,clebertsuconic/activemq-artemis,jmesnil/activemq-artemis,mnovak1/activemq-artemis,mnovak1/activemq-artemis,andytaylor/activemq-artemis,orpiske/activemq-artemis,kjniemi/activemq-artemis,jbertram/activemq-artemis,jbertram/activemq-artemis,dejanb/activemq-artemis,clebertsuconic/activemq-artemis,dejanb/activemq-artemis,orpiske/activemq-artemis,jbertram/activemq-artemis,mnovak1/activemq-artemis,rgodfrey/activemq-artemis,dejanb/activemq-artemis,mnovak1/activemq-artemis,gaohoward/activemq-artemis,kjniemi/activemq-artemis,jmesnil/activemq-artemis,TomRoss/activemq-artemis,jmesnil/activemq-artemis,rgodfrey/activemq-artemis,jmesnil/activemq-artemis,clebertsuconic/activemq-artemis,tabish121/activemq-artemis,dejanb/activemq-artemis,orpiske/activemq-artemis,iweiss/activemq-artemis,TomRoss/activemq-artemis,clebertsuconic/activemq-artemis,apache/activemq-artemis,apache/activemq-artemis,rgodfrey/activemq-artemis,mnovak1/activemq-artemis,gaohoward/activemq-artemis,tabish121/activemq-artemis,dejanb/activemq-artemis,rgodfrey/activemq-artemis,apache/activemq-artemis,graben/activemq-artemis,graben/activemq-artemis,graben/activemq-artemis,TomRoss/activemq-artemis,jmesnil/activemq-artemis,kjniemi/activemq-artemis,andytaylor/activemq-artemis,graben/activemq-artemis,iweiss/activemq-artemis,kjniemi/activemq-artemis,TomRoss/activemq-artemis,jbertram/activemq-artemis,dejanb/activemq-artemis,tabish121/activemq-artemis,apache/activemq-artemis,mnovak1/activemq-artemis,iweiss/activemq-artemis,andytaylor/activemq-artemis,orpiske/activemq-artemis,tabish121/activemq-artemis,kjniemi/activemq-artemis,andytaylor/activemq-artemis,iweiss/activemq-artemis,jmesnil/activemq-artemis,rgodfrey/activemq-artemis,gaohoward/activemq-artemis,gaohoward/activemq-artemis | /*
* 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.artemis.tests.integration.amqp;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.QueueBrowser;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.artemis.core.server.Queue;
import org.apache.activemq.artemis.tests.util.Wait;
import org.apache.qpid.jms.JmsConnection;
import org.apache.qpid.jms.policy.JmsDefaultPrefetchPolicy;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JMSMessageConsumerTest extends JMSClientTestSupport {
protected static final Logger LOG = LoggerFactory.getLogger(JMSMessageConsumerTest.class);
@Override
protected String getConfiguredProtocols() {
return "AMQP,OPENWIRE,CORE";
}
@Test(timeout = 30000)
public void testDeliveryModeAMQPProducerCoreConsumer() throws Exception {
Connection connection = createConnection(); //AMQP
Connection connection2 = createCoreConnection(); //CORE
testDeliveryMode(connection, connection2);
}
@Test(timeout = 30000)
public void testDeliveryModeAMQPProducerAMQPConsumer() throws Exception {
Connection connection = createConnection(); //AMQP
Connection connection2 = createConnection(); //AMQP
testDeliveryMode(connection, connection2);
}
@Test(timeout = 30000)
public void testDeliveryModeCoreProducerAMQPConsumer() throws Exception {
Connection connection = createCoreConnection(); //CORE
Connection connection2 = createConnection(); //AMQP
testDeliveryMode(connection, connection2);
}
@Test(timeout = 30000)
public void testDeliveryModeCoreProducerCoreConsumer() throws Exception {
Connection connection = createCoreConnection(); //CORE
Connection connection2 = createCoreConnection(); //CORE
testDeliveryMode(connection, connection2);
}
private void testDeliveryMode(Connection connection1, Connection connection2) throws JMSException {
try {
Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue1 = session1.createQueue(getQueueName());
javax.jms.Queue queue2 = session2.createQueue(getQueueName());
final MessageConsumer consumer2 = session2.createConsumer(queue2);
MessageProducer producer = session1.createProducer(queue1);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
connection1.start();
TextMessage message = session1.createTextMessage();
message.setText("hello");
producer.send(message);
Message received = consumer2.receive(100);
assertNotNull("Should have received a message by now.", received);
assertTrue("Should be an instance of TextMessage", received instanceof TextMessage);
assertEquals(DeliveryMode.PERSISTENT, received.getJMSDeliveryMode());
} finally {
connection1.close();
connection2.close();
}
}
@Test(timeout = 30000)
public void testPriorityAMQPProducerCoreConsumer() throws Exception {
Connection connection = createConnection(); //AMQP
Connection connection2 = createCoreConnection(); //CORE
testPriority(connection, connection2);
}
@Test(timeout = 30000)
public void testPriorityAMQPProducerAMQPConsumer() throws Exception {
Connection connection = createConnection(); //AMQP
Connection connection2 = createConnection(); //AMQP
testPriority(connection, connection2);
}
@Test(timeout = 30000)
public void testPriorityModeCoreProducerAMQPConsumer() throws Exception {
Connection connection = createCoreConnection(); //CORE
Connection connection2 = createConnection(); //AMQP
testPriority(connection, connection2);
}
@Test(timeout = 30000)
public void testPriorityCoreProducerCoreConsumer() throws Exception {
Connection connection = createCoreConnection(); //CORE
Connection connection2 = createCoreConnection(); //CORE
testPriority(connection, connection2);
}
private void testPriority(Connection connection1, Connection connection2) throws JMSException {
try {
Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue1 = session1.createQueue(getQueueName());
javax.jms.Queue queue2 = session2.createQueue(getQueueName());
final MessageConsumer consumer2 = session2.createConsumer(queue2);
MessageProducer producer = session1.createProducer(queue1);
producer.setPriority(2);
connection1.start();
TextMessage message = session1.createTextMessage();
message.setText("hello");
producer.send(message);
Message received = consumer2.receive(100);
assertNotNull("Should have received a message by now.", received);
assertTrue("Should be an instance of TextMessage", received instanceof TextMessage);
assertEquals(2, received.getJMSPriority());
} finally {
connection1.close();
connection2.close();
}
}
@Test(timeout = 60000)
public void testSelectorOnTopic() throws Exception {
doTestSelector(true);
}
@Test(timeout = 60000)
public void testSelectorOnQueue() throws Exception {
doTestSelector(false);
}
private void doTestSelector(boolean topic) throws Exception {
Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = null;
if (topic) {
destination = session.createTopic(getTopicName());
} else {
destination = session.createQueue(getQueueName());
}
MessageProducer producer = session.createProducer(destination);
MessageConsumer messageConsumer = session.createConsumer(destination, "color = 'RED'");
TextMessage message = session.createTextMessage();
message.setText("msg:0");
producer.send(message);
message = session.createTextMessage();
message.setText("msg:1");
message.setStringProperty("color", "RED");
producer.send(message);
connection.start();
TextMessage m = (TextMessage) messageConsumer.receive(5000);
assertNotNull(m);
assertEquals("msg:1", m.getText());
assertEquals(m.getStringProperty("color"), "RED");
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testSelectorsWithJMSTypeOnTopic() throws Exception {
doTestSelectorsWithJMSType(true);
}
@Test(timeout = 30000)
public void testSelectorsWithJMSTypeOnQueue() throws Exception {
doTestSelectorsWithJMSType(false);
}
private void doTestSelectorsWithJMSType(boolean topic) throws Exception {
final Connection connection = createConnection();
final String type = "myJMSType";
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = null;
if (topic) {
destination = session.createTopic(getTopicName());
} else {
destination = session.createQueue(getQueueName());
}
MessageProducer producer = session.createProducer(destination);
MessageConsumer consumer = session.createConsumer(destination, "JMSType = '" + type + "'");
TextMessage message1 = session.createTextMessage();
message1.setText("text");
producer.send(message1, DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
TextMessage message2 = session.createTextMessage();
message2.setJMSType(type);
message2.setText("text + type");
producer.send(message2, DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
connection.start();
Message msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("Unexpected JMSType value", type, msg.getJMSType());
assertEquals("Unexpected message content", "text + type", ((TextMessage) msg).getText());
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testSelectorsWithJMSCorrelationID() throws Exception {
Connection connection = createConnection();
final String correlationID = UUID.randomUUID().toString();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(queue);
TextMessage message1 = session.createTextMessage();
message1.setText("text");
producer.send(message1);
TextMessage message2 = session.createTextMessage();
message2.setJMSCorrelationID(correlationID);
message2.setText("JMSCorrelationID");
producer.send(message2);
QueueBrowser browser = session.createBrowser(queue);
Enumeration<?> enumeration = browser.getEnumeration();
int count = 0;
while (enumeration.hasMoreElements()) {
Message m = (Message) enumeration.nextElement();
assertTrue(m instanceof TextMessage);
count++;
}
assertEquals(2, count);
MessageConsumer consumer = session.createConsumer(queue, "JMSCorrelationID = '" + correlationID + "'");
Message msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("Unexpected JMSCorrelationID value", correlationID, msg.getJMSCorrelationID());
assertEquals("Unexpected message content", "JMSCorrelationID", ((TextMessage) msg).getText());
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testSelectorsWithJMSPriority() throws Exception {
Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(queue);
TextMessage message = session.createTextMessage();
message.setText("hello");
producer.send(message, DeliveryMode.PERSISTENT, 5, 0);
message = session.createTextMessage();
message.setText("hello + 9");
producer.send(message, DeliveryMode.PERSISTENT, 9, 0);
QueueBrowser browser = session.createBrowser(queue);
Enumeration<?> enumeration = browser.getEnumeration();
int count = 0;
while (enumeration.hasMoreElements()) {
Message m = (Message) enumeration.nextElement();
assertTrue(m instanceof TextMessage);
count++;
}
assertEquals(2, count);
MessageConsumer consumer = session.createConsumer(queue, "JMSPriority > 8");
Message msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("hello + 9", ((TextMessage) msg).getText());
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testSelectorsWithJMSXGroupIDOnTopic() throws Exception {
doTestSelectorsWithJMSXGroupID(true);
}
@Test(timeout = 30000)
public void testSelectorsWithJMSXGroupIDOnQueue() throws Exception {
doTestSelectorsWithJMSXGroupID(false);
}
private void doTestSelectorsWithJMSXGroupID(boolean topic) throws Exception {
Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = null;
if (topic) {
destination = session.createTopic(getTopicName());
} else {
destination = session.createQueue(getQueueName());
}
MessageProducer producer = session.createProducer(destination);
MessageConsumer consumer = session.createConsumer(destination, "JMSXGroupID = '1'");
TextMessage message = session.createTextMessage();
message.setText("group 1 - 1");
message.setStringProperty("JMSXGroupID", "1");
message.setIntProperty("JMSXGroupSeq", 1);
producer.send(message);
message = session.createTextMessage();
message.setText("group 2");
message.setStringProperty("JMSXGroupID", "2");
producer.send(message);
message = session.createTextMessage();
message.setText("group 1 - 2");
message.setStringProperty("JMSXGroupID", "1");
message.setIntProperty("JMSXGroupSeq", -1);
producer.send(message);
connection.start();
Message msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("group 1 - 1", ((TextMessage) msg).getText());
msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("group 1 - 2", ((TextMessage) msg).getText());
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testSelectorsWithJMSDeliveryOnQueue() throws Exception {
final Connection connection = createConnection();
String selector = "JMSDeliveryMode = 'PERSISTENT'";
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(destination);
MessageConsumer consumer = session.createConsumer(destination, selector);
TextMessage message1 = session.createTextMessage();
message1.setText("non-persistent");
producer.send(message1, DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
TextMessage message2 = session.createTextMessage();
message2.setText("persistent");
producer.send(message2, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
connection.start();
Message msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("Unexpected JMSDeliveryMode value", DeliveryMode.PERSISTENT, msg.getJMSDeliveryMode());
assertEquals("Unexpected message content", "persistent", ((TextMessage) msg).getText());
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testSelectorsWithJMSTimestampOnQueue() throws Exception {
final Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(destination);
TextMessage message1 = session.createTextMessage();
message1.setText("filtered");
producer.send(message1, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
// short delay to prevent the timestamps from being the same
Thread.sleep(2);
TextMessage message2 = session.createTextMessage();
message2.setText("expected");
producer.send(message2, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
MessageConsumer consumer = session.createConsumer(destination, "JMSTimestamp = " + message2.getJMSTimestamp());
connection.start();
Message msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("Unexpected JMSTimestamp value", message2.getJMSTimestamp(), msg.getJMSTimestamp());
assertEquals("Unexpected message content", "expected", ((TextMessage) msg).getText());
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testSelectorsWithJMSExpirationOnQueue() throws Exception {
final Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(destination);
TextMessage message1 = session.createTextMessage();
message1.setText("filtered");
producer.send(message1, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
TextMessage message2 = session.createTextMessage();
message2.setText("expected");
producer.send(message2, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, 60000);
MessageConsumer consumer = session.createConsumer(destination, "JMSExpiration = " + message2.getJMSExpiration());
connection.start();
Message msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("Unexpected JMSExpiration value", message2.getJMSExpiration(), msg.getJMSExpiration());
assertEquals("Unexpected message content", "expected", ((TextMessage) msg).getText());
} finally {
connection.close();
}
}
@Test(timeout = 60000)
public void testJMSSelectorFiltersJMSMessageIDOnTopic() throws Exception {
Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(queue);
// Send one to receive
TextMessage message = session.createTextMessage();
producer.send(message);
// Send another to filter
producer.send(session.createTextMessage());
connection.start();
// First one should make it through
MessageConsumer messageConsumer = session.createConsumer(queue, "JMSMessageID = '" + message.getJMSMessageID() + "'");
TextMessage m = (TextMessage) messageConsumer.receive(5000);
assertNotNull(m);
assertEquals(message.getJMSMessageID(), m.getJMSMessageID());
// The second one should not be received.
assertNull(messageConsumer.receive(1000));
} finally {
connection.close();
}
}
@Test(timeout = 60000)
public void testZeroPrefetchWithTwoConsumers() throws Exception {
JmsConnection connection = (JmsConnection) createConnection();
((JmsDefaultPrefetchPolicy) connection.getPrefetchPolicy()).setAll(0);
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(queue);
producer.send(session.createTextMessage("Msg1"));
producer.send(session.createTextMessage("Msg2"));
// now lets receive it
MessageConsumer consumer1 = session.createConsumer(queue);
MessageConsumer consumer2 = session.createConsumer(queue);
TextMessage answer = (TextMessage) consumer1.receive(5000);
assertNotNull(answer);
assertEquals("Should have received a message!", answer.getText(), "Msg1");
answer = (TextMessage) consumer2.receive(5000);
assertNotNull(answer);
assertEquals("Should have received a message!", answer.getText(), "Msg2");
answer = (TextMessage) consumer2.receiveNoWait();
assertNull("Should have not received a message!", answer);
}
@Test(timeout = 30000)
public void testProduceAndConsumeLargeNumbersOfTopicMessagesClientAck() throws Exception {
doTestProduceAndConsumeLargeNumbersOfMessages(true, Session.CLIENT_ACKNOWLEDGE);
}
@Test(timeout = 30000)
public void testProduceAndConsumeLargeNumbersOfQueueMessagesClientAck() throws Exception {
doTestProduceAndConsumeLargeNumbersOfMessages(false, Session.CLIENT_ACKNOWLEDGE);
}
@Test(timeout = 30000)
public void testProduceAndConsumeLargeNumbersOfTopicMessagesAutoAck() throws Exception {
doTestProduceAndConsumeLargeNumbersOfMessages(true, Session.AUTO_ACKNOWLEDGE);
}
@Test(timeout = 30000)
public void testProduceAndConsumeLargeNumbersOfQueueMessagesAutoAck() throws Exception {
doTestProduceAndConsumeLargeNumbersOfMessages(false, Session.AUTO_ACKNOWLEDGE);
}
public void doTestProduceAndConsumeLargeNumbersOfMessages(boolean topic, int ackMode) throws Exception {
final int MSG_COUNT = 1000;
final CountDownLatch done = new CountDownLatch(MSG_COUNT);
JmsConnection connection = (JmsConnection) createConnection();
connection.setForceAsyncSend(true);
connection.start();
Session session = connection.createSession(false, ackMode);
final Destination destination;
if (topic) {
destination = session.createTopic(getTopicName());
} else {
destination = session.createQueue(getQueueName());
}
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
try {
message.acknowledge();
done.countDown();
} catch (JMSException ex) {
LOG.info("Caught exception.", ex);
}
}
});
MessageProducer producer = session.createProducer(destination);
TextMessage textMessage = session.createTextMessage();
textMessage.setText("messageText");
for (int i = 0; i < MSG_COUNT; i++) {
producer.send(textMessage);
}
assertTrue("Did not receive all messages: " + MSG_COUNT, done.await(15, TimeUnit.SECONDS));
}
@Test(timeout = 60000)
public void testPrefetchedMessagesAreNotConsumedOnConsumerClose() throws Exception {
final int NUM_MESSAGES = 10;
Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(queue);
byte[] bytes = new byte[2048];
new Random().nextBytes(bytes);
for (int i = 0; i < NUM_MESSAGES; i++) {
TextMessage message = session.createTextMessage();
message.setText("msg:" + i);
producer.send(message);
}
connection.close();
Queue queueView = getProxyToQueue(getQueueName());
assertTrue("Not all messages were enqueud", Wait.waitFor(() -> queueView.getMessageCount() == NUM_MESSAGES));
// Create a consumer and prefetch the messages
connection = createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queue);
Thread.sleep(100);
consumer.close();
connection.close();
assertTrue("Not all messages were enqueud", Wait.waitFor(() -> queueView.getMessageCount() == NUM_MESSAGES));
} finally {
connection.close();
}
}
@Test(timeout = 60000)
public void testMessagesReceivedInParallel() throws Throwable {
final int numMessages = 50000;
long time = System.currentTimeMillis();
final ArrayList<Throwable> exceptions = new ArrayList<>();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Connection connectionConsumer = null;
try {
connectionConsumer = createConnection();
connectionConsumer.start();
Session sessionConsumer = connectionConsumer.createSession(false, Session.AUTO_ACKNOWLEDGE);
final javax.jms.Queue queue = sessionConsumer.createQueue(getQueueName());
final MessageConsumer consumer = sessionConsumer.createConsumer(queue);
long n = 0;
int count = numMessages;
while (count > 0) {
try {
if (++n % 1000 == 0) {
System.out.println("received " + n + " messages");
}
Message m = consumer.receive(5000);
Assert.assertNotNull("Could not receive message count=" + count + " on consumer", m);
count--;
} catch (JMSException e) {
e.printStackTrace();
break;
}
}
} catch (Throwable e) {
exceptions.add(e);
e.printStackTrace();
} finally {
try {
connectionConsumer.close();
} catch (Throwable ignored) {
// NO OP
}
}
}
});
Connection connection = createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
t.start();
MessageProducer p = session.createProducer(queue);
p.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
for (int i = 0; i < numMessages; i++) {
BytesMessage message = session.createBytesMessage();
message.writeUTF("Hello world!!!!" + i);
message.setIntProperty("count", i);
p.send(message);
}
// Wait for the consumer thread to completely read the Queue
t.join();
if (!exceptions.isEmpty()) {
throw exceptions.get(0);
}
Queue queueView = getProxyToQueue(getQueueName());
connection.close();
assertTrue("Not all messages consumed", Wait.waitFor(() -> queueView.getMessageCount() == 0));
long taken = (System.currentTimeMillis() - time);
System.out.println("Microbenchamrk ran in " + taken + " milliseconds, sending/receiving " + numMessages);
double messagesPerSecond = ((double) numMessages / (double) taken) * 1000;
System.out.println(((int) messagesPerSecond) + " messages per second");
}
@Test(timeout = 60000)
public void testClientAckMessages() throws Exception {
final int numMessages = 10;
Connection connection = createConnection();
try {
long time = System.currentTimeMillis();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(queue);
byte[] bytes = new byte[2048];
new Random().nextBytes(bytes);
for (int i = 0; i < numMessages; i++) {
TextMessage message = session.createTextMessage();
message.setText("msg:" + i);
producer.send(message);
}
connection.close();
Queue queueView = getProxyToQueue(getQueueName());
assertTrue("Not all messages enqueued", Wait.waitFor(() -> queueView.getMessageCount() == numMessages));
// Now create a new connection and receive and acknowledge
connection = createConnection();
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queue);
for (int i = 0; i < numMessages; i++) {
Message msg = consumer.receive(5000);
if (msg == null) {
System.out.println("ProtonTest.testManyMessages");
}
Assert.assertNotNull("" + i, msg);
Assert.assertTrue("" + msg, msg instanceof TextMessage);
String text = ((TextMessage) msg).getText();
// System.out.println("text = " + text);
Assert.assertEquals(text, "msg:" + i);
msg.acknowledge();
}
consumer.close();
connection.close();
// Wait for Acks to be processed and message removed from queue.
Thread.sleep(500);
assertTrue("Not all messages consumed", Wait.waitFor(() -> queueView.getMessageCount() == 0));
long taken = (System.currentTimeMillis() - time) / 1000;
System.out.println("taken = " + taken);
} finally {
connection.close();
}
}
@Test(timeout = 240000)
public void testTimedOutWaitingForWriteLogOnConsumer() throws Throwable {
String name = "exampleQueue1";
final int numMessages = 40;
Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(name);
MessageProducer producer = session.createProducer(queue);
for (int i = 0; i < numMessages; i++) {
TextMessage message = session.createTextMessage();
message.setText("Message temporary");
producer.send(message);
}
producer.close();
session.close();
for (int i = 0; i < numMessages; i++) {
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
queue = session.createQueue(name);
MessageConsumer c = session.createConsumer(queue);
c.receive(1000);
producer.close();
session.close();
}
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
queue = session.createQueue(name);
MessageConsumer c = session.createConsumer(queue);
for (int i = 0; i < numMessages; i++) {
c.receive(1000);
}
producer.close();
session.close();
} finally {
connection.close();
}
}
}
| tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/JMSMessageConsumerTest.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.artemis.tests.integration.amqp;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.QueueBrowser;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.artemis.core.server.Queue;
import org.apache.activemq.artemis.tests.util.Wait;
import org.apache.qpid.jms.JmsConnection;
import org.apache.qpid.jms.policy.JmsDefaultPrefetchPolicy;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JMSMessageConsumerTest extends JMSClientTestSupport {
protected static final Logger LOG = LoggerFactory.getLogger(JMSMessageConsumerTest.class);
@Override
protected String getConfiguredProtocols() {
return "AMQP,OPENWIRE,CORE";
}
@Test(timeout = 30000)
public void testDeliveryModeAMQPProducerCoreConsumer() throws Exception {
Connection connection = createConnection(); //AMQP
Connection connection2 = createCoreConnection(); //CORE
testDeliveryMode(connection, connection2);
}
@Test(timeout = 30000)
public void testDeliveryModeAMQPProducerAMQPConsumer() throws Exception {
Connection connection = createConnection(); //AMQP
Connection connection2 = createConnection(); //AMQP
testDeliveryMode(connection, connection2);
}
@Test(timeout = 30000)
public void testDeliveryModeCoreProducerAMQPConsumer() throws Exception {
Connection connection = createCoreConnection(); //CORE
Connection connection2 = createConnection(); //AMQP
testDeliveryMode(connection, connection2);
}
@Test(timeout = 30000)
public void testDeliveryModeCoreProducerCoreConsumer() throws Exception {
Connection connection = createCoreConnection(); //CORE
Connection connection2 = createCoreConnection(); //CORE
testDeliveryMode(connection, connection2);
}
private void testDeliveryMode(Connection connection1, Connection connection2) throws JMSException {
try {
Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue1 = session1.createQueue(getQueueName());
javax.jms.Queue queue2 = session2.createQueue(getQueueName());
final MessageConsumer consumer2 = session2.createConsumer(queue2);
MessageProducer producer = session1.createProducer(queue1);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
connection1.start();
TextMessage message = session1.createTextMessage();
message.setText("hello");
producer.send(message);
Message received = consumer2.receive(100);
assertNotNull("Should have received a message by now.", received);
assertTrue("Should be an instance of TextMessage", received instanceof TextMessage);
assertEquals(DeliveryMode.PERSISTENT, received.getJMSDeliveryMode());
} finally {
connection1.close();
connection2.close();
}
}
@Test(timeout = 30000)
public void testPriorityAMQPProducerCoreConsumer() throws Exception {
Connection connection = createConnection(); //AMQP
Connection connection2 = createCoreConnection(); //CORE
testPriority(connection, connection2);
}
@Test(timeout = 30000)
public void testPriorityAMQPProducerAMQPConsumer() throws Exception {
Connection connection = createConnection(); //AMQP
Connection connection2 = createConnection(); //AMQP
testPriority(connection, connection2);
}
@Test(timeout = 30000)
public void testPriorityModeCoreProducerAMQPConsumer() throws Exception {
Connection connection = createCoreConnection(); //CORE
Connection connection2 = createConnection(); //AMQP
testPriority(connection, connection2);
}
@Test(timeout = 30000)
public void testPriorityCoreProducerCoreConsumer() throws Exception {
Connection connection = createCoreConnection(); //CORE
Connection connection2 = createCoreConnection(); //CORE
testPriority(connection, connection2);
}
private void testPriority(Connection connection1, Connection connection2) throws JMSException {
try {
Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue1 = session1.createQueue(getQueueName());
javax.jms.Queue queue2 = session2.createQueue(getQueueName());
final MessageConsumer consumer2 = session2.createConsumer(queue2);
MessageProducer producer = session1.createProducer(queue1);
producer.setPriority(2);
connection1.start();
TextMessage message = session1.createTextMessage();
message.setText("hello");
producer.send(message);
Message received = consumer2.receive(100);
assertNotNull("Should have received a message by now.", received);
assertTrue("Should be an instance of TextMessage", received instanceof TextMessage);
assertEquals(2, received.getJMSPriority());
} finally {
connection1.close();
connection2.close();
}
}
@Test(timeout = 60000)
public void testSelectorOnTopic() throws Exception {
doTestSelector(true);
}
@Test(timeout = 60000)
public void testSelectorOnQueue() throws Exception {
doTestSelector(false);
}
private void doTestSelector(boolean topic) throws Exception {
Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = null;
if (topic) {
destination = session.createTopic(getTopicName());
} else {
destination = session.createQueue(getQueueName());
}
MessageProducer producer = session.createProducer(destination);
MessageConsumer messageConsumer = session.createConsumer(destination, "color = 'RED'");
TextMessage message = session.createTextMessage();
message.setText("msg:0");
producer.send(message);
message = session.createTextMessage();
message.setText("msg:1");
message.setStringProperty("color", "RED");
producer.send(message);
connection.start();
TextMessage m = (TextMessage) messageConsumer.receive(5000);
assertNotNull(m);
assertEquals("msg:1", m.getText());
assertEquals(m.getStringProperty("color"), "RED");
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testSelectorsWithJMSTypeOnTopic() throws Exception {
doTestSelectorsWithJMSType(true);
}
@Test(timeout = 30000)
public void testSelectorsWithJMSTypeOnQueue() throws Exception {
doTestSelectorsWithJMSType(false);
}
private void doTestSelectorsWithJMSType(boolean topic) throws Exception {
final Connection connection = createConnection();
final String type = "myJMSType";
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = null;
if (topic) {
destination = session.createTopic(getTopicName());
} else {
destination = session.createQueue(getQueueName());
}
MessageProducer producer = session.createProducer(destination);
MessageConsumer consumer = session.createConsumer(destination, "JMSType = '" + type + "'");
TextMessage message1 = session.createTextMessage();
message1.setText("text");
producer.send(message1, DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
TextMessage message2 = session.createTextMessage();
message2.setJMSType(type);
message2.setText("text + type");
producer.send(message2, DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
connection.start();
Message msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("Unexpected JMSType value", type, msg.getJMSType());
assertEquals("Unexpected message content", "text + type", ((TextMessage) msg).getText());
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testSelectorsWithJMSCorrelationID() throws Exception {
Connection connection = createConnection();
final String correlationID = UUID.randomUUID().toString();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(queue);
TextMessage message1 = session.createTextMessage();
message1.setText("text");
producer.send(message1);
TextMessage message2 = session.createTextMessage();
message2.setJMSCorrelationID(correlationID);
message2.setText("JMSCorrelationID");
producer.send(message2);
QueueBrowser browser = session.createBrowser(queue);
Enumeration<?> enumeration = browser.getEnumeration();
int count = 0;
while (enumeration.hasMoreElements()) {
Message m = (Message) enumeration.nextElement();
assertTrue(m instanceof TextMessage);
count++;
}
assertEquals(2, count);
MessageConsumer consumer = session.createConsumer(queue, "JMSCorrelationID = '" + correlationID + "'");
Message msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("Unexpected JMSCorrelationID value", correlationID, msg.getJMSCorrelationID());
assertEquals("Unexpected message content", "JMSCorrelationID", ((TextMessage) msg).getText());
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testSelectorsWithJMSPriority() throws Exception {
Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(queue);
TextMessage message = session.createTextMessage();
message.setText("hello");
producer.send(message, DeliveryMode.PERSISTENT, 5, 0);
message = session.createTextMessage();
message.setText("hello + 9");
producer.send(message, DeliveryMode.PERSISTENT, 9, 0);
QueueBrowser browser = session.createBrowser(queue);
Enumeration<?> enumeration = browser.getEnumeration();
int count = 0;
while (enumeration.hasMoreElements()) {
Message m = (Message) enumeration.nextElement();
assertTrue(m instanceof TextMessage);
count++;
}
assertEquals(2, count);
MessageConsumer consumer = session.createConsumer(queue, "JMSPriority > 8");
Message msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("hello + 9", ((TextMessage) msg).getText());
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testSelectorsWithJMSXGroupIDOnTopic() throws Exception {
doTestSelectorsWithJMSXGroupID(true);
}
@Test(timeout = 30000)
public void testSelectorsWithJMSXGroupIDOnQueue() throws Exception {
doTestSelectorsWithJMSXGroupID(false);
}
private void doTestSelectorsWithJMSXGroupID(boolean topic) throws Exception {
Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = null;
if (topic) {
destination = session.createTopic(getTopicName());
} else {
destination = session.createQueue(getQueueName());
}
MessageProducer producer = session.createProducer(destination);
MessageConsumer consumer = session.createConsumer(destination, "JMSXGroupID = '1'");
TextMessage message = session.createTextMessage();
message.setText("group 1 - 1");
message.setStringProperty("JMSXGroupID", "1");
message.setIntProperty("JMSXGroupSeq", 1);
producer.send(message);
message = session.createTextMessage();
message.setText("group 2");
message.setStringProperty("JMSXGroupID", "2");
producer.send(message);
message = session.createTextMessage();
message.setText("group 1 - 2");
message.setStringProperty("JMSXGroupID", "1");
message.setIntProperty("JMSXGroupSeq", -1);
producer.send(message);
connection.start();
Message msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("group 1 - 1", ((TextMessage) msg).getText());
msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("group 1 - 2", ((TextMessage) msg).getText());
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testSelectorsWithJMSDeliveryOnQueue() throws Exception {
final Connection connection = createConnection();
String selector = "JMSDeliveryMode = 'PERSISTENT'";
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(destination);
MessageConsumer consumer = session.createConsumer(destination, selector);
TextMessage message1 = session.createTextMessage();
message1.setText("non-persistent");
producer.send(message1, DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
TextMessage message2 = session.createTextMessage();
message2.setText("persistent");
producer.send(message2, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
connection.start();
Message msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("Unexpected JMSDeliveryMode value", DeliveryMode.PERSISTENT, msg.getJMSDeliveryMode());
assertEquals("Unexpected message content", "persistent", ((TextMessage) msg).getText());
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testSelectorsWithJMSTimestampOnQueue() throws Exception {
final Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(destination);
TextMessage message1 = session.createTextMessage();
message1.setText("filtered");
producer.send(message1, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
TextMessage message2 = session.createTextMessage();
message2.setText("expected");
producer.send(message2, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
MessageConsumer consumer = session.createConsumer(destination, "JMSTimestamp = " + message2.getJMSTimestamp());
connection.start();
Message msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("Unexpected JMSTimestamp value", message2.getJMSTimestamp(), msg.getJMSTimestamp());
assertEquals("Unexpected message content", "expected", ((TextMessage) msg).getText());
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testSelectorsWithJMSExpirationOnQueue() throws Exception {
final Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(destination);
TextMessage message1 = session.createTextMessage();
message1.setText("filtered");
producer.send(message1, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
TextMessage message2 = session.createTextMessage();
message2.setText("expected");
producer.send(message2, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, 60000);
MessageConsumer consumer = session.createConsumer(destination, "JMSExpiration = " + message2.getJMSExpiration());
connection.start();
Message msg = consumer.receive(2000);
assertNotNull(msg);
assertTrue(msg instanceof TextMessage);
assertEquals("Unexpected JMSExpiration value", message2.getJMSExpiration(), msg.getJMSExpiration());
assertEquals("Unexpected message content", "expected", ((TextMessage) msg).getText());
} finally {
connection.close();
}
}
@Test(timeout = 60000)
public void testJMSSelectorFiltersJMSMessageIDOnTopic() throws Exception {
Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(queue);
// Send one to receive
TextMessage message = session.createTextMessage();
producer.send(message);
// Send another to filter
producer.send(session.createTextMessage());
connection.start();
// First one should make it through
MessageConsumer messageConsumer = session.createConsumer(queue, "JMSMessageID = '" + message.getJMSMessageID() + "'");
TextMessage m = (TextMessage) messageConsumer.receive(5000);
assertNotNull(m);
assertEquals(message.getJMSMessageID(), m.getJMSMessageID());
// The second one should not be received.
assertNull(messageConsumer.receive(1000));
} finally {
connection.close();
}
}
@Test(timeout = 60000)
public void testZeroPrefetchWithTwoConsumers() throws Exception {
JmsConnection connection = (JmsConnection) createConnection();
((JmsDefaultPrefetchPolicy) connection.getPrefetchPolicy()).setAll(0);
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(queue);
producer.send(session.createTextMessage("Msg1"));
producer.send(session.createTextMessage("Msg2"));
// now lets receive it
MessageConsumer consumer1 = session.createConsumer(queue);
MessageConsumer consumer2 = session.createConsumer(queue);
TextMessage answer = (TextMessage) consumer1.receive(5000);
assertNotNull(answer);
assertEquals("Should have received a message!", answer.getText(), "Msg1");
answer = (TextMessage) consumer2.receive(5000);
assertNotNull(answer);
assertEquals("Should have received a message!", answer.getText(), "Msg2");
answer = (TextMessage) consumer2.receiveNoWait();
assertNull("Should have not received a message!", answer);
}
@Test(timeout = 30000)
public void testProduceAndConsumeLargeNumbersOfTopicMessagesClientAck() throws Exception {
doTestProduceAndConsumeLargeNumbersOfMessages(true, Session.CLIENT_ACKNOWLEDGE);
}
@Test(timeout = 30000)
public void testProduceAndConsumeLargeNumbersOfQueueMessagesClientAck() throws Exception {
doTestProduceAndConsumeLargeNumbersOfMessages(false, Session.CLIENT_ACKNOWLEDGE);
}
@Test(timeout = 30000)
public void testProduceAndConsumeLargeNumbersOfTopicMessagesAutoAck() throws Exception {
doTestProduceAndConsumeLargeNumbersOfMessages(true, Session.AUTO_ACKNOWLEDGE);
}
@Test(timeout = 30000)
public void testProduceAndConsumeLargeNumbersOfQueueMessagesAutoAck() throws Exception {
doTestProduceAndConsumeLargeNumbersOfMessages(false, Session.AUTO_ACKNOWLEDGE);
}
public void doTestProduceAndConsumeLargeNumbersOfMessages(boolean topic, int ackMode) throws Exception {
final int MSG_COUNT = 1000;
final CountDownLatch done = new CountDownLatch(MSG_COUNT);
JmsConnection connection = (JmsConnection) createConnection();
connection.setForceAsyncSend(true);
connection.start();
Session session = connection.createSession(false, ackMode);
final Destination destination;
if (topic) {
destination = session.createTopic(getTopicName());
} else {
destination = session.createQueue(getQueueName());
}
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
try {
message.acknowledge();
done.countDown();
} catch (JMSException ex) {
LOG.info("Caught exception.", ex);
}
}
});
MessageProducer producer = session.createProducer(destination);
TextMessage textMessage = session.createTextMessage();
textMessage.setText("messageText");
for (int i = 0; i < MSG_COUNT; i++) {
producer.send(textMessage);
}
assertTrue("Did not receive all messages: " + MSG_COUNT, done.await(15, TimeUnit.SECONDS));
}
@Test(timeout = 60000)
public void testPrefetchedMessagesAreNotConsumedOnConsumerClose() throws Exception {
final int NUM_MESSAGES = 10;
Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(queue);
byte[] bytes = new byte[2048];
new Random().nextBytes(bytes);
for (int i = 0; i < NUM_MESSAGES; i++) {
TextMessage message = session.createTextMessage();
message.setText("msg:" + i);
producer.send(message);
}
connection.close();
Queue queueView = getProxyToQueue(getQueueName());
assertTrue("Not all messages were enqueud", Wait.waitFor(() -> queueView.getMessageCount() == NUM_MESSAGES));
// Create a consumer and prefetch the messages
connection = createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queue);
Thread.sleep(100);
consumer.close();
connection.close();
assertTrue("Not all messages were enqueud", Wait.waitFor(() -> queueView.getMessageCount() == NUM_MESSAGES));
} finally {
connection.close();
}
}
@Test(timeout = 60000)
public void testMessagesReceivedInParallel() throws Throwable {
final int numMessages = 50000;
long time = System.currentTimeMillis();
final ArrayList<Throwable> exceptions = new ArrayList<>();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Connection connectionConsumer = null;
try {
connectionConsumer = createConnection();
connectionConsumer.start();
Session sessionConsumer = connectionConsumer.createSession(false, Session.AUTO_ACKNOWLEDGE);
final javax.jms.Queue queue = sessionConsumer.createQueue(getQueueName());
final MessageConsumer consumer = sessionConsumer.createConsumer(queue);
long n = 0;
int count = numMessages;
while (count > 0) {
try {
if (++n % 1000 == 0) {
System.out.println("received " + n + " messages");
}
Message m = consumer.receive(5000);
Assert.assertNotNull("Could not receive message count=" + count + " on consumer", m);
count--;
} catch (JMSException e) {
e.printStackTrace();
break;
}
}
} catch (Throwable e) {
exceptions.add(e);
e.printStackTrace();
} finally {
try {
connectionConsumer.close();
} catch (Throwable ignored) {
// NO OP
}
}
}
});
Connection connection = createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
t.start();
MessageProducer p = session.createProducer(queue);
p.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
for (int i = 0; i < numMessages; i++) {
BytesMessage message = session.createBytesMessage();
message.writeUTF("Hello world!!!!" + i);
message.setIntProperty("count", i);
p.send(message);
}
// Wait for the consumer thread to completely read the Queue
t.join();
if (!exceptions.isEmpty()) {
throw exceptions.get(0);
}
Queue queueView = getProxyToQueue(getQueueName());
connection.close();
assertTrue("Not all messages consumed", Wait.waitFor(() -> queueView.getMessageCount() == 0));
long taken = (System.currentTimeMillis() - time);
System.out.println("Microbenchamrk ran in " + taken + " milliseconds, sending/receiving " + numMessages);
double messagesPerSecond = ((double) numMessages / (double) taken) * 1000;
System.out.println(((int) messagesPerSecond) + " messages per second");
}
@Test(timeout = 60000)
public void testClientAckMessages() throws Exception {
final int numMessages = 10;
Connection connection = createConnection();
try {
long time = System.currentTimeMillis();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(queue);
byte[] bytes = new byte[2048];
new Random().nextBytes(bytes);
for (int i = 0; i < numMessages; i++) {
TextMessage message = session.createTextMessage();
message.setText("msg:" + i);
producer.send(message);
}
connection.close();
Queue queueView = getProxyToQueue(getQueueName());
assertTrue("Not all messages enqueued", Wait.waitFor(() -> queueView.getMessageCount() == numMessages));
// Now create a new connection and receive and acknowledge
connection = createConnection();
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queue);
for (int i = 0; i < numMessages; i++) {
Message msg = consumer.receive(5000);
if (msg == null) {
System.out.println("ProtonTest.testManyMessages");
}
Assert.assertNotNull("" + i, msg);
Assert.assertTrue("" + msg, msg instanceof TextMessage);
String text = ((TextMessage) msg).getText();
// System.out.println("text = " + text);
Assert.assertEquals(text, "msg:" + i);
msg.acknowledge();
}
consumer.close();
connection.close();
// Wait for Acks to be processed and message removed from queue.
Thread.sleep(500);
assertTrue("Not all messages consumed", Wait.waitFor(() -> queueView.getMessageCount() == 0));
long taken = (System.currentTimeMillis() - time) / 1000;
System.out.println("taken = " + taken);
} finally {
connection.close();
}
}
@Test(timeout = 240000)
public void testTimedOutWaitingForWriteLogOnConsumer() throws Throwable {
String name = "exampleQueue1";
final int numMessages = 40;
Connection connection = createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(name);
MessageProducer producer = session.createProducer(queue);
for (int i = 0; i < numMessages; i++) {
TextMessage message = session.createTextMessage();
message.setText("Message temporary");
producer.send(message);
}
producer.close();
session.close();
for (int i = 0; i < numMessages; i++) {
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
queue = session.createQueue(name);
MessageConsumer c = session.createConsumer(queue);
c.receive(1000);
producer.close();
session.close();
}
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
queue = session.createQueue(name);
MessageConsumer c = session.createConsumer(queue);
for (int i = 0; i < numMessages; i++) {
c.receive(1000);
}
producer.close();
session.close();
} finally {
connection.close();
}
}
}
| NO-JIRA fix timing issue in test
| tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/JMSMessageConsumerTest.java | NO-JIRA fix timing issue in test | <ide><path>ests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/JMSMessageConsumerTest.java
<ide> TextMessage message1 = session.createTextMessage();
<ide> message1.setText("filtered");
<ide> producer.send(message1, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
<add>
<add> // short delay to prevent the timestamps from being the same
<add> Thread.sleep(2);
<ide>
<ide> TextMessage message2 = session.createTextMessage();
<ide> message2.setText("expected"); |
|
Java | mpl-2.0 | 5596f89cd08806ca26b2e2f0ec94eb9d7ab254dc | 0 | Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV | package org.helioviewer.jhv.camera;
import java.awt.Point;
import org.helioviewer.jhv.base.astronomy.Sun;
import org.helioviewer.jhv.base.logging.Log;
import org.helioviewer.jhv.base.math.Mat4d;
import org.helioviewer.jhv.base.math.Quatd;
import org.helioviewer.jhv.base.math.Vec2d;
import org.helioviewer.jhv.base.math.Vec3d;
import org.helioviewer.jhv.base.time.JHVDate;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.gui.ImageViewerGui;
import org.helioviewer.jhv.layers.Layers;
import org.helioviewer.jhv.viewmodel.metadata.MetaData;
import com.jogamp.opengl.GL2;
public abstract class GL3DCamera {
public static final double INITFOV = (48. / 60.) * Math.PI / 180.;
public static final double MIN_FOV = INITFOV * 0.02;
public static final double MAX_FOV = INITFOV * 30;
private static final double clipNear = Sun.Radius * 3;
private static final double clipFar = Sun.Radius * 10000;
private double fov = INITFOV;
private double previousAspect = -1.0;
private Mat4d cameraTransformation;
private Quatd rotation;
private Vec3d translation;
private final Quatd currentDragRotation;
protected Quatd localRotation;
private boolean trackingMode;
private Mat4d orthoMatrixInverse = Mat4d.identity();
private double cameraWidth = 1.;
private double previousCameraWidth = -1;
private double cameraWidthTimesAspect;
private double FOVangleToDraw;
private final GL3DTrackballRotationInteraction rotationInteraction;
private final GL3DPanInteraction panInteraction;
private final GL3DAnnotateInteraction annotateInteraction;
private GL3DInteraction currentInteraction;
public GL3DCamera() {
this.cameraTransformation = Mat4d.identity();
this.rotation = new Quatd();
this.currentDragRotation = new Quatd();
this.localRotation = new Quatd();
this.translation = new Vec3d();
this.fov = INITFOV;
this.rotationInteraction = new GL3DTrackballRotationInteraction(this);
this.panInteraction = new GL3DPanInteraction(this);
this.annotateInteraction = new GL3DAnnotateInteraction(this);
this.currentInteraction = this.rotationInteraction;
}
public void reset() {
this.translation = new Vec3d(0, 0, this.translation.z);
this.currentDragRotation.clear();
this.currentInteraction.reset();
zoomToFit();
}
/**
* This method is called when the camera changes and should copy the
* required settings of the preceding camera objects.
*
* @param precedingCamera
*/
public void activate(GL3DCamera precedingCamera) {
if (precedingCamera != null) {
this.rotation = precedingCamera.rotation.copy();
this.translation = precedingCamera.translation.copy();
this.FOVangleToDraw = precedingCamera.getFOVAngleToDraw();
this.updateRotation(Layers.getLastUpdatedTimestamp(), null);
this.updateCameraWidthAspect(precedingCamera.previousAspect);
GL3DInteraction precedingInteraction = precedingCamera.getCurrentInteraction();
if (precedingInteraction.equals(precedingCamera.getRotateInteraction())) {
this.setCurrentInteraction(this.getRotateInteraction());
} else if (precedingInteraction.equals(precedingCamera.getPanInteraction())) {
this.setCurrentInteraction(this.getPanInteraction());
} else if (precedingInteraction.equals(precedingCamera.getAnnotateInteraction())) {
this.setCurrentInteraction(this.getAnnotateInteraction());
}
} else {
Log.debug("GL3DCamera: No Preceding Camera, resetting Camera");
this.reset();
}
}
private Quatd saveRotation;
private Quatd saveLocalRotation;
private Vec3d saveTranslation;
private Mat4d saveTransformation;
public void push(JHVDate date, MetaData m) {
if (!trackingMode) {
saveRotation = rotation.copy();
saveLocalRotation = localRotation.copy();
saveTranslation = translation.copy();
saveTransformation = cameraTransformation.copy();
updateRotation(date, m);
}
}
public void pop() {
if (!trackingMode) {
rotation = saveRotation;
localRotation = saveLocalRotation;
translation = saveTranslation;
cameraTransformation = saveTransformation;
}
}
public double getFOVAngleToDraw() {
return this.FOVangleToDraw;
}
public void setPanning(double x, double y) {
translation.x = x;
translation.y = y;
}
protected void setZTranslation(double z) {
translation.z = z;
updateCameraWidthAspect(previousAspect);
}
public double getZTranslation() {
return this.translation.z;
}
public Vec3d getTranslation() {
return this.translation;
}
public Quatd getLocalRotation() {
return this.localRotation;
}
public void setLocalRotation(Quatd localRotation) {
this.localRotation = localRotation;
this.rotation.clear();
this.updateCameraTransformation();
}
public void rotateCurrentDragRotation(Quatd currentDragRotation) {
this.currentDragRotation.rotate(currentDragRotation);
this.rotation.clear();
this.updateCameraTransformation();
}
// quantization bits per half width camera
private static final int quantFactor = 1 << 12;
public void updateCameraWidthAspect(double aspect) {
cameraWidth = -translation.z * Math.tan(fov / 2.);
if (cameraWidth == 0.)
cameraWidth = 1.;
cameraWidth = (long) (cameraWidth * quantFactor) / (double) quantFactor;
if (cameraWidth == previousCameraWidth && aspect == previousAspect) {
return;
}
previousCameraWidth = cameraWidth;
previousAspect = aspect;
cameraWidthTimesAspect = cameraWidth * aspect;
//orthoMatrix = GL3DMat4d.ortho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar);
orthoMatrixInverse = Mat4d.orthoInverse(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar);
if (this == Displayer.getViewport().getCamera()) {
// Displayer.render();
ImageViewerGui.getZoomStatusPanel().updateZoomLevel(cameraWidth);
}
}
public Mat4d getOrthoMatrixInverse() {
return orthoMatrixInverse.copy();
}
public void applyPerspective(GL2 gl) {
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrtho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar);
// applyCamera
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glLoadMatrixd(cameraTransformation.m, 0);
}
public Vec3d getVectorFromSphereOrPlane(Vec2d normalizedScreenpos, Quatd cameraDifferenceRotation) {
double up1x = normalizedScreenpos.x * cameraWidthTimesAspect - translation.x;
double up1y = normalizedScreenpos.y * cameraWidth - translation.y;
Vec3d hitPoint;
Vec3d rotatedHitPoint;
double radius2 = up1x * up1x + up1y * up1y;
if (radius2 <= 1) {
hitPoint = new Vec3d(up1x, up1y, Math.sqrt(1. - radius2));
rotatedHitPoint = cameraDifferenceRotation.rotateInverseVector(hitPoint);
if (rotatedHitPoint.z > 0.) {
return rotatedHitPoint;
}
}
Vec3d altnormal = cameraDifferenceRotation.rotateVector(Vec3d.ZAxis);
double zvalue = -(altnormal.x * up1x + altnormal.y * up1y) / altnormal.z;
hitPoint = new Vec3d(up1x, up1y, zvalue);
return cameraDifferenceRotation.rotateInverseVector(hitPoint);
}
private static double computeNormalizedX(Point viewportCoordinates) {
return +2. * ((viewportCoordinates.getX() - Displayer.getViewport().getOffsetX()) / Displayer.getViewport().getWidth() - 0.5);
}
private static double computeNormalizedY(Point viewportCoordinates) {
return -2. * ((viewportCoordinates.getY() - Displayer.getViewport().getOffsetY()) / Displayer.getViewport().getHeight() - 0.5);
}
private double computeUpX(Point viewportCoordinates) {
return computeNormalizedX(viewportCoordinates) * cameraWidthTimesAspect - translation.x;
}
private double computeUpY(Point viewportCoordinates) {
return computeNormalizedY(viewportCoordinates) * cameraWidth - translation.y;
}
public Vec3d getVectorFromSphere(Point viewportCoordinates) {
Vec3d hitPoint = getVectorFromSphereAlt(viewportCoordinates);
if (hitPoint != null) {
return localRotation.rotateInverseVector(hitPoint);
}
return null;
}
public Vec3d getVectorFromPlane(Point viewportCoordinates) {
double up1x = computeUpX(viewportCoordinates);
double up1y = computeUpY(viewportCoordinates);
Vec3d altnormal = currentDragRotation.rotateVector(Vec3d.ZAxis);
if (altnormal.z == 0) {
return null;
}
double zvalue = -(altnormal.x * up1x + altnormal.y * up1y) / altnormal.z;
Vec3d hitPoint = new Vec3d(up1x, up1y, zvalue);
return currentDragRotation.rotateInverseVector(hitPoint);
}
public Vec3d getVectorFromSphereAlt(Point viewportCoordinates) {
double up1x = computeUpX(viewportCoordinates);
double up1y = computeUpY(viewportCoordinates);
Vec3d hitPoint;
double radius2 = up1x * up1x + up1y * up1y;
if (radius2 <= 1.) {
hitPoint = new Vec3d(up1x, up1y, Math.sqrt(1. - radius2));
return currentDragRotation.rotateInverseVector(hitPoint);
}
return null;
}
public double getRadiusFromSphereAlt(Point viewportCoordinates) {
double up1x = computeUpX(viewportCoordinates);
double up1y = computeUpY(viewportCoordinates);
return Math.sqrt(up1x * up1x + up1y * up1y);
}
public Vec3d getVectorFromSphereTrackball(Point viewportCoordinates) {
double up1x = computeUpX(viewportCoordinates);
double up1y = computeUpY(viewportCoordinates);
Vec3d hitPoint;
double radius2 = up1x * up1x + up1y * up1y;
if (radius2 <= Sun.Radius2 / 2.) {
hitPoint = new Vec3d(up1x, up1y, Math.sqrt(Sun.Radius2 - radius2));
} else {
hitPoint = new Vec3d(up1x, up1y, Sun.Radius2 / (2. * Math.sqrt(radius2)));
}
return currentDragRotation.rotateInverseVector(hitPoint);
}
public Quatd getCameraDifferenceRotationQuatd(Quatd rot) {
Quatd cameraDifferenceRotation = rotation.copy();
cameraDifferenceRotation.rotateWithConjugate(rot);
return cameraDifferenceRotation;
}
/**
* Updates the camera transformation by applying the rotation and
* translation information.
*/
public void updateCameraTransformation() {
this.rotation = this.currentDragRotation.copy();
this.rotation.rotate(this.localRotation);
cameraTransformation = this.rotation.toMatrix().translate(this.translation);
}
public double getCameraFOV() {
return fov;
}
public void setCameraFOV(double fov) {
if (fov < MIN_FOV) {
this.fov = MIN_FOV;
} else if (fov > MAX_FOV) {
this.fov = MAX_FOV;
} else {
this.fov = fov;
}
updateCameraWidthAspect(previousAspect);
}
@Override
public String toString() {
return getName();
}
public void setTrackingMode(boolean trackingMode) {
this.trackingMode = trackingMode;
}
public boolean getTrackingMode() {
return trackingMode;
}
public void deactivate() {
}
public double getCameraWidth() {
return cameraWidth;
}
public void zoom(int wr) {
double newfov = Math.atan2(cameraWidth * (1 + 0.015 * wr), -translation.z) * 2.;
setCameraFOV(newfov);
}
public void setFOVangleDegrees(double fovAngle) {
this.FOVangleToDraw = fovAngle * Math.PI / 180.0;
}
public void setCurrentInteraction(GL3DInteraction currentInteraction) {
this.currentInteraction = currentInteraction;
}
public GL3DInteraction getCurrentInteraction() {
return this.currentInteraction;
}
public GL3DInteraction getPanInteraction() {
return this.panInteraction;
}
public GL3DInteraction getRotateInteraction() {
return this.rotationInteraction;
}
public GL3DInteraction getAnnotateInteraction() {
return this.annotateInteraction;
}
public abstract String getName();
public abstract GL3DCameraOptionPanel getOptionPanel();
public abstract void timeChanged(JHVDate date);
public abstract void updateRotation(JHVDate date, MetaData m);
public void zoomToFit() {
double size = Layers.getLargestPhysicalSize();
if (size == 0)
setCameraFOV(INITFOV);
else
setCameraFOV(2. * Math.atan(-size / 2. / this.getZTranslation()));
}
public Mat4d getRotation() {
return this.rotation.toMatrix();
}
}
| src/jhv/src/org/helioviewer/jhv/camera/GL3DCamera.java | package org.helioviewer.jhv.camera;
import java.awt.Point;
import org.helioviewer.jhv.base.astronomy.Sun;
import org.helioviewer.jhv.base.logging.Log;
import org.helioviewer.jhv.base.math.Mat4d;
import org.helioviewer.jhv.base.math.Quatd;
import org.helioviewer.jhv.base.math.Vec2d;
import org.helioviewer.jhv.base.math.Vec3d;
import org.helioviewer.jhv.base.time.JHVDate;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.gui.ImageViewerGui;
import org.helioviewer.jhv.layers.Layers;
import org.helioviewer.jhv.viewmodel.metadata.MetaData;
import com.jogamp.opengl.GL2;
public abstract class GL3DCamera {
public static final double INITFOV = (48. / 60.) * Math.PI / 180.;
public static final double MIN_FOV = INITFOV * 0.02;
public static final double MAX_FOV = INITFOV * 30;
private static final double clipNear = Sun.Radius * 3;
private static final double clipFar = Sun.Radius * 10000;
private double fov = INITFOV;
private double previousAspect = -1.0;
private Mat4d cameraTransformation;
private Quatd rotation;
private Vec3d translation;
private final Quatd currentDragRotation;
protected Quatd localRotation;
private boolean trackingMode;
private Mat4d orthoMatrixInverse = Mat4d.identity();
private double cameraWidth = 1.;
private double previousCameraWidth = -1;
private double cameraWidthTimesAspect;
private double FOVangleToDraw;
private final GL3DTrackballRotationInteraction rotationInteraction;
private final GL3DPanInteraction panInteraction;
private final GL3DAnnotateInteraction annotateInteraction;
private GL3DInteraction currentInteraction;
public GL3DCamera() {
this.cameraTransformation = Mat4d.identity();
this.rotation = new Quatd();
this.currentDragRotation = new Quatd();
this.localRotation = new Quatd();
this.translation = new Vec3d();
this.fov = INITFOV;
this.rotationInteraction = new GL3DTrackballRotationInteraction(this);
this.panInteraction = new GL3DPanInteraction(this);
this.annotateInteraction = new GL3DAnnotateInteraction(this);
this.currentInteraction = this.rotationInteraction;
}
public void reset() {
this.translation = new Vec3d(0, 0, this.translation.z);
this.currentDragRotation.clear();
this.currentInteraction.reset();
zoomToFit();
}
/**
* This method is called when the camera changes and should copy the
* required settings of the preceding camera objects.
*
* @param precedingCamera
*/
public void activate(GL3DCamera precedingCamera) {
if (precedingCamera != null) {
this.rotation = precedingCamera.rotation.copy();
this.translation = precedingCamera.translation.copy();
this.FOVangleToDraw = precedingCamera.getFOVAngleToDraw();
this.updateRotation(Layers.getLastUpdatedTimestamp(), null);
this.updateCameraWidthAspect(precedingCamera.previousAspect);
GL3DInteraction precedingInteraction = precedingCamera.getCurrentInteraction();
if (precedingInteraction.equals(precedingCamera.getRotateInteraction())) {
this.setCurrentInteraction(this.getRotateInteraction());
} else if (precedingInteraction.equals(precedingCamera.getPanInteraction())) {
this.setCurrentInteraction(this.getPanInteraction());
} else if (precedingInteraction.equals(precedingCamera.getAnnotateInteraction())) {
this.setCurrentInteraction(this.getAnnotateInteraction());
}
} else {
Log.debug("GL3DCamera: No Preceding Camera, resetting Camera");
this.reset();
}
}
private Quatd saveRotation;
private Quatd saveLocalRotation;
private Vec3d saveTranslation;
private Mat4d saveTransformation;
public void push(JHVDate date, MetaData m) {
if (!trackingMode) {
saveRotation = rotation.copy();
saveLocalRotation = localRotation.copy();
saveTranslation = translation.copy();
saveTransformation = cameraTransformation.copy();
updateRotation(date, m);
}
}
public void pop() {
if (!trackingMode) {
rotation = saveRotation;
localRotation = saveLocalRotation;
translation = saveTranslation;
cameraTransformation = saveTransformation;
}
}
public double getFOVAngleToDraw() {
return this.FOVangleToDraw;
}
public void setPanning(double x, double y) {
translation.x = x;
translation.y = y;
}
protected void setZTranslation(double z) {
translation.z = z;
updateCameraWidthAspect(previousAspect);
}
public double getZTranslation() {
return this.translation.z;
}
public Vec3d getTranslation() {
return this.translation;
}
public Quatd getLocalRotation() {
return this.localRotation;
}
private void resetCurrentDragRotation() {
this.currentDragRotation.clear();
}
public void setLocalRotation(Quatd localRotation) {
this.localRotation = localRotation;
this.rotation.clear();
this.updateCameraTransformation();
}
public void rotateCurrentDragRotation(Quatd currentDragRotation) {
this.currentDragRotation.rotate(currentDragRotation);
this.rotation.clear();
this.updateCameraTransformation();
}
// quantization bits per half width camera
private static final int quantFactor = 1 << 12;
public void updateCameraWidthAspect(double aspect) {
cameraWidth = -translation.z * Math.tan(fov / 2.);
if (cameraWidth == 0.)
cameraWidth = 1.;
cameraWidth = (long) (cameraWidth * quantFactor) / (double) quantFactor;
if (cameraWidth == previousCameraWidth && aspect == previousAspect) {
return;
}
previousCameraWidth = cameraWidth;
previousAspect = aspect;
cameraWidthTimesAspect = cameraWidth * aspect;
//orthoMatrix = GL3DMat4d.ortho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar);
orthoMatrixInverse = Mat4d.orthoInverse(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar);
if (this == Displayer.getViewport().getCamera()) {
// Displayer.render();
ImageViewerGui.getZoomStatusPanel().updateZoomLevel(cameraWidth);
}
}
public Mat4d getOrthoMatrixInverse() {
return orthoMatrixInverse.copy();
}
public void applyPerspective(GL2 gl) {
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrtho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar);
// applyCamera
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glLoadMatrixd(cameraTransformation.m, 0);
}
public Vec3d getVectorFromSphereOrPlane(Vec2d normalizedScreenpos, Quatd cameraDifferenceRotation) {
double up1x = normalizedScreenpos.x * cameraWidthTimesAspect - translation.x;
double up1y = normalizedScreenpos.y * cameraWidth - translation.y;
Vec3d hitPoint;
Vec3d rotatedHitPoint;
double radius2 = up1x * up1x + up1y * up1y;
if (radius2 <= 1) {
hitPoint = new Vec3d(up1x, up1y, Math.sqrt(1. - radius2));
rotatedHitPoint = cameraDifferenceRotation.rotateInverseVector(hitPoint);
if (rotatedHitPoint.z > 0.) {
return rotatedHitPoint;
}
}
Vec3d altnormal = cameraDifferenceRotation.rotateVector(Vec3d.ZAxis);
double zvalue = -(altnormal.x * up1x + altnormal.y * up1y) / altnormal.z;
hitPoint = new Vec3d(up1x, up1y, zvalue);
return cameraDifferenceRotation.rotateInverseVector(hitPoint);
}
private static double computeNormalizedX(Point viewportCoordinates) {
return +2. * ((viewportCoordinates.getX() - Displayer.getViewport().getOffsetX()) / Displayer.getViewport().getWidth() - 0.5);
}
private static double computeNormalizedY(Point viewportCoordinates) {
return -2. * ((viewportCoordinates.getY() - Displayer.getViewport().getOffsetY()) / Displayer.getViewport().getHeight() - 0.5);
}
private double computeUpX(Point viewportCoordinates) {
return computeNormalizedX(viewportCoordinates) * cameraWidthTimesAspect - translation.x;
}
private double computeUpY(Point viewportCoordinates) {
return computeNormalizedY(viewportCoordinates) * cameraWidth - translation.y;
}
public Vec3d getVectorFromSphere(Point viewportCoordinates) {
Vec3d hitPoint = getVectorFromSphereAlt(viewportCoordinates);
if (hitPoint != null) {
return localRotation.rotateInverseVector(hitPoint);
}
return null;
}
public Vec3d getVectorFromPlane(Point viewportCoordinates) {
double up1x = computeUpX(viewportCoordinates);
double up1y = computeUpY(viewportCoordinates);
Vec3d altnormal = currentDragRotation.rotateVector(Vec3d.ZAxis);
if (altnormal.z == 0) {
return null;
}
double zvalue = -(altnormal.x * up1x + altnormal.y * up1y) / altnormal.z;
Vec3d hitPoint = new Vec3d(up1x, up1y, zvalue);
return currentDragRotation.rotateInverseVector(hitPoint);
}
public Vec3d getVectorFromSphereAlt(Point viewportCoordinates) {
double up1x = computeUpX(viewportCoordinates);
double up1y = computeUpY(viewportCoordinates);
Vec3d hitPoint;
double radius2 = up1x * up1x + up1y * up1y;
if (radius2 <= 1.) {
hitPoint = new Vec3d(up1x, up1y, Math.sqrt(1. - radius2));
return currentDragRotation.rotateInverseVector(hitPoint);
}
return null;
}
public double getRadiusFromSphereAlt(Point viewportCoordinates) {
double up1x = computeUpX(viewportCoordinates);
double up1y = computeUpY(viewportCoordinates);
return Math.sqrt(up1x * up1x + up1y * up1y);
}
public Vec3d getVectorFromSphereTrackball(Point viewportCoordinates) {
double up1x = computeUpX(viewportCoordinates);
double up1y = computeUpY(viewportCoordinates);
Vec3d hitPoint;
double radius2 = up1x * up1x + up1y * up1y;
if (radius2 <= Sun.Radius2 / 2.) {
hitPoint = new Vec3d(up1x, up1y, Math.sqrt(Sun.Radius2 - radius2));
} else {
hitPoint = new Vec3d(up1x, up1y, Sun.Radius2 / (2. * Math.sqrt(radius2)));
}
return currentDragRotation.rotateInverseVector(hitPoint);
}
public Quatd getCameraDifferenceRotationQuatd(Quatd rot) {
Quatd cameraDifferenceRotation = rotation.copy();
cameraDifferenceRotation.rotateWithConjugate(rot);
return cameraDifferenceRotation;
}
/**
* Updates the camera transformation by applying the rotation and
* translation information.
*/
public void updateCameraTransformation() {
this.rotation = this.currentDragRotation.copy();
this.rotation.rotate(this.localRotation);
cameraTransformation = this.rotation.toMatrix().translate(this.translation);
}
public double getCameraFOV() {
return fov;
}
public void setCameraFOV(double fov) {
if (fov < MIN_FOV) {
this.fov = MIN_FOV;
} else if (fov > MAX_FOV) {
this.fov = MAX_FOV;
} else {
this.fov = fov;
}
updateCameraWidthAspect(previousAspect);
}
@Override
public String toString() {
return getName();
}
public void setTrackingMode(boolean trackingMode) {
this.trackingMode = trackingMode;
}
public boolean getTrackingMode() {
return trackingMode;
}
public void deactivate() {
}
public double getCameraWidth() {
return cameraWidth;
}
public void zoom(int wr) {
double newfov = Math.atan2(cameraWidth * (1 + 0.015 * wr), -translation.z) * 2.;
setCameraFOV(newfov);
}
public void setFOVangleDegrees(double fovAngle) {
this.FOVangleToDraw = fovAngle * Math.PI / 180.0;
}
public void setCurrentInteraction(GL3DInteraction currentInteraction) {
this.currentInteraction = currentInteraction;
}
public GL3DInteraction getCurrentInteraction() {
return this.currentInteraction;
}
public GL3DInteraction getPanInteraction() {
return this.panInteraction;
}
public GL3DInteraction getRotateInteraction() {
return this.rotationInteraction;
}
public GL3DInteraction getAnnotateInteraction() {
return this.annotateInteraction;
}
public abstract String getName();
public abstract GL3DCameraOptionPanel getOptionPanel();
public abstract void timeChanged(JHVDate date);
public abstract void updateRotation(JHVDate date, MetaData m);
public void zoomToFit() {
double size = Layers.getLargestPhysicalSize();
if (size == 0)
setCameraFOV(INITFOV);
else
setCameraFOV(2. * Math.atan(-size / 2. / this.getZTranslation()));
}
public Mat4d getRotation() {
return this.rotation.toMatrix();
}
}
| remove unused function
git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@5910 b4e469a2-07ce-4b26-9273-4d7d95a670c7
| src/jhv/src/org/helioviewer/jhv/camera/GL3DCamera.java | remove unused function | <ide><path>rc/jhv/src/org/helioviewer/jhv/camera/GL3DCamera.java
<ide> return this.localRotation;
<ide> }
<ide>
<del> private void resetCurrentDragRotation() {
<del> this.currentDragRotation.clear();
<del> }
<del>
<ide> public void setLocalRotation(Quatd localRotation) {
<ide> this.localRotation = localRotation;
<ide> this.rotation.clear(); |
|
Java | mit | d8ad2fe747b11e9f041b0287f3290e37f29f80c3 | 0 | jensborch/kontentsu,jensborch/kontentsu,jensborch/kontentsu,jensborch/kontentsu | /*
* The MIT License
*
* Copyright 2016 Jens Borch Christiansen.
*
* 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 dk.kontentsu.processing;
import static dk.kontentsu.processing.JsonContent.*;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonToken;
import dk.kontentsu.model.Content;
import dk.kontentsu.model.SemanticUri;
import dk.kontentsu.model.internal.Metadata;
import dk.kontentsu.model.internal.MetadataType;
import dk.kontentsu.model.internal.ReferenceType;
import dk.kontentsu.parsers.ContentParser;
import dk.kontentsu.parsers.ContentParserException;
import dk.kontentsu.parsers.Link;
import dk.kontentsu.spi.ContentProcessingMimeType;
import dk.kontentsu.spi.ContentProcessingScoped;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Parser for JSON content. The parser will find metadata and compositions in
* the data.
*
* @author Jens Borch Christiansen
*/
@ContentProcessingScoped
@ContentProcessingMimeType({"application/json"})
public class JsonParser implements ContentParser {
private static final Logger LOGGER = LoggerFactory.getLogger(JsonParser.class);
private com.fasterxml.jackson.core.JsonParser jp;
@Inject
private Content content;
@PostConstruct
public void init() {
JsonFactory jf = new JsonFactory();
try {
jp = jf.createParser(content.getData());
} catch (IOException ex) {
LOGGER.error("Error creating JSON parser", ex);
}
}
@Override
public Results parse() {
try {
Map<Metadata.Key, Metadata> metadata = new HashMap<>();
List<Link> links = new ArrayList<>();
List<Processor> fieldProcessors = new ArrayList<>();
fieldProcessors.add(new Processor(
(p, f) -> {
return JSON_HREF.equals(f) && p.contains(JSON_COMPOSITION);
},
(k, v) -> {
links.add(new Link(SemanticUri.parse(v), ReferenceType.LINK));
})
);
fieldProcessors.add(new Processor(
(p, f) -> {
return JSON_HREF.equals(f)
&& !p.contains(JSON_COMPOSITION)
&& !"template".equals(p.peekLast())
&& !"composition-type".equals(p.peekLast());
},
(k, v) -> {
links.add(new Link(SemanticUri.parse(v), ReferenceType.COMPOSITION));
})
);
fieldProcessors.add(new Processor(
(p, f) -> {
return JSON_METADATA.equals(p.peekLast());
},
(k, v) -> {
LOGGER.debug("Adding metadata - key:{}, type:{}, value:{}", k, MetadataType.PAGE, v);
metadata.put(new Metadata.Key(MetadataType.PAGE, k), new Metadata(v));
})
);
process(fieldProcessors);
return new Results(links, metadata);
} catch (IOException ex) {
throw new ContentParserException("Unable to parse content for contetn with UUID: " + content.getUuid(), ex);
}
}
private void process(List<Processor> processors) throws IOException {
String fieldName = null;
Deque<String> path = new ArrayDeque<>();
while (!jp.isClosed()) {
JsonToken token = jp.nextToken();
if (token == JsonToken.FIELD_NAME) {
fieldName = jp.getCurrentName();
for (Processor p : processors) {
if (p.fieldMatcher.apply(path, fieldName)) {
jp.nextToken();
p.fieldConsumer.accept(fieldName, jp.getValueAsString());
}
}
}
if (token == JsonToken.START_OBJECT && fieldName != null) {
path.push(fieldName);
}
if (token == JsonToken.END_OBJECT && !path.isEmpty()) {
path.pop();
}
if (token == JsonToken.END_OBJECT) {
fieldName = null;
}
}
}
private static class Processor {
BiConsumer<String, String> fieldConsumer;
BiFunction<Deque<String>, String, Boolean> fieldMatcher;
Processor(BiFunction<Deque<String>, String, Boolean> fieldMatcher, BiConsumer<String, String> fieldConsumer) {
this.fieldConsumer = fieldConsumer;
this.fieldMatcher = fieldMatcher;
}
}
}
| processing/src/main/java/dk/kontentsu/processing/JsonParser.java | /*
* The MIT License
*
* Copyright 2016 Jens Borch Christiansen.
*
* 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 dk.kontentsu.processing;
import static dk.kontentsu.processing.JsonContent.*;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonToken;
import dk.kontentsu.model.Content;
import dk.kontentsu.model.SemanticUri;
import dk.kontentsu.model.internal.Metadata;
import dk.kontentsu.model.internal.MetadataType;
import dk.kontentsu.model.internal.ReferenceType;
import dk.kontentsu.parsers.ContentParser;
import dk.kontentsu.parsers.ContentParserException;
import dk.kontentsu.parsers.Link;
import dk.kontentsu.spi.ContentProcessingMimeType;
import dk.kontentsu.spi.ContentProcessingScoped;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Parser for JSON content. The parser will find metadata and compositions in
* the data.
*
* @author Jens Borch Christiansen
*/
@ContentProcessingScoped
@ContentProcessingMimeType({"application/json"})
public class JsonParser implements ContentParser {
private static final Logger LOGGER = LoggerFactory.getLogger(JsonParser.class);
private com.fasterxml.jackson.core.JsonParser jp;
@Inject
private Content content;
@PostConstruct
public void init() {
JsonFactory jf = new JsonFactory();
try {
jp = jf.createParser(content.getData());
} catch (IOException ex) {
LOGGER.error("", ex);
}
}
@Override
public Results parse() {
try {
Map<Metadata.Key, Metadata> metadata = new HashMap<>();
List<Link> links = new ArrayList<>();
List<Processor> fieldProcessors = new ArrayList<>();
fieldProcessors.add(new Processor(
(p, f) -> {
return JSON_HREF.equals(f) && p.contains(JSON_COMPOSITION);
},
(k, v) -> {
links.add(new Link(SemanticUri.parse(v), ReferenceType.LINK));
})
);
fieldProcessors.add(new Processor(
(p, f) -> {
return JSON_HREF.equals(f)
&& !p.contains(JSON_COMPOSITION)
&& !"template".equals(p.peekLast())
&& !"composition-type".equals(p.peekLast());
},
(k, v) -> {
links.add(new Link(SemanticUri.parse(v), ReferenceType.COMPOSITION));
})
);
fieldProcessors.add(new Processor(
(p, f) -> {
return JSON_METADATA.equals(p.peekLast());
},
(k, v) -> {
LOGGER.debug("Adding metadata - key:{}, type:{}, value:{}", k, MetadataType.PAGE, v);
metadata.put(new Metadata.Key(MetadataType.PAGE, k), new Metadata(v));
})
);
process(fieldProcessors);
return new Results(links, metadata);
} catch (IOException ex) {
throw new ContentParserException("Unable to parse content for contetn with UUID: " + content.getUuid(), ex);
}
}
private void process(List<Processor> processors) throws IOException {
String fieldName = null;
Deque<String> path = new ArrayDeque<>();
while (!jp.isClosed()) {
JsonToken token = jp.nextToken();
if (token == JsonToken.FIELD_NAME) {
fieldName = jp.getCurrentName();
for (Processor p : processors) {
if (p.fieldMatcher.apply(path, fieldName)) {
jp.nextToken();
p.fieldConsumer.accept(fieldName, jp.getValueAsString());
}
}
}
if (token == JsonToken.START_OBJECT && fieldName != null) {
path.push(fieldName);
}
if (token == JsonToken.END_OBJECT && !path.isEmpty()) {
path.pop();
}
if (token == JsonToken.END_OBJECT) {
fieldName = null;
}
}
}
private static class Processor {
BiConsumer<String, String> fieldConsumer;
BiFunction<Deque<String>, String, Boolean> fieldMatcher;
Processor(BiFunction<Deque<String>, String, Boolean> fieldMatcher, BiConsumer<String, String> fieldConsumer) {
this.fieldConsumer = fieldConsumer;
this.fieldMatcher = fieldMatcher;
}
}
}
| Updated logging
| processing/src/main/java/dk/kontentsu/processing/JsonParser.java | Updated logging | <ide><path>rocessing/src/main/java/dk/kontentsu/processing/JsonParser.java
<ide> try {
<ide> jp = jf.createParser(content.getData());
<ide> } catch (IOException ex) {
<del> LOGGER.error("", ex);
<add> LOGGER.error("Error creating JSON parser", ex);
<ide> }
<ide> }
<ide> |
|
Java | mpl-2.0 | 6874e4025ccda007e81cdb3c449ebb34c5a79d19 | 0 | ajschult/etomica,etomica/etomica,ajschult/etomica,ajschult/etomica,etomica/etomica,etomica/etomica | package etomica.normalmode;
import java.io.Serializable;
import etomica.atom.AtomSet;
import etomica.atom.IAtom;
import etomica.lattice.crystal.Basis;
import etomica.lattice.crystal.BasisMonatomic;
import etomica.lattice.crystal.Primitive;
import etomica.phase.Phase;
import etomica.space.IVector;
/**
* CoordinateDefinition implementation for molecules. The class takes the first
* space.D values of u to be real space displacements of the molecule center of
* mass from its nominal position. Subclasses should add additional u values for
* intramolecular degrees of freedom.
*
* @author Andrew Schultz
*/
public class CoordinateDefinitionMolecule extends CoordinateDefinition
implements Serializable {
public CoordinateDefinitionMolecule(Phase phase, Primitive primitive, int orientationDim) {
this(phase, primitive, orientationDim, new BasisMonatomic(phase.getSpace()));
}
public CoordinateDefinitionMolecule(Phase phase, Primitive primitive, int orientationDim, Basis basis) {
super(phase, phase.getSpace().D() + orientationDim, primitive, basis);
work1 = phase.getSpace().makeVector();
u = new double[coordinateDim];
}
public double[] calcU(AtomSet molecules) {
// calculates components of U related to the the center of mass of the
// molecules
// subclass is responsible for setting orientation or intramolecular
// degrees of freedom
int j = 0;
for (int i=0; i<molecules.getAtomCount(); i++) {
IAtom molecule = molecules.getAtom(i);
IVector pos = molecule.getType().getPositionDefinition().position(molecule);
IVector site = getLatticePosition(molecule);
work1.Ev1Mv2(pos, site);
for (int k = 0; k < pos.getD(); k++) {
u[j+k] = work1.x(k);
}
j += pos.getD();
}
return u;
}
/**
* Override if nominal U is more than the lattice position of the molecule
*/
public void initNominalU(AtomSet molecules) {
}
public void setToU(AtomSet molecules, double[] newU) {
// sets the center of mass of the molecules to that specified by newU
// subclass is responsible for setting orientation or intramolecular
// degrees of freedom
int j = 0;
for (int i=0; i<molecules.getAtomCount(); i++) {
IAtom molecule = molecules.getAtom(i);
IVector site = getLatticePosition(molecule);
for (int k = 0; k < site.getD(); k++) {
work1.setX(k, site.x(k) + newU[j+k]);
}
atomActionTranslateTo.setDestination(work1);
atomActionTranslateTo.actionPerformed(molecule);
j += site.getD();
}
}
private static final long serialVersionUID = 1L;
protected final IVector work1;
protected final double[] u;
}
| etomica.apps/etomica/normalmode/CoordinateDefinitionMolecule.java | package etomica.normalmode;
import java.io.Serializable;
import etomica.atom.AtomSet;
import etomica.atom.IAtom;
import etomica.lattice.crystal.Basis;
import etomica.lattice.crystal.BasisMonatomic;
import etomica.lattice.crystal.Primitive;
import etomica.phase.Phase;
import etomica.space.IVector;
/**
* CoordinateDefinition implementation for molecules. The class takes the first
* space.D values of u to be real space displacements of the molecule center of
* mass from its nominal position. Subclasses should add additional u values for
* intramolecular degrees of freedom.
*
* @author Andrew Schultz
*/
public class CoordinateDefinitionMolecule extends CoordinateDefinition
implements Serializable {
public CoordinateDefinitionMolecule(Phase phase, Primitive primitive, int orientationDim) {
this(phase, primitive, orientationDim, new BasisMonatomic(phase.getSpace()));
}
public CoordinateDefinitionMolecule(Phase phase, Primitive primitive, int orientationDim, Basis basis) {
super(phase, phase.getSpace().D() + orientationDim, primitive, basis);
work1 = phase.getSpace().makeVector();
u = new double[coordinateDim];
}
public double[] calcU(AtomSet molecules) {
// calculates components of U related to the the center of mass of the
// molecules
// subclass is responsible for setting orientation or intramolecular
// degrees of freedom
int j = 0;
for (int i=0; i<molecules.getAtomCount(); i++) {
IAtom molecule = molecules.getAtom(i);
IVector pos = molecule.getType().getPositionDefinition().position(molecule);
IVector site = getLatticePosition(molecule);
work1.Ev1Mv2(pos, site);
for (int k = 0; i < pos.getD(); i++) {
u[j+k] = work1.x(k);
}
j += pos.getD();
}
return u;
}
/**
* Override if nominal U is more than the lattice position of the molecule
*/
public void initNominalU(AtomSet molecules) {
}
public void setToU(AtomSet molecules, double[] newU) {
// sets the center of mass of the molecules to that specified by newU
// subclass is responsible for setting orientation or intramolecular
// degrees of freedom
int j = 0;
for (int i=0; i<molecules.getAtomCount(); i++) {
IAtom molecule = molecules.getAtom(i);
IVector site = getLatticePosition(molecule);
for (int k = 0; k < site.getD(); k++) {
work1.setX(k, site.x(k) + newU[j+k]);
}
atomActionTranslateTo.setDestination(work1);
atomActionTranslateTo.actionPerformed(molecule);
j += site.getD();
}
}
private static final long serialVersionUID = 1L;
protected final IVector work1;
protected final double[] u;
}
| error in the notation
changing from i to k
| etomica.apps/etomica/normalmode/CoordinateDefinitionMolecule.java | error in the notation changing from i to k | <ide><path>tomica.apps/etomica/normalmode/CoordinateDefinitionMolecule.java
<ide> IVector pos = molecule.getType().getPositionDefinition().position(molecule);
<ide> IVector site = getLatticePosition(molecule);
<ide> work1.Ev1Mv2(pos, site);
<del> for (int k = 0; i < pos.getD(); i++) {
<add> for (int k = 0; k < pos.getD(); k++) {
<ide> u[j+k] = work1.x(k);
<ide> }
<ide> j += pos.getD(); |
|
JavaScript | mit | b7df487286d1b5bdf26a597f953534b40371ecf4 | 0 | sq/JSIL,x335/JSIL,mispy/JSIL,TukekeSoft/JSIL,sq/JSIL,sander-git/JSIL,acourtney2015/JSIL,sq/JSIL,sander-git/JSIL,dmirmilshteyn/JSIL,FUSEEProjectTeam/JSIL,x335/JSIL,volkd/JSIL,FUSEEProjectTeam/JSIL,hach-que/JSIL,hach-que/JSIL,sander-git/JSIL,volkd/JSIL,sq/JSIL,antiufo/JSIL,acourtney2015/JSIL,iskiselev/JSIL,sander-git/JSIL,x335/JSIL,FUSEEProjectTeam/JSIL,x335/JSIL,iskiselev/JSIL,acourtney2015/JSIL,FUSEEProjectTeam/JSIL,sander-git/JSIL,volkd/JSIL,acourtney2015/JSIL,iskiselev/JSIL,volkd/JSIL,dmirmilshteyn/JSIL,acourtney2015/JSIL,dmirmilshteyn/JSIL,hach-que/JSIL,TukekeSoft/JSIL,mispy/JSIL,iskiselev/JSIL,TukekeSoft/JSIL,sq/JSIL,mispy/JSIL,TukekeSoft/JSIL,dmirmilshteyn/JSIL,antiufo/JSIL,antiufo/JSIL,hach-que/JSIL,hach-que/JSIL,iskiselev/JSIL,mispy/JSIL,FUSEEProjectTeam/JSIL,volkd/JSIL,antiufo/JSIL | "use strict";
if (typeof (JSIL) === "undefined")
throw new Error("JSIL.js must be loaded first");
if (typeof(JSIL.SuppressInterfaceWarnings) === "undefined")
JSIL.SuppressInterfaceWarnings = true;
JSIL.ReadOnlyPropertyWriteWarnings = false;
if (typeof(JSIL.ThrowOnUnimplementedExternals) === "undefined")
JSIL.ThrowOnUnimplementedExternals = false;
if (typeof(JSIL.ThrowOnStaticCctorError) === "undefined")
JSIL.ThrowOnStaticCctorError = false;
JSIL.WarnAboutGenericResolveFailures = false;
JSIL.StructFormatWarnings = false;
JSIL.$NextAssemblyId = 0;
JSIL.PrivateNamespaces = {};
JSIL.AssemblyShortNames = {};
var $private = null;
// FIXME: Why does this slightly deopt global performance vs. Object.create? Object.create should be worse.
JSIL.$CreateCrockfordObject = function (prototype) {
if (!prototype && (prototype !== null))
JSIL.RuntimeError("Prototype not specified");
// FIXME: Generate this with a better name?
function crockfordobject () {
};
crockfordobject.prototype = prototype || null;
return new crockfordobject();
};
JSIL.CreateDictionaryObject = function (prototype) {
if (!prototype && (prototype !== null))
JSIL.RuntimeError("Prototype not specified");
return Object.create(prototype);
};
JSIL.CreateSingletonObject = function (prototype) {
return JSIL.CreateDictionaryObject(prototype);
};
JSIL.CreatePrototypeObject = function (prototype) {
// HACK: Nesting may protect type information
// return JSIL.CreateDictionaryObject(JSIL.CreateDictionaryObject(prototype));
// Not faster though. Probably because of the longer prototype chain.
return JSIL.CreateDictionaryObject(prototype);
};
JSIL.CreateInstanceObject = function (prototype) {
if (!prototype && (prototype !== null))
JSIL.RuntimeError("Prototype not specified");
return Object.create(prototype);
};
JSIL.HasOwnPropertyRecursive = function (target, name) {
while (!target.hasOwnProperty(name)) {
target = Object.getPrototypeOf(target);
if ((typeof (target) === "undefined") || (target === null))
return false;
}
return target.hasOwnProperty(name);
};
JSIL.GetOwnPropertyDescriptorRecursive = function (target, name) {
while (!target.hasOwnProperty(name)) {
target = Object.getPrototypeOf(target);
if ((typeof (target) === "undefined") || (target === null))
return null;
}
return Object.getOwnPropertyDescriptor(target, name);
};
JSIL.SetValueProperty = function (target, key, value, enumerable, readOnly) {
var descriptor = {
configurable: true,
enumerable: !(enumerable === false)
};
if (readOnly === false) {
descriptor.value = value;
descriptor.writable = descriptor.writeable = !readOnly;
} else {
if (JSIL.ReadOnlyPropertyWriteWarnings) {
descriptor.get = function () {
return value;
};
descriptor.set = function () {
JSIL.RuntimeError("Attempt to write to read-only property '" + key + "'!");
};
} else {
descriptor.value = value;
descriptor.writable = descriptor.writeable = false;
}
}
Object.defineProperty(target, key, descriptor);
};
JSIL.DefineLazyDefaultProperty = function (target, key, getDefault) {
var isInitialized = false;
var defaultValue;
var descriptor = {
configurable: true,
enumerable: true
};
var cleanup = function () {
var currentDescriptor = Object.getOwnPropertyDescriptor(target, key);
// Someone could have replaced us with a new property. If so, don't trample
// over them.
if (
currentDescriptor &&
(currentDescriptor.get === descriptor.get) &&
(currentDescriptor.set === descriptor.set)
)
Object.defineProperty(target, key, {
configurable: true,
enumerable: true,
writable: true,
value: target[key]
});
};
var initIfNeeded = function (self) {
if (!isInitialized) {
isInitialized = true;
defaultValue = getDefault.call(self);
cleanup();
}
};
var getter = function LazyDefaultProperty_Get () {
initIfNeeded(this);
// HACK: We could return defaultValue here, but that would ignore cases where the initializer overwrote the default.
// The cctor for a static array field containing values is an example of this (issue #234)
var currentDescriptor = Object.getOwnPropertyDescriptor(target, key);
if (currentDescriptor.value)
return currentDescriptor.value;
else if (currentDescriptor.get !== descriptor.get)
return this[key];
else
return defaultValue;
};
var setter = function LazyDefaultProperty_Set (value) {
var setterDesc = {
configurable: true,
enumerable: true,
writable: true,
value: value
};
initIfNeeded(this);
// Overwrite the defaultValue so that any getter calls
// still return the correct result.
defaultValue = value;
// We *NEED* to update the field after we run the initializer,
// not before! If we update it before the initializer may overwrite
// it, and worse still, the initializer may not be expecting to see
// the write yet.
Object.defineProperty(
this, key, setterDesc
);
return value;
};
descriptor.get = getter;
descriptor.set = setter;
Object.defineProperty(target, key, descriptor);
};
JSIL.SetLazyValueProperty = function (target, key, getValue, onPrototype, readOnly) {
var isInitialized = false;
var descriptor = {
configurable: true,
enumerable: true,
};
if (onPrototype) {
var cleanup = function (value) {
JSIL.SetValueProperty(this, key, value, true, readOnly);
};
var getter = function LazyValueProperty_Get () {
var value = getValue.call(this);
cleanup.call(this, value);
return value;
};
descriptor.get = getter;
} else {
var value;
var cleanup = function () {
var currentDescriptor = Object.getOwnPropertyDescriptor(target, key);
// Someone could have replaced us with a new property. If so, don't trample
// over them.
if (
currentDescriptor &&
(currentDescriptor.get === descriptor.get)
) {
JSIL.SetValueProperty(target, key, value, true, readOnly);
} else {
return;
}
};
var getter = function LazyValueProperty_Get () {
if (!isInitialized) {
value = getValue.call(this);
if (!isInitialized) {
isInitialized = true;
cleanup.call(this);
}
}
return value;
};
descriptor.get = getter;
}
Object.defineProperty(target, key, descriptor);
};
JSIL.$NextTypeId = 0;
JSIL.$NextDispatcherId = 0;
JSIL.$AssignedTypeIds = {};
JSIL.$GenericParameterTypeIds = {};
JSIL.$PublicTypes = {};
JSIL.$PublicTypeAssemblies = {};
JSIL.$PrivateTypeAssemblies = {};
JSIL.$EntryPoints = {};
JSIL.$SpecialTypeObjects = {};
JSIL.$SpecialTypePrototypes = {};
JSIL.$MakeSpecialType = function (name, typeObjectBase, prototypeBase) {
var typeObject = Object.create(typeObjectBase);
JSIL.$SpecialTypeObjects[name] = typeObject;
var prototype = null;
if (prototypeBase)
prototype = JSIL.$MakeSpecialPrototype(name, prototypeBase);
return {
typeObject: typeObject,
prototype: prototype
};
};
JSIL.$MakeSpecialPrototype = function (name, prototypeBase) {
var prototype = Object.create(prototypeBase);
JSIL.$SpecialTypePrototypes[name] = prototype;
return prototype;
};
JSIL.$GetSpecialType = function (name) {
return {
typeObject: JSIL.$SpecialTypeObjects[name] || null,
prototype: JSIL.$SpecialTypePrototypes[name] || null
};
};
( function () {
JSIL.TypeObjectPrototype = Object.create(null);
// FIXME: It's gross that methods are split between this and System.Type externals.
JSIL.TypeObjectPrototype.toString = function () {
return JSIL.GetTypeName(this, true);
};
JSIL.TypeObjectPrototype.get_Assembly = function() {
return this.__Context__.__Assembly__;
};
JSIL.TypeObjectPrototype.get_BaseType = function() {
return this.__BaseType__;
};
JSIL.TypeObjectPrototype.get_Namespace = function() {
// FIXME: Probably wrong for nested types.
return JSIL.GetParentName(this.__FullNameWithoutArguments__ || this.__FullName__);
};
JSIL.TypeObjectPrototype.get_Name = function() {
return JSIL.GetLocalName(this.__FullNameWithoutArguments__ || this.__FullName__);
};
JSIL.TypeObjectPrototype.get_FullName = function() {
if (this.get_IsGenericType() && !this.get_IsGenericTypeDefinition()) {
var result = this.__FullNameWithoutArguments__;
result += "[";
var ga = this.__GenericArgumentValues__;
for (var i = 0, l = ga.length; i < l; i++) {
var type = ga[i];
result += "[" + type.get_AssemblyQualifiedName() + "]";
}
result += "]";
return result;
} else {
return this.__FullName__;
}
};
JSIL.TypeObjectPrototype.get_AssemblyQualifiedName = function() {
return this.get_FullName() + ", " + this.get_Assembly().toString();
};
JSIL.TypeObjectPrototype.get_IsEnum = function() {
return this.__IsEnum__;
};
JSIL.TypeObjectPrototype.get_ContainsGenericParameters = function() {
return this.__IsClosed__ === false;
};
JSIL.TypeObjectPrototype.get_IsGenericType = function() {
return (this.__OpenType__ !== undefined || this.__IsClosed__ === false) && !(this instanceof JSIL.GenericParameter);
};
JSIL.TypeObjectPrototype.get_IsGenericTypeDefinition = function() {
return this.__IsClosed__ === false && this.__GenericArgumentValues__ === undefined && !(this instanceof JSIL.GenericParameter);
};
JSIL.TypeObjectPrototype.get_IsValueType = function() {
return this.__IsValueType__;
};
JSIL.TypeObjectPrototype.get_IsArray = function() {
return this.__IsArray__;
};
JSIL.TypeObjectPrototype.get_IsGenericParameter = function() {
return false;
};
JSIL.TypeObjectPrototype.get_IsByRef = function() {
return this.__IsByRef__;
};
JSIL.TypeObjectPrototype.get_IsInterface = function() {
// FIXME: I think Object.DefineProperty might mess with us here. Should probably rename the backing value to __IsInterface__.
return this.IsInterface;
};
var systemObjectPrototype = JSIL.$MakeSpecialPrototype("System.Object", Object.prototype);
var memberInfoPrototype = JSIL.$MakeSpecialPrototype("System.Reflection.MemberInfo", systemObjectPrototype);
var systemTypePrototype = JSIL.$MakeSpecialPrototype("System.Type", memberInfoPrototype);
var typeInfoPrototype = JSIL.$MakeSpecialPrototype("System.Reflection.TypeInfo", systemTypePrototype);
var runtimeTypePrototype = JSIL.$MakeSpecialPrototype("System.RuntimeType", typeInfoPrototype);
var dict = JSIL.$MakeSpecialType("System.RuntimeType", runtimeTypePrototype, null);
var runtimeType = dict.typeObject;
for (var k in JSIL.TypeObjectPrototype)
runtimeType[k] = JSIL.TypeObjectPrototype[k];
JSIL.SetValueProperty(runtimeType, "__IsReferenceType__", true);
runtimeType.IsInterface = false;
runtimeType.__IsEnum__ = false;
runtimeType.__ThisType__ = runtimeType;
runtimeType.__TypeInitialized__ = false;
runtimeType.__LockCount__ = 0;
JSIL.SetValueProperty(runtimeType, "__FullName__", "System.RuntimeType");
JSIL.SetValueProperty(runtimeType, "__ShortName__", "RuntimeType");
var assemblyPrototype = JSIL.$MakeSpecialPrototype("System.Reflection.Assembly", systemObjectPrototype);
dict = JSIL.$MakeSpecialType("System.Reflection.RuntimeAssembly", runtimeTypePrototype, assemblyPrototype);
var runtimeAssembly = dict.typeObject;
JSIL.SetValueProperty(runtimeAssembly, "__IsReferenceType__", true);
runtimeAssembly.IsInterface = false;
runtimeAssembly.__IsEnum__ = false;
runtimeAssembly.__ThisType__ = runtimeType;
runtimeAssembly.__ThisTypeId__ = runtimeType.__TypeId__;
runtimeAssembly.__TypeInitialized__ = false;
runtimeAssembly.__LockCount__ = 0;
JSIL.SetValueProperty(runtimeAssembly, "__FullName__", "System.Reflection.RuntimeAssembly");
JSIL.SetValueProperty(runtimeAssembly, "__ShortName__", "RuntimeAssembly");
} )();
JSIL.SetTypeId = function (typeObject, publicInterface, prototype, value) {
if (!value)
value = prototype;
if (typeof (value) !== "string")
JSIL.RuntimeError("Type IDs must be strings");
JSIL.SetValueProperty(typeObject, "__TypeId__", value);
JSIL.SetValueProperty(publicInterface, "__TypeId__", value);
if (arguments.length === 4)
JSIL.SetValueProperty(prototype, "__ThisTypeId__", value);
}
JSIL.AssignTypeId = function (assembly, typeName) {
if (JSIL.EscapeName)
typeName = JSIL.EscapeName(typeName);
if (typeof (assembly.__AssemblyId__) === "undefined")
JSIL.RuntimeError("Invalid assembly context");
if (typeof (JSIL.$PublicTypeAssemblies[typeName]) !== "undefined") {
assembly = JSIL.$PublicTypeAssemblies[typeName];
} else if (typeof (JSIL.$PrivateTypeAssemblies[typeName]) !== "undefined") {
assembly = JSIL.$PrivateTypeAssemblies[typeName];
}
var key = assembly.__AssemblyId__ + "$" + typeName;
var result = JSIL.$AssignedTypeIds[key];
if (typeof (result) !== "string")
result = JSIL.$AssignedTypeIds[key] = String(++(JSIL.$NextTypeId));
return result;
};
JSIL.DeclareAssembly = function (assemblyName) {
var existing = JSIL.GetAssembly(assemblyName, true);
if ((existing !== null) && (existing.__Declared__))
JSIL.RuntimeError("Assembly '" + assemblyName + "' already declared.");
var result = JSIL.GetAssembly(assemblyName, false);
JSIL.SetValueProperty(result, "__Declared__", true);
$private = result;
return result;
};
JSIL.GetAssembly = function (assemblyName, requireExisting) {
var existing = JSIL.PrivateNamespaces[assemblyName];
if (typeof (existing) !== "undefined")
return existing;
var shortName = assemblyName;
var commaPos = shortName.indexOf(",");
if (commaPos >= 0)
shortName = shortName.substr(0, commaPos);
if (typeof (JSIL.AssemblyShortNames[shortName]) !== "undefined") {
var existingFullName = JSIL.AssemblyShortNames[shortName];
if ((existingFullName !== null) && (commaPos <= 0)) {
existing = JSIL.PrivateNamespaces[existingFullName];
if (typeof (existing) !== "undefined")
return existing;
} else if (commaPos >= 0) {
// Multiple assemblies with the same short name, so disable the mapping.
JSIL.AssemblyShortNames[shortName] = null;
}
} else if (commaPos >= 0) {
JSIL.AssemblyShortNames[shortName] = assemblyName;
}
if (requireExisting)
return null;
var isMscorlib = (shortName === "mscorlib") || (assemblyName.indexOf("mscorlib,") === 0);
var isSystem = (shortName === "System") || (assemblyName.indexOf("System,") === 0);
var isSystemCore = (shortName === "System.Core") || (assemblyName.indexOf("System.Core,") === 0);
var isSystemXml = (shortName === "System.Xml") || (assemblyName.indexOf("System.Xml,") === 0);
var isJsilMeta = (shortName === "JSIL.Meta") || (assemblyName.indexOf("JSIL.Meta,") === 0);
// Create a new private global namespace for the new assembly
var template = {};
// Ensure that BCL private namespaces inherit from the JSIL namespace.
if (isMscorlib || isSystem || isSystemCore || isSystemXml || isJsilMeta)
template = $jsilcore;
var result = JSIL.CreateSingletonObject(template);
var assemblyId;
// Terrible hack to assign the mscorlib and JSIL.Core types the same IDs
if (isMscorlib) {
assemblyId = $jsilcore.__AssemblyId__;
} else {
assemblyId = ++JSIL.$NextAssemblyId;
}
var makeReflectionAssembly = function () {
var proto = JSIL.$GetSpecialType("System.Reflection.RuntimeAssembly").prototype;
var reflectionAssembly = Object.create(proto);
JSIL.SetValueProperty(reflectionAssembly, "__PublicInterface__", result);
JSIL.SetValueProperty(reflectionAssembly, "__FullName__", assemblyName);
return reflectionAssembly;
};
JSIL.SetValueProperty(result, "__Declared__", false);
JSIL.SetLazyValueProperty(result, "__Assembly__", makeReflectionAssembly);
JSIL.SetValueProperty(result, "__AssemblyId__", assemblyId, false);
JSIL.SetValueProperty(result, "TypeRef",
function (name, ga) {
return new JSIL.TypeRef(result, name, ga);
}, false
);
JSIL.SetValueProperty(result, "toString",
function Assembly_ToString () {
return "<" + assemblyName + " Public Interface>";
}
);
JSIL.SetValueProperty(result, "$typesByName", {}, false);
JSIL.PrivateNamespaces[assemblyName] = result;
return result;
};
var $jsilcore = JSIL.DeclareAssembly("JSIL.Core");
(function () {
JSIL.$SpecialTypePrototypes["System.RuntimeType"].__ThisTypeId__ =
JSIL.$SpecialTypeObjects["System.RuntimeType"].__TypeId__ =
JSIL.AssignTypeId($jsilcore, "System.RuntimeType");
})();
// Using these constants instead of 'null' turns some call sites from dimorphic to monomorphic in SpiderMonkey's
// type inference engine.
$jsilcore.ArrayNotInitialized = ["ArrayNotInitialized"];
$jsilcore.ArrayNull = [];
$jsilcore.FunctionNotInitialized = function () { throw new Error("FunctionNotInitialized"); };
$jsilcore.FunctionNull = function () { };
JSIL.Memoize = function Memoize (value) {
if (typeof (value) === "undefined")
JSIL.RuntimeError("Memoized value is undefined");
return function MemoizedValue () {
return value;
};
};
JSIL.PreInitMembrane = function (target, initializer) {
if (typeof (initializer) !== "function")
JSIL.RuntimeError("initializer is not a function");
if (
(typeof (target) !== "object") &&
(typeof (target) !== "function")
)
JSIL.RuntimeError("target must be an object or function");
if (target.__PreInitMembrane__)
JSIL.RuntimeError("object already has a membrane");
this.target = target;
this.target.__PreInitMembrane__ = this;
this.hasRunInitializer = false;
this.hasRunCleanup = false;
this.initializer = initializer;
this.cleanupList = [];
this.aliasesByKey = {};
this.propertiesToRebind = [];
// Function.bind is too slow to rely on in a hot path function like these
var self = this;
var _maybeInit = Object.getPrototypeOf(this).maybeInit;
var _cleanup = Object.getPrototypeOf(this).cleanup;
this.maybeInit = function bound_maybeInit () {
_maybeInit.call(self);
};
this.cleanup = function bound_cleanup () {
return _cleanup.call(self);
};
};
JSIL.PreInitMembrane.prototype.checkForUseAfterCleanup = function () {
if (this.hasRunCleanup)
JSIL.RuntimeError("Membrane in use after cleanup");
};
JSIL.PreInitMembrane.prototype.maybeInit = function () {
if (this.hasRunCleanup && this.hasRunInitializer) {
// HACK for #651
// JSIL.RuntimeError("maybeInit called after init and cleanup");
}
if (!this.hasRunInitializer) {
this.hasRunInitializer = true;
this.initializer();
}
if (!this.hasRunCleanup) {
this.cleanup();
}
};
JSIL.PreInitMembrane.prototype.rebindProperties = function () {
for (var i = 0, l = this.propertiesToRebind.length; i < l; i++) {
var propertyName = this.propertiesToRebind[i];
var descriptor = Object.getOwnPropertyDescriptor(this.target, propertyName);
if (!descriptor)
continue;
var doRebind = false;
if (descriptor.get && descriptor.get.__IsMembrane__) {
descriptor.get = this.target[descriptor.get.__OriginalKey__];
doRebind = true;
}
if (descriptor.set && descriptor.set.__IsMembrane__) {
descriptor.set = this.target[descriptor.set.__OriginalKey__];
doRebind = true;
}
if (doRebind) {
Object.defineProperty(this.target, propertyName, descriptor);
}
};
};
JSIL.PreInitMembrane.prototype.cleanup = function () {
this.hasRunCleanup = true;
for (var i = 0, l = this.cleanupList.length; i < l; i++) {
var cleanupFunction = this.cleanupList[i];
cleanupFunction();
}
this.rebindProperties();
this.initializer = null;
this.cleanupList = null;
this.aliasesByKey = null;
this.target.__PreInitMembrane__ = null;
// this.propertiesToRebind = null;
// this.target = null;
return true;
};
JSIL.PreInitMembrane.prototype.defineField = function (key, getInitialValue) {
this.checkForUseAfterCleanup();
var needToGetFieldValue = true;
var fieldValue;
var target = this.target;
this.cleanupList.push(function PreInitField_Cleanup () {
if (needToGetFieldValue) {
needToGetFieldValue = false;
fieldValue = getInitialValue();
}
Object.defineProperty(target, key, {
configurable: true,
enumerable: true,
writable: true,
value: fieldValue
});
});
var maybeInit = this.maybeInit;
var getter = function PreInitField_Get () {
maybeInit();
if (needToGetFieldValue) {
needToGetFieldValue = false;
fieldValue = getInitialValue();
}
return fieldValue;
}
var setter = function PreInitField_Set (value) {
needToGetFieldValue = false;
fieldValue = value;
return value;
};
Object.defineProperty(
target, key, {
configurable: true,
enumerable: true,
get: getter,
set: setter
}
);
};
JSIL.PreInitMembrane.prototype.defineMethod = function (key, fnGetter) {
this.checkForUseAfterCleanup();
var aliasesByKey = this.aliasesByKey;
var actualFn = $jsilcore.FunctionNotInitialized;
var target = this.target;
var membrane;
this.cleanupList.push(function PreInitMethod_Cleanup () {
if (actualFn === $jsilcore.FunctionNotInitialized)
actualFn = fnGetter();
if (target[key].__IsMembrane__)
JSIL.SetValueProperty(target, key, actualFn);
var aliases = aliasesByKey[key];
if (aliases) {
for (var i = 0, l = aliases.length; i < l; i++) {
var alias = aliases[i];
if (target[alias].__IsMembrane__)
JSIL.SetValueProperty(target, alias, actualFn);
}
}
// delete this.aliasesByKey[key];
});
var maybeInit = this.maybeInit;
membrane = function PreInitMethod_Invoke () {
maybeInit();
if (actualFn === $jsilcore.FunctionNotInitialized)
actualFn = fnGetter();
return actualFn.apply(this, arguments);
};
membrane.__Membrane__ = this;
membrane.__IsMembrane__ = true;
membrane.__OriginalKey__ = key;
membrane.__Unwrap__ = function () {
maybeInit();
if (actualFn === $jsilcore.FunctionNotInitialized)
actualFn = fnGetter();
return actualFn;
};
JSIL.SetValueProperty(target, key, membrane);
};
JSIL.PreInitMembrane.prototype.defineMethodAlias = function (key, alias) {
this.checkForUseAfterCleanup();
var aliases = this.aliasesByKey[key];
if (!aliases)
aliases = this.aliasesByKey[key] = [];
aliases.push(alias);
};
JSIL.PreInitMembrane.prototype.registerPropertyForRebind = function (key) {
this.checkForUseAfterCleanup();
this.propertiesToRebind.push(key);
};
JSIL.DefinePreInitField = function (target, key, getInitialValue, initializer) {
var membrane = target.__PreInitMembrane__;
if (!membrane)
membrane = new JSIL.PreInitMembrane(target, initializer);
membrane.defineField(key, getInitialValue);
};
JSIL.DefinePreInitMethod = function (target, key, fnGetter, initializer) {
var membrane = target.__PreInitMembrane__;
if (!membrane)
membrane = new JSIL.PreInitMembrane(target, initializer);
membrane.defineMethod(key, fnGetter);
};
JSIL.DefinePreInitMethodAlias = function (target, alias, originalMethod) {
if (!originalMethod.__IsMembrane__)
JSIL.RuntimeError("Method is not a membrane");
var membrane = originalMethod.__Membrane__;
membrane.defineMethodAlias(originalMethod.__OriginalKey__, alias);
};
JSIL.RebindPropertyAfterPreInit = function (target, propertyName) {
var membrane = target.__PreInitMembrane__;
if (!membrane)
membrane = new JSIL.PreInitMembrane(target, initializer);
membrane.registerPropertyForRebind(propertyName);
};
$jsilcore.SystemObjectInitialized = false;
$jsilcore.RuntimeTypeInitialized = false;
$jsilcore.TypedArrayToType = {};
JSIL.AssemblyCollection = function (obj) {
var makeGetter = function (assemblyName) {
return function GetAssemblyFromCollection () {
var state = JSIL.GetAssembly(assemblyName, true);
return state;
};
};
for (var k in obj) {
JSIL.SetLazyValueProperty(
this, k, makeGetter(obj[k])
);
}
};
JSIL.Name = function (name, context) {
if (typeof (context) !== "string") {
if (context.__FullName__)
context = context.__FullName__;
else
context = String(context);
}
this.humanReadable = context + "." + String(name);
this.key = JSIL.EscapeName(context) + "$" + JSIL.EscapeName(String(name));
};
JSIL.Name.prototype.get = function (target) {
return target[this.key];
};
JSIL.Name.prototype.set = function (target, value) {
target[this.key] = value;
return value;
};
JSIL.Name.prototype.defineProperty = function (target, decl) {
Object.defineProperty(
target, this.key, decl
);
};
JSIL.Name.prototype.toString = function () {
return this.humanReadable;
};
JSIL.SplitRegex = /[\.]/g;
JSIL.UnderscoreRegex = /[\.\/\+]/g;
JSIL.AngleGroupRegex = /\<([^<>]*)\>/g;
JSIL.EscapedNameCharacterRegex = /[\.\/\+\`\~\:\<\>\(\)\{\}\[\]\@\-\=\?\!\*\ \&\,\|\']/g;
JSIL.EscapeName = function (name) {
if ((!name) || (typeof (name) !== "string"))
throw new Error("EscapeName only accepts a string");
// FIXME: It sucks that this has to manually duplicate the C# escape logic.
name = name.replace(JSIL.AngleGroupRegex, function (match, group1) {
return "$l" + group1.replace(JSIL.UnderscoreRegex, "_") + "$g";
});
// HACK: Using a regex here to try to avoid generating huge rope strings in v8
name = name.replace(JSIL.EscapedNameCharacterRegex, function (match) {
var ch = match[0];
switch (ch) {
case ".":
case "/":
case "+":
return "_";
case "`":
return "$b";
case "~":
return "$t";
case ":":
return "$co";
case "<":
return "$l";
case ">":
return "$g";
case "(":
return "$lp";
case ")":
return "$rp";
case "{":
return "$lc";
case "}":
return "$rc";
case "[":
return "$lb";
case "]":
return "$rb";
case "@":
return "$at";
case "-":
return "$da";
case "=":
return "$eq";
case " ":
return "$sp";
case "?":
return "$qu";
case "!":
return "$ex";
case "*":
return "$as";
case "&":
return "$am";
case ",":
return "$cm";
case "|":
return "$vb";
case "'":
return "$q";
}
var chIndex = ch.charCodeAt(0);
if ((chIndex < 32) || (chIndex >= 127)) {
// FIXME: Padding?
return "$" + ch.toString(16);
}
return ch;
});
return name;
};
JSIL.GetParentName = function (name) {
var parts = JSIL.SplitName(name);
return name.substr(0, name.length - (parts[parts.length - 1].length + 1));
};
JSIL.GetLocalName = function (name) {
var parts = JSIL.SplitName(name);
return parts[parts.length - 1];
};
JSIL.SplitName = function (name) {
if (typeof (name) !== "string")
JSIL.Host.abort(new Error("Not a name: " + name));
var escapedName = name.replace(JSIL.AngleGroupRegex, function (match, group1) {
return "$l" + group1.replace(JSIL.UnderscoreRegex, "_") + "$g";
});
return escapedName.split(JSIL.SplitRegex);
};
JSIL.ResolvedName = function (parent, parentName, key, allowInheritance) {
this.parent = parent;
this.parentName = parentName;
this.key = key;
this.allowInheritance = allowInheritance;
};
JSIL.ResolvedName.prototype.exists = function (allowInheritance) {
if (this.allowInheritance && (allowInheritance !== false))
return (this.key in this.parent);
else
return this.parent.hasOwnProperty(this.key);
};
JSIL.ResolvedName.prototype.get = function () {
return this.parent[this.key];
};
JSIL.ResolvedName.prototype.set = function (value) {
JSIL.SetValueProperty(this.parent, this.key, value);
return value;
};
JSIL.ResolvedName.prototype.setLazy = function (getter) {
JSIL.SetLazyValueProperty(this.parent, this.key, getter);
};
JSIL.ResolvedName.prototype.define = function (declaration) {
Object.defineProperty(this.parent, this.key, declaration);
var descriptor = Object.getOwnPropertyDescriptor(this.parent, this.key);
if (declaration.value) {
if (descriptor.value != declaration.value)
JSIL.RuntimeError("Failed to define property '" + this.key + "'.");
} else if (declaration.get) {
if (descriptor.get != declaration.get)
JSIL.RuntimeError("Failed to define property '" + this.key + "'.");
}
};
JSIL.ResolveName = function (root, name, allowInheritance, throwOnFail) {
var parts = JSIL.SplitName(name);
var current = root;
if (typeof (root) === "undefined")
JSIL.RuntimeError("Invalid search root");
var makeError = function (_key, _current) {
var namespaceName;
if (_current === JSIL.GlobalNamespace)
namespaceName = "<global>";
else {
try {
namespaceName = _current.toString();
} catch (e) {
namespaceName = "<unknown>";
}
}
return new Error("Could not find the name '" + _key + "' in the namespace '" + namespaceName + "'.");
};
for (var i = 0, l = parts.length - 1; i < l; i++) {
var key = JSIL.EscapeName(parts[i]);
if (!(key in current)) {
if (throwOnFail !== false)
throw makeError(key, current);
else
return null;
}
if (!allowInheritance) {
if (!current.hasOwnProperty(key)) {
if (throwOnFail !== false)
throw makeError(key, current);
else
return null;
}
}
var next = current[key];
current = next;
}
var localName = parts[parts.length - 1];
return new JSIL.ResolvedName(
current, name.substr(0, name.length - (localName.length + 1)),
JSIL.EscapeName(localName), allowInheritance
);
};
// Must not be used to construct type or interact with members. Only to get a reference to the type for access to type information.
JSIL.GetTypeByName = function (name, assembly) {
if (name.indexOf("!!") === 0)
JSIL.RuntimeError("Positional generic method parameter '" + name + "' cannot be resolved by GetTypeByName.");
if (assembly !== undefined) {
var tbn = assembly.$typesByName;
if (typeof (tbn) === "object") {
var typeFunction = tbn[name];
if (typeof (typeFunction) === "function")
return typeFunction(false);
} else {
JSIL.Host.warning("Invalid assembly reference passed to GetTypeByName: " + assembly);
}
}
var key = JSIL.EscapeName(name);
var typeFunction = JSIL.$PublicTypes[key];
if (typeof (typeFunction) !== "function")
JSIL.RuntimeError("Type '" + name + "' has not been defined.");
return typeFunction(false);
};
JSIL.DefineTypeName = function (name, getter, isPublic) {
if (typeof (getter) !== "function")
JSIL.RuntimeError("Definition for type name '" + name + "' is not a function");
if (isPublic) {
var key = JSIL.EscapeName(name);
var existing = JSIL.$PublicTypes[key];
var existingAssembly = JSIL.$PublicTypeAssemblies[key];
if ((typeof (existing) === "function") && (existingAssembly !== $jsilcore)) {
JSIL.$PublicTypes[key] = function AmbiguousPublicTypeReference () {
JSIL.RuntimeError("Type '" + name + "' has multiple public definitions. You must access it through a specific assembly.");
};
if (existingAssembly != undefined) {
JSIL.WarningFormat(
"Public type '{0}' defined twice: {1} and {2}",
[name, existingAssembly.toString(), $private.toString()]
);
delete JSIL.$PublicTypeAssemblies[key];
} else {
JSIL.WarningFormat(
"Public type '{0}' defined more than twice: {1} and several other assemblies",
[name, $private.toString()]
);
}
} else {
JSIL.$PublicTypes[key] = getter;
JSIL.$PublicTypeAssemblies[key] = $private;
}
} else if ($private == $jsilcore) {
var key = JSIL.EscapeName(name);
JSIL.$PrivateTypeAssemblies[key] = $private;
} else {
var key = JSIL.EscapeName(name);
var existing = JSIL.$PrivateTypeAssemblies[key];
if (existing !== undefined){
if (existing != $jsilcore) {
JSIL.WarningFormat(
"Private type '{0}' with external implementation defined more than twice: '{1}'" +
[$private.toString(), existing.toString()]
);
}
JSIL.$PrivateTypeAssemblies[key] = $private;
}
}
var existing = $private.$typesByName[name];
if (typeof (existing) === "function")
JSIL.RuntimeError("Type '" + name + "' has already been defined.");
$private.$typesByName[name] = getter;
};
JSIL.DeclareNamespace = function (name, sealed) {
if (typeof (sealed) === "undefined")
sealed = true;
var toStringImpl = function Namespace_ToString () {
return name;
};
var resolved = JSIL.ResolveName(JSIL.GlobalNamespace, name, true);
if (!resolved.exists())
resolved.define({
enumerable: true,
configurable: !sealed,
value: {
__FullName__: name,
toString: toStringImpl
}
});
var resolved = JSIL.ResolveName($private, name, true);
if (!resolved.exists())
resolved.define({
enumerable: true,
configurable: !sealed,
value: {
__FullName__: name,
toString: toStringImpl
}
});
};
JSIL.DeclareNamespace("System");
JSIL.DeclareNamespace("System.Collections");
JSIL.DeclareNamespace("System.Collections.Generic");
JSIL.DeclareNamespace("System.Text");
JSIL.DeclareNamespace("System.Threading");
JSIL.DeclareNamespace("System.Globalization");
JSIL.DeclareNamespace("System.Runtime");
JSIL.DeclareNamespace("System.Runtime.InteropServices");
JSIL.DeclareNamespace("System.Reflection");
JSIL.DeclareNamespace("JSIL");
JSIL.DeclareNamespace("JSIL.Array");
JSIL.DeclareNamespace("JSIL.Delegate");
JSIL.DeclareNamespace("JSIL.MulticastDelegate");
JSIL.DeclareNamespace("JSIL.Dynamic");
// Hack
JSIL.DeclareNamespace("Property");
// Implemented in JSIL.Host.js
JSIL.DeclareNamespace("JSIL.Host", false);
JSIL.UnmaterializedReference = function (targetExpression) {
JSIL.Host.abort(new Error("A reference to expression '" + targetExpression + "' could not be translated."));
};
JSIL.UntranslatableNode = function (nodeType) {
JSIL.Host.abort(new Error("An ILAst node of type " + nodeType + " could not be translated."));
};
JSIL.UntranslatableFunction = function (functionName) {
return function UntranslatableFunctionInvoked () {
JSIL.Host.abort(new Error("The function '" + functionName + "' could not be translated."));
};
};
JSIL.UntranslatableInstruction = function (instruction, operand) {
if (typeof (operand) !== "undefined")
JSIL.Host.abort(new Error("A MSIL instruction of type " + instruction + " with an operand of type " + operand + " could not be translated."));
else
JSIL.Host.abort(new Error("A MSIL instruction of type " + instruction + " could not be translated."));
};
JSIL.IgnoredType = function (typeName) {
JSIL.Host.abort(new Error("An attempt was made to reference the type '" + typeName + "', but it was explicitly ignored during translation."));
};
JSIL.IgnoredMember = function (memberName) {
JSIL.Host.abort(new Error("An attempt was made to reference the member '" + memberName + "', but it was explicitly ignored during translation."));
};
JSIL.UnknownMember = function (memberName) {
JSIL.Host.abort(new Error("An attempt was made to reference the member '" + memberName + "', but it has no type information."));
};
JSIL.$UnimplementedExternalError = function (err) {
if (typeof err === "string") {
if (arguments.length === 2)
err = JSIL.$FormatStringImpl(err, arguments[1]);
else if (arguments.length > 2)
JSIL.RuntimeError("$UnimplementedExternalError only accepts (errString), (error), or (errString, [value0, value1, ...])");
err = new Error(err);
}
var msg = err.message;
if (typeof (err.stack) !== "undefined") {
if (err.stack.indexOf(err.toString()) === 0)
msg = err.stack;
else
msg += "\n" + err.stack;
}
JSIL.Host.warning(msg);
if (JSIL.ThrowOnUnimplementedExternals) {
JSIL.Host.abort(err);
}
}
JSIL.$ExternalMemberWarningFormat =
"The external method '{0}' of type '{1}' has not been implemented.";
JSIL.$ExternalMemberInheritedWarningFormat =
"The external method '{0}' of type '{1}' has not been implemented; calling inherited method.";
JSIL.MakeExternalMemberStub = function (namespaceName, getMemberName, inheritedMember) {
var state = {
warningCount: 0
};
var result;
if (typeof (inheritedMember) === "function") {
result = function ExternalMemberStub () {
if (state.warningCount < 1) {
JSIL.WarningFormat(
JSIL.$ExternalMemberInheritedWarningFormat,
[getMemberName.call(this), namespaceName]
);
state.warningCount += 1;
}
return Function.prototype.apply.call(inheritedMember, this, arguments);
};
} else {
result = function ExternalMemberStub () {
if (state.warningCount > 3)
return;
var fmtArgs = [getMemberName.call(this), namespaceName];
if (JSIL.ThrowOnUnimplementedExternals)
throw new Error(
JSIL.$FormatStringImpl(
JSIL.$ExternalMemberWarningFormat, fmtArgs
)
);
else
JSIL.WarningFormat(
JSIL.$ExternalMemberWarningFormat, fmtArgs
);
state.warningCount += 1;
};
}
result.__IsPlaceholder__ = true;
return result;
};
JSIL.MemberRecord = function (type, descriptor, data, attributes, overrides) {
this.type = type;
this.descriptor = descriptor;
this.data = data;
this.attributes = attributes;
this.overrides = overrides;
};
JSIL.AttributeRecord = function (context, type, getConstructorArguments, initializer) {
this.context = context;
this.type = type;
this.getConstructorArguments = getConstructorArguments;
this.initializer = initializer;
};
JSIL.OverrideRecord = function (interfaceNameOrReference, interfaceMemberName) {
if (
(
(typeof (interfaceNameOrReference) !== "string") &&
(typeof (interfaceNameOrReference) !== "object")
) || !interfaceNameOrReference
) {
JSIL.RuntimeError("Override must specify interface name or typeref");
}
this.interfaceNameOrReference = interfaceNameOrReference;
this.interfaceMemberName = interfaceMemberName;
};
JSIL.AttributeRecord.prototype.GetType = function () {
if (this.resolvedType)
return this.resolvedType;
var resolvedType = JSIL.ResolveTypeReference(this.type, this.context)[1];
if (!resolvedType)
JSIL.RuntimeError("Failed to resolve attribute type '" + this.type + "'")
return this.resolvedType = resolvedType;
};
JSIL.AttributeRecord.prototype.Construct = function () {
var resolvedType = this.GetType();
var constructorArguments;
if (this.getConstructorArguments)
this.constructorArguments = constructorArguments = this.getConstructorArguments();
else
this.constructorArguments = constructorArguments = [];
var instance = JSIL.CreateInstanceOfType(resolvedType, "_ctor", constructorArguments);
return instance;
};
JSIL.RawMethodRecord = function (name, isStatic) {
this.name = name;
this.isStatic = isStatic;
};
JSIL.ImplementExternals = function (namespaceName, externals) {
if (typeof (namespaceName) !== "string") {
JSIL.Host.abort(new Error("ImplementExternals expected name of namespace"));
return;
}
var trace = false;
var context = $private;
var queue = JSIL.ExternalsQueue[namespaceName];
if (!JSIL.IsArray(queue)) {
JSIL.ExternalsQueue[namespaceName] = queue = [];
}
var obj = JSIL.AllImplementedExternals[namespaceName];
if (typeof (obj) !== "object") {
JSIL.AllImplementedExternals[namespaceName] = obj = {};
}
if (obj.__IsInitialized__) {
JSIL.Host.abort(new Error("Type '" + namespaceName + "' already initialized"));
return;
}
if (typeof (externals) !== "function") {
if (trace)
JSIL.WarningFormat("Old-style ImplementExternals call for '{0}' ignored!", [namespaceName]);
return;
}
// Deferring the execution of externals functions is important in case they reference
// other types or assemblies.
queue.push(function ImplementExternalsImpl () {
var typeId = JSIL.AssignTypeId(context, namespaceName);
var typeObject = {
__Members__: [],
__RawMethods__: [],
__TypeId__: typeId,
__FullName__: namespaceName
};
var publicInterface = {
prototype: {
__TypeId__: typeId
},
__TypeId__: typeId
};
var ib = new JSIL.InterfaceBuilder(context, typeObject, publicInterface);
externals(ib);
var prefix = "instance$";
var m = typeObject.__Members__;
for (var i = 0; i < m.length; i++) {
var member = m[i];
var type = member.type;
var descriptor = member.descriptor;
var data = member.data;
var name = data.mangledName || descriptor.EscapedName;
var target = descriptor.Static ? publicInterface : publicInterface.prototype;
if (typeof (data.constant) !== "undefined") {
obj[descriptor.EscapedName + "$constant"] = data.constant;
} else if (data.mangledName) {
obj[descriptor.Static ? data.mangledName : prefix + data.mangledName] = [member, target[name]];
}
}
var rm = typeObject.__RawMethods__;
for (var i = 0; i < rm.length; i++) {
var rawMethod = rm[i];
var suffix = "$raw";
if (rawMethod.isStatic) {
obj[rawMethod.name + suffix] = [null, publicInterface[rawMethod.name]];
} else {
obj[prefix + rawMethod.name + suffix] = [null, publicInterface.prototype[rawMethod.name]];
}
}
});
};
JSIL.QueueTypeInitializer = function (type, initializer) {
if (type.__TypeInitialized__) {
initializer(type);
} else {
type.__Initializers__.push(initializer);
}
};
JSIL.Initialize = function () {
// Seal all registered names so that their static constructors run on use
var arn = JSIL.AllRegisteredNames;
for (var i = 0, l = arn.length; i < l; i++)
arn[i].sealed = true;
// Necessary because we can't rely on membranes for these types.
JSIL.InitializeType($jsilcore.System.RuntimeType);
JSIL.InitializeType($jsilcore.System.Reflection.RuntimeAssembly);
JSIL.InitializeType($jsilcore.System.Object);
};
JSIL.GenericParameter = function (name, context) {
var key;
this.name = new JSIL.Name(name, context);
this.covariant = false;
this.contravariant = false;
if (typeof (context) === "string") {
key = JSIL.EscapeName(String(context)) + "$" + JSIL.EscapeName(String(name));
} else if (typeof (context.__TypeId__) === "undefined") {
JSIL.RuntimeError("Invalid context for generic parameter");
} else {
key = context.__TypeId__ + "$" + JSIL.EscapeName(String(name));
}
if (typeof (JSIL.$GenericParameterTypeIds[key]) === "undefined") {
var typeId = String(++JSIL.$NextTypeId);
JSIL.$GenericParameterTypeIds[key] = typeId;
JSIL.SetValueProperty(this, "__TypeId__", typeId);
} else {
JSIL.SetValueProperty(this, "__TypeId__", JSIL.$GenericParameterTypeIds[key]);
}
JSIL.SetValueProperty(this, "__ShortName__", name);
JSIL.SetValueProperty(this, "__FullName__", this.name.humanReadable);
};
JSIL.GenericParameter.prototype = Object.create(JSIL.TypeObjectPrototype);
JSIL.GenericParameter.prototype.in = function () {
this.contravariant = true;
return this;
};
JSIL.GenericParameter.prototype.out = function () {
this.covariant = true;
return this;
};
JSIL.GenericParameter.prototype.get = function (context) {
if (!context) {
JSIL.RuntimeError("No context provided when resolving generic parameter '" + this.name + "'");
return JSIL.AnyType;
}
return this.name.get(context);
};
JSIL.GenericParameter.prototype.toString = function () {
var result = "<GP ";
if (this.contravariant)
result += "in ";
if (this.covariant)
result += "out ";
result += this.name.humanReadable + ">";
return result;
};
JSIL.GenericParameter.prototype.get_IsGenericParameter = function () {
return true;
};
JSIL.GenericParameter.prototype.get_Name = function () {
return this.name.humanReadable;
};
JSIL.GenericParameter.prototype.__IsClosed__ = false;
JSIL.PositionalGenericParameter = function (name, context) {
this.index = parseInt(name.substr(2));
JSIL.SetValueProperty(this, "__TypeId__", name);
this.__Context__ = context || $jsilcore;
var fullNameDecl = {
configurable: true,
enumerable: true,
get: this.getFullName
};
Object.defineProperty(this, "__FullName__", fullNameDecl);
Object.defineProperty(this, "__FullNameWithoutArguments__", fullNameDecl);
};
JSIL.PositionalGenericParameter.prototype = Object.create(JSIL.TypeObjectPrototype);
JSIL.PositionalGenericParameter.prototype.getFullName = function () {
return "!!" + this.index;
};
JSIL.PositionalGenericParameter.prototype.get = function (context) {
if ((typeof (context) !== "object") && (typeof (context) !== "function")) {
JSIL.RuntimeError("No context provided when resolving generic method parameter #" + this.index);
return JSIL.AnyType;
}
JSIL.RuntimeError("Not implemented");
};
JSIL.PositionalGenericParameter.prototype.toString = function (context) {
if (
(typeof (context) === "object") && (context !== null) &&
(Object.getPrototypeOf(context) === JSIL.MethodSignature.prototype)
) {
return context.genericArgumentNames[this.index];
}
return "<Generic Method Parameter #" + this.index + ">";
};
JSIL.PositionalGenericParameter.prototype.get_IsGenericParameter = function () {
return true;
};
JSIL.PositionalGenericParameter.prototype.get_Name = function () {
return "!!" + this.index;
};
JSIL.PositionalGenericParameter.prototype.__IsClosed__ = false;
JSIL.NamespaceRef = function (context, namespace) {
if (arguments.length === 1) {
this.context = null;
this.namespace = arguments[0];
} else if (arguments.length === 2) {
this.context = context;
this.namespace = namespace;
} else {
JSIL.RuntimeError("Invalid argument count");
}
this.cachedReference = null;
};
JSIL.NamespaceRef.prototype.toString = function () {
var result = null;
result = "ref namespace " + this.namespace;
return result;
};
JSIL.NamespaceRef.prototype.get = function () {
if (this.cachedReference !== null)
return this.cachedReference;
var result = JSIL.ResolveName(this.context, this.namespace, true);
if (!result.exists())
JSIL.RuntimeError("The name '" + this.namespace + "' does not exist.");
this.cachedReference = result.get();
return this.cachedReference;
};
JSIL.NamespaceRef.prototype.TypeRef = function (name, genericArguments) {
return new JSIL.TypeRef(this, name, genericArguments);
};
JSIL.TypeRef = function (context, name, genericArguments) {
if (arguments.length === 1) {
this.context = null;
this.typeName = null;
this.genericArguments = null;
this.cachedReference = arguments[0];
} else {
if (typeof (name) === "string") {
this.context = context;
this.typeName = name;
this.genericArguments = genericArguments || $jsilcore.ArrayNull;
this.cachedReference = null;
} else {
JSIL.Host.abort(new Error("Invalid type reference: " + name + " in context " + context));
}
}
if (JSIL.IsArray(this.genericArguments)) {
for (var i = 0, l = this.genericArguments.length; i < l; i++) {
var ga = this.genericArguments[i];
if (typeof (ga) === "undefined")
JSIL.RuntimeError("Undefined passed as generic argument #" + i);
else if (ga === null)
JSIL.RuntimeError("Null passed as generic argument #" + i);
}
}
};
JSIL.TypeRef.prototype.getAssembly = function () {
if (
this.context &&
Object.getPrototypeOf(this.context) === JSIL.NamespaceRef.prototype
)
return this.context.context;
else
return this.context;
};
JSIL.TypeRef.prototype.getContext = function () {
if (
this.context &&
Object.getPrototypeOf(this.context) === JSIL.NamespaceRef.prototype
)
return this.context.get();
else
return this.context;
};
JSIL.TypeRef.prototype.getTypeName = function () {
if (
this.context &&
Object.getPrototypeOf(this.context) === JSIL.NamespaceRef.prototype
)
return this.context.namespace + "." + this.typeName;
else
return this.typeName;
};
JSIL.TypeRef.prototype.toString = function () {
var result = null;
if (this.typeName === null)
result = "ref " + JSIL.GetTypeName(this.cachedReference);
else
result = "ref " + this.getTypeName();
if (this.genericArguments && this.genericArguments.length) {
result += "[";
for (var i = 0, l = this.genericArguments.length; i < l; i++) {
result += this.genericArguments[i].toString();
if (i < (l - 1))
result += ", ";
}
result += "]";
}
return result;
};
JSIL.TypeRef.prototype.toName = function () {
var result = null;
if (this.typeName === null)
result = JSIL.GetTypeName(this.cachedReference);
else
result = this.getTypeName();
// HACK: System.Array[T] -> T[]
if (
(this.getTypeName() === "System.Array") &&
this.genericArguments &&
this.genericArguments.length
) {
return JSIL.TypeReferenceToName(this.genericArguments[0]) + "[]";
}
if (this.genericArguments && this.genericArguments.length) {
result += "[";
for (var i = 0, l = this.genericArguments.length; i < l; i++) {
result += JSIL.TypeReferenceToName(this.genericArguments[i]);
if (i < (l - 1))
result += ", ";
}
result += "]";
}
return result;
};
JSIL.TypeRef.prototype.getTypeId = function () {
if (this.cachedReference !== null)
return this.cachedReference.__TypeId__;
else {
var result = JSIL.AssignTypeId(this.getAssembly(), this.getTypeName());
if (this.genericArguments.length > 0) {
result += "[";
result += JSIL.HashTypeArgumentArray(this.genericArguments, this.getAssembly());
result += "]";
// print(result);
}
return result;
}
};
JSIL.TypeRef.prototype.bindGenericArguments = function (unbound) {
if (this.genericArguments.length > 0) {
var ga = this.genericArguments;
for (var i = 0, l = ga.length; i < l; i++) {
var arg = ga[i];
if (typeof (arg) === "string") {
if (arg.indexOf("!!") === 0) {
ga[i] = arg = new JSIL.PositionalGenericParameter(arg, this.getContext());
} else {
ga[i] = arg = new JSIL.TypeRef(this.context, arg);
}
}
if (typeof (arg) === "object" && Object.getPrototypeOf(arg) === JSIL.TypeRef.prototype) {
ga[i] = arg = arg.get(true);
}
}
return unbound.Of$NoInitialize.apply(unbound, ga);
}
return unbound;
};
JSIL.TypeRef.prototype.getNoInitialize = function () {
if (this.cachedReference !== null)
return this.cachedReference;
var result = JSIL.GetTypeByName(this.getTypeName(), this.getAssembly());
result = this.bindGenericArguments(result);
return result;
};
JSIL.TypeRef.prototype.get = function (allowPartiallyConstructed) {
if (this.cachedReference !== null)
return this.cachedReference;
if (allowPartiallyConstructed === true) {
var inFlight = $jsilcore.InFlightObjectConstructions[this.getTypeName()];
if (inFlight)
return inFlight.publicInterface;
}
var result = JSIL.ResolveName(this.getContext(), this.typeName, true);
if (!result.exists())
JSIL.RuntimeError("The name '" + this.typeName + "' does not exist.");
this.cachedReference = result.get();
try {
this.cachedReference = this.bindGenericArguments(this.cachedReference);
} catch (exc) {
var err = new Error("Failed to bind generic arguments for typeRef '" + this.toString() + "': " + String(exc));
err.innerException = exc;
throw err;
}
return this.cachedReference;
};
JSIL.TypeRef.prototype.genericParameter = function (name) {
return new JSIL.GenericParameter(name, this.getTypeName());
};
JSIL.AllRegisteredNames = [];
JSIL.AllImplementedExternals = {};
JSIL.ExternalsQueue = {};
// FIXME: Used to prevent cycles in type cachers from causing problems. Not sure if this is right.
$jsilcore.SuppressRecursiveConstructionErrors = 0;
// HACK: So we can allow a class's base class to include itself as a generic argument. :/
$jsilcore.InFlightObjectConstructions = JSIL.CreateDictionaryObject(null);
JSIL.RegisterName = function (name, privateNamespace, isPublic, creator, initializer) {
var privateName = JSIL.ResolveName(privateNamespace, name, true);
if (isPublic)
var publicName = JSIL.ResolveName(JSIL.GlobalNamespace, name, true);
var localName = JSIL.GetLocalName(name);
var existingInSameAssembly = JSIL.ResolveName(privateNamespace, name, false, false);
if (existingInSameAssembly && existingInSameAssembly.exists(false)) {
JSIL.DuplicateDefinitionWarning(name, false, existingInSameAssembly.get().__CallStack__ || null, privateNamespace);
return;
}
var state = {
creator: creator,
initializer: initializer,
sealed: false,
value: null,
constructing: false,
name: name
};
JSIL.AllRegisteredNames.push(state);
var getter = function RegisterName_getter (unseal) {
var result;
try {
if (state.constructing) {
if (($jsilcore.SuppressRecursiveConstructionErrors > 0) && state.value) {
JSIL.WarningFormat(
"Ignoring recursive construction of type '{0}'.",
[name]
);
return state.value;
} else {
var err = new Error("Recursive construction of type '" + name + "' detected.");
state.value = err;
throw err;
}
}
if (typeof (state.creator) === "function") {
state.constructing = true;
var cf = state.creator;
try {
result = cf();
if ((result === null) || ((typeof (result) !== "object") && (typeof (result) !== "function"))) {
var err = new Error("Invalid result from type creator for type '" + name + "'");
state.value = err;
throw err;
}
state.value = result;
} catch (exc) {
JSIL.Host.abort(exc);
} finally {
state.creator = null;
state.constructing = false;
}
} else {
result = state.value;
if (
(result === null) ||
(
(typeof (result) !== "object") &&
(typeof (result) !== "function")
)
) {
var err = new Error("Type initialization failed for type '" + name + "'");
state.value = err;
throw err;
}
}
if (typeof (state.initializer) === "function") {
var ifn = state.initializer;
state.constructing = true;
var setThisType = null;
try {
setThisType = ifn(result);
if (typeof(setThisType) === "function")
setThisType(result);
} catch (exc) {
JSIL.Host.abort(exc);
} finally {
state.initializer = null;
state.constructing = false;
}
}
if (typeof (unseal) !== "boolean") {
unseal = true;
}
if (state.sealed && unseal) {
state.sealed = false;
JSIL.InitializeType(result);
privateName.define({ value: result });
if (isPublic)
publicName.define({ value: result });
}
} finally {
}
return result;
};
privateName.setLazy(getter);
if (isPublic)
publicName.setLazy(getter);
JSIL.DefineTypeName(name, getter, isPublic);
// V8 closure leaks yaaaaaay
creator = null;
initializer = null;
};
JSIL.FixupPrototype = function (prototype, baseTypeObject, typeObject, typeName, isReferenceType) {
JSIL.SetValueProperty(prototype, "__ThisType__", typeObject);
JSIL.SetValueProperty(prototype, "__ThisTypeId__", typeObject.__TypeId__);
JSIL.SetValueProperty(prototype, "__BaseType__", baseTypeObject);
JSIL.SetValueProperty(prototype, "__ShortName__", JSIL.GetLocalName(typeName));
JSIL.SetValueProperty(prototype, "__FullName__", typeName);
JSIL.SetValueProperty(prototype, "__IsReferenceType__", Boolean(isReferenceType));
};
JSIL.MakeProto = function (baseType, typeObject, typeName, isReferenceType, assembly) {
var _ = JSIL.ResolveTypeReference(baseType, assembly);
var baseTypePublicInterface = _[0];
var baseTypeObject = _[1];
if (baseTypePublicInterface === Object)
baseTypeObject = null;
var prototype = JSIL.$GetSpecialType(typeName).prototype;
if (!prototype)
prototype = JSIL.CreatePrototypeObject(baseTypePublicInterface.prototype);
JSIL.FixupPrototype(prototype, baseTypeObject, typeObject, typeName, isReferenceType);
return prototype;
};
JSIL.MakeNumericType = function (baseType, typeName, isIntegral, typedArrayName) {
var typeArgs = {
BaseType: baseType,
Name: typeName,
GenericArguments: $jsilcore.ArrayNull,
IsReferenceType: false,
IsPublic: true,
ConstructorAcceptsManyArguments: false
};
JSIL.MakeType(typeArgs, function ($) {
$.SetValue("__IsNumeric__", true);
$.SetValue("__IsIntegral__", isIntegral);
$.SetValue("__IsNativeType__", true);
if (typedArrayName) {
var typedArrayCtorExists = false;
var checkFn = new Function("return typeof (" + typedArrayName + ") !== \"undefined\"");
var getFn = new Function("return " + typedArrayName);
try {
typedArrayCtorExists = checkFn();
} catch (exc) {
}
if (typedArrayCtorExists) {
$.SetValue("__TypedArray__", getFn());
var ctor = getFn();
var key = ctor.name || String(ctor);
$jsilcore.TypedArrayToType[key] = typeName;
} else
$.SetValue("__TypedArray__", null);
} else {
$.SetValue("__TypedArray__", null);
}
var castSpecialType;
if (typeName === "System.Char") {
castSpecialType = "char";
} else if (typeName == "System.Boolean") {
castSpecialType = "bool";
} else if (isIntegral) {
castSpecialType = "integer";
} else {
castSpecialType = "number";
}
JSIL.MakeCastMethods(
$.publicInterface, $.typeObject, castSpecialType
);
$.RawMethod(
true, "$OverflowCheck",
function OverflowCheck (value) {
var minValue = $.publicInterface.MinValue;
var maxValue = $.publicInterface.MaxValue;
if ((value < minValue) || (value > maxValue))
throw new System.OverflowException("Arithmetic operation resulted in an overflow.");
if ($.publicInterface.name == "System_Char") {
return String.fromCharCode((value.charCodeAt(0) | 0));
}
return (value | 0);
}
);
});
};
JSIL.MakeIndirectProperty = function (target, key, source) {
var hasValue = false, state;
var getter = function GetIndirectProperty () {
if (hasValue)
return state;
else
return source[key];
};
var setter = function SetIndirectProperty (value) {
hasValue = true;
return state = value;
};
Object.defineProperty(target, key, {
configurable: true,
enumerable: true,
get: getter,
set: setter
});
};
// FIXME: The $...Internal version returns null if no resolution was necessary,
// which isn't quite as convenient. This is still pretty ugly.
JSIL.ResolveGenericTypeReference = function (obj, context) {
var result = JSIL.$ResolveGenericTypeReferenceInternal(obj, context);
if (result === null)
return obj;
return result;
};
JSIL.$ResolveGenericTypeReferenceInternal = function (obj, context) {
if ((typeof (obj) !== "object") || (obj === null))
return null;
if (Object.getPrototypeOf(obj) === JSIL.GenericParameter.prototype) {
var result = obj.get(context);
if (
(typeof (result) === "undefined") ||
(result === null)
) {
if (JSIL.WarnAboutGenericResolveFailures) {
var errorText = "Failed to resolve generic parameter " + String(obj);
JSIL.Host.warning(errorText);
}
return null;
}
if (result === obj)
throw new System.InvalidOperationException("Cannot pass a generic parameter as its own value");
var result2 = JSIL.$ResolveGenericTypeReferenceInternal(result, context);
if (!result2)
return result;
else
return result2;
} else if (Object.getPrototypeOf(obj) === JSIL.TypeRef.prototype) {
var resolvedGa = [];
var anyChanges = false;
for (var i = 0, l = obj.genericArguments.length; i < l; i++) {
var unresolved = obj.genericArguments[i];
var resolved = JSIL.$ResolveGenericTypeReferenceInternal(unresolved, context);
if (resolved !== null) {
resolvedGa[i] = resolved;
anyChanges = true;
} else
resolvedGa[i] = unresolved;
}
if (anyChanges)
return new JSIL.TypeRef(obj.context, obj.getTypeName(), resolvedGa);
else
return null;
} else if (obj.__IsClosed__ === false) {
if (obj.__IsArray__) {
var elementType = JSIL.$ResolveGenericTypeReferenceInternal(obj.__ElementType__, context);
if (elementType !== null)
return System.Array.Of(elementType);
return null;
}
var ga = obj.__GenericArguments__ || $jsilcore.ArrayNull;
if (ga.length < 1)
return null;
var openType = obj.__OpenType__;
if (typeof (openType) !== "object")
return null;
var openPublicInterface = openType.__PublicInterface__;
var existingParameters = obj.__GenericArgumentValues__ || $jsilcore.ArrayNull;
var closedParameters = new Array(existingParameters.length);
for (var i = 0; i < closedParameters.length; i++) {
closedParameters[i] = JSIL.$ResolveGenericTypeReferenceInternal(
existingParameters[i], context
);
if (!closedParameters[i]) {
if (
(Object.getPrototypeOf(existingParameters[i]) === JSIL.GenericParameter.prototype) ||
(existingParameters[i].__IsClosed__ === false)
) {
if (JSIL.WarnAboutGenericResolveFailures)
JSIL.WarningFormat(
"Failed to resolve generic parameter #{0} of type reference '{1}'.",
[i, obj.toString()]
);
return null;
}
closedParameters[i] = existingParameters[i];
}
}
var result = openPublicInterface.Of.apply(openPublicInterface, closedParameters);
return result.__Type__;
}
return null;
};
JSIL.FoundGenericParameter = function (name, value) {
this.name = name;
this.value = value;
};
JSIL.FindGenericParameters = function (obj, type, resultList) {
// Walk through our base types and identify any unresolved generic parameters.
// This produces a list of parameters that need new values assigned in the target prototype.
if ((typeof (obj) !== "object") && (typeof (obj) !== "function"))
JSIL.RuntimeError("Cannot resolve generic parameters of non-object");
var currentType = type;
while ((typeof(currentType) !== "undefined") && (currentType !== null)) {
var localGa = currentType.__GenericArguments__ || $jsilcore.ArrayNull;
var localFullName = currentType.__FullNameWithoutArguments__ || currentType.__FullName__;
for (var i = 0, l = localGa.length; i < l; i++) {
var key = localGa[i];
var qualifiedName = new JSIL.Name(key, localFullName);
var value = qualifiedName.get(obj);
if ((typeof (value) === "object") && (value !== null)) {
if ((Object.getPrototypeOf(value) === JSIL.GenericParameter.prototype) || (!value.__IsClosed__)) {
resultList.push(new JSIL.FoundGenericParameter(qualifiedName, value));
}
}
}
currentType = currentType.__BaseType__;
if (
(typeof(currentType) === "object") &&
(currentType !== null) &&
(Object.getPrototypeOf(currentType) === JSIL.TypeRef.prototype)
)
currentType = currentType.get().__Type__;
}
};
JSIL.ResolveTypeReference = function (typeReference, context) {
var result = null;
if (
typeof (typeReference) === "undefined"
) {
JSIL.RuntimeError("Undefined type reference");
} else if (
typeof (typeReference) === "string"
) {
if (typeReference.indexOf("!!") === 0) {
result = new JSIL.PositionalGenericParameter(typeReference, context);
} else {
if (
(typeof (context) === "object") && (context !== null) &&
(Object.getPrototypeOf(context) === JSIL.MethodSignature.prototype)
) {
result = JSIL.GetTypeByName(typeReference, context.context);
} else {
result = JSIL.GetTypeByName(typeReference, context);
}
}
} else if (
typeof (typeReference) === "object"
) {
if (typeReference === null)
JSIL.RuntimeError("Null type reference");
if (Object.getPrototypeOf(typeReference) === JSIL.TypeRef.prototype)
result = typeReference.get();
else
result = typeReference;
} else if (
typeof (typeReference) === "function"
) {
result = typeReference;
} else {
result = typeReference;
}
if (typeof (result.__Type__) === "object") {
return [result, result.__Type__];
} else if (
typeof (result.__PublicInterface__) !== "undefined"
) {
return [result.__PublicInterface__, result];
} else {
return [result, result];
}
};
JSIL.ResolveTypeArgument = function (typeArg, context) {
var result = JSIL.ResolveTypeReference(typeArg, context)[1];
if (typeof (result) === "undefined")
JSIL.RuntimeError("Undefined passed as type argument");
else if (result === null)
JSIL.RuntimeError("Null passed as type argument");
return result;
};
JSIL.ResolveTypeArgumentArray = function (typeArgs, context) {
var resolvedArguments = typeArgs;
// Ensure that each argument is the public interface of a type (not the type object or a type reference)
for (var i = 0, l = resolvedArguments.length; i < l; i++)
resolvedArguments[i] = JSIL.ResolveTypeArgument(typeArgs[i], context);
return resolvedArguments;
};
JSIL.$GetTypeIDForHash = function (typeReference, context) {
var trType = typeof (typeReference);
var typeId;
if (trType === "undefined") {
JSIL.RuntimeError("Undefined passed as type argument");
} else if (typeReference === null) {
JSIL.RuntimeError("Null passed as type argument");
} else if (typeId = typeReference.__TypeId__) {
return typeId;
} else if (
trType === "string"
) {
if (typeReference.indexOf("!!") === 0) {
return typeReference;
} else {
if (typeof (context) === "undefined")
JSIL.RuntimeError("Context required");
return JSIL.AssignTypeId(context, typeReference);
}
} else if (
trType === "object"
) {
if (Object.getPrototypeOf(typeReference) === JSIL.TypeRef.prototype)
return typeReference.getTypeId();
}
JSIL.RuntimeError("Type missing type ID");
};
JSIL.HashTypeArgumentArray = function (typeArgs, context) {
if (typeArgs.length <= 0)
return "void";
var cacheKey = null;
for (var i = 0, l = typeArgs.length; i < l; i++) {
var typeId = JSIL.$GetTypeIDForHash(typeArgs[i], context);
if (i === 0)
cacheKey = typeId;
else
cacheKey += "," + typeId;
}
return cacheKey;
};
$jsilcore.$Of$NoInitialize = function () {
// This whole function would be 100x simpler if you could provide a prototype when constructing a function. Javascript sucks so much.
var staticClassObject = this;
var typeObject = this.__Type__;
var ga = typeObject.__GenericArguments__;
if (arguments.length != ga.length)
JSIL.RuntimeError("Invalid number of generic arguments for type '" + JSIL.GetTypeName(this) + "' (got " + arguments.length + ", expected " + ga.length + ")");
var cacheKey = JSIL.HashTypeArgumentArray(arguments, typeObject.__Context__);
var ofCache = typeObject.__OfCache__;
// If we do not return the same exact closed type instance from every call to Of(...), derivation checks will fail
var result = ofCache[cacheKey];
if (result)
return result;
var resolvedArguments = JSIL.ResolveTypeArgumentArray(
Array.prototype.slice.call(arguments)
);
var gaNames = typeObject.__GenericArgumentNames__;
if (!JSIL.IsArray(gaNames)) {
typeObject.__GenericArgumentNames__ = gaNames = [];
for (var i = 0; i < ga.length; i++)
gaNames[i] = new JSIL.Name(ga[i], typeObject.__FullName__);
}
var unresolvedBaseType;
if (typeObject.IsInterface)
// HACK
unresolvedBaseType = $jsilcore.System.Object.__Type__;
else
unresolvedBaseType = typeObject.__BaseType__;
var resolvedBaseType = unresolvedBaseType;
var resolveContext = null;
if (staticClassObject.prototype) {
resolveContext = JSIL.CreatePrototypeObject(staticClassObject.prototype);
} else {
resolveContext = JSIL.CreateSingletonObject(null);
}
for (var i = 0; i < resolvedArguments.length; i++) {
gaNames[i].set(resolveContext, resolvedArguments[i]);
}
// We need to resolve any generic arguments contained in the base type so that the base type of a closed generic type is also closed.
// thus, given Derived<T> : Base<T> and Base<U> : Object, Derived<int>.BaseType must be Base<int>, not Base<U>.
resolvedBaseType = JSIL.$ResolveGenericTypeReferenceInternal(resolvedBaseType, resolveContext);
if (!resolvedBaseType) {
resolvedBaseType = unresolvedBaseType;
}
JSIL.$ResolveGenericTypeReferences(typeObject, resolvedArguments);
var resultTypeObject = JSIL.CreateSingletonObject(typeObject);
// Since .Of() will now be called even for open types, we need to ensure that we flag
// the type as open if it has any unresolved generic parameters.
var isClosed = true;
for (var i = 0, l = arguments.length; i < l; i++) {
if (Object.getPrototypeOf(resolvedArguments[i]) === JSIL.GenericParameter.prototype)
isClosed = false;
else if (resolvedArguments[i].__IsClosed__ === false)
isClosed = false;
}
resultTypeObject.__IsClosed__ = isClosed;
var constructor;
if (typeObject.IsInterface) {
constructor = function Interface__ctor () {
JSIL.RuntimeError("Cannot construct an instance of an interface");
};
} else if (typeObject.__IsNullable__ === true) {
constructor = function Nullable__ctor () {
JSIL.RuntimeError("Cannot construct an instance of Nullable");
};
} else {
constructor = JSIL.MakeTypeConstructor(resultTypeObject, typeObject.__MaxConstructorArguments__);
}
JSIL.SetValueProperty(resultTypeObject, "__PublicInterface__", result = constructor);
resultTypeObject.__OpenType__ = typeObject;
JSIL.SetValueProperty(resultTypeObject, "__BaseType__", resolvedBaseType);
result.__Type__ = resultTypeObject;
resultTypeObject.__RenamedMethods__ = JSIL.CreateDictionaryObject(typeObject.__RenamedMethods__ || null);
// Prevents recursion when Of is called indirectly during initialization of the new closed type
ofCache[cacheKey] = result;
if (staticClassObject.prototype) {
// Given Derived<T> : Base<T> and Base<U> : Object, the prototype of Derived<T> instances must have this chain:
// Derived<T> -> Base<T> -> Object, not:
// Derived<T> -> Derived -> Base<U> -> Object
var basePrototype = resolvedBaseType.__PublicInterface__.prototype;
var resultPrototype = JSIL.CreatePrototypeObject(basePrototype);
result.prototype = resultPrototype;
JSIL.$CopyMembersIndirect(resultPrototype, staticClassObject.prototype, JSIL.$IgnoredPrototypeMembers, false);
var genericParametersToResolve = [];
JSIL.FindGenericParameters(result.prototype, resultTypeObject, genericParametersToResolve);
for (var i = 0; i < genericParametersToResolve.length; i++) {
var qualifiedName = genericParametersToResolve[i].name;
var value = genericParametersToResolve[i].value;
var resolved = JSIL.$ResolveGenericTypeReferenceInternal(value, resolveContext);
if (resolved !== null) {
// console.log(qualifiedName.humanReadable, " ", value, " -> ", resolved);
qualifiedName.defineProperty(
result.prototype, {
value: resolved,
enumerable: true,
configurable: true
}
);
}
}
}
JSIL.$CopyMembersIndirect(result, staticClassObject, JSIL.$IgnoredPublicInterfaceMembers, true);
var fullName = typeObject.__FullName__ + "[";
for (var i = 0; i < resolvedArguments.length; i++) {
if (i > 0)
fullName += ",";
var arg = resolvedArguments[i];
var stringified = arg.__FullName__; // || String(arg);
if (!stringified)
JSIL.RuntimeError("No name for generic argument #" + i + " to closed form of type " + typeObject.__FullName__);
fullName += stringified;
}
fullName += "]";
var typeId = typeObject.__TypeId__ + "[";
for (var i = 0; i < resolvedArguments.length; i++) {
if (i > 0)
typeId += ",";
typeId += resolvedArguments[i].__TypeId__;
}
typeId += "]";
JSIL.SetTypeId(result, resultTypeObject, typeId);
resultTypeObject.__ReflectionCache__ = null;
resultTypeObject.__GenericArgumentValues__ = resolvedArguments;
resultTypeObject.__FullNameWithoutArguments__ = typeObject.__FullName__;
JSIL.SetValueProperty(resultTypeObject, "__FullName__", fullName);
JSIL.SetValueProperty(resultTypeObject, "toString",
function GenericType_ToString () {
return JSIL.GetTypeName(this, true);
}
);
JSIL.SetValueProperty(result, "toString",
function GenericTypePublicInterface_ToString () {
return "<" + this.__Type__.__FullName__ + " Public Interface>";
}
);
result.__Self__ = result;
if (typeof (result.prototype) !== "undefined") {
JSIL.SetValueProperty(result.prototype, "__ThisType__", resultTypeObject);
JSIL.SetValueProperty(result.prototype, "__ThisTypeId__", resultTypeObject.__TypeId__);
JSIL.SetValueProperty(result.prototype, "__FullName__", fullName);
}
// This is important: It's possible for recursion to cause the initializer to run while we're defining properties.
// We prevent this from happening by forcing the initialized state to true.
resultTypeObject.__TypeInitialized__ = true;
// Resolve any generic parameter references in the interfaces this type implements.
var interfaces = resultTypeObject.__Interfaces__ = [];
var sourceInterfaces = typeObject.__Interfaces__;
var writeGenericArgument = function (key, name, resolvedArgument) {
var getter = function GetGenericArgument () {
return name.get(this);
}
var decl = {
configurable: true,
enumerable: true,
value: resolvedArgument
};
var getterDecl = {
configurable: true,
enumerable: true,
get: getter
};
name.defineProperty(result, decl);
if (key)
Object.defineProperty(result, key, getterDecl);
if (result.prototype) {
name.defineProperty(result.prototype, decl);
if (key)
Object.defineProperty(result.prototype, key, getterDecl);
}
};
for (var i = 0, l = sourceInterfaces.length; i < l; i++) {
var unresolvedInterface = sourceInterfaces[i];
var resolvedInterface = JSIL.$ResolveGenericTypeReferenceInternal(unresolvedInterface, resolveContext);
if (resolvedInterface === null)
resolvedInterface = unresolvedInterface;
// It's possible there are duplicates in the interface list.
if (interfaces.indexOf(resolvedInterface) >= 0)
continue;
interfaces.push(resolvedInterface);
if (resolvedInterface !== unresolvedInterface) {
var resolvedInterfaceTypeObj = JSIL.ResolveTypeReference(resolvedInterface)[1];
var names = resolvedInterfaceTypeObj.__OpenType__.__GenericArgumentNames__;
for (var j = 0, l2 = names.length; j < l2; j++) {
var name = names[j];
var value = resolvedInterfaceTypeObj.__GenericArgumentValues__[j];
writeGenericArgument(null, name, value);
}
}
}
for (var i = 0, l = resolvedArguments.length; i < l; i++) {
var key = ga[i];
var escapedKey = JSIL.EscapeName(key);
var name = new JSIL.Name(key, resultTypeObject.__FullNameWithoutArguments__);
writeGenericArgument(escapedKey, name, resolvedArguments[i]);
}
if (typeObject.IsInterface)
JSIL.CopyObjectValues(resolveContext, result.prototype, false);
if (isClosed) {
resultTypeObject.__AssignableFromTypes__ = {};
JSIL.ResolveGenericMemberSignatures(result, resultTypeObject);
JSIL.RenameGenericMethods(result, resultTypeObject);
JSIL.RebindRawMethods(result, resultTypeObject);
JSIL.FixupFieldTypes(result, resultTypeObject);
JSIL.ResolveGenericExternalMethods(result, resultTypeObject);
} else {
resultTypeObject.__OfCache__ = {};
}
JSIL.MakeCastMethods(result, resultTypeObject, typeObject.__CastSpecialType__);
// Force the initialized state back to false
resultTypeObject.__TypeInitialized__ = false;
return result;
};
$jsilcore.$MakeOf$NoInitialize = function (publicInterface) {
var fn = $jsilcore.$Of$NoInitialize;
return function Of$NoInitialize_bound () {
return fn.apply(publicInterface, arguments);
};
};
$jsilcore.$MakeOf = function (publicInterface) {
var typeObject = publicInterface.__Type__;
var typeName = typeObject.__FullName__;
return JSIL.CreateNamedFunction(
typeName + ".Of", [],
"var result = publicInterface.Of$NoInitialize.apply(publicInterface, arguments);\r\n" +
"// If the outer type is initialized, initialize the inner type.\r\n" +
"if (!result.__Type__.__TypeInitialized__ && typeObject.__TypeInitialized__)\r\n" +
" JSIL.InitializeType(result);\r\n" +
"return result;",
{
publicInterface: publicInterface,
typeObject: typeObject
}
);
};
JSIL.StaticClassPrototype = {};
JSIL.StaticClassPrototype.toString = function () {
return JSIL.GetTypeName(JSIL.GetType(this), true);
};
JSIL.$ResolveGenericMethodSignature = function (typeObject, signature, resolveContext) {
var returnType = [signature.returnType];
var argumentTypes = Array.prototype.slice.call(signature.argumentTypes);
var genericArgumentNames = signature.genericArgumentNames;
var changed = JSIL.$ResolveGenericTypeReferences(resolveContext, returnType);
changed = JSIL.$ResolveGenericTypeReferences(resolveContext, argumentTypes) || changed;
if (changed)
return new JSIL.MethodSignature(returnType[0], argumentTypes, genericArgumentNames, typeObject.__Context__, signature);
/*
if (!signature.IsClosed) {
console.log("Resolving failed for open signature", signature, "with context", resolveContext);
}
*/
return null;
};
// Static RawMethods need to be rebound so that their 'this' reference is the publicInterface
// of the type object.
JSIL.RebindRawMethods = function (publicInterface, typeObject) {
var rm = typeObject.__RawMethods__;
var isGeneric = typeObject.__OpenType__;
if (JSIL.IsArray(rm)) {
for (var i = 0; i < rm.length; i++) {
var item = rm[i];
var methodName = item.name;
if (item.isStatic) {
var method = publicInterface[methodName];
// FIXME: Stop using Function.bind here, it's slow
var boundMethod = method.bind(publicInterface);
JSIL.SetValueProperty(publicInterface, methodName, boundMethod);
}
}
}
// Rebind CheckType for delegate types so that it uses the new closed delegate type
if (typeObject.__IsDelegate__) {
JSIL.SetValueProperty(
publicInterface, "CheckType",
$jsilcore.CheckDelegateType.bind(typeObject)
);
}
}
// Any methods with generic parameters as their return type or argument type(s) must be renamed
// after the generic type is closed; otherwise overload resolution will fail to locate them because
// the method signature won't match.
// We also need to copy any methods without generic parameters over from the open version of the type's prototype.
JSIL.RenameGenericMethods = function (publicInterface, typeObject) {
var members = typeObject.__Members__;
if (!JSIL.IsArray(members))
return;
members = typeObject.__Members__ = Array.prototype.slice.call(members);
var resolveContext = typeObject.__IsStatic__ ? publicInterface : publicInterface.prototype;
var rm = typeObject.__RenamedMethods__;
var trace = false;
var throwOnFail = false;
var isInterface = typeObject.IsInterface;
_loop:
for (var i = 0, l = members.length; i < l; i++) {
var member = members[i];
switch (member.type) {
case "MethodInfo":
case "ConstructorInfo":
break;
default:
continue _loop;
}
var descriptor = member.descriptor;
var data = member.data;
var signature = data.signature;
var genericSignature = data.genericSignature;
var unqualifiedName = descriptor.EscapedName;
var oldName = data.mangledName;
var target = descriptor.Static ? publicInterface : publicInterface.prototype;
if (isInterface) {
var oldObject = publicInterface[unqualifiedName];
if (!oldObject)
JSIL.RuntimeError("Failed to find unrenamed generic interface method");
if (!signature.IsClosed) {
genericSignature = signature;
signature = JSIL.$ResolveGenericMethodSignature(
typeObject, genericSignature, resolveContext
);
if (!signature) {
if (throwOnFail) {
JSIL.RuntimeError("Failed to resolve generic signature", genericSignature);
} else {
signature = genericSignature;
}
}
}
var newObject = oldObject.Rebind(typeObject, signature);
JSIL.SetValueProperty(publicInterface, unqualifiedName, newObject);
if (trace)
console.log(typeObject.__FullName__ + ": " + unqualifiedName + " rebound");
} else {
// If the method is already renamed, don't bother trying to rename it again.
// Renaming it again would clobber the rename target with null.
if (typeof (rm[oldName]) !== "undefined") {
if (trace)
console.log(typeObject.__FullName__ + ": " + oldName + " not found");
continue;
}
if ((genericSignature !== null) && (genericSignature.get_Hash() != signature.get_Hash())) {
var newName = signature.GetNamedKey(descriptor.EscapedName, true);
var methodReference = JSIL.$FindMethodBodyInTypeChain(typeObject, descriptor.Static, oldName, false);
if (!methodReference)
JSIL.RuntimeError("Failed to find unrenamed generic method");
typeObject.__RenamedMethods__[oldName] = newName;
delete target[oldName];
JSIL.SetValueProperty(target, newName, methodReference);
if (trace)
console.log(typeObject.__FullName__ + ": " + oldName + " -> " + newName);
}
}
}
};
JSIL.FixupFieldTypes = function (publicInterface, typeObject) {
var members = typeObject.__Members__;
if (!JSIL.IsArray(members))
return;
var members = typeObject.__Members__ = Array.prototype.slice.call(members);
var resolveContext = publicInterface.prototype;
var rm = typeObject.__RenamedMethods__;
var trace = false;
var resolvedFieldTypeRef, resolvedFieldType;
_loop:
for (var i = 0, l = members.length; i < l; i++) {
var member = members[i];
if (member.type !== "FieldInfo")
continue _loop;
var descriptor = member.descriptor;
var data = member.data;
var fieldType = data.fieldType;
resolvedFieldTypeRef = JSIL.$ResolveGenericTypeReferenceInternal(fieldType, resolveContext);
if (resolvedFieldTypeRef !== null)
resolvedFieldType = JSIL.ResolveTypeReference(resolvedFieldTypeRef, typeObject.__Context__)[1];
else
resolvedFieldType = fieldType;
var newData = JSIL.CreateDictionaryObject(data);
newData.fieldType = resolvedFieldType;
members[i] = new JSIL.MemberRecord(member.type, member.descriptor, newData, member.attributes, member.overrides);
}
};
JSIL.InstantiateProperties = function (publicInterface, typeObject) {
var originalTypeObject = typeObject;
var recursed = false;
while ((typeof (typeObject) !== "undefined") && (typeObject !== null)) {
var currentPublicInterface = typeObject.__PublicInterface__;
var ps = typeObject.__Properties__;
if (JSIL.IsArray(ps)) {
var typeShortName = typeObject.__ShortName__;
for (var i = 0, l = ps.length; i < l; i++) {
var property = ps[i];
var isStatic = property[0];
var name = property[1];
var isVirtual = property[2];
var methodSource = publicInterface;
if (isStatic)
JSIL.InterfaceBuilder.MakeProperty(typeShortName, name, publicInterface, methodSource, recursed);
else
JSIL.InterfaceBuilder.MakeProperty(typeShortName, name, publicInterface.prototype, methodSource.prototype, recursed);
}
}
typeObject = typeObject.__BaseType__;
recursed = true;
}
};
$jsilcore.CanFixUpEnumInterfaces = false;
JSIL.FixupInterfaces = function (publicInterface, typeObject) {
var trace = false;
if (typeObject.__FullName__ === "System.Enum") {
if (!$jsilcore.CanFixUpEnumInterfaces)
return;
else
/* trace = true */;
}
// FIXME: Is this right? I think it might be. We don't actually use the types,
// just use their type objects as tokens for comparisons.
if (typeObject.__IsFixingUpInterfaces__)
return;
if (typeObject.IsInterface)
return;
// This is the table of interfaces that is used by .Overrides' numeric indices.
var indexedInterfaceTable = JSIL.GetInterfacesImplementedByType(typeObject, false, false);
// This is the table of every interface we actually implement (exhaustively).
var interfaces = JSIL.GetInterfacesImplementedByType(typeObject, true, false);
if (!interfaces.length)
return;
typeObject.__IsFixingUpInterfaces__ = true;
var context = typeObject.__Context__;
var typeName = typeObject.__FullName__;
var missingMembers = [];
var ambiguousMembers = [];
var typeMembers = JSIL.GetMembersInternal(typeObject, $jsilcore.BindingFlags.$Flags("Instance", "NonPublic", "Public"));
var resolveContext = typeObject.__IsStatic__ ? publicInterface : publicInterface.prototype;
__interfaces__:
for (var i = 0, l = interfaces.length; i < l; i++) {
var iface = interfaces[i];
if (typeof (iface) === "undefined") {
JSIL.WarningFormat(
"Type '{0}' implements an undefined interface.",
[typeName]
);
continue __interfaces__;
} else if (typeof (iface) === "string") {
var resolved = JSIL.ResolveName(
context, iface, true
);
if (resolved.exists())
iface = resolved.get();
else {
JSIL.WarningFormat(
"Type '{0}' implements an undefined interface named '{1}'.",
[typeName, iface]
);
interfaces[i] = null;
continue __interfaces__;
}
} else if ((typeof (iface) === "object") && (typeof (iface.get) === "function")) {
var resolvedGenericInterface = JSIL.$ResolveGenericTypeReferenceInternal(iface, resolveContext);
try {
if (resolvedGenericInterface)
iface = resolvedGenericInterface.get();
else
iface = iface.get();
} catch (exc) {
JSIL.WarningFormat(
"Type '{0}' implements an interface named '{1}' that could not be resolved: {2}",
[typeName, String(iface.getTypeName() || iface), exc]
);
interfaces[i] = null;
continue __interfaces__;
}
}
if (typeof (iface.__Type__) === "object")
iface = iface.__Type__;
interfaces[i] = iface;
var ifaceName = iface.__FullNameWithoutArguments__ || iface.__FullName__;
var ifaceLocalName = JSIL.GetLocalName(ifaceName);
if (iface.IsInterface !== true) {
JSIL.Host.warning("Type " + ifaceName + " is not an interface.");
continue __interfaces__;
}
// In cases where an interface method (IInterface_MethodName) is implemented by a regular method
// (MethodName), we make a copy of the regular method with the name of the interface method, so
// that attempts to directly invoke the interface method will still work.
var members = JSIL.GetMembersInternal(
iface,
$jsilcore.BindingFlags.$Flags("DeclaredOnly", "Instance", "NonPublic", "Public")
);
var proto = publicInterface.prototype;
var escapedLocalName = JSIL.EscapeName(ifaceLocalName);
var hasOwn = function (name) {
return Object.prototype.hasOwnProperty.call(proto, name);
};
var hasNonPlaceholder = function (obj, name) {
var value = obj[name];
if ((typeof (value) === "undefined") ||
(value === null))
return false;
if (value.__IsPlaceholder__)
return false;
return true;
}
__members__:
for (var j = 0; j < members.length; j++) {
var member = members[j];
var qualifiedName = JSIL.$GetSignaturePrefixForType(iface) + member._descriptor.EscapedName;
var signature = member._data.signature || null;
var signatureQualifiedName = null;
if (signature) {
signatureQualifiedName = signature.GetNamedKey(qualifiedName, true);
}
if (signature
&& hasNonPlaceholder(proto, signatureQualifiedName)
&& hasOwn(signatureQualifiedName)
)
continue;
if (
hasNonPlaceholder(proto, qualifiedName)
&& hasOwn(qualifiedName)
)
continue;
var isMissing = false, isAmbiguous = false;
switch (member.__MemberType__) {
case "MethodInfo":
case "ConstructorInfo":
// FIXME: Match signatures
var matchingMethods = typeObject.$GetMatchingInstanceMethods(
member.get_Name(), member.GetParameterTypes(), member.get_ReturnType()
);
if (matchingMethods.length === 0) {
isMissing = true;
} else if (matchingMethods.length > 1) {
isAmbiguous = true;
} else {
var implementation = matchingMethods[0];
var sourceQualifiedName = implementation._data.signature.GetNamedKey(
implementation._descriptor.EscapedName, true
);
if (trace)
console.log(typeName + "::" + signatureQualifiedName + " (" + iface + ") = " + sourceQualifiedName);
JSIL.SetLazyValueProperty(
proto, signatureQualifiedName,
JSIL.MakeInterfaceMemberGetter(proto, sourceQualifiedName)
);
}
break;
default:
// FIXME: Not implemented
break;
}
if (isMissing)
missingMembers.push(signatureQualifiedName || qualifiedName);
else if (isAmbiguous)
ambiguousMembers.push(signatureQualifiedName || qualifiedName);
}
if (interfaces.indexOf(iface) < 0)
interfaces.push(iface);
}
// Now walk all the members defined in the typeObject itself, and see if any of them explicitly override
// an interface member (.overrides in IL, .Overrides() in JS)
for (var i = 0; i < typeMembers.length; i++) {
var member = typeMembers[i];
var overrides = member.__Overrides__;
if (!overrides || !overrides.length)
continue;
if (member._data.isExternal) {
if (trace)
console.log("Skipping external method '" + member._descriptor.EscapedName + "'");
continue;
}
for (var j = 0; j < overrides.length; j++) {
var override = overrides[j];
var iface = null;
switch (typeof (override.interfaceNameOrReference)) {
case "object":
iface = JSIL.ResolveTypeReference(override.interfaceNameOrReference)[1];
break;
case "string":
// Search for interfaces that have an exact name match.
// Doing this first ensures that "IFoo" does not match "IFoo`1" if "IFoo" is also in the list..
var matchingInterfaces = interfaces.filter(function (iface) {
return iface.__FullName__ === override.interfaceNameOrReference;
});
// If we didn't find any exact matches, search for a prefix match.
// This ensures that we can write something like 'IList`1' to match 'System.Collections.Generic.IList`1' if we are super lazy and terrible.
if (matchingInterfaces.length === 0)
matchingInterfaces = interfaces.filter(function (iface) {
return iface.__FullName__.indexOf(override.interfaceNameOrReference) >= 0;
});
if (matchingInterfaces.length > 1) {
// TODO: Enable this warning?
/*
JSIL.RuntimeError(
"Member '" + member._descriptor.EscapedName +
"' overrides interface '" + override.interfaceNameOrReference +
"' but " + matchingInterfaces.length + " interfaces match that name: \r\n" +
"\r\n".join(matchingInterfaces)
);
*/
iface = matchingInterfaces[0];
} else if (matchingInterfaces.length === 0) {
iface = null;
} else {
iface = matchingInterfaces[0];
}
break;
}
if (!iface)
JSIL.RuntimeErrorFormat(
"Member '{0}::{1}' overrides nonexistent interface member '{2}::{3}'",
[
typeObject.__FullName__, member._descriptor.EscapedName,
override.interfaceNameOrReference, override.interfaceMemberName
]
);
var interfaceQualifiedName = JSIL.$GetSignaturePrefixForType(iface) + JSIL.EscapeName(override.interfaceMemberName);
var key = member._data.signature.GetNamedKey(interfaceQualifiedName, true);
var missingIndex = missingMembers.indexOf(key);
if (missingIndex >= 0)
missingMembers.splice(missingIndex, 1);
if (trace) {
console.log("Overrides set " + typeName + "::" + key + " (#" + override.interfaceNameOrReference + "=" + iface + ") = " + member._descriptor.EscapedName);
}
// Important: This may overwrite an existing member with this key, from an automatic interface fixup
// like 'Foo.GetEnumerator' -> 'Foo.Ixx$GetEnumerator'.
// This is desirable because an explicit override (via .Overrides) should always trump automatic
// overrides via name/signature matching.
JSIL.SetLazyValueProperty(proto, key, JSIL.MakeInterfaceMemberGetter(proto, member._descriptor.EscapedName));
}
}
if (missingMembers.length > 0) {
if ((JSIL.SuppressInterfaceWarnings !== true) || trace)
JSIL.Host.warning("Type '" + typeObject.__FullName__ + "' is missing implementation of interface member(s): " + missingMembers.join(", "));
}
if (ambiguousMembers.length > 0) {
if ((JSIL.SuppressInterfaceWarnings !== true) || trace)
JSIL.Host.warning("Type '" + typeObject.__FullName__ + "' has ambiguous implementation of interface member(s): " + ambiguousMembers.join(", "));
}
typeObject.__IsFixingUpInterfaces__ = false;
};
$jsilcore.BuildingFieldList = new Array();
JSIL.GetFieldList = function (typeObject) {
var fl = typeObject.__FieldList__;
if (fl === $jsilcore.ArrayNotInitialized) {
fl = $jsilcore.BuildingFieldList;
fl = JSIL.$BuildFieldList(typeObject);
} else if (fl === $jsilcore.BuildingFieldList) {
JSIL.RuntimeError("Recursive invocation of GetFieldList on type " + typeObject.__FullName__);
}
if ((fl === $jsilcore.ArrayNull) || (!JSIL.IsArray(fl)))
return $jsilcore.ArrayNull;
return fl;
};
JSIL.EscapeJSIdentifier = function (identifier) {
var nameRe = /[^A-Za-z_0-9\$]/g;
return JSIL.EscapeName(identifier).replace(nameRe, "_");
};
JSIL.GetObjectKeys = function (obj) {
// This is a .NET object, so return the names of any public fields/properties.
if (obj && obj.GetType) {
var typeObject = obj.GetType();
var bindingFlags = $jsilcore.BindingFlags.$Flags("Instance", "Public");
var fields = JSIL.GetMembersInternal(typeObject, bindingFlags, "FieldInfo");
var properties = JSIL.GetMembersInternal(typeObject, bindingFlags, "PropertyInfo");
var result = [];
for (var i = 0, l = fields.length; i < l; i++)
result.push(fields[i].get_Name());
for (var i = 0, l = properties.length; i < l; i++)
result.push(properties[i].get_Name());
return result;
} else {
return Object.keys(obj);
}
};
JSIL.CreateNamedFunction = function (name, argumentNames, body, closure) {
var result = null, keys = null, closureArgumentList = null;
if (closure) {
keys = JSIL.GetObjectKeys(closure);
closureArgumentList = new Array(keys.length);
for (var i = 0, l = keys.length; i < l; i++)
closureArgumentList[i] = closure[keys[i]];
}
var constructor = JSIL.CreateRebindableNamedFunction(name, argumentNames, body, closure);
result = constructor.apply(null, closureArgumentList);
return result;
};
JSIL.CreateRebindableNamedFunction = function (name, argumentNames, body, closure) {
var uriRe = /[\<\>\+\/\\\.]/g;
var strictPrefix = "\"use strict\";\r\n";
var uriPrefix = "//# sourceURL=jsil://closure/" + name + "\r\n";
var escapedFunctionIdentifier = JSIL.EscapeJSIdentifier(name);
var rawFunctionText = "function " + escapedFunctionIdentifier + "(" +
argumentNames.join(", ") +
") {\r\n" +
body +
"\r\n};\r\n";
var lineBreakRE = /\r(\n?)/g;
rawFunctionText =
uriPrefix + strictPrefix +
rawFunctionText.replace(lineBreakRE, "\r\n ") +
" return " + escapedFunctionIdentifier + ";\r\n";
var result = null, keys = null;
if (closure) {
keys = JSIL.GetObjectKeys(closure).concat([rawFunctionText]);
} else {
keys = [rawFunctionText];
}
result = Function.apply(Function, keys);
return result;
};
JSIL.FormatMemberAccess = function (targetExpression, memberName) {
// Can't reuse a global instance because .test mutates the RegExp. JavaScript is stupid.
var shortMemberRegex = /^[_a-zA-Z][a-zA-Z_0-9]*$/g;
if (typeof (memberName) !== "string")
JSIL.RuntimeError("Member name must be a string");
if (shortMemberRegex.test(memberName)) {
return targetExpression + "." + memberName;
} else {
return targetExpression + "['" + memberName + "']";
}
};
JSIL.MakeFieldInitializer = function (typeObject, returnNamedFunction) {
var fl = JSIL.GetFieldList(typeObject);
if ((fl.length < 1) && returnNamedFunction)
return $jsilcore.FunctionNull;
var prototype = typeObject.__PublicInterface__.prototype;
var body = [];
var targetArgName = returnNamedFunction ? "target" : "this";
var initializerClosure = null;
if (typeObject.__IsUnion__) {
var sizeBytes = typeObject.__NativeSize__;
body.push(JSIL.FormatMemberAccess(targetArgName, "$backingStore") + " = new Uint8Array(" + sizeBytes + ");");
// HACK: Generate accessors for the (now missing) fields that hit our backing store
JSIL.$GenerateUnionAccessors(typeObject, fl, body, targetArgName);
} else {
var types = {};
var defaults = {};
for (var i = 0, l = fl.length; i < l; i++) {
var field = fl[i];
if ((field.type === typeObject) && (field.isStruct)) {
JSIL.Host.warning("Ignoring self-typed struct field " + field.name);
continue;
}
var key = "f" + i.toString();
if (field.isStruct) {
if (field.type.__IsNullable__) {
body.push(JSIL.FormatMemberAccess(targetArgName, field.name) + " = null;");
} else {
body.push(JSIL.FormatMemberAccess(targetArgName, field.name) + " = new types." + key + "();");
types[key] = field.type.__PublicInterface__;
}
} else if (field.type.__IsNativeType__ && field.type.__IsNumeric__) {
// This is necessary because JS engines are incredibly dumb about figuring out the actual type(s)
// an object's field slots should be.
var defaultValueString;
if (field.type.__FullName__ === "System.Boolean") {
defaultValueString = "(false)";
} else if (field.type.__FullName__ === "System.Char") {
defaultValueString = "('\\0')";
} else if (field.type.__IsIntegral__) {
defaultValueString = "(0 | 0)";
} else {
defaultValueString = "(+0.0)";
}
body.push(JSIL.FormatMemberAccess(targetArgName, field.name) + " = " + defaultValueString + ";");
} else {
body.push(JSIL.FormatMemberAccess(targetArgName, field.name) + " = defaults." + key + ";");
if (typeof (field.defaultValueExpression) === "function") {
// FIXME: This wants a this-reference?
defaults[key] = field.defaultValueExpression();
} else if (field.defaultValueExpression) {
defaults[key] = field.defaultValueExpression;
} else {
defaults[key] = JSIL.DefaultValue(field.type);
}
}
}
initializerClosure = {
types: types,
defaults: defaults
};
}
if (returnNamedFunction) {
var boundFunction = JSIL.CreateNamedFunction(
typeObject.__FullName__ + ".InitializeFields",
["target"],
body.join("\r\n"),
initializerClosure
);
boundFunction.__ThisType__ = typeObject;
JSIL.SetValueProperty(boundFunction, "__ThisTypeId__", typeObject.__TypeId__);
return boundFunction;
} else {
return [body, initializerClosure];
}
};
JSIL.GetFieldInitializer = function (typeObject) {
var fi = typeObject.__FieldInitializer__;
if (fi === $jsilcore.FunctionNotInitialized)
typeObject.__FieldInitializer__ = fi = JSIL.MakeFieldInitializer(typeObject, true);
return fi;
};
JSIL.InitializeInstanceFields = function (instance, typeObject) {
var fi = JSIL.GetFieldInitializer(typeObject);
if (fi === $jsilcore.FunctionNull)
return;
fi(instance);
};
JSIL.CopyObjectValues = function (source, target, allowOverwrite) {
for (var k in source) {
if (!Object.prototype.hasOwnProperty.call(source, k))
continue;
if (allowOverwrite === false) {
if (k in target)
continue;
}
target[k] = source[k];
}
};
JSIL.CopyMembers = function (source, target) {
var thisType = source.__ThisType__;
var copier = thisType.__MemberCopier__;
if (copier === $jsilcore.FunctionNotInitialized)
copier = thisType.__MemberCopier__ = JSIL.$MakeMemberCopier(thisType, thisType.__PublicInterface__);
copier(source, target);
};
JSIL.$MakeComparerCore = function (typeObject, context, body) {
var fields = JSIL.GetFieldList(typeObject);
if (context.prototype.__CompareMembers__) {
context.comparer = context.prototype.__CompareMembers__;
body.push(" return context.comparer(lhs, rhs);");
} else {
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
var fieldType = field.type;
if (fieldType.__IsNumeric__ || fieldType.__IsEnum__) {
body.push(" if (" + JSIL.FormatMemberAccess("lhs", field.name) + " !== " + JSIL.FormatMemberAccess("rhs", field.name) + ")");
} else {
body.push(" if (!JSIL.ObjectEquals(" + JSIL.FormatMemberAccess("lhs", field.name) + ", " + JSIL.FormatMemberAccess("rhs", field.name) + "))");
}
body.push(" return false;");
}
body.push(" return true;");
}
}
JSIL.$MakeStructComparer = function (typeObject, publicInterface) {
var prototype = publicInterface.prototype;
var context = {
prototype: prototype
};
var body = [];
JSIL.$MakeComparerCore(typeObject, context, body);
return JSIL.CreateNamedFunction(
typeObject.__FullName__ + ".StructComparer",
["lhs", "rhs"],
body.join("\r\n")
);
};
JSIL.$MakeCopierCore = function (typeObject, context, body, resultVar) {
var fields = JSIL.GetFieldList(typeObject);
if (typeObject.__IsUnion__) {
var nativeSize = typeObject.__NativeSize__;
body.push(" " + resultVar + ".$backingStore = new Uint8Array(" + nativeSize + ");");
JSIL.$EmitMemcpyIntrinsic(body, resultVar + ".$backingStore", "source.$backingStore", 0, 0, nativeSize);
} else if (context.prototype.__CopyMembers__) {
context.copier = context.prototype.__CopyMembers__;
body.push(" context.copier(source, " + resultVar + ");");
} else {
for (var i = 0; i < fields.length; i++) {
// FIXME
var field = fields[i];
var isStruct = field.isStruct;
// Type-hint the assignments
var isChar = field.type.__FullName__ === "System.Char";
var isBool = field.type.__FullName__ === "System.Boolean";
var isInteger = field.type.__IsNumeric__ && field.type.__IsIntegral__ && !isChar && !isBool;
var isFloat = field.type.__IsNumeric__ && !field.type.__IsIntegral__ && !isChar && !isBool;
var line = " " + JSIL.FormatMemberAccess(resultVar, field.name) + " = ";
if (isFloat)
line += "+(";
line += JSIL.FormatMemberAccess("source", field.name);
if (isStruct)
line += ".MemberwiseClone();"
else if (isInteger)
line += " | 0;";
else if (isFloat)
line += ");";
else
line += ";"
body.push(line);
}
}
};
JSIL.$MakeMemberCopier = function (typeObject, publicInterface) {
var prototype = publicInterface.prototype;
var context = {
prototype: prototype
};
var body = [];
JSIL.$MakeCopierCore(typeObject, context, body, "result");
return JSIL.CreateNamedFunction(
typeObject.__FullName__ + ".MemberCopier",
["source", "result"],
body.join("\r\n")
);
};
JSIL.$MakeMemberwiseCloner = function (typeObject, publicInterface) {
var prototype = publicInterface.prototype;
var context = {
prototype: prototype
};
var body = ["// Copy constructor"];
JSIL.$MakeCopierCore(typeObject, context, body, "this");
var subtypeRe = /[\+\/]/g;
var nameRe = /[^A-Za-z_0-9]/g;
var uri = typeObject.__FullName__.replace(subtypeRe, ".");
var constructor = JSIL.CreateNamedFunction(
typeObject.__FullName__ + ".CopyConstructor",
["source"],
body.join("\r\n"),
{
context: context
}
);
constructor.prototype = prototype;
var memberwiseCloner = JSIL.CreateNamedFunction(
typeObject.__FullName__ + ".MemberwiseClone",
[],
"return new clone(this);",
{
clone: constructor
}
);
return memberwiseCloner;
};
JSIL.$BuildFieldList = function (typeObject) {
if (typeObject.__IsClosed__ === false)
return;
var isUnion = false;
var bindingFlags = $jsilcore.BindingFlags.$Flags("Instance", "NonPublic", "Public");
var fields = JSIL.GetMembersInternal(
typeObject, bindingFlags, "FieldInfo"
);
var fl = typeObject.__FieldList__ = [];
var fieldOffset = 0;
var customPacking = typeObject.__CustomPacking__ | 0;
$fieldloop:
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
var fieldType = field._data.fieldType;
var didGenericResolve = false;
while (fieldType && (Object.getPrototypeOf(fieldType) === JSIL.GenericParameter.prototype)) {
didGenericResolve = true;
var fieldTypeRef = fieldType;
fieldType = JSIL.$ResolveGenericTypeReferenceInternal(fieldType, typeObject.__PublicInterface__.prototype);
if (!fieldType) {
JSIL.Host.warning(
"Could not resolve open generic parameter '" + fieldTypeRef.name +
"' when building field list for type '" + typeObject.__FullName__ + "'"
);
continue $fieldloop;
}
}
if (!didGenericResolve) {
fieldType = JSIL.ResolveTypeReference(fieldType, typeObject.__Context__)[1];
}
if ((typeof (fieldType) === "undefined") || (fieldType === null))
JSIL.RuntimeError("Invalid field type");
// Native types may derive from System.ValueType but we can't treat them as structs.
var isStruct = (fieldType.__IsStruct__ || false) && (!fieldType.__IsNativeType__);
var fieldSize = JSIL.GetNativeSizeOf(fieldType, true);
var fieldAlignment = JSIL.GetNativeAlignmentOf(fieldType, true);
// StructLayout.Pack seems to only be able to eliminate extra space between fields,
// not add extra space as one might also expect.
if (customPacking && (customPacking < fieldAlignment)) {
if (JSIL.StructFormatWarnings) {
if (fieldAlignment !== customPacking)
JSIL.WarningFormat("Custom packing for field {0}.{1} is non-native for JavaScript", [typeObject.__FullName__, field._descriptor.Name]);
}
fieldAlignment = customPacking;
}
var actualFieldOffset = fieldOffset;
if (typeof (field._data.offset) === "number") {
if (typeObject.__ExplicitLayout__)
actualFieldOffset = field._data.offset;
else if (JSIL.StructFormatWarnings)
JSIL.WarningFormat("Ignoring offset for field {0}.{1} because {0} does not have explicit layout", [typeObject.__FullName__, field.descriptor.Name]);
} else if (fieldAlignment > 0) {
actualFieldOffset = (((fieldOffset + (fieldAlignment - 1)) / fieldAlignment) | 0) * fieldAlignment;
}
var fieldRecord = {
name: field._descriptor.Name,
type: fieldType,
isStruct: isStruct,
defaultValueExpression: field._data.defaultValueExpression,
offsetBytes: actualFieldOffset,
sizeBytes: fieldSize,
alignmentBytes: fieldAlignment
};
if (fieldSize > 0) {
// Scan through preceding fields to see if we overlap any of them.
for (var j = 0; j < fl.length; j++) {
var priorRecord = fl[j];
var start = priorRecord.offsetBytes;
var end = start + priorRecord.sizeBytes;
var myInclusiveEnd = actualFieldOffset + fieldSize - 1;
if (
(
(actualFieldOffset < end) &&
(actualFieldOffset >= start)
) ||
(
(myInclusiveEnd < end) &&
(myInclusiveEnd >= start)
)
) {
if (JSIL.StructFormatWarnings)
JSIL.WarningFormat("Field {0}.{1} overlaps field {0}.{2}.", [typeObject.__FullName__, fieldRecord.name, priorRecord.name]);
fieldRecord.overlapsOtherFields = true;
isUnion = true;
}
}
}
if (!field.IsStatic)
fl.push(fieldRecord);
if (fieldSize >= 0)
fieldOffset = actualFieldOffset + fieldSize;
}
// Sort fields by name so that we get a predictable initialization order.
fl.sort(function (lhs, rhs) {
return JSIL.CompareValues(lhs.name, rhs.name);
})
if (isUnion && !typeObject.__ExplicitLayout__)
JSIL.RuntimeError("Non-explicit-layout structure appears to be a union: " + typeObject.__FullName__);
Object.defineProperty(typeObject, "__IsUnion_BackingStore__", {
value: isUnion,
configurable: true,
enumerable: false
});
return fl;
};
JSIL.$ResolveGenericTypeReferences = function (context, types) {
var result = false;
for (var i = 0; i < types.length; i++) {
var resolved = JSIL.$ResolveGenericTypeReferenceInternal(types[i], context);
if (resolved !== null) {
// console.log("ga[" + i + "] " + types[i] + " -> " + resolved);
types[i] = resolved;
result = true;
}
}
return result;
};
JSIL.$MakeAnonymousMethod = function (target, body) {
if (typeof (body) !== "function")
JSIL.RuntimeError("body must be a function");
var key = "$$" + (++JSIL.$NextDispatcherId).toString(16);
Object.defineProperty(
target, key, {
value: body,
writable: false,
configurable: true,
enumerable: false
}
);
if (body.__IsMembrane__)
JSIL.DefinePreInitMethodAlias(target, key, body);
return key;
};
JSIL.MethodSetByGenericArgumentCount = function () {
this.dict = {};
this.count = 0;
};
JSIL.MethodSetByGenericArgumentCount.prototype.get = function (argumentCount) {
var result = this.dict[argumentCount];
if (!result)
result = this.dict[argumentCount] = new JSIL.MethodSetByArgumentCount(this, argumentCount);
return result;
};
JSIL.MethodSetByArgumentCount = function (genericSet, genericCount) {
this.genericSet = genericSet;
this.genericCount = genericCount;
this.dict = {};
this.count = 0;
};
JSIL.MethodSetByArgumentCount.prototype.get = function (argumentCount) {
var result = this.dict[argumentCount];
if (!result) {
result = this.dict[argumentCount] = new JSIL.MethodSet(this, argumentCount);
}
return result;
};
JSIL.MethodSet = function (argumentSet, argumentCount) {
this.argumentSet = argumentSet;
this.argumentCount = argumentCount;
this.list = [];
this.count = 0;
};
JSIL.MethodSet.prototype.add = function (signature) {
this.list.push(signature);
this.count += 1;
this.argumentSet.count += 1;
this.argumentSet.genericSet.count += 1;
};
JSIL.$MakeMethodGroup = function (typeObject, isStatic, target, renamedMethods, methodName, methodEscapedName, overloadSignatures) {
var typeName = typeObject.__FullName__;
var methodFullName = typeName + "." + methodName;
var makeDispatcher, makeGenericArgumentGroup;
var makeMethodMissingError = function (signature) {
return "Method not found: " + signature.toString(methodFullName);
};
var makeNoMatchFoundError = function (group) {
var text = group.count + " candidate(s) for method invocation:";
for (var i = 0; i < group.count; i++) {
text += "\n" + group.list[i].toString(methodFullName);
}
return new Error(text);
};
// If the method group contains only a single method, we call this to fetch the method implementation
// and then use that as the method group.
var makeSingleMethodGroup = function (id, group, offset) {
var singleMethod = group.list[0];
var key = singleMethod.GetNamedKey(methodEscapedName, true);
var unrenamedKey = key;
if (typeof (renamedMethods[key]) === "string")
key = renamedMethods[key];
var method = JSIL.$FindMethodBodyInTypeChain(typeObject, isStatic, key, false);
if (typeof (method) !== "function") {
JSIL.Host.warning(makeMethodMissingError(singleMethod));
var stub = function MissingMethodInvoked () {
JSIL.RuntimeError(makeMethodMissingError(singleMethod));
};
return JSIL.$MakeAnonymousMethod(target, stub);
} else {
// We need to manufacture an anonymous name for the method
// So that overload dispatch can invoke it using 'this.x' syntax instead
// of using thisType['x']
// return key;
return JSIL.$MakeAnonymousMethod(target, method);
}
};
// For methods with generic arguments we figure out whether there are multiple options for the generic
// argument dispatcher, and bind the appropriate generic method dispatcher.
makeGenericArgumentGroup = function (id, group, offset) {
var groupDispatcher = makeDispatcher(id, group, offset);
var genericArgumentCount = offset;
var stub = JSIL.$MakeGenericMethodBinder(groupDispatcher, methodFullName, genericArgumentCount, group.dict);
return JSIL.$MakeAnonymousMethod(target, stub);
};
// For methods with multiple candidate signatures that all have the same number of arguments, we do
// dynamic dispatch at runtime on each invocation by comparing the types of the actual argument
// values against the expected type objects for each signature, in order to select the right
// method to call.
var makeMultipleMethodGroup = function (id, group, offset) {
// [resolvedSignatures, differentReturnTypeError]
var isResolved = false;
var resolvedGroup = null;
// Take the method signature(s) in this group and resolve all their type references.
// We do this once and cache it since type reference resolution takes time.
var getResolvedGroup = function GetResolvedGroup () {
if (isResolved)
return resolvedGroup;
var result = [];
for (var i = 0; i < group.count; i++) {
var groupEntry = group.list[i];
// FIXME: Do we still need generic logic here?
var typeObject = JSIL.GetType(target);
var resolveContext = target;
var resolvedGeneric = JSIL.$ResolveGenericMethodSignature(typeObject, groupEntry, resolveContext);
if (resolvedGeneric != null)
result[i] = resolvedGeneric.Resolve(methodEscapedName);
else
result[i] = groupEntry.Resolve(methodEscapedName);
}
isResolved = true;
return (resolvedGroup = result);
};
var stub = function OverloadedMethod_InvokeDynamic () {
var argc = arguments.length;
var resolvedGroup = getResolvedGroup();
// If resolving the group fails, it will return null.
if (resolvedGroup === null)
throw makeNoMatchFoundError(group);
var genericDispatcherKey = null;
scan_methods:
for (var i = 0, l = resolvedGroup.length; i < l; i++) {
var resolvedMethod = resolvedGroup[i];
// We've got a generic dispatcher for a generic method with N generic arguments.
// Store it to use as a fallback if none of the normal overloads match.
if (typeof (resolvedMethod) === "string") {
genericDispatcherKey = resolvedMethod;
continue;
}
var argTypes = resolvedMethod.argumentTypes;
var numGenericArguments = argc - argTypes.length;
var resolvedGenericMethod = resolvedMethod;
// If the method signature has any generic arguments, resolve any positional generic parameters
// referenced in the method signature. If we don't do this those types will just be "!!0" etc
if (numGenericArguments > 0) {
var genericArguments = Array.prototype.slice.call(arguments, 0, numGenericArguments);
resolvedGenericMethod = resolvedMethod.ResolvePositionalGenericParameters(genericArguments);
argTypes = resolvedGenericMethod.argumentTypes;
}
// Check the types of the passed in argument values against the types expected for
// this particular signature. Note that we use the resolved generic version so that
// any positional generic parameters are used for type matching.
for (var j = 0; j < argc; j++) {
var expectedType = argTypes[j];
var arg = arguments[j + offset];
if ((typeof (expectedType) === "undefined") || (expectedType === null)) {
// Specific types, like generic parameters, resolve to null or undefined.
} else if (expectedType.__IsReferenceType__ && (arg === null)) {
// Null is a valid value for any reference type.
} else if (!expectedType.$Is(arg)) {
continue scan_methods;
}
}
// Find the method implementation. Note that we don't use the key generated from the
// resolved generic version, because the actual method key contains !!0 etc.
var foundOverload = target[resolvedMethod.key];
if (typeof (foundOverload) !== "function") {
JSIL.RuntimeError(makeMethodMissingError(resolvedMethod));
} else {
return foundOverload.apply(this, arguments);
}
}
// None of the normal overloads matched, but if we found a generic dispatcher, call that.
// This isn't quite right, but the alternative (check to see if the arg is System.Type) is
// worse since it would break for methods that actually take Type instances as arguments.
if (genericDispatcherKey !== null) {
return this[genericDispatcherKey].apply(this, arguments);
}
throw makeNoMatchFoundError(group);
};
return JSIL.$MakeAnonymousMethod(target, stub);
};
makeDispatcher = function (id, g, offset) {
var body = [];
var maxArgumentCount = 0;
body.push(" var argc = arguments.length | 0;");
var methodKey = null;
var gProto = Object.getPrototypeOf(g);
var cases = [];
for (var k in g.dict) {
if (!g.dict.hasOwnProperty(k))
continue;
var argumentCount = parseInt(k) + offset;
if (isNaN(argumentCount))
throw new Error();
maxArgumentCount = Math.max(maxArgumentCount, argumentCount);
var caseDesc = {
key: argumentCount
};
var group = g.dict[k];
if (gProto === JSIL.MethodSetByGenericArgumentCount.prototype) {
methodKey = makeGenericArgumentGroup(id + "`" + k, group, group.genericCount + offset);
} else if (gProto === JSIL.MethodSetByArgumentCount.prototype) {
if (group.count > 1) {
methodKey = makeMultipleMethodGroup(id, group, offset);
} else {
methodKey = makeSingleMethodGroup(id, group, offset);
}
}
var invocation = " return this." + methodKey + "(";
for (var ai = 0; ai < argumentCount; ai++) {
if (ai !== 0)
invocation += ", ";
invocation += "arg" + ai.toString();
}
invocation += ");";
caseDesc.code = invocation;
cases.push(caseDesc);
}
JSIL.$MakeOptimizedNumericSwitch(
body, "argc", cases,
" JSIL.RuntimeError('No overload of ' + name + ' can accept ' + (argc - offset) + ' argument(s).')"
);
var bodyText = body.join("\r\n");
var formalArgumentNames = [];
for (var ai = 0; ai < maxArgumentCount; ai++)
formalArgumentNames.push("arg" + ai.toString());
var boundDispatcher = JSIL.CreateNamedFunction(
id, formalArgumentNames,
bodyText,
{
name: methodName,
offset: offset
}
);
return JSIL.$MakeAnonymousMethod(target, boundDispatcher);
};
var methodSet = new JSIL.MethodSetByGenericArgumentCount();
for (var i = 0, l = overloadSignatures.length; i < l; i++) {
var signature = overloadSignatures[i];
var argumentCount = signature.argumentTypes.length;
var gaCount = signature.genericArgumentNames.length;
var genargcSet = methodSet.get(gaCount);
var argcSet = genargcSet.get(argumentCount);
argcSet.add(signature);
}
var gaKeys = Object.keys(methodSet.dict);
// For method groups with no generic arguments, skip creating a generic argument dispatcher.
if ((gaKeys.length === 1) && (gaKeys[0] == 0)) {
// If there's only one method definition, don't generate a dispatcher at all.
// This ensures that if our implementation uses JS varargs, it works.
if (methodSet.count === 1) {
var theSet = methodSet.dict[0];
var theMethodList = theSet.dict[Object.keys(theSet.dict)[0]];
return makeSingleMethodGroup(methodFullName, theMethodList, 0);
} else {
return makeDispatcher(methodFullName, methodSet.dict[0], 0);
}
} else {
return makeDispatcher(methodFullName, methodSet, 0);
}
};
JSIL.$ApplyMemberHiding = function (typeObject, memberList, resolveContext) {
if (memberList.length < 1)
return;
// This is called during type system initialization, so we can't rely on any of MemberInfo's
// properties or methods - we need to access the data members directly.
var comparer = function (lhs, rhs) {
var lhsCount = lhs._data.signature.argumentTypes.length;
var rhsCount = rhs._data.signature.argumentTypes.length;
// Group by argument count.
var result = JSIL.CompareValues(lhsCount, rhsCount);
// Sub-cluster by hash (the hash encodes argument types, etc.)
if (result === 0) {
var lhsHash = lhs._data.signature.get_Hash();
var rhsHash = rhs._data.signature.get_Hash();
result = JSIL.CompareValues(lhsHash, rhsHash);
}
// Non-placeholders override placeholders.
if (result === 0)
result = JSIL.CompareValues(
lhs._data.isPlaceholder ? 1 : 0,
rhs._data.isPlaceholder ? 1 : 0
);
// Non-externals override externals.
if (result === 0)
result = JSIL.CompareValues(
lhs._data.isExternal ? 1 : 0,
rhs._data.isExternal ? 1 : 0
);
// A derived type's methods override inherited methods.
if (result === 0)
result = -JSIL.CompareValues(
lhs._typeObject.__InheritanceDepth__,
rhs._typeObject.__InheritanceDepth__
);
return result;
};
// Sort the member list by method signature hash, then by whether they are external
// placeholders, then by inheritance depth.
// This produces a list of 'signature groups' (methods with the same signature), and
// the first method in each signature group is the most-derived (hides the rest).
// This also ensures that external placeholders will not overwrite non-placeholder
// methods unless they are all that remains (in which case the most-derived one will
// win).
memberList.sort(comparer);
var originalCount = memberList.length;
var currentSignatureHash = null;
var currentArgumentCount = null;
var currentGroupStart;
var groupUpdate = function (i, memberSignature) {
var argumentCount = memberSignature.argumentTypes.length;
var memberSignatureHash = memberSignature.get_Hash();
if (
(currentArgumentCount === null) ||
(currentSignatureHash === null) ||
(currentArgumentCount != argumentCount) ||
(
(currentSignatureHash != memberSignatureHash) &&
// *Every* method with zero arguments is a part of a group, no matter what.
// They will automatically sort into one group because they all start with '$void='
(currentArgumentCount !== 0)
)
) {
// New group
currentArgumentCount = argumentCount;
currentSignatureHash = memberSignatureHash;
currentGroupStart = i;
return false;
} else {
return true;
}
};
var trace = false;
var traceOut = function () {
if ((typeof(console) !== "undefined") && console.log)
console.log.apply(console, arguments);
else
print.apply(null, arguments);
};
var memberName = memberList[0]._descriptor.Name;
// Sweep through the member list and replace any hidden members with null.
for (var i = 0, l = memberList.length; i < l; i++) {
var member = memberList[i];
var memberSignature = member._data.signature;
var isHidden = groupUpdate(i, memberSignature);
if (isHidden) {
var hidingMember = memberList[currentGroupStart];
if (trace) {
var localMemberName =
member._typeObject.__FullName__ +
"." + member._descriptor.Name;
var hidingMemberName =
hidingMember._typeObject.__FullName__ +
"." + hidingMember._descriptor.Name;
var memberSuffix = "", hidingMemberSuffix = "";
if (member._data.isPlaceholder)
memberSuffix = " (placeholder)";
else if (member._data.isExternal)
memberSuffix = " (external)";
if (hidingMember._data.isPlaceholder)
hidingMemberSuffix = " (placeholder)";
else if (hidingMember._data.isExternal)
hidingMemberSuffix = " (external)";
traceOut(
memberName + ": Purged " +
localMemberName + memberSuffix +
" because it is hidden by " +
hidingMemberName + hidingMemberSuffix
);
}
memberList[i] = null;
}
}
// Perform a second pass through the member list and shrink it to eliminate the nulls.
for (var i = originalCount - 1; i >= 0; i--) {
var member = memberList[i];
if (member === null)
memberList.splice(i, 1);
}
if ((trace) && (originalCount != memberList.length)) {
traceOut("Shrank method group from " + originalCount + " item(s) to " + memberList.length);
}
};
JSIL.$CreateMethodMembranes = function (typeObject, publicInterface) {
var maybeRunCctors = function MaybeRunStaticConstructors () {
JSIL.RunStaticConstructors(publicInterface, typeObject);
};
var makeReturner = function (value) {
return function () { return value; };
};
var bindingFlags = $jsilcore.BindingFlags.$Flags("NonPublic", "Public");
var methods = JSIL.GetMembersInternal(
typeObject, bindingFlags, "$MethodOrConstructor"
);
// We need to ensure that all the mangled method names have membranes applied.
// This can't be done before now due to generic types.
for (var i = 0, l = methods.length; i < l; i++) {
var method = methods[i];
var isStatic = method._descriptor.Static;
// FIXME: I'm not sure this is right for open generic methods.
// I think it might be looking up the old open form of the method signature
// instead of the closed form.
var key = method._data.signature.GetNamedKey(method._descriptor.EscapedName, true);
var useMembrane = isStatic &&
($jsilcore.cctorKeys.indexOf(method._descriptor.Name) < 0) &&
($jsilcore.cctorKeys.indexOf(method._descriptor.EscapedName) < 0);
if (useMembrane) {
var originalFunction = publicInterface[key];
if (typeof (originalFunction) !== "function") {
// throw new Error("No function with key '" + key + "' found");
continue;
}
JSIL.DefinePreInitMethod(
publicInterface, key, makeReturner(originalFunction), maybeRunCctors
);
}
}
};
JSIL.$GroupMethodsByName = function (methods) {
var methodsByName = {};
for (var i = 0, l = methods.length; i < l; i++) {
var method = methods[i];
var key = (method._descriptor.Static ? "static" : "instance") + "$" + method._descriptor.EscapedName;
var methodList = methodsByName[key];
if (!JSIL.IsArray(methodList))
methodList = methodsByName[key] = [];
// Don't add duplicate copies of the same method to the method list.
if (methodList.indexOf(method) < 0)
methodList.push(method);
}
return methodsByName;
};
JSIL.$BuildMethodGroups = function (typeObject, publicInterface, forceLazyMethodGroups) {
// This is called during type system initialization, so we can't rely on any of MemberInfo's
// properties or methods - we need to access the data members directly.
var instanceMethods = JSIL.GetMembersInternal(
typeObject, $jsilcore.BindingFlags.$Flags("Instance", "Public", "NonPublic"), "MethodInfo"
);
var constructors = JSIL.GetMembersInternal(
typeObject, $jsilcore.BindingFlags.$Flags("DeclaredOnly", "Instance", "Public", "NonPublic"), "ConstructorInfo"
);
var staticMethods = JSIL.GetMembersInternal(
typeObject, $jsilcore.BindingFlags.$Flags("DeclaredOnly", "Static", "Public", "NonPublic"), "$AllMethods"
);
var methods = staticMethods.concat(instanceMethods).concat(constructors);
var renamedMethods = typeObject.__RenamedMethods__ || {};
var trace = false;
var active = true;
// Set to true to enable lazy method group construction. This increases
// javascript heap size but improves startup performance.
var lazyMethodGroups = true || (forceLazyMethodGroups === true);
var printedTypeName = false;
var resolveContext = publicInterface.prototype;
// Group up all the methods by name in preparation for building the method groups
var methodsByName = JSIL.$GroupMethodsByName(methods);
for (var key in methodsByName) {
var methodList = methodsByName[key];
JSIL.$ApplyMemberHiding(typeObject, methodList, resolveContext);
}
var record = function (distance, signature) {
this.distance = distance;
this.signature = signature;
};
var typesHiearchy = JSIL.GetTypeAndBases(typeObject);
for (var key in methodsByName) {
var methodList = methodsByName[key];
var methodName = methodList[0]._descriptor.Name;
var methodEscapedName = methodList[0]._descriptor.EscapedName;
var isStatic = methodList[0]._descriptor.Static;
var signature = methodList[0]._data.signature;
var entriesToSort = [];
for (var i = 0, l = methodList.length; i < l; i++) {
var method = methodList[i];
entriesToSort.push(new record(typesHiearchy.indexOf(method._typeObject), method._data.signature));
}
entriesToSort.sort(function (lhs, rhs) {
return JSIL.CompareValues(lhs.distance, rhs.distance);
});
var entries = [];
var numZeroArgEntries = 0;
for (var i = 0, l = entriesToSort.length; i < l; i++) {
var method = entriesToSort[i];
entries.push(method.signature);
if (method.signature.argumentTypes.length === 0) {
numZeroArgEntries += 1;
}
}
if (numZeroArgEntries > 1) {
throw new Error(
"Method '" + methodName + "' has more than one zero-argument overload"
);
}
var target = isStatic ? publicInterface : publicInterface.prototype;
if (
target.hasOwnProperty(methodEscapedName) &&
(typeof (target[methodEscapedName]) === "function") &&
(target[methodEscapedName].__IsPlaceholder__ !== true)
) {
if (trace) {
console.log("Not overwriting " + typeObject.__FullName__ + "." + methodEscapedName);
}
continue;
}
// We defer construction of the actual method group dispatcher(s) until the first
// time the method is used. This reduces the up-front cost of BuildMethodGroups
// and reduces the amount of memory used for methods that are never invoked via
// dynamic dispatch.
var makeMethodGroupGetter = function (
target, isStatic, renamedMethods, methodName, methodEscapedName, entries
) {
var key = null;
return function GetMethodGroup () {
if (key === null) {
key = JSIL.$MakeMethodGroup(
typeObject, isStatic, target, renamedMethods, methodName, methodEscapedName, entries
);
}
var methodGroupTarget = target[key];
if (methodGroupTarget.__IsMembrane__)
JSIL.DefinePreInitMethodAlias(target, methodEscapedName, methodGroupTarget);
return methodGroupTarget;
};
};
if (trace) {
console.log(typeObject.__FullName__ + "[" + methodEscapedName + "] = ", getter);
}
if (active) {
var getter = makeMethodGroupGetter(
target, isStatic, renamedMethods, methodName, methodEscapedName, entries
);
if (lazyMethodGroups) {
JSIL.SetLazyValueProperty(
target, methodEscapedName, getter
);
} else {
JSIL.SetValueProperty(
target, methodEscapedName, getter()
);
}
}
}
};
JSIL.BuildTypeList = function (type, publicInterface) {
var myTypeId = type.__TypeId__;
var typeList = type.__AssignableTypes__ = {};
var context = type.__Context__;
var toVisit = [];
var current = type;
while ((typeof (current) === "object") && (current !== null)) {
toVisit.push(current);
current = current.__BaseType__;
}
while (toVisit.length > 0) {
current = toVisit.shift();
var id = current.__TypeId__;
typeList[id] = true;
if (typeof(current.__AssignableFromTypes__) !== "undefined")
current.__AssignableFromTypes__[myTypeId] = true;
var interfaces = current.__Interfaces__;
if (JSIL.IsArray(interfaces)) {
for (var i = 0; i < interfaces.length; i++) {
var ifaceRef = interfaces[i];
// This should have already generated a warning in FixupInterfaces.
if (ifaceRef === null)
continue;
var iface = JSIL.ResolveTypeReference(ifaceRef, context)[1];
toVisit.push(iface);
}
}
}
};
$jsilcore.cctorKeys = ["_cctor", "_cctor2", "_cctor3", "_cctor4", "_cctor5"];
JSIL.InitializeType = function (type) {
var classObject = type, typeObject = type;
if (typeof (type) === "undefined")
JSIL.RuntimeError("Type is null");
else if (typeof (type.__PublicInterface__) !== "undefined")
classObject = type.__PublicInterface__;
else if (typeof (type.__Type__) === "object")
typeObject = type.__Type__;
else
return;
if (typeObject.__TypeInitialized__ || false)
return;
// Not entirely correct, but prevents recursive type initialization
typeObject.__TypeInitialized__ = true;
if (typeObject.__IsClosed__) {
var forceLazyMethodGroups = false;
// We need to ensure that method groups for BCL classes are always lazy
// because otherwise, initializing the method groups may rely on the classes themselves
if (typeObject.__FullName__.indexOf("System.") === 0)
forceLazyMethodGroups = true;
if (typeObject.IsInterface !== true) {
JSIL.$CreateMethodMembranes(typeObject, classObject);
JSIL.$BuildMethodGroups(typeObject, classObject, forceLazyMethodGroups);
}
JSIL.InitializeFields(classObject, typeObject);
JSIL.InstantiateProperties(classObject, typeObject);
if (typeObject.IsInterface !== true) {
JSIL.QueueTypeInitializer(typeObject, function () {
JSIL.FixupInterfaces(classObject, typeObject);
});
JSIL.RebindRawMethods(classObject, typeObject);
}
if (!typeObject.__IsStatic__) {
JSIL.BuildTypeList(typeObject, classObject);
}
if (
classObject.prototype &&
(typeof (classObject.prototype) === "object") &&
// HACK: We need to use a special implementation for System.Object.MemberwiseClone,
// since when called explicitly it acts 'virtually' (conforms to the instance type)
// (issue #146)
(typeObject.__FullName__ !== "System.Object")
) {
JSIL.SetLazyValueProperty(
classObject.prototype, "MemberwiseClone", function () {
return JSIL.$MakeMemberwiseCloner(typeObject, classObject);
}
);
}
if (classObject.__PreInitMembrane__)
classObject.__PreInitMembrane__.maybeInit();
if (classObject.prototype && classObject.prototype.__PreInitMembrane__)
classObject.prototype.__PreInitMembrane__.maybeInit();
} else {
// console.log("Type '" + typeObject.__FullName__ + "' is open so not initializing");
}
// Any closed forms of the type, if it's an open type, should be initialized too.
if (typeof (typeObject.__OfCache__) !== "undefined") {
var oc = typeObject.__OfCache__;
for (var k in oc) {
if (!oc.hasOwnProperty(k))
continue;
JSIL.InitializeType(oc[k]);
}
}
if (
(typeof (type.__BaseType__) !== "undefined") &&
(type.__BaseType__ !== null)
) {
JSIL.InitializeType(type.__BaseType__);
}
};
JSIL.$InvokeStaticConstructor = function (staticConstructor, typeObject, classObject) {
if (JSIL.ThrowOnStaticCctorError) {
staticConstructor.call(classObject);
} else {
try {
staticConstructor.call(classObject);
} catch (e) {
typeObject.__StaticConstructorError__ = e;
JSIL.Host.warning("Unhandled exception in static constructor for type " + JSIL.GetTypeName(typeObject) + ":");
JSIL.Host.warning(e);
}
}
}
JSIL.RunStaticConstructors = function (classObject, typeObject) {
var base = typeObject.__BaseType__;
if (base && base.__PublicInterface__)
JSIL.RunStaticConstructors(base.__PublicInterface__, base);
JSIL.InitializeType(typeObject);
if (typeObject.__RanCctors__)
return;
typeObject.__RanCctors__ = true;
// Run any queued initializers for the type
var ti = typeObject.__Initializers__ || $jsilcore.ArrayNull;
while (ti.length > 0) {
var initializer = ti.unshift();
if (typeof (initializer) === "function")
initializer(classObject);
};
// If the type is closed, invoke its static constructor(s)
for (var i = 0; i < $jsilcore.cctorKeys.length; i++) {
var key = $jsilcore.cctorKeys[i];
var cctor = classObject[key];
if (typeof (cctor) === "function")
JSIL.$InvokeStaticConstructor(cctor, typeObject, classObject);
}
};
JSIL.InitializeFields = function (classObject, typeObject) {
var typeObjects = [];
var to = typeObject;
while (to) {
typeObjects.push(to);
to = to.__BaseType__;
}
// Run the initializers in reverse order, so we start with the base class
// and work our way up, just in case derived initializers overwrite stuff
// that was put in place by base initializers.
for (var i = typeObjects.length - 1; i >= 0; i--) {
var to = typeObjects[i];
var fi = to.__FieldInitializers__;
if (fi) {
for (var j = 0, l = fi.length; j < l; j++)
fi[j](classObject, to.__PublicInterface__, typeObject, to);
}
}
}
JSIL.ShadowedTypeWarning = function (fullName) {
JSIL.Host.abort(new Error("Type " + fullName + " is shadowed by another type of the same name."));
};
JSIL.DuplicateDefinitionWarning = function (fullName, isPublic, definedWhere, inAssembly) {
var message = (isPublic ? "Public" : "Private") + " type '" + fullName + "' is already defined";
if (inAssembly)
message += " in assembly '" + inAssembly + "'";
if (definedWhere && (definedWhere !== null)) {
message += ".\r\nPreviously defined at:\r\n ";
message += definedWhere.join("\r\n ");
}
JSIL.Host.abort(new Error(message));
};
JSIL.GetFunctionName = function (fn) {
return fn.name || fn.__name__ || "unknown";
};
JSIL.ApplyExternals = function (publicInterface, typeObject, fullName) {
var queue = JSIL.ExternalsQueue[fullName];
if (JSIL.IsArray(queue)) {
while (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
var externals = JSIL.AllImplementedExternals[fullName];
var instancePrefix = "instance$";
var rawSuffix = "$raw";
var constantSuffix = "$constant";
var hasPrototype = typeof (publicInterface.prototype) === "object";
var prototype = hasPrototype ? publicInterface.prototype : null;
for (var k in externals) {
if (!externals.hasOwnProperty(k))
continue;
if (k === "__IsInitialized__")
continue;
var target = publicInterface;
var key = k;
var isRaw = false, isStatic;
if (key.indexOf(instancePrefix) === 0) {
isStatic = false;
if (hasPrototype) {
key = key.replace(instancePrefix, "");
target = prototype;
} else {
JSIL.Host.warning("Type '" + fullName + "' has no prototype to apply instance externals to.");
continue;
}
} else {
isStatic = true;
}
if (key.indexOf(rawSuffix) > 0) {
key = key.replace(rawSuffix, "");
isRaw = true;
}
if (key.indexOf(constantSuffix) > 0) {
JSIL.SetValueProperty(target, key.replace(constantSuffix, ""), externals[k]);
continue;
}
var external = externals[k];
if (!Array.isArray(external))
continue;
var member = external[0];
var value = external[1];
if (member !== null) {
if (Object.getPrototypeOf(member) !== JSIL.MemberRecord.prototype)
JSIL.RuntimeError("Invalid prototype");
typeObject.__Members__.push(member);
}
if (isRaw) {
var rawRecord = new JSIL.RawMethodRecord(key, isStatic);
typeObject.__RawMethods__.push(rawRecord);
}
JSIL.SetValueProperty(target, key, value);
}
if (externals) {
externals.__IsInitialized__ = true;
} else {
JSIL.AllImplementedExternals[fullName] = {
__IsInitialized__: true
};
}
};
JSIL.MakeExternalType = function (fullName, isPublic) {
if (typeof (isPublic) === "undefined")
JSIL.Host.abort(new Error("Must specify isPublic"));
var assembly = $private;
var state = {
hasValue: false
};
var getter = function GetExternalType () {
if (state.hasValue)
return state.value;
else
JSIL.Host.abort(new Error("The external type '" + fullName + "' has not been implemented."));
};
var setter = function SetExternalType (newValue) {
state.value = newValue;
state.hasValue = true;
};
var definition = {
get: getter, set: setter,
configurable: true, enumerable: true
};
var privateName = JSIL.ResolveName(assembly, fullName, false);
if (!privateName.exists())
privateName.define(definition);
if (isPublic) {
var publicName = JSIL.ResolveName(JSIL.GlobalNamespace, fullName, true);
if (!publicName.exists())
publicName.define(definition);
}
};
JSIL.GetCorlib = function () {
return JSIL.GetAssembly("mscorlib", true) || $jsilcore;
};
$jsilcore.$GetRuntimeType = function () {
// Initializing System.Object forms a cyclical dependency through RuntimeType.
return JSIL.$GetSpecialType("System.RuntimeType").typeObject;
};
JSIL.$MakeTypeObject = function (fullName) {
var runtimeType = $jsilcore.$GetRuntimeType();
var result = Object.create(runtimeType.__PublicInterface__.prototype);
return result;
};
JSIL.MakeStaticClass = function (fullName, isPublic, genericArguments, initializer) {
if (typeof (isPublic) === "undefined")
JSIL.Host.abort(new Error("Must specify isPublic"));
var assembly = $private;
var localName = JSIL.GetLocalName(fullName);
var callStack = null;
if (typeof (printStackTrace) === "function")
callStack = printStackTrace();
var memberBuilder = new JSIL.MemberBuilder($private);
var attributes = memberBuilder.attributes;
var typeObject, staticClassObject;
var creator = function CreateStaticClassObject () {
typeObject = JSIL.$MakeTypeObject(fullName);
JSIL.SetValueProperty(typeObject, "__Context__", assembly);
JSIL.SetValueProperty(typeObject, "__FullName__", fullName);
JSIL.SetValueProperty(typeObject, "__ShortName__", localName);
JSIL.SetValueProperty(typeObject, "__BaseType__", null);
typeObject.__ReflectionCache__ = null;
typeObject.__CallStack__ = callStack;
typeObject.__InheritanceDepth__ = 1;
typeObject.__IsStatic__ = true;
typeObject.__Properties__ = [];
typeObject.__Initializers__ = [];
typeObject.__Interfaces__ = [];
typeObject.__Members__ = [];
typeObject.__ExternalMethods__ = [];
typeObject.__RenamedMethods__ = {};
typeObject.__RawMethods__ = [];
typeObject.__TypeInitialized__ = false;
JSIL.FillTypeObjectGenericArguments(typeObject, genericArguments);
typeObject.__Attributes__ = attributes;
typeObject.IsInterface = false;
staticClassObject = JSIL.CreateSingletonObject(JSIL.StaticClassPrototype);
staticClassObject.__Type__ = typeObject;
var typeId = JSIL.AssignTypeId(assembly, fullName);
JSIL.SetTypeId(typeObject, staticClassObject, typeId);
JSIL.SetValueProperty(typeObject, "__PublicInterface__", staticClassObject);
if (typeObject.__GenericArguments__.length > 0) {
staticClassObject.Of$NoInitialize = $jsilcore.$MakeOf$NoInitialize(staticClassObject);
staticClassObject.Of = $jsilcore.$MakeOf(staticClassObject);
typeObject.__IsClosed__ = false;
typeObject.__OfCache__ = {};
} else {
typeObject.__IsClosed__ = true;
}
for (var i = 0, l = typeObject.__GenericArguments__.length; i < l; i++) {
var ga = typeObject.__GenericArguments__[i];
var name = new JSIL.Name(ga, fullName);
JSIL.SetValueProperty(staticClassObject, ga, name);
}
JSIL.ApplyExternals(staticClassObject, typeObject, fullName);
JSIL.SetValueProperty(staticClassObject, "toString", function StaticClass_toString () {
return "<" + fullName + " Public Interface>";
});
return staticClassObject;
};
var wrappedInitializer = null;
if (initializer) {
wrappedInitializer = function (to) {
var interfaceBuilder = new JSIL.InterfaceBuilder(assembly, to.__Type__, to);
return initializer(interfaceBuilder);
};
}
JSIL.RegisterName(fullName, assembly, isPublic, creator, wrappedInitializer);
return memberBuilder;
};
JSIL.$ActuallyMakeCastMethods = function (publicInterface, typeObject, specialType) {
if (!typeObject)
JSIL.RuntimeError("Null type object");
if (!publicInterface)
JSIL.RuntimeError("Null public interface");
JSIL.InitializeType(publicInterface);
var castFunction, asFunction, isFunction;
var customCheckOnly = false;
var checkMethod = publicInterface.CheckType || null;
var typeId = typeObject.__TypeId__;
var assignableFromTypes = typeObject.__AssignableFromTypes__ || {};
typeObject.__CastSpecialType__ = specialType;
var typeName = JSIL.GetTypeName(typeObject);
var throwCastError = function (value) {
throw new System.InvalidCastException("Unable to cast object of type '" + JSIL.GetTypeName(JSIL.GetType(value)) + "' to type '" + typeName + "'.");
};
var throwInvalidAsError = function (value) {
throw new System.InvalidCastException("It is invalid to use 'as' to cast values to this type.");
};
var isIEnumerable = typeName.indexOf(".IEnumerable") >= 0;
var isICollection = typeName.indexOf(".ICollection") >= 0;
var isIList = typeName.indexOf(".IList") >= 0;
var isPointer = typeName.indexOf("JSIL.Pointer") === 0;
var isInterface = typeObject.IsInterface || false;
// HACK: Handle casting arrays to IEnumerable by creating an overlay.
if (isIEnumerable || isICollection || isIList) {
checkMethod = function Check_ArrayInterface (value) {
// FIXME: IEnumerable<int>.Is(float[]) will return true.
if (JSIL.IsArray(value))
return true;
// Fallback to default check logic
return false;
};
} else if (isPointer) {
var expectedElementTypeId = typeObject.__GenericArgumentValues__[0].__TypeId__;
checkMethod = function Check_IsPointer (value) {
var isPointer = value.__IsPointer__ || false;
if (isPointer) {
var matches = value.elementType.__TypeId__ === expectedElementTypeId;
return matches;
} else {
return false;
}
};
}
if (checkMethod) {
isFunction = JSIL.CreateNamedFunction(
typeName + ".$Is",
["expression", "bypassCustomCheckMethod"],
"if (!bypassCustomCheckMethod && checkMethod(expression))\r\n" +
" return true;\r\n" +
"if (expression) {\r\n" +
" var expressionTypeId = expression.__ThisTypeId__;\r\n" +
" return (expressionTypeId === typeId) || (!!assignableFromTypes[expressionTypeId]);\r\n" +
"} else\r\n" +
" return false;\r\n",
{
typeId: typeId,
assignableFromTypes: assignableFromTypes,
checkMethod: checkMethod
}
);
} else {
isFunction = JSIL.CreateNamedFunction(
typeName + ".$Is",
["expression"],
"if (expression) {\r\n" +
" var expressionTypeId = expression.__ThisTypeId__;\r\n" +
" return (expressionTypeId === typeId) || (!!assignableFromTypes[expressionTypeId]);\r\n" +
"} else\r\n" +
" return false;\r\n",
{
typeId: typeId,
assignableFromTypes: assignableFromTypes,
}
);
}
if (checkMethod) {
asFunction = JSIL.CreateNamedFunction(
typeName + ".$As",
["expression"],
"if (checkMethod(expression))\r\n" +
" return expression;\r\n" +
"else if (expression) {\r\n" +
" var expressionTypeId = expression.__ThisTypeId__;\r\n" +
" if ((expressionTypeId === typeId) || (!!assignableFromTypes[expressionTypeId]))\r\n" +
" return expression;\r\n" +
"}\r\n\r\n" +
"return null;\r\n",
{
typeId: typeId,
assignableFromTypes: assignableFromTypes,
checkMethod: checkMethod
}
);
} else {
asFunction = JSIL.CreateNamedFunction(
typeName + ".$As",
["expression"],
"if (expression) {\r\n" +
" var expressionTypeId = expression.__ThisTypeId__;\r\n" +
" if ((expressionTypeId === typeId) || (!!assignableFromTypes[expressionTypeId]))\r\n" +
" return expression;\r\n" +
"}\r\n\r\n" +
"return null;\r\n",
{
typeId: typeId,
assignableFromTypes: assignableFromTypes,
}
);
}
castFunction = function Cast (expression) {
if (isFunction(expression))
return expression;
else if (expression === null)
return null;
else
throwCastError(expression);
};
var integerCastFunction = function Cast_Integer (expression) {
if (typeof (expression) === "number") {
var max = publicInterface.MaxValue | 0;
var result = (expression | 0) & max;
return result;
} else if (expression === false) {
return 0;
} else if (expression === true) {
return 1;
} else if (
expression.__ThisType__ &&
expression.__ThisType__.__IsEnum__
) {
return expression.value;
} else
throwCastError(expression);
};
var numericCastFunction = function Cast_Number (expression) {
if (typeof (expression) === "number") {
return expression;
} else if (expression === false) {
return 0;
} else if (expression === true) {
return 1;
} else
throwCastError(expression);
};
var int64CastFunction = function Cast_Int64_Impl (expression) {
if (expression === false)
return System.Int64.Zero;
else if (expression === true)
return System.Int64.One;
else if (typeof (expression) === "number")
return System.Int64.FromNumber(expression);
else if (checkMethod(expression))
return expression;
else
throwCastError(expression);
};
switch (specialType) {
case "enum":
customCheckOnly = true;
asFunction = throwInvalidAsError;
var castCache = [];
var valueToName = typeObject.__ValueToName__;
var populateCastCache = function (value) {
value |= 0;
var name = valueToName[value] || null;
if (name !== null)
return publicInterface[name];
return publicInterface.$MakeValue(value, null);
};
castFunction = function Cast_Enum (value) {
value |= 0;
var result = castCache[value] || null;
if (result === null)
result = castCache[value] = populateCastCache(value);
return result;
};
break;
case "delegate":
var _isFunction = isFunction;
isFunction = function Is_Delegate (expression) {
return _isFunction(expression) || (typeof (expression) === "function");
};
var _asFunction = asFunction;
asFunction = function As_Delegate (expression) {
var result = _asFunction(expression);
if ((result === null) && (typeof (expression) === "function"))
result = expression;
return result;
};
break;
case "array":
// Allow casting array interface overlays back to appropriate array types
var _isFunction = isFunction;
isFunction = function Is_Array (expression) {
return _isFunction(expression) || (
expression &&
expression.$overlayToArray &&
expression.$overlayToArray(typeObject)
);
};
var _asFunction = asFunction;
asFunction = function As_Array (expression) {
var result = _asFunction(expression);
if ((result === null) && (expression && expression.$overlayToArray))
result = expression.$overlayToArray(typeObject);
return result;
};
castFunction = function CastArray (expression) {
if (_isFunction(expression))
return expression;
if (expression && expression.$overlayToArray) {
var overlayArray = expression.$overlayToArray(typeObject);
if (overlayArray)
return overlayArray;
}
throwCastError(expression);
};
break;
case "char":
customCheckOnly = true;
asFunction = throwInvalidAsError;
break;
case "integer":
customCheckOnly = true;
asFunction = throwInvalidAsError;
castFunction = integerCastFunction;
break;
case "number":
customCheckOnly = true;
asFunction = throwCastError;
castFunction = numericCastFunction;
break;
case "int64":
customCheckOnly = true;
asFunction = throwCastError;
castFunction = function Cast_Int64 (expression) {
return int64CastFunction(expression);
};
break;
}
if (checkMethod && customCheckOnly) {
isFunction = checkMethod;
asFunction = function As_Checked (expression) {
if (checkMethod(expression))
return expression;
else
return null;
};
}
if (isIEnumerable || isICollection || isIList) {
var innerAsFunction = asFunction;
var innerCastFunction = castFunction;
var createOverlay = function Overlay_ArrayInterface (value) {
if (JSIL.IsArray(value)) {
var tElement = $jsilcore.System.Object.__Type__;
if (typeObject.__GenericArguments__.length === 1)
tElement = typeObject.__GenericArgumentValues__[0];
var tOverlay = JSIL.ArrayInterfaceOverlay.Of(tElement);
return new tOverlay(value);
}
return value;
};
asFunction = function As_ArrayInterface (value) {
// FIXME: I think the order of these function calls should be reversed.
return createOverlay(innerAsFunction(value));
};
castFunction = function Cast_ArrayInterface (value) {
// FIXME: I think the order of these function calls should be reversed.
return createOverlay(innerCastFunction(value));
};
}
if (isInterface) {
var wrappedFunctions = JSIL.WrapCastMethodsForInterfaceVariance(typeObject, isFunction, asFunction);
isFunction = wrappedFunctions.is;
asFunction = wrappedFunctions.as;
}
return {
Cast: castFunction,
As: asFunction,
Is: isFunction
}
};
JSIL.MakeCastMethods = function (publicInterface, typeObject, specialType) {
var state = null;
var doLazyInitialize = function () {
if (state === null)
state = JSIL.$ActuallyMakeCastMethods(publicInterface, typeObject, specialType);
};
var getIsMethod = function () {
doLazyInitialize();
return state.Is;
}
var getAsMethod = function () {
doLazyInitialize();
return state.As;
}
var getCastMethod = function () {
doLazyInitialize();
return state.Cast;
}
JSIL.SetLazyValueProperty(publicInterface, "$Is", getIsMethod);
JSIL.SetLazyValueProperty(typeObject, "$Is", getIsMethod);
JSIL.SetLazyValueProperty(publicInterface, "$As", getAsMethod);
JSIL.SetLazyValueProperty(typeObject, "$As", getAsMethod);
JSIL.SetLazyValueProperty(publicInterface, "$Cast", getCastMethod);
JSIL.SetLazyValueProperty(typeObject, "$Cast", getCastMethod);
};
JSIL.MakeTypeAlias = function (sourceAssembly, fullName) {
var context = $private;
var tbn = sourceAssembly.$typesByName;
Object.defineProperty(
context.$typesByName, fullName, {
configurable: false,
enumerable: true,
get: function () {
return tbn[fullName];
}
}
);
if (sourceAssembly.__AssemblyId__ === context.__AssemblyId__) {
// HACK: This is a recursive type alias, so don't define the name alias.
// We still want to leave the typesByName logic above intact since the two aliases have separate assembly
// objects, and thus separate typesByName lists, despite sharing an assembly id.
return;
}
var privateName = JSIL.ResolveName(context, fullName, true);
var sourcePrivateName = null;
var getter = function TypeAlias_getter () {
if (!sourcePrivateName)
sourcePrivateName = JSIL.ResolveName(sourceAssembly, fullName, true);
var result = sourcePrivateName.get();
if (!result)
JSIL.RuntimeError("Type alias for '" + fullName + "' points to a nonexistent type");
return result;
};
privateName.setLazy(getter);
};
JSIL.$MakeOptimizedNumericSwitch = function (output, variableName, cases, defaultCase) {
// TODO: For large numbers of cases, do a divide-and-conquer search to reduce number of comparisons, like:
// if (x > b) {
// if (x === c) casec else if (x === d) cased else casedefault
// } else {
// if (x === a) casea else if (x === b) caseb else casedefault
// }
// switch statements appear to generate better code in JS runtimes now. Neat!
var useIfStatements = false;
if (useIfStatements) {
for (var i = 0, l = cases.length; i < l; i++) {
var caseDesc = cases[i];
if (i === 0)
output.push("if (" + variableName + " === " + caseDesc.key + ") {");
else
output.push("} else if (" + variableName + " === " + caseDesc.key + ") {");
output.push(" " + caseDesc.code);
}
if (defaultCase) {
output.push("} else {");
output.push(" " + defaultCase);
}
output.push("}");
} else {
output.push("switch (" + variableName + ") {");
for (var i = 0, l = cases.length; i < l; i++) {
var caseDesc = cases[i];
output.push(" case " + caseDesc.key + ":");
output.push(" " + caseDesc.code);
output.push(" break;");
}
if (defaultCase) {
output.push(" default:");
output.push(" " + defaultCase);
output.push(" break;");
}
output.push("}");
}
};
JSIL.MakeTypeConstructor = function (typeObject, maxConstructorArguments) {
if (typeObject.__IsClosed__ === false) {
return function () {
JSIL.RuntimeError("Cannot create an instance of an open type");
};
}
var ctorClosure = {
typeObject: typeObject,
fieldInitializer: $jsilcore.FunctionNotInitialized,
isTypeInitialized: false
};
var ctorBody = [];
var argumentNames = [];
ctorBody.push("if (!isTypeInitialized) {");
ctorBody.push(" JSIL.RunStaticConstructors(typeObject.__PublicInterface__, typeObject);");
ctorBody.push(" fieldInitializer = JSIL.GetFieldInitializer(typeObject);");
ctorBody.push(" isTypeInitialized = true;");
ctorBody.push("}");
ctorBody.push("");
ctorBody.push("fieldInitializer(this);");
ctorBody.push("");
// Only generate specialized dispatch if we know the number of arguments.
if (typeof (maxConstructorArguments) === "number") {
var numPositionalArguments = maxConstructorArguments | 0;
ctorBody.push("var argc = arguments.length | 0;");
var cases = [
{ key: 0, code: (typeObject.__IsStruct__ ? "return;" : "return this._ctor();") }
];
for (var i = 1; i < (numPositionalArguments + 1); i++)
argumentNames.push("arg" + (i - 1));
for (var i = 1; i < (numPositionalArguments + 1); i++) {
var line = "return this._ctor(";
for (var j = 0, jMax = Math.min(argumentNames.length, i); j < jMax; j++) {
line += argumentNames[j];
if (j == jMax - 1)
line += ");";
else
line += ", ";
}
cases.push({ key: i, code: line });
}
JSIL.$MakeOptimizedNumericSwitch(
ctorBody, "argc", cases,
"JSIL.RuntimeError('Too many arguments passed to constructor; expected 0 - " + maxConstructorArguments + ", got ' + arguments.length);"
);
} else if (typeObject.__IsStruct__) {
ctorBody.push("if (arguments.length === 0)");
ctorBody.push(" return;");
ctorBody.push("else");
ctorBody.push(" return this._ctor.apply(this, arguments);");
} else {
ctorBody.push("return this._ctor.apply(this, arguments);");
}
var result = JSIL.CreateNamedFunction(
typeObject.__FullName__, argumentNames,
ctorBody.join("\r\n"),
ctorClosure
);
return result;
};
JSIL.MakeType = function (typeArgs, initializer) {
var baseType = typeArgs.BaseType || null;
var fullName = typeArgs.Name || null;
var isReferenceType = Boolean(typeArgs.IsReferenceType);
var isPublic = Boolean(typeArgs.IsPublic);
var genericArguments = typeArgs.GenericParameters || $jsilcore.ArrayNull;
var maxConstructorArguments = typeArgs.MaximumConstructorArguments;
if (typeof (isPublic) === "undefined")
JSIL.Host.abort(new Error("Must specify isPublic"));
var assembly = $private;
var localName = JSIL.GetLocalName(fullName);
var memberBuilder = new JSIL.MemberBuilder($private);
var attributes = memberBuilder.attributes;
var stack = null;
if (typeof (printStackTrace) === "function")
stack = printStackTrace();
var typeObject, staticClassObject;
var createTypeObject = function CreateTypeObject () {
var runtimeType;
runtimeType = $jsilcore.$GetRuntimeType(assembly, fullName);
// We need to make the type object we're constructing available early on, in order for
// recursive generic base classes to work.
typeObject = JSIL.$GetSpecialType(fullName).typeObject;
if (!typeObject)
typeObject = JSIL.CreateSingletonObject(runtimeType);
// Needed for basic bookkeeping to function correctly.
typeObject.__Context__ = assembly;
JSIL.SetValueProperty(typeObject, "__FullName__", fullName);
JSIL.SetValueProperty(typeObject, "__ShortName__", localName);
typeObject.__ReflectionCache__ = null;
// Without this, the generated constructor won't behave correctly for 0-argument construction
typeObject.__IsStruct__ = !isReferenceType;
var ctorFunction = null;
if (genericArguments && genericArguments.length) {
ctorFunction = function OpenType () {
JSIL.RuntimeError("Cannot create an instance of open generic type '" + fullName + "'");
};
} else {
ctorFunction = JSIL.MakeTypeConstructor(typeObject, maxConstructorArguments);
}
staticClassObject = ctorFunction;
JSIL.SetValueProperty(typeObject, "__PublicInterface__", staticClassObject);
JSIL.SetValueProperty(staticClassObject, "__Type__", typeObject);
typeObject.__MaxConstructorArguments__ = maxConstructorArguments;
var typeId = JSIL.AssignTypeId(assembly, fullName);
JSIL.SetTypeId(typeObject, staticClassObject, typeId);
// FIXME: This should probably be a per-assembly dictionary to work right in the case of name collisions.
$jsilcore.InFlightObjectConstructions[fullName] = {
fullName: fullName,
typeObject: typeObject,
publicInterface: staticClassObject
};
if (fullName !== "System.Object") {
JSIL.SetValueProperty(typeObject, "__BaseType__", JSIL.ResolveTypeReference(baseType, assembly)[1]);
var baseTypeName = typeObject.__BaseType__.__FullName__ || baseType.toString();
var baseTypeInterfaces = typeObject.__BaseType__.__Interfaces__ || $jsilcore.ArrayNull;
// HACK: We can't do this check before creating the constructor, because recursion. UGH.
typeObject.__IsStruct__ = typeObject.__IsStruct__ && (baseTypeName === "System.ValueType");
typeObject.__InheritanceDepth__ = (typeObject.__BaseType__.__InheritanceDepth__ || 0) + 1;
typeObject.__Interfaces__ = Array.prototype.slice.call(baseTypeInterfaces);
typeObject.__ExternalMethods__ = Array.prototype.slice.call(typeObject.__BaseType__.__ExternalMethods__ || $jsilcore.ArrayNull);
typeObject.__RenamedMethods__ = JSIL.CreateDictionaryObject(typeObject.__BaseType__.__RenamedMethods__ || null);
} else {
JSIL.SetValueProperty(typeObject, "__BaseType__", null);
typeObject.__IsStruct__ = false;
typeObject.__InheritanceDepth__ = 0;
typeObject.__Interfaces__ = [];
typeObject.__ExternalMethods__ = [];
typeObject.__RenamedMethods__ = JSIL.CreateDictionaryObject(null);
}
typeObject.__IsArray__ = false;
typeObject.__IsNullable__ = fullName.indexOf("System.Nullable`1") === 0;
typeObject.__FieldList__ = $jsilcore.ArrayNotInitialized;
typeObject.__FieldInitializer__ = $jsilcore.FunctionNotInitialized;
typeObject.__MemberCopier__ = $jsilcore.FunctionNotInitialized;
typeObject.__Comparer__ = $jsilcore.FunctionNotInitialized;
typeObject.__Marshaller__ = $jsilcore.FunctionNotInitialized;
typeObject.__Unmarshaller__ = $jsilcore.FunctionNotInitialized;
typeObject.__UnmarshalConstructor__ = $jsilcore.FunctionNotInitialized;
typeObject.__ElementProxyConstructor__ = $jsilcore.FunctionNotInitialized;
typeObject.__Properties__ = [];
typeObject.__Initializers__ = [];
typeObject.__TypeInitialized__ = false;
typeObject.__IsNativeType__ = false;
typeObject.__AssignableTypes__ = null;
typeObject.__AssignableFromTypes__ = {};
JSIL.SetValueProperty(typeObject, "__IsReferenceType__", isReferenceType);
typeObject.__LockCount__ = 0;
typeObject.__Members__ = [];
// FIXME: I'm not sure this is right. See InheritedExternalStubError.cs
typeObject.__Attributes__ = attributes;
typeObject.__RanCctors__ = false;
typeObject.__RawMethods__ = [];
JSIL.FillTypeObjectGenericArguments(typeObject, genericArguments);
typeObject.IsInterface = false;
typeObject.__IsValueType__ = !isReferenceType;
typeObject.__IsByRef__ = false;
typeObject.__CustomPacking__ = typeArgs.Pack;
// Packings of 16 or more are silently ignored by the windows .NET runtime.
if (typeObject.__CustomPacking__ >= 16)
typeObject.__CustomPacking__ = 0;
typeObject.__CustomSize__ = typeArgs.SizeBytes;
typeObject.__ExplicitLayout__ = typeArgs.ExplicitLayout;
typeObject.__SequentialLayout__ = typeArgs.SequentialLayout;
// Lazily initialize struct's native size and alignment properties
if (typeObject.__IsStruct__) {
JSIL.SetLazyValueProperty(
typeObject, "__NativeAlignment__",
JSIL.ComputeNativeAlignmentOfStruct.bind(null, typeObject)
);
JSIL.SetLazyValueProperty(
typeObject, "__NativeSize__",
JSIL.ComputeNativeSizeOfStruct.bind(null, typeObject)
);
JSIL.SetLazyValueProperty(
typeObject, "__IsUnion__",
function () {
JSIL.GetFieldList(typeObject);
return typeObject.__IsUnion_BackingStore__;
}
);
}
if (stack !== null)
typeObject.__CallStack__ = stack;
var inited = false;
JSIL.SetValueProperty(staticClassObject, "toString", function TypePublicInterface_ToString () {
return "<" + fullName + " Public Interface>";
});
JSIL.SetValueProperty(typeObject, "toString", function Type_ToString () {
return JSIL.GetTypeName(this, true);
});
staticClassObject.prototype = JSIL.MakeProto(baseType, typeObject, fullName, false, assembly);
if (typeObject.__GenericArguments__.length > 0) {
staticClassObject.Of$NoInitialize = $jsilcore.$MakeOf$NoInitialize(staticClassObject);
staticClassObject.Of = $jsilcore.$MakeOf(staticClassObject);
typeObject.__IsClosed__ = false;
typeObject.__OfCache__ = {};
} else {
typeObject.__IsClosed__ = (baseType.__IsClosed__ !== false);
}
if (fullName === "System.Object") {
typeObject._IsAssignableFrom = function (typeOfValue) {
return true;
};
} else {
typeObject._IsAssignableFrom = function (typeOfValue) {
return typeOfValue.__AssignableTypes__[this.__TypeId__] === true;
};
}
for (var i = 0, l = typeObject.__GenericArguments__.length; i < l; i++) {
var ga = typeObject.__GenericArguments__[i];
var name = new JSIL.Name(ga, fullName);
var escapedKey = JSIL.EscapeName(ga);
JSIL.SetValueProperty(staticClassObject, escapedKey, name);
}
JSIL.ApplyExternals(staticClassObject, typeObject, fullName);
JSIL.MakeCastMethods(staticClassObject, typeObject, null);
delete $jsilcore.InFlightObjectConstructions[fullName];
return staticClassObject;
};
var state = null;
var getTypeObject = function GetTypeObject () {
if (state === null) {
state = createTypeObject();
}
return state;
};
var wrappedInitializer = null;
if (initializer) {
var makeWrappedInitializer = function (i, a) {
return function (to) {
var interfaceBuilder = new JSIL.InterfaceBuilder(a, to.__Type__, to);
return i(interfaceBuilder);
};
};
wrappedInitializer = makeWrappedInitializer(initializer, assembly);
}
JSIL.RegisterName(fullName, assembly, isPublic, getTypeObject, wrappedInitializer);
// Goddamn V8 closure leaks UGH JESUS
initializer = null;
wrappedInitializer = null;
return memberBuilder;
};
JSIL.MakeClass = function (baseType, fullName, isPublic, genericArguments, initializer) {
var typeArgs = {
BaseType: baseType,
Name: fullName,
GenericParameters: genericArguments,
IsReferenceType: true,
IsPublic: isPublic,
ConstructorAcceptsManyArguments: true
};
return JSIL.MakeType(typeArgs, initializer);
};
JSIL.MakeStruct = function (baseType, fullName, isPublic, genericArguments, initializer) {
var typeArgs = {
BaseType: baseType,
Name: fullName,
GenericParameters: genericArguments,
IsReferenceType: false,
IsPublic: isPublic,
ConstructorAcceptsManyArguments: true
};
return JSIL.MakeType(typeArgs, initializer);
};
JSIL.MakeInterface = function (fullName, isPublic, genericArguments, initializer, interfaces) {
var assembly = $private;
var localName = JSIL.GetLocalName(fullName);
if (typeof (initializer) !== "function") {
JSIL.RuntimeError("Non-function initializer passed to MakeInterface");
}
var callStack = null;
if (typeof (printStackTrace) === "function")
callStack = printStackTrace();
var memberBuilder = new JSIL.MemberBuilder(fullName);
var attributes = memberBuilder.attributes;
var creator = function CreateInterface () {
var publicInterface = new Object();
JSIL.SetValueProperty(publicInterface, "toString", function InterfacePublicInterface_ToString () {
return "<" + fullName + " Public Interface>";
});
var typeObject = JSIL.$MakeTypeObject(fullName);
publicInterface.prototype = null;
publicInterface.__Type__ = typeObject;
JSIL.SetValueProperty(typeObject, "__PublicInterface__", publicInterface);
JSIL.SetValueProperty(typeObject, "__BaseType__", null);
typeObject.__CallStack__ = callStack;
JSIL.SetTypeId(typeObject, publicInterface, JSIL.AssignTypeId(assembly, fullName));
typeObject.__Members__ = [];
typeObject.__RenamedMethods__ = {};
JSIL.SetValueProperty(typeObject, "__ShortName__", localName);
typeObject.__Context__ = $private;
JSIL.SetValueProperty(typeObject, "__FullName__", fullName);
typeObject.__TypeInitialized__ = false;
if (interfaces && interfaces.length) {
// FIXME: This seems wrong.
// JSIL.$CopyInterfaceMethods(interfaces, publicInterface);
}
JSIL.FillTypeObjectGenericArguments(typeObject, genericArguments);
JSIL.SetValueProperty(typeObject, "__IsReferenceType__", true);
typeObject.__AssignableTypes__ = null;
typeObject.IsInterface = true;
typeObject.__Attributes__ = attributes;
typeObject.__Interfaces__ = interfaces || [];
var interfaceBuilder = new JSIL.InterfaceBuilder(assembly, typeObject, publicInterface, "interface");
initializer(interfaceBuilder);
if (typeObject.__GenericArguments__.length > 0) {
publicInterface.Of$NoInitialize = $jsilcore.$MakeOf$NoInitialize(publicInterface);
publicInterface.Of = $jsilcore.$MakeOf(publicInterface);
typeObject.__IsClosed__ = false;
typeObject.__OfCache__ = {};
} else {
typeObject.__IsClosed__ = true;
typeObject.__AssignableFromTypes__ = {};
}
typeObject._IsAssignableFrom = function (typeOfValue) {
return typeOfValue.__AssignableTypes__[this.__TypeId__] === true;
};
JSIL.MakeCastMethods(publicInterface, typeObject, "interface");
return publicInterface;
};
JSIL.RegisterName(fullName, $private, isPublic, creator);
return memberBuilder;
};
JSIL.EnumValue = function (m) {
JSIL.RuntimeError("Cannot create an abstract instance of an enum");
};
JSIL.EnumValue.prototype = JSIL.CreatePrototypeObject(null);
JSIL.EnumValue.prototype.GetType = function () {
return this.__ThisType__;
};
JSIL.EnumValue.prototype.GetHashCode = function () {
return this.value;
};
JSIL.EnumValue.prototype.toString = function () {
if (!this.stringified) {
if (this.isFlags) {
var enumType = this.__ThisType__;
var publicInterface = enumType.__PublicInterface__;
var names = enumType.__Names__;
var result = [];
for (var i = 0, l = names.length; i < l; i++) {
var name = names[i];
var nameValue = publicInterface[name].value;
if (nameValue === this.value) {
result.push(name);
} else if (nameValue) {
if ((this.value & nameValue) === nameValue)
result.push(name);
}
}
if (result.length === 0)
this.stringified = this.value.toString();
else
this.stringified = result.join(", ");
} else {
this.stringified = this.value.toString();
}
}
return this.stringified;
};
JSIL.EnumValue.prototype.valueOf = function () {
return this.value;
}
/* old arglist: fullName, isPublic, members, isFlagsEnum */
JSIL.MakeEnum = function (_descriptor, _members) {
var descriptor, members;
if (arguments.length !== 2) {
descriptor = {
FullName: arguments[0],
IsPublic: arguments[1],
IsFlags: arguments[3] || false,
BaseType: $jsilcore.TypeRef("System.Int32")
};
members = arguments[2];
} else {
descriptor = _descriptor;
members = _members;
}
if (!descriptor || !members)
JSIL.RuntimeError("Invalid arguments");
var localName = JSIL.GetLocalName(descriptor.FullName);
var callStack = null;
if (typeof (printStackTrace) === "function")
callStack = printStackTrace();
var context = $private;
var typeObject, publicInterface;
var creator = function CreateEnum () {
publicInterface = function Enum__ctor () {
JSIL.RuntimeError("Cannot construct an instance of an enum");
};
typeObject = JSIL.$MakeTypeObject(descriptor.FullName);
publicInterface.prototype = JSIL.CreatePrototypeObject($jsilcore.System.Enum.prototype);
publicInterface.__Type__ = typeObject;
JSIL.SetValueProperty(typeObject, "__PublicInterface__", publicInterface);
JSIL.SetValueProperty(typeObject, "__BaseType__", $jsilcore.System.Enum.__Type__);
typeObject.__Context__ = context;
typeObject.__CallStack__ = callStack;
JSIL.SetValueProperty(typeObject, "__FullName__", descriptor.FullName);
typeObject.__IsArray__ = false;
typeObject.__IsEnum__ = true;
typeObject.__IsByRef__ = false;
typeObject.__IsValueType__ = true;
JSIL.SetValueProperty(typeObject, "__IsReferenceType__", false);
typeObject.__IsClosed__ = true;
typeObject.__TypeInitialized__ = false;
if (descriptor.BaseType) {
typeObject.__StorageType__ = JSIL.ResolveTypeReference(descriptor.BaseType)[1];
} else {
typeObject.__StorageType__ = $jsilcore.System.Int32.__Type__;
}
var typeId = JSIL.AssignTypeId(context, descriptor.FullName);
JSIL.SetValueProperty(typeObject, "__TypeId__", typeId);
JSIL.SetValueProperty(publicInterface, "__TypeId__", typeId);
typeObject.__IsFlagsEnum__ = descriptor.IsFlags;
// HACK to ensure that enum types implement the interfaces System.Enum does.
typeObject.__Interfaces__ = typeObject.__BaseType__.__Interfaces__;
var enumTypeId = JSIL.AssignTypeId($jsilcore, "System.Enum");
typeObject.__AssignableTypes__ = {};
typeObject.__AssignableTypes__[typeObject.__TypeId__] = true;
typeObject.__AssignableTypes__[enumTypeId] = true;
typeObject.__AssignableFromTypes__ = {};
typeObject.__AssignableFromTypes__[typeObject.__TypeId__] = true;
typeObject.__ValueToName__ = [];
typeObject.__Names__ = [];
JSIL.SetValueProperty(typeObject, "toString", function Type_ToString () {
return JSIL.GetTypeName(this, true);
});
JSIL.SetValueProperty(publicInterface, "toString", function Type_ToString () {
return "<" + descriptor.FullName + " Public Interface>";
});
typeObject.Of$NoInitialize = function () {
return typeObject;
};
typeObject.Of = function () {
return typeObject;
};
if (descriptor.IsFlags) {
publicInterface.$Flags = function FlagsEnum_Flags () {
var argc = arguments.length;
var resultValue = 0;
for (var i = 0; i < argc; i++) {
var flagName = arguments[i];
resultValue = resultValue | publicInterface[flagName].value;
}
return publicInterface.$MakeValue(resultValue, null);
};
} else {
publicInterface.$Flags = function Enum_Flags () {
JSIL.RuntimeError("Enumeration is not a flags enumeration.");
};
}
typeObject.CheckType = function Enum_CheckType (v) {
if (v.__ThisType__ === typeObject)
return true;
return false;
};
var valueType = publicInterface.$Value = JSIL.CreateNamedFunction(
descriptor.FullName,
["value", "name"],
"this.value = value;\r\n" +
"this.stringified = this.name = name;\r\n"
);
var valueProto = valueType.prototype = publicInterface.prototype;
// Copy members from EnumValue.prototype since we have to derive from System.Enum
for (var k in JSIL.EnumValue.prototype) {
JSIL.MakeIndirectProperty(valueProto, k, JSIL.EnumValue.prototype);
}
JSIL.SetValueProperty(
valueProto, "isFlags", descriptor.IsFlags
);
JSIL.SetValueProperty(
valueProto, "__ThisType__", typeObject
);
JSIL.SetValueProperty(
valueProto, "__ThisTypeId__", typeObject.__TypeId__
);
// Because there's no way to change the behavior of ==,
// we need to ensure that all calls to $MakeValue for a given value
// return the same instance.
// FIXME: Memory leak! Weak references would help here, but TC39 apparently thinks
// hiding GC behavior from developers is more important than letting them control
// memory usage.
var valueCache = JSIL.CreateDictionaryObject(null);
var fixedUpEnumInterfaces = false;
var maybeFixUpInterfaces = function () {
// HACK: Letting System.Enum's interfaces get fixed up normally causes a cycle.
if (!fixedUpEnumInterfaces) {
fixedUpEnumInterfaces = true;
if (!$jsilcore.CanFixUpEnumInterfaces) {
$jsilcore.CanFixUpEnumInterfaces = true;
JSIL.FixupInterfaces($jsilcore.System.Enum, $jsilcore.System.Enum.__Type__);
JSIL.RunStaticConstructors(publicInterface, typeObject);
JSIL.FixupInterfaces(publicInterface, typeObject);
}
}
};
publicInterface.$MakeValue = function (value, name) {
maybeFixUpInterfaces();
var result = valueCache[value];
if (!result)
result = valueCache[value] = new valueType(value, name);
return result;
};
return publicInterface;
};
var initializer = function ($) {
var asm = JSIL.GetAssembly("mscorlib", true) || $jsilcore;
if (!asm)
JSIL.RuntimeError("mscorlib not found!");
var enumType = JSIL.GetTypeFromAssembly(asm, "System.Enum");
var prototype = JSIL.CreatePrototypeObject(enumType.__PublicInterface__.prototype);
JSIL.SetValueProperty(prototype, "__BaseType__", enumType);
JSIL.SetValueProperty(prototype, "__ShortName__", localName);
JSIL.SetValueProperty(prototype, "__FullName__", descriptor.FullName);
JSIL.SetValueProperty($, "__BaseType__", enumType);
$.prototype = prototype;
var ib = new JSIL.InterfaceBuilder(context, typeObject, publicInterface);
for (var key in members) {
if (!members.hasOwnProperty(key))
continue;
var value = members[key];
if (typeof (value) === "function")
continue;
value = Math.floor(value);
$.__Type__.__Names__.push(key);
$.__Type__.__ValueToName__[value] = key;
var makeGetter = function (key, value) {
return function () {
return $.$MakeValue(value, key);
}
};
JSIL.SetLazyValueProperty($, key, makeGetter(key, value));
var memberDescriptor = ib.ParseDescriptor({Public: true, Static: true}, key);
var mb = new JSIL.MemberBuilder(context);
var data = {
fieldType: $.__Type__,
constant: value
};
ib.PushMember("FieldInfo", memberDescriptor, data, mb);
}
// FIXME: This is doing FixupInterfaces on Enum every time instead of on the specific enum type.
// Should be harmless, but...?
// JSIL.FixupInterfaces(enumType.__PublicInterface__, enumType);
JSIL.MakeCastMethods($, $.__Type__, "enum");
};
JSIL.RegisterName(descriptor.FullName, $private, descriptor.IsPublic, creator, initializer);
};
JSIL.MakeInterfaceMemberGetter = function (thisReference, name) {
return function GetInterfaceMember () {
return thisReference[name];
};
};
JSIL.CheckDerivation = function (haystack, needle) {
var proto = haystack;
while (proto !== null) {
if (proto === needle)
return true;
if (typeof (proto) !== "object")
return false;
proto = Object.getPrototypeOf(proto);
}
return false;
};
JSIL.IsArray = function (value) {
if (value === null)
return false;
else if (Array.isArray(value))
return true;
if (JSIL.IsTypedArray(value))
return true;
return false;
};
JSIL.AreTypedArraysSupported = function () {
return (typeof (ArrayBuffer) !== "undefined");
}
JSIL.IsTypedArray = function (value) {
if ((typeof (value) === "object") && value && value.buffer) {
if (typeof (ArrayBuffer) !== "undefined") {
if (Object.getPrototypeOf(value.buffer) === ArrayBuffer.prototype)
return true;
}
}
return false;
}
JSIL.IsSystemArray = function (value) {
if (JSIL.IsArray(value))
return true;
if (!value)
return false;
var valueType = value.__ThisType__;
if (valueType)
return valueType.__IsArray__;
else
return JSIL.GetType(value).__IsArray__;
};
JSIL.GetBaseType = function (typeObject) {
var result = typeObject.__BaseType__;
if (typeof (result) === "string")
result = JSIL.ResolveName(typeObject.__Context__, result, true);
if ((typeof (result) !== "undefined") && (typeof (result.get) === "function"))
result = result.get();
if ((typeof (result) !== "undefined") && (typeof (result.__Type__) === "object"))
result = result.__Type__;
return result;
};
JSIL.GetType = function (value) {
var type = typeof (value);
if (value === null)
return null;
else if (type === "undefined")
return null;
if ((type === "object") || (type === "function")) {
var tt;
if (tt = value.__ThisType__)
return tt;
else if (value.GetType)
return value.GetType();
else if (JSIL.IsTypedArray(value))
return JSIL.$GetTypeForTypedArray(value);
else if (JSIL.IsArray(value))
return System.Array.__Type__;
else
return System.Object.__Type__;
} else if (type === "string") {
return System.String.__Type__;
} else if (type === "number") {
if (value === (value | 0))
return System.Int32.__Type__;
else
return System.Double.__Type__;
} else if (type === "boolean") {
return System.Boolean.__Type__;
} else {
return System.Object.__Type__;
}
};
JSIL.$GetTypeForTypedArray = function (value) {
var proto = Object.getPrototypeOf(value);
var typeName = proto.constructor.name || String(proto.constructor);
var typeKey = $jsilcore.TypedArrayToType[typeName];
if (typeKey) {
// HACK: Construct an array type given the element type we know about for this typed array constructor.
var parsedTypeName = JSIL.ParseTypeName(typeKey);
var elementType = JSIL.GetTypeInternal(parsedTypeName, $jsilcore, true);
var arrayType = System.Array.Of(elementType).__Type__;
return arrayType;
}
// Who knows what happened, just return System.Array.
return System.Array.__Type__;
};
// type may be a a type object, a type public interface, or an instance of a type.
JSIL.GetTypeName = function (type, dotNetTypeToString) {
if (type === null)
return "System.Object";
if (typeof (type) === "string")
return "System.String";
var typeObject = null;
if (type.__PublicInterface__)
typeObject = type;
else if (type.__Type__)
typeObject = type.__Type__;
else if (type.__ThisType__)
typeObject = type.__ThisType__;
if (typeObject) {
var result = typeObject.__FullName__;
// Emulate the exact behavior of Type.ToString in .NET
if (dotNetTypeToString && !typeObject.__IsClosed__) {
result = typeObject.__FullNameWithoutArguments__ || typeObject.__FullName__;
result += "[";
var ga = typeObject.__GenericArguments__;
var gav = typeObject.__GenericArgumentValues__;
for (var i = 0, l = ga.length; i < l; i++) {
if (gav && gav[i]) {
result += gav[i].__ShortName__;
} else {
result += ga[i];
}
if (i < (l - 1))
result += ",";
}
result += "]";
}
return result;
}
var result;
if (typeof (type.prototype) !== "undefined")
result = type.prototype.__FullName__;
if (typeof (result) === "undefined")
result = typeof (type);
if (typeof (result) !== "string")
result = "unknown type";
return result;
};
JSIL.Coalesce = function (lhs, rhs) {
if (lhs == null)
return rhs;
else
return lhs;
};
JSIL.Dynamic.Cast = function (value, expectedType) {
return value;
};
JSIL.$MakeGenericMethodBinder = function (groupDispatcher, methodFullName, genericArgumentCount, argumentCounts) {
var body = [];
var maxArgumentCount = 0;
var normalArgumentNames = [];
var normalArgumentList = "";
var binderArgumentNames = [];
var binderArgumentList = "";
var closure = {
dispatcherKey: groupDispatcher,
methodFullName: methodFullName
};
for (var i = 0; i < genericArgumentCount; i++) {
binderArgumentNames.push("genericArg" + i);
binderArgumentList += binderArgumentNames[i];
if (i !== (genericArgumentCount - 1))
binderArgumentList += ", ";
}
for (var k in argumentCounts)
maxArgumentCount = Math.max(maxArgumentCount, k | 0);
for (var i = 0; i < maxArgumentCount; i++) {
normalArgumentNames.push("arg" + i);
normalArgumentList += normalArgumentNames[i];
if (i !== (maxArgumentCount - 1))
normalArgumentList += ", ";
}
/*
result.call = function BoundGenericMethod_Call (thisReference) {
// concat doesn't work on the raw 'arguments' value :(
var invokeArguments = genericArguments.concat(
Array.prototype.slice.call(arguments, 1)
);
return body.apply(thisReference, invokeArguments);
};
result.apply = function BoundGenericMethod_Apply (thisReference, invokeArguments) {
// This value might be an Arguments object instead of an array.
invokeArguments = genericArguments.concat(
Array.prototype.slice.call(invokeArguments)
);
return body.apply(thisReference, invokeArguments);
};
return result;
*/
// The user might pass in a public interface instead of a type object, so map that to the type object.
for (var i = 0; i < genericArgumentCount; i++) {
var varName = binderArgumentNames[i];
body.push("if (" + varName + " && " + varName + ".__Type__)");
body.push(" " + varName + " = " + varName + ".__Type__");
}
var innerDispatchCode = [" switch (argc) {"];
for (var k in argumentCounts) {
var localArgCount = k | 0;
innerDispatchCode.push(" case " + localArgCount + ":");
innerDispatchCode.push(" return dispatcher.call(");
innerDispatchCode.push(" thisReference,");
innerDispatchCode.push(" " + binderArgumentList + (
(localArgCount !== 0)
? ", "
: ""
)
);
for (var i = 0; i < localArgCount; i++) {
innerDispatchCode.push(
" " + normalArgumentNames[i] + (
(i === localArgCount - 1)
? ""
: ", "
)
);
}
innerDispatchCode.push(" );");
}
innerDispatchCode.push(" default:");
innerDispatchCode.push(" JSIL.RuntimeError('Unexpected argument count');");
innerDispatchCode.push(" }");
body.push("");
body.push("var boundThis = this;");
body.push("var dispatcher = this[dispatcherKey];");
body.push("");
body.push("var result = function BoundGenericMethod_Invoke (");
body.push(" " + normalArgumentList);
body.push(") {");
body.push(" var thisReference = this;");
// HACK: Strict-mode functions get an undefined 'this' in cases where none is provided.
// In non-strict mode, 'this' will be the global object, which would break this.
// Thanks to strict mode, we don't need custom .call or .apply methods!
body.push(" if (typeof (thisReference) === 'undefined')");
body.push(" thisReference = boundThis;");
body.push(" var argc = arguments.length | 0;");
body.push(" ");
body.push.apply(body, innerDispatchCode);
body.push("};");
body.push("");
body.push("return result;");
var result = JSIL.CreateNamedFunction(
methodFullName + "`" + genericArgumentCount + ".BindGenericArguments[" + maxArgumentCount + "]",
binderArgumentNames,
body.join("\r\n"),
closure
);
return result;
};
JSIL.MemberBuilder = function (context) {
this.context = context;
this.attributes = [];
this.overrides = [];
this.parameterInfo = {};
};
JSIL.MemberBuilder.prototype.Attribute = function (attributeType, getConstructorArguments, initializer) {
var record = new JSIL.AttributeRecord(this.context, attributeType, getConstructorArguments, initializer);
this.attributes.push(record);
// Allows call chaining for multiple attributes
return this;
};
JSIL.MemberBuilder.prototype.Overrides = function (interfaceNameOrReference, interfaceMemberName) {
var record = new JSIL.OverrideRecord(interfaceNameOrReference, interfaceMemberName);
this.overrides.push(record);
return this;
};
JSIL.MemberBuilder.prototype.Parameter = function (index, name, attributes) {
this.parameterInfo[index] = {
name: name,
attributes: attributes || null
};
return this;
};
JSIL.InterfaceBuilder = function (context, typeObject, publicInterface, builderMode) {
this.context = context;
this.typeObject = typeObject;
this.publicInterface = publicInterface;
if (Object.getPrototypeOf(typeObject) === Object.prototype) {
// HACK: Handle the fact that ImplementExternals doesn't pass us a real type object.
this.namespace = this.typeObject.__FullName__;
} else {
this.namespace = JSIL.GetTypeName(typeObject);
}
this.externals = JSIL.AllImplementedExternals[this.namespace];
if (typeof (this.externals) !== "object")
this.externals = JSIL.AllImplementedExternals[this.namespace] = {};
this.builderMode = builderMode || "class";
this._genericParameterCache = {};
var selfRef = typeObject;
var gaNames = typeObject.__GenericArguments__;
if (gaNames && gaNames.length > 0) {
var genericArgs = [];
for (var i = 0, l = gaNames.length; i < l; i++) {
var gpName = gaNames[i];
var gp = new JSIL.GenericParameter(gpName, this.namespace);
genericArgs.push(gp);
this._genericParameterCache[gpName] = gp;
}
selfRef = new JSIL.TypeRef(context, this.namespace, genericArgs);
}
Object.defineProperty(this, "Type", {
configurable: false,
enumerable: true,
value: selfRef
});
Object.defineProperty(this, "prototype", {
configurable: false,
enumerable: false,
get: function () {
JSIL.RuntimeError("Old-style use of $.prototype");
}
});
this.DefineTypeAliases(
JSIL.GetCorlib, [
"System.Byte", "System.UInt16", "System.UInt32", "System.UInt64",
"System.SByte", "System.Int16", "System.Int32", "System.Int64",
"System.Single", "System.Double", "System.String", "System.Object",
"System.Boolean", "System.Char", "System.IntPtr", "System.UIntPtr"
]
);
this.memberDescriptorPrototype = {
Static: false,
Public: false,
SpecialName: false,
Name: null,
toString: function () {
return "<" + this.Name + " Descriptor>";
}
};
this.anonymousMemberCount = 0;
};
JSIL.InterfaceBuilder.prototype.DefineTypeAliases = function (getAssembly, names) {
var asm = null;
var makeGetter = function (name) {
return function GetTypeAlias () {
if (asm === null)
asm = getAssembly();
return asm.TypeRef(name);
};
};
for (var i = 0; i < names.length; i++) {
var name = names[i];
var key = JSIL.GetLocalName(name);
JSIL.SetLazyValueProperty(
this, key, makeGetter(name)
);
}
};
JSIL.InterfaceBuilder.prototype.toString = function () {
return "<Interface Builder for " + this.namespace + ">";
};
JSIL.InterfaceBuilder.prototype.GenericParameter = function (name) {
var result = this._genericParameterCache[name];
if (!result)
result = this._genericParameterCache[name] = new JSIL.GenericParameter(name, this.namespace);
return result;
};
JSIL.InterfaceBuilder.prototype.SetValue = function (key, value) {
var descriptor = {
configurable: true,
enumerable: true,
value: value
};
Object.defineProperty(this.publicInterface, key, descriptor);
Object.defineProperty(this.typeObject, key, descriptor);
if (typeof (this.publicInterface.prototype) !== "undefined")
Object.defineProperty(this.publicInterface.prototype, key, descriptor);
};
JSIL.InterfaceBuilder.prototype.ParseDescriptor = function (descriptor, name, signature) {
if (name === null) {
name = "anonymous$" + this.anonymousMemberCount;
this.anonymousMemberCount += 1;
}
var result = JSIL.CreateDictionaryObject(this.memberDescriptorPrototype);
var escapedName = JSIL.EscapeName(name);
result.Static = descriptor.Static || false;
result.Public = descriptor.Public || false;
result.Virtual = descriptor.Virtual || false;
result.ReadOnly = descriptor.ReadOnly || false;
if (this.builderMode === "interface") {
// HACK: Interfaces have different default visibility than classes, so enforce that.
result.Public = descriptor.Public = true;
result.Static = descriptor.Static = false;
}
result.Name = name;
result.EscapedName = escapedName;
if (
signature &&
signature.genericArgumentNames &&
signature.genericArgumentNames.length
) {
result.EscapedName += "$b" + signature.genericArgumentNames.length;
}
result.SpecialName = (name == ".ctor") || (name == "_ctor") ||
(name.indexOf(".cctor") === 0) ||
(name.indexOf("_cctor") === 0) ||
(name.indexOf("op_") === 0);
JSIL.SetValueProperty(
result, "Target",
(result.Static || this.typeObject.IsInterface) ? this.publicInterface : this.publicInterface.prototype,
false
);
return result;
};
JSIL.InterfaceBuilder.prototype.PushMember = function (type, descriptor, data, memberBuilder, forExternal) {
var members = this.typeObject.__Members__;
if (!JSIL.IsArray(members))
this.typeObject.__Members__ = members = [];
// Simplify usage of member records by not requiring a null check on data
if (!data)
data = JSIL.CreateDictionaryObject(null);
// Throw if two members with identical signatures and names are added
if (data.signature) {
var includeReturnType =
descriptor.SpecialName;
var existingMembersWithSameNameAndSignature = members.filter(function (m) {
if (!m.data.signature)
return false;
var sig1 = m.data.signature.GetNamedKey(m.descriptor.EscapedName, includeReturnType);
var sig2 = data.signature.GetNamedKey(descriptor.EscapedName, includeReturnType);
return (sig1 == sig2);
});
if (existingMembersWithSameNameAndSignature.length > 0) {
if (forExternal) {
// No need to push this, the external is already implemented. Cool!
} else {
// This means that we accidentally implemented the same method twice, or something equally terrible.
var msgPrefix = includeReturnType ?
"A member with the signature '" :
"A member with the name and argument list '";
JSIL.RuntimeError(
msgPrefix + data.signature.toString(descriptor.EscapedName, includeReturnType) +
"' has already been declared in the type '" +
this.typeObject.__FullName__ + "'."
);
}
}
}
var record = new JSIL.MemberRecord(type, descriptor, data, memberBuilder.attributes, memberBuilder.overrides);
Array.prototype.push.call(members, record);
return members.length - 1;
};
JSIL.$PlacePInvokeMember = function (
target, memberName, signature, methodName, pInvokeInfo
) {
var newValue = null;
var existingValue = target[memberName];
if (existingValue) {
// JSIL.RuntimeError("PInvoke member " + memberName + " obstructed");
// Most likely explanation is that an external method took our place.
return;
}
var dllName = pInvokeInfo.Module;
var importedName = pInvokeInfo.EntryPoint || methodName;
var lookupThunk = function PInvokeLookupThunk () {
var module = JSIL.PInvoke.GetModule(dllName, false);
if (!module)
return (function MissingPInvokeModule () {
throw new System.DllNotFoundException("Unable to load DLL '" + dllName + "': The specified module could not be found.");
});
var methodImpl = JSIL.PInvoke.FindNativeMethod(module, importedName);
if (!methodImpl)
return (function MissingPInvokeEntryPoint () {
throw new System.EntryPointNotFoundException("Unable to find an entry point named '" + importedName + "' in DLL '" + dllName + "'.");
});
var wrapper = JSIL.PInvoke.CreateManagedToNativeWrapper(
module, methodImpl, memberName, signature, pInvokeInfo, null
);
return wrapper;
};
JSIL.SetLazyValueProperty(target, memberName, lookupThunk);
};
JSIL.InterfaceBuilder.prototype.PInvokeMethod = function (_descriptor, methodName, signature, pInvokeInfo) {
var descriptor = this.ParseDescriptor(_descriptor, methodName, signature);
var mangledName = signature.GetNamedKey(descriptor.EscapedName, true);
var prefix = "";
var fullName = this.namespace + "." + methodName;
if (!descriptor.Static)
JSIL.RuntimeError("PInvoke methods must be static: " + fullName);
if (!pInvokeInfo)
JSIL.RuntimeError("PInvoke methods must have PInvoke info");
if (!pInvokeInfo.Module)
JSIL.RuntimeError("PInvoke methods must have a module name");
JSIL.$PlacePInvokeMember(
descriptor.Target, mangledName, signature, methodName, pInvokeInfo
);
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember("MethodInfo", descriptor, {
signature: signature,
genericSignature: null,
mangledName: mangledName,
isExternal: true,
isPInvoke: true,
isPlaceholder: false,
isConstructor: false,
parameterInfo: memberBuilder.parameterInfo,
pInvokeInfo: pInvokeInfo
}, memberBuilder, true);
return memberBuilder;
};
JSIL.$PlaceExternalMember = function (
target, implementationSource, implementationPrefix,
memberName, namespace, getDisplayName
) {
var newValue = null;
var existingValue = target[memberName];
if (implementationSource.hasOwnProperty(implementationPrefix + memberName)) {
newValue = implementationSource[implementationPrefix + memberName][1];
} else if (!target.hasOwnProperty(memberName)) {
if (!getDisplayName)
getDisplayName = function () { return memberName; };
newValue = JSIL.MakeExternalMemberStub(namespace, getDisplayName, existingValue);
newValue.__PlaceholderFor__ = memberName;
}
if (newValue === null)
return;
if (existingValue === newValue)
return;
if (existingValue) {
// console.log("replacing '" + memberName + "':", existingValue, "\r\n with:", newValue);
}
JSIL.SetValueProperty(target, memberName, newValue);
};
JSIL.InterfaceBuilder.prototype.ExternalMembers = function (isInstance /*, ...names */) {
var impl = this.externals;
var prefix = isInstance ? "instance$" : "";
var target = this.publicInterface;
if (isInstance)
target = target.prototype;
for (var i = 1, l = arguments.length; i < l; i++) {
var memberName = arguments[i];
JSIL.$PlaceExternalMember(
target, impl, prefix, memberName, this.namespace, null
);
}
};
JSIL.InterfaceBuilder.prototype.Constant = function (_descriptor, name, value) {
var descriptor = this.ParseDescriptor(_descriptor, name);
var data = {
constant: value
};
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember("FieldInfo", descriptor, data, memberBuilder);
JSIL.SetValueProperty(this.publicInterface, descriptor.EscapedName, value);
return memberBuilder;
};
JSIL.InterfaceBuilder.MakeProperty = function (typeShortName, name, target, methodSource, recursed) {
var prop = {
configurable: true,
enumerable: true
};
var interfacePrefix = JSIL.GetParentName(name);
if (interfacePrefix.length)
interfacePrefix += ".";
var localName = JSIL.GetLocalName(name);
var getterName = JSIL.EscapeName(interfacePrefix + "get_" + localName);
var setterName = JSIL.EscapeName(interfacePrefix + "set_" + localName);
var getter = methodSource[getterName];
var setter = methodSource[setterName];
if (typeof (getter) === "function") {
prop["get"] = getter;
} else {
prop["get"] = function () {
JSIL.RuntimeError("Property is not readable");
};
}
if (typeof (setter) === "function") {
prop["set"] = setter;
} else {
prop["set"] = function () {
JSIL.RuntimeError("Property is not writable");
};
}
if (!prop.get && !prop.set) {
prop["get"] = prop["set"] = function () {
JSIL.RuntimeError("Property has no getter or setter: " + name + "\r\n looked for: " + getterName + " & " + setterName);
};
}
var escapedName = JSIL.EscapeName(name);
Object.defineProperty(target, escapedName, prop);
// HACK: Ensure that we do not override BaseType$Foo with a derived implementation of $Foo.
if (!recursed) {
var typeQualifiedName = JSIL.EscapeName(typeShortName + "$" + interfacePrefix + localName);
Object.defineProperty(target, typeQualifiedName, prop);
}
if ((getter && getter.__IsMembrane__) || (setter && setter.__IsMembrane__)) {
JSIL.RebindPropertyAfterPreInit(target, escapedName);
if (!recursed)
JSIL.RebindPropertyAfterPreInit(target, typeQualifiedName);
}
};
JSIL.InterfaceBuilder.prototype.Property = function (_descriptor, name, propertyType) {
var descriptor = this.ParseDescriptor(_descriptor, name);
if (this.typeObject.IsInterface) {
} else {
var props = this.typeObject.__Properties__;
props.push([descriptor.Static, name, descriptor.Virtual, propertyType]);
}
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember("PropertyInfo", descriptor, null, memberBuilder);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.GenericProperty = function (_descriptor, name, propertyType) {
var descriptor = this.ParseDescriptor(_descriptor, name);
var props = this.typeObject.__Properties__;
props.push([descriptor.Static, name, descriptor.Virtual, propertyType]);
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember("PropertyInfo", descriptor, null, memberBuilder);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.Event = function (_descriptor, name, eventType) {
var descriptor = this.ParseDescriptor(_descriptor, name);
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember("EventInfo", descriptor, null, memberBuilder);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.GenericEvent = function (_descriptor, name, eventType) {
var descriptor = this.ParseDescriptor(_descriptor, name);
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember("EventInfo", descriptor, null, memberBuilder);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.Field = function (_descriptor, fieldName, fieldType, defaultValueExpression) {
var descriptor = this.ParseDescriptor(_descriptor, fieldName);
var data = {
fieldType: fieldType,
defaultValueExpression: defaultValueExpression
};
if (typeof (_descriptor.Offset) === "number")
data.offset = _descriptor.Offset | 0;
var memberBuilder = new JSIL.MemberBuilder(this.context);
var fieldIndex = this.PushMember("FieldInfo", descriptor, data, memberBuilder);
// Instance fields have no special logic applied to the prototype or public interface.
// This is important because having default values or other magic on the prototype
// can impair the creation of dense memory layouts and consistent hidden classes/shapes.
if (!descriptor.Static) {
return memberBuilder;
}
var maybeRunCctors = this.maybeRunCctors;
var context = this.context;
var fieldCreator = function InitField (
fullyDerivedClassObject, classObject,
fullyDerivedTypeObject, typeObject
) {
var actualTarget = descriptor.Static ? classObject : fullyDerivedClassObject.prototype;
var maybeRunCctors = function MaybeRunStaticConstructors () {
JSIL.RunStaticConstructors(fullyDerivedClassObject, fullyDerivedTypeObject);
};
// If the field has already been initialized, don't overwrite it.
if (Object.getOwnPropertyDescriptor(actualTarget, descriptor.EscapedName))
return;
if (typeof (defaultValueExpression) === "function") {
JSIL.DefineLazyDefaultProperty(
actualTarget, descriptor.EscapedName,
function InitFieldDefaultExpression () {
if (descriptor.Static)
maybeRunCctors();
return data.defaultValue = defaultValueExpression(this);
}
);
} else if (typeof (defaultValueExpression) !== "undefined") {
if (descriptor.Static) {
JSIL.DefineLazyDefaultProperty(
actualTarget, descriptor.EscapedName,
function InitFieldDefaultExpression () {
if (descriptor.Static)
maybeRunCctors();
return data.defaultValue = defaultValueExpression;
}
);
} else {
actualTarget[descriptor.EscapedName] = data.defaultValue = defaultValueExpression;
}
} else {
var members = typeObject.__Members__;
var initFieldDefault = function InitFieldDefault () {
var actualFieldInfo = members[fieldIndex];
var actualFieldType = actualFieldInfo.data.fieldType;
var fieldTypeResolved;
if (actualFieldType.getNoInitialize) {
// FIXME: We can't use ResolveTypeReference here because it would initialize the field type, which can form a cycle.
// This means that when we create a default value for a struct type, we may create an instance of an uninitalized type
// or form a cycle anyway. :/
fieldTypeResolved = actualFieldType.getNoInitialize();
} else {
fieldTypeResolved = actualFieldType;
}
if (!fieldTypeResolved)
return;
else if (Object.getPrototypeOf(fieldTypeResolved) === JSIL.GenericParameter.prototype)
return;
return data.defaultValue = JSIL.DefaultValue(fieldTypeResolved);
};
if (
descriptor.Static
) {
JSIL.DefinePreInitField(
actualTarget, descriptor.EscapedName,
initFieldDefault, maybeRunCctors
);
} else {
JSIL.DefineLazyDefaultProperty(
actualTarget, descriptor.EscapedName,
initFieldDefault
);
}
}
};
var fi = this.typeObject.__FieldInitializers__;
if (!fi)
fi = this.typeObject.__FieldInitializers__ = [];
fi.push(fieldCreator);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.ExternalMethod = function (_descriptor, methodName, signature) {
var descriptor = this.ParseDescriptor(_descriptor, methodName, signature);
var mangledName = signature.GetNamedKey(descriptor.EscapedName, true);
var impl = this.externals;
var prefix = descriptor.Static ? "" : "instance$";
var memberValue = descriptor.Target[mangledName];
var newValue = null;
var isPlaceholder;
var fullName = this.namespace + "." + methodName;
{
var externalMethods = this.typeObject.__ExternalMethods__;
var externalMethodIndex = externalMethods.length;
// FIXME: Avoid doing this somehow?
externalMethods.push(signature);
var getName = function () {
var thisType = (this.__Type__ || this.__ThisType__);
var lateBoundSignature = thisType.__ExternalMethods__[externalMethodIndex];
// FIXME: Why is this necessary now when it wasn't before?
if (lateBoundSignature == null)
lateBoundSignature = signature;
return lateBoundSignature.toString(methodName);
};
}
JSIL.$PlaceExternalMember(
descriptor.Target, impl, prefix, mangledName, this.namespace, getName
);
var isConstructor = (descriptor.EscapedName === "_ctor");
var memberTypeName = isConstructor ? "ConstructorInfo" : "MethodInfo";
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember(memberTypeName, descriptor, {
signature: signature,
genericSignature: null,
mangledName: mangledName,
isExternal: true,
isPlaceholder: isPlaceholder,
isConstructor: isConstructor,
parameterInfo: memberBuilder.parameterInfo
}, memberBuilder, true);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.ExternalProperty = function (descriptor, propertyName, propertyType) {
this.ExternalMethod(
descriptor, "get_" + propertyName,
JSIL.MethodSignature.Return(propertyType)
);
this.ExternalMethod(
descriptor, "set_" + propertyName,
JSIL.MethodSignature.Action(propertyType)
);
return this.Property(descriptor, propertyName, propertyType);
};
JSIL.InterfaceBuilder.prototype.ExternalEvent = function (descriptor, eventName, eventType) {
this.ExternalMethod(
descriptor, "add_" + eventName,
JSIL.MethodSignature.Return(eventType)
);
this.ExternalMethod(
descriptor, "remove_" + eventName,
JSIL.MethodSignature.Action(eventType)
);
return this.Event(descriptor, eventName, eventType);
};
JSIL.InterfaceBuilder.prototype.RawMethod = function (isStatic, methodName, fn) {
methodName = JSIL.EscapeName(methodName);
if (typeof (fn) !== "function")
JSIL.RuntimeError("RawMethod only accepts function arguments");
JSIL.SetValueProperty(
isStatic ? this.publicInterface : this.publicInterface.prototype,
methodName, fn
);
var rawRecord = new JSIL.RawMethodRecord(methodName, isStatic);
this.typeObject.__RawMethods__.push(rawRecord);
};
JSIL.InterfaceBuilder.prototype.Method = function (_descriptor, methodName, signature, fn) {
var descriptor = this.ParseDescriptor(_descriptor, methodName, signature);
var mangledName = signature.GetNamedKey(descriptor.EscapedName, true);
var memberBuilder = new JSIL.MemberBuilder(this.context);
if (this.typeObject.IsInterface) {
var methodObject = new JSIL.InterfaceMethod(this.typeObject, descriptor.EscapedName, signature, memberBuilder.parameterInfo);
JSIL.SetValueProperty(descriptor.Target, mangledName, methodObject);
if (!descriptor.Target[descriptor.EscapedName])
JSIL.SetValueProperty(descriptor.Target, descriptor.EscapedName, methodObject);
} else {
if (typeof (fn) !== "function")
JSIL.RuntimeError("Method expected a function as 4th argument when defining '" + methodName + "'");
var fullName = this.namespace + "." + methodName;
JSIL.SetValueProperty(descriptor.Target, mangledName, fn);
}
var isConstructor = (descriptor.EscapedName === "_ctor");
var memberTypeName = isConstructor ? "ConstructorInfo" : "MethodInfo";
this.PushMember(memberTypeName, descriptor, {
signature: signature,
genericSignature: null,
mangledName: mangledName,
isExternal: false,
isConstructor: isConstructor,
parameterInfo: memberBuilder.parameterInfo
}, memberBuilder);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.MakeEventAccessors = function (_descriptor, name, type) {
var signature = JSIL.MethodSignature.Action(type);
function adder (value) {
var existingValue = this[name] || null;
var newValue = $jsilcore.$CombineDelegates(existingValue, value);
return this[name] = newValue;
};
function remover (value) {
var existingValue = this[name] || null;
var newValue = $jsilcore.$RemoveDelegate(existingValue, value);
return this[name] = newValue;
};
this.Method(_descriptor, "add_" + name, signature, adder);
this.Method(_descriptor, "remove_" + name, signature, remover);
};
JSIL.InterfaceBuilder.prototype.InheritBaseMethod = function (name, signature) {
var descriptor = this.ParseDescriptor({Public: true, Static: false}, name, signature);
var mangledName = signature.GetNamedKey(descriptor.EscapedName, true);
var fn = null;
fn = function InheritedBaseMethod_Invoke () {
var proto = Object.getPrototypeOf(this);
var baseMethod;
while (true) {
baseMethod = proto[mangledName];
if (baseMethod === fn)
proto = Object.getPrototypeOf(proto);
else
break;
}
if (typeof (baseMethod) === "function")
return baseMethod.apply(this, arguments);
else
JSIL.Host.warning("InheritBaseMethod() used but no method was found to inherit!");
};
JSIL.SetValueProperty(descriptor.Target, mangledName, fn);
var isConstructor = (descriptor.EscapedName === "_ctor");
var memberTypeName = isConstructor ? "ConstructorInfo" : "MethodInfo";
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember(memberTypeName, descriptor, {
signature: signature,
genericSignature: null,
mangledName: mangledName,
isExternal: false,
isConstructor: isConstructor,
isInherited: true,
parameterInfo: memberBuilder.parameterInfo
}, memberBuilder);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.InheritDefaultConstructor = function () {
this.InheritBaseMethod(".ctor", JSIL.MethodSignature.Void);
};
JSIL.InterfaceBuilder.prototype.ImplementInterfaces = function (/* ...interfacesToImplement */) {
var interfaces = this.typeObject.__Interfaces__;
if (typeof (interfaces) === "undefined")
JSIL.RuntimeError("Type has no interface list");
for (var i = 0; i < arguments.length; i++) {
var iface = arguments[i];
if (!iface)
JSIL.RuntimeError("Nonexistent interface passed to ImplementInterfaces");
interfaces.push(iface);
}
};
JSIL.SignatureBase = function () {
JSIL.RuntimeError("Abstract base class");
};
JSIL.SignatureBase.prototype.GetNamedKey$CacheMiss = function (name, includeReturnType) {
var result = name + "" + this.get_Hash(includeReturnType);
if (includeReturnType !== false) {
this._lastKeyName = null;
this._lastKey = result;
}
return result;
};
JSIL.SignatureBase.prototype.GetNamedKey = function (name, includeReturnType) {
if (!name)
return this.GetUnnamedKey(includeReturnType);
else if ((name === this._lastKeyName) && (includeReturnType !== false))
return this._lastKey;
return this.GetNamedKey$CacheMiss(name, includeReturnType);
};
JSIL.SignatureBase.prototype.GetUnnamedKey$CacheMiss = function (includeReturnType) {
var result = this.get_Hash(includeReturnType);
if (includeReturnType !== false) {
this._lastKeyName = null;
this._lastKey = result;
}
return result;
};
JSIL.SignatureBase.prototype.GetUnnamedKey = function (includeReturnType) {
if ((!this._lastKeyName) && (includeReturnType !== false))
return this._lastKey;
return this.GetUnnamedKey$CacheMiss(includeReturnType);
};
JSIL.SignatureBase.prototype.GetKey = function (name, includeReturnType) {
if (arguments.length === 2)
return this.GetNamedKey(name, includeReturnType);
else if (arguments.length === 1)
return this.GetNamedKey(name, true);
else
return this.GetUnnamedKey(true);
};
JSIL.SignatureBase.prototype.ResolveTypeReference = function (typeReference) {
return JSIL.ResolveTypeReference(typeReference, this);
};
JSIL.SignatureBase.prototype.LookupMethod = function (context, name) {
if (!context)
JSIL.RuntimeError("Attempting to invoke method named '" + name + "' on null/undefined object");
var key = this.GetNamedKey(name, true);
var method = context[key];
if (typeof (method) !== "function") {
var signature = this.toString(name);
JSIL.RuntimeError(
"No method with signature '" + signature +
"' defined in context '" + JSIL.GetTypeName(context) + "'"
);
}
return method;
};
JSIL.MethodSignature = function (returnType, argumentTypes, genericArgumentNames, context, openSignature, genericArgumentValues) {
this._lastKeyName = "<null>";
this._lastKey = "<null>";
this._genericSuffix = null;
this._hash = null;
this._hashIncludesReturnType = null;
this.context = context || $private;
this.returnType = returnType;
if (!JSIL.IsArray(argumentTypes)) {
if (argumentTypes !== null) {
var argumentTypesString = typeof(argumentTypes) + " " + String(argumentTypes);
JSIL.RuntimeError("ArgumentTypes must be an array or null, was: " + argumentTypesString);
} else
this.argumentTypes = $jsilcore.ArrayNull;
} else {
this.argumentTypes = argumentTypes;
}
if (JSIL.IsArray(genericArgumentNames))
this.genericArgumentNames = genericArgumentNames;
else
this.genericArgumentNames = $jsilcore.ArrayNull;
this.openSignature = openSignature || null;
if (JSIL.IsArray(genericArgumentValues)){
this.genericArgumentValues = genericArgumentValues;
}
this.recompileCount = 0;
this.useInlineCache = JSIL.MethodSignature.EnableInlineCaches;
this.inlineCacheEntries = [];
this.isInterfaceSignature = false;
};
JSIL.MethodSignature.prototype = JSIL.CreatePrototypeObject(JSIL.SignatureBase.prototype);
JSIL.MethodSignature.prototype.Clone = function (isInterfaceSignature) {
var result = new JSIL.MethodSignature(
this.returnType, this.argumentTypes, this.genericArgumentNames,
this.context, this.openSignature, this.genericArgumentValues
);
result.isInterfaceSignature = isInterfaceSignature;
return result;
};
JSIL.SetLazyValueProperty(JSIL.MethodSignature, "Void", function () {
return new JSIL.MethodSignature(null, null, null);
});
JSIL.MethodSignature.$returnCache = {};
JSIL.MethodSignature.$actionCache = {};
JSIL.MethodSignature.Return = function (returnType) {
var key = null;
if (!returnType)
JSIL.RuntimeError("Return type must be specified");
else if (Object.getPrototypeOf(returnType) === JSIL.TypeRef.prototype)
key = returnType.getTypeId();
else if (returnType.__TypeId__)
key = returnType.__TypeId__;
else
JSIL.RuntimeError("Unsupported return type format");
var result = JSIL.MethodSignature.$returnCache[key];
if (!result) {
result = new JSIL.MethodSignature(returnType, null, null);
JSIL.MethodSignature.$returnCache[key] = result;
}
return result;
};
JSIL.MethodSignature.Action = function (argumentType) {
var key = null;
if (!argumentType)
JSIL.RuntimeError("Argument type must be specified");
else if (Object.getPrototypeOf(argumentType) === JSIL.TypeRef.prototype)
key = argumentType.getTypeId();
else if (argumentType.__TypeId__)
key = argumentType.__TypeId__;
else
JSIL.RuntimeError("Unsupported argument type format");
var result = JSIL.MethodSignature.$actionCache[key];
if (!result) {
result = new JSIL.MethodSignature(null, [argumentType], null);
JSIL.MethodSignature.$actionCache[key] = result;
}
return result;
};
JSIL.SetLazyValueProperty(
JSIL.MethodSignature.prototype, "Call",
function () { return this.$MakeCallMethod("Call", null, null); }, true, false
);
JSIL.SetLazyValueProperty(
JSIL.MethodSignature.prototype, "CallStatic",
function () { return this.$MakeCallMethod("CallStatic", null, null); }, true, false
);
JSIL.SetLazyValueProperty(
JSIL.MethodSignature.prototype, "CallVirtual",
function () { return this.$MakeCallMethod("CallVirtual", null, null); }, true, false
);
JSIL.MethodSignature.prototype.Resolve = function (name) {
var argTypes = [];
var resolvedReturnType = null;
if (this.returnType !== null) {
resolvedReturnType = JSIL.ResolveTypeReference(this.returnType, this)[1];
}
for (var i = 0; i < this.argumentTypes.length; i++) {
argTypes[i] = JSIL.ResolveTypeReference(this.argumentTypes[i], this)[1];
}
return new JSIL.ResolvedMethodSignature(
this,
this.GetNamedKey(name, true),
resolvedReturnType,
argTypes
);
};
JSIL.MethodSignature.prototype.toString = function (name, includeReturnType) {
var signature;
if (includeReturnType === false) {
signature = "";
} else if (this.returnType !== null) {
signature = JSIL.TypeReferenceToName(this.returnType) + " ";
} else {
signature = "void ";
}
if (typeof (name) === "string") {
signature += name;
}
if (this.genericArgumentNames.length > 0) {
signature += "<";
for (var i = 0, l = this.genericArgumentNames.length; i < l; i++) {
if (i > 0)
signature += ", ";
signature += this.genericArgumentNames[i];
}
signature += "> (";
} else {
signature += "(";
}
for (var i = 0; i < this.argumentTypes.length; i++) {
signature += JSIL.TypeReferenceToName(this.argumentTypes[i]);
if (i < this.argumentTypes.length - 1)
signature += ", "
}
signature += ")";
return signature;
};
JSIL.MethodSignature.$EmitInvocation = function (
body, callText,
thisReferenceArg, prefix,
argumentTypes, genericArgumentNames,
isInterface, indentation
) {
var comma;
var needsBindingForm = false;
if (typeof (indentation) !== "string")
indentation = " ";
if (genericArgumentNames)
comma = (genericArgumentNames.length + argumentTypes.length) > 0 ? "," : "";
else
comma = argumentTypes.length > 0 ? "," : "";
body.push(indentation + prefix + callText + "(");
if (thisReferenceArg)
body.push(indentation + " " + thisReferenceArg + comma);
if (genericArgumentNames)
for (var i = 0, l = genericArgumentNames.length; i < l; i++) {
comma = ((i < (l - 1)) || (!needsBindingForm && argumentTypes.length > 0)) ? "," : "";
body.push(indentation + " ga[" + i + "]" + comma);
}
if (needsBindingForm)
body.push(indentation + ")(");
for (var i = 0, l = argumentTypes.length; i < l; i++) {
comma = (i < (l - 1)) ? "," : "";
body.push(indentation + " arg" + i + comma);
}
body.push(indentation + ");");
};
// Used as a global cache for generated invocation method bodies.
// Caching them reduces memory usage but probably ruins type info, so we're not
// going to do it by default.
if (false) {
JSIL.MethodSignature.$CallMethodCache = JSIL.CreateDictionaryObject(null);
} else {
JSIL.MethodSignature.$CallMethodCache = null;
}
// Control whether generated ICs check argument & generic argument counts.
// Shouldn't ever be necessary, but it's a useful debugging tool.
JSIL.MethodSignature.CheckArgumentCount = false;
JSIL.MethodSignature.CheckGenericArgumentCount = false;
JSIL.MethodSignature.EnableInlineCaches = true;
JSIL.MethodSignatureInlineCacheEntry = function (name, typeId, methodKey) {
this.name = name;
this.typeId = typeId;
this.methodKey = methodKey;
};
JSIL.MethodSignatureInlineCacheEntry.prototype.equals = function (name, typeId, methodKey) {
return (this.name === name) &&
(this.typeId === typeId) &&
(this.methodKey === methodKey);
};
JSIL.MethodSignature.prototype.$MakeInlineCacheBody = function (callMethodName, knownMethodKey, fallbackMethod) {
// Welcome to optimization hell! Enjoy your stay.
var returnType = this.returnType;
var argumentTypes = this.argumentTypes;
var genericArgumentNames = this.genericArgumentNames;
var argumentNames;
var methodLookupArg, thisReferenceArg;
var suffix;
var isInterfaceCall = false;
// We're generating an optimized inline cache or invocation thunk that handles
// method dispatch for four different types of calls. They are all similar.
switch (callMethodName) {
case "CallStatic":
// Invoking a specific static method of a given type. There's no this-reference.
// methodSource is the public interface of the type, we can call off it directly.
thisReferenceArg = methodLookupArg = "methodSource";
argumentNames = ["methodSource", "name", "ga"];
break;
case "Call":
// Invoking a specific method against a specific object instance.
thisReferenceArg = "thisReference";
methodLookupArg = "methodSource";
argumentNames = ["methodSource", "name", "ga", "thisReference"];
break;
case "CallVirtual":
// Invoking a specific virtual method of a specific object instance.
// The thisReference is the source of the method so we can call off it directly.
suffix = "Virtual";
thisReferenceArg = methodLookupArg = "thisReference";
argumentNames = ["name", "ga", "thisReference"];
break;
case "CallInterface":
case "CallVariantInterface":
// Interface calls that are non-variant don't need an IC. Their target is constant.
if (callMethodName === "CallInterface")
this.useInlineCache = false;
// Invoking an interface method against a this-reference.
// If the method is part of a variant generic interface, we need to do variant
// lookup. Otherwise, the name is constant and we can dispatch to it directly.
isInterfaceCall = true;
thisReferenceArg = methodLookupArg = "thisReference";
argumentNames = ["thisReference", "ga"];
break;
default:
JSIL.RuntimeError("Invalid callMethodName");
}
for (var i = 0, l = argumentTypes.length; i < l; i++) {
var argumentName = "arg" + i;
argumentNames.push(argumentName);
}
var requiredArgumentCount = argumentNames.length;
var argumentCheckOperator = "!==";
// HACK to allow simple 'method.call(x)' form for zero-argument, non-generic methods.
if ((genericArgumentNames.length === 0) && (argumentTypes.length === 0)) {
requiredArgumentCount = 1;
argumentCheckOperator = "<";
}
// We attempt to generate unique-enough and friendly names for our generated closures.
// These names make it clear what the IC is for and how many times it has been recompiled.
// The recompile count is important; otherwise some debuggers overwrite older compiles
// with new ones, making it confusing to debug.
this.recompileCount += 1;
var functionName = (isInterfaceCall ? "InterfaceMethod" : "MethodSignature") +
"." + callMethodName;
if (knownMethodKey && (callMethodName === "CallInterface")) {
// Generate straightforward closure names for non-variant interface methods.
functionName += "_" +
knownMethodKey;
} else {
functionName +=
"$" + genericArgumentNames.length +
"$" + argumentTypes.length;
}
if (this.useInlineCache)
functionName += "$inlineCache" + this.recompileCount;
var body = [];
// Check the # of provided arguments to detect an invalid invocation.
if (JSIL.MethodSignature.CheckArgumentCount) {
body.push("var argc = arguments.length | 0;");
body.push("if (argc " + argumentCheckOperator + " " + requiredArgumentCount + ")");
body.push(" JSIL.RuntimeError('" + requiredArgumentCount + " argument(s) required, ' + argc + ' provided.');");
}
// If the function accepts generic arguments, we need to do a check to ensure
// that the appropriate # of arguments were passed.
if (genericArgumentNames.length > 0) {
if (JSIL.MethodSignature.CheckGenericArgumentCount) {
body.push("if (!ga || ga.length !== " + genericArgumentNames.length + ")");
body.push(" JSIL.RuntimeError('Invalid number of generic arguments');");
}
body.push("JSIL.ResolveTypeArgumentArray(ga);");
body.push("");
} else {
// If it doesn't accept them, and we're in validation mode, insert a check.
// This wastes cycles normally so we don't always want to put it in there.
if (JSIL.MethodSignature.CheckGenericArgumentCount) {
body.push("if (ga && ga.length > 0)");
body.push(" JSIL.RuntimeError('Invalid number of generic arguments');");
body.push("");
}
}
var nameIdentifier = "name";
var thisReferenceExpression = null;
if (methodLookupArg !== thisReferenceArg)
thisReferenceExpression = thisReferenceArg;
var emitMissingMethodCheck = function (result, methodExpression, methodName, indentation) {
var errMethod =
indentation + " " +
(callMethodName === "CallStatic")
? "this.$StaticMethodNotFound("
: "this.$MethodNotFound(";
result.push(indentation + "if (!" + methodExpression + ")");
if (thisReferenceArg !== methodLookupArg)
result.push(errMethod + thisReferenceExpression + ", " + methodName + ");");
else
result.push(errMethod + thisReferenceArg + ", " + methodName + ");");
result.push(indentation);
};
// This is the path used for simple invocations - no IC, etc.
var emitDefaultInvocation = function (indentation, methodKeyToken) {
// For every invocation type other than Call, the this-reference will
// automatically bind thanks to JS call semantics.
var methodName = (callMethodName === "Call")
? methodLookupArg + "[" + methodKeyToken + "].call"
: methodLookupArg + "[" + methodKeyToken + "]";
if (fallbackMethod) {
body.push(indentation + " var methodReference = " + methodName + ";");
body.push(indentation + " if (!methodReference) {");
body.push(indentation + " methodReference = fallbackMethod(this.typeObject, this, thisReference)");
body.push(indentation + " }");
body.push("");
JSIL.MethodSignature.$EmitInvocation(
body, "methodReference.call", "thisReference",
(!!returnType) ? "return " : "",
argumentTypes, genericArgumentNames,
false, indentation + " "
);
} else {
emitMissingMethodCheck(body, methodName, methodKeyToken, "");
JSIL.MethodSignature.$EmitInvocation(
body, methodName, thisReferenceExpression,
(!!returnType) ? "return " : "",
argumentTypes, genericArgumentNames,
false, indentation
);
}
};
// The 'method key' used to find the method in the method source depends on
// the call scenario.
var getMethodKeyLookup = function () {
if (isInterfaceCall) {
if (callMethodName === "CallVariantInterface") {
return "this.LookupVariantMethodKey(thisReference)";
} else if (knownMethodKey) {
return "\"" + knownMethodKey + "\"";
} else {
return "this.methodKey";
}
} else {
return "this.GetNamedKey(name, true)";
}
};
// When an IC is enabled, if a cache miss occurs we update the IC before finally
// doing a typical invocation.
var emitCacheMissInvocation = function (indentation) {
// Interface ICs are keyed off the type ID of the this-reference.
// Non-interface ICs are keyed off method name.
var typeIdExpression =
isInterfaceCall
? "typeId"
: "null";
// Interface ICs live on the InterfaceMethod's signature.
var cacheMissMethod =
isInterfaceCall
? "this.signature.$InlineCacheMiss(this, '"
: "this.$InlineCacheMiss(this, '";
// Look up the actual method key, update the IC...
body.push(indentation + "var methodKey = " + getMethodKeyLookup() + ";");
body.push(
indentation + cacheMissMethod +
callMethodName + "', " +
nameIdentifier + ", " +
typeIdExpression + ", methodKey);"
);
// Then finally invoke.
emitDefaultInvocation(indentation, "methodKey");
};
if (this.useInlineCache) {
// Crazy inline cache nonsense time!
if (fallbackMethod)
JSIL.RuntimeError("Inline caching does not support fallback methods");
// Look up the type ID of the this-reference for interface calls. We'll be using it a lot.
if (isInterfaceCall) {
nameIdentifier = "null";
body.push("var typeId = thisReference.__ThisTypeId__;");
}
// Generate the lookup switch for the IC, along with IC management code.
for (var i = 0, l = this.inlineCacheEntries.length; i < l; i++) {
var entry = this.inlineCacheEntries[i];
// Check to see if the cache entry matches. Note that the condition depends
// on whether this is an interface method IC.
// FIXME: Can the key end up with a single quote in it, or a backslash?
var conditionExpression =
isInterfaceCall
? "\"" + entry.typeId + "\""
: "\"" + entry.name + "\"";
// So, you might be asking yourself... why a switch block keyed on the name?
// It's a good question. The first IC implementation built a name -> index
// dictionary, and looked up the name in the dictionary to choose the method
// to call. This was a performance improvement.
// The key observation, however, is that the value of these ICs is actually for
// inlining. If the call target is known, inlining can occur more easily,
// and once a method is inlining lots of cool new optimizations become possible.
// In an ideal world, *both* this IC *and* the call target will be inlined,
// so we want to design the IC to make this possible and make it *fast*.
// The old table lookup is not particularly optimizer-friendly. Even if it inlined
// the IC, it wouldn't have any easy way to know that the table lookup
// was constant.
// Replacing the table lookup with a switch (or if statements, even) keyed on
// the name/typeId means that once inlined, the IC looks like this:
//
// function ic (name /* = 'knownName' */, ...) {
// if (name === 'knownName' /* true */) {
// ...
// } else if (name === 'otherKnownName' /* false */) {
// ...
//
// Thanks to the inline, the JIT now has all the information it needs to
// *completely* optimize out the IC. It can kill all the false branch
// conditions and it's only left with the true branch - which calls a specific
// known method directly on the provided this-reference.
// In most scenarios the method name being passed into the IC is a constant,
// so it's fairly likely that inlining can happen and that it will optimize this way.
// Finally, in testing switch statements were not found to be any slower than
// if statements, so we generate an if statement. The generated code is denser
// and clearer, which is nice, and it makes it less work for the JIT to figure
// out that it can use a jump table or whatever it likes in the case where
// we aren't optimized out entirely.
if (i === 0) {
body.push(
"switch (" +
(isInterfaceCall
? "typeId"
: "name") +
") {"
);
}
body.push(
" case " + conditionExpression + ": "
);
// For every invocation type other than Call, the this-reference will
// automatically bind thanks to JS call semantics.
var methodName = (callMethodName === "Call")
? methodLookupArg + "['" + entry.methodKey + "'].call"
: methodLookupArg + "['" + entry.methodKey + "']";
emitMissingMethodCheck(body, methodName, "'" + entry.methodKey + "'", " ");
// This inline cache entry matches, so build an appropriate invocation.
JSIL.MethodSignature.$EmitInvocation(
body, methodName, thisReferenceExpression,
(!!returnType) ? "return " : "",
argumentTypes, genericArgumentNames,
false, " "
);
body.push(" break;");
body.push(" ");
}
if (this.inlineCacheEntries.length >= 1) {
body.push(" default: ");
emitCacheMissInvocation(" ");
body.push("}");
body.push("");
} else {
emitCacheMissInvocation("");
}
} else {
emitDefaultInvocation("", getMethodKeyLookup());
}
var joinedBody = body.join("\r\n");
var closure = null;
if (fallbackMethod)
closure = { fallbackMethod: fallbackMethod };
return JSIL.CreateNamedFunction(
functionName,
argumentNames,
joinedBody,
closure
);
};
JSIL.MethodSignature.prototype.$StaticMethodNotFound = function (publicInterface, methodName) {
JSIL.RuntimeErrorFormat(
"No static method with signature '{0}' found in context '{1}'", [
this.toString(methodName),
publicInterface
]
);
};
JSIL.MethodSignature.prototype.$MethodNotFound = function (thisReference, methodName) {
JSIL.RuntimeErrorFormat(
"No method with signature '{0}' found on instance '{1}'", [
this.toString(methodName),
thisReference
]
);
};
JSIL.MethodSignature.prototype.$MakeCallMethod = function (callMethodName, knownMethodKey, fallbackMethod) {
// FIXME: Is this correct? I think having all instances of a given unique signature
// share the same IC is probably correct.
var cacheKey = callMethodName + "$" + this.GetUnnamedKey(true);
if (JSIL.MethodSignature.$CallMethodCache) {
var cachedResult = JSIL.MethodSignature.$CallMethodCache[cacheKey];
if (cachedResult)
return cachedResult;
}
// Doing an IC with a fallback method in play is totally not worth the trouble.
// Fallback methods are an infrequently used hack anyway.
if (fallbackMethod)
this.useInlineCache = false;
var result = this.$MakeInlineCacheBody(callMethodName, knownMethodKey, fallbackMethod);
if (JSIL.MethodSignature.$CallMethodCache) {
JSIL.MethodSignature.$CallMethodCache[cacheKey] = result;
}
return result;
};
JSIL.MethodSignature.prototype.$InlineCacheMiss = function (target, callMethodName, name, typeId, methodKey) {
if (!this.useInlineCache)
return;
// FIXME: This might be too small.
var inlineCacheCapacity = 3;
var numEntries = this.inlineCacheEntries.length | 0;
if (numEntries >= inlineCacheCapacity) {
// Once the IC gets too large we convert it back to a simple invocation method.
// This is important since these ICs are only a big optimization if the JIT is
// able to inline them into the caller (so the conditionals become free).
// Making an IC too big will prevent inlining and at that point it's not gonna
// be particularly fast or worthwhile.
this.inlineCacheEntries = null;
this.useInlineCache = false;
this.$RecompileInlineCache(target, callMethodName);
} else {
for (var i = 0; i < numEntries; i++) {
var entry = this.inlineCacheEntries[i];
// Our caller is an expired inline cache function.
if (entry.equals(name, typeId, methodKey)) {
// Some bugs cause this to happen over and over so perf sucks.
// JSIL.RuntimeError("Inline cache miss w/ pending recompile.");
return;
}
}
// If we had a cache miss and the target doesn't have an entry, add it and recompile.
var newEntry = new JSIL.MethodSignatureInlineCacheEntry(name, typeId, methodKey);
this.inlineCacheEntries.push(newEntry);
this.$RecompileInlineCache(target, callMethodName);
}
};
JSIL.MethodSignature.prototype.$RecompileInlineCache = function (target, callMethodName) {
var cacheKey = callMethodName + "$" + this.GetUnnamedKey(true);
var newFunction = this.$MakeInlineCacheBody(callMethodName, target.methodKey || null);
if (JSIL.MethodSignature.$CallMethodCache) {
JSIL.MethodSignature.$CallMethodCache[cacheKey] = newFunction;
}
// HACK
var propertyName = this.isInterfaceSignature
? "Call"
: callMethodName;
// Once we've recompiled the inline cache, overwrite the old one on the target.
// Note that this is not 'this' because for interface methods, the IC is managed
// by their signature but lives on the interface method object instead.
JSIL.SetValueProperty(target, propertyName, newFunction);
};
JSIL.MethodSignature.prototype.get_GenericSuffix = function () {
if (this._genericSuffix !== null)
return this._genericSuffix;
if (this.genericArgumentNames.length > 0) {
return this._genericSuffix = "`" + this.genericArgumentNames.length.toString();
}
return this._genericSuffix = "";
};
JSIL.MethodSignature.prototype.get_Hash = function (includeReturnType) {
if ((this._hash !== null) && (this._hashIncludesReturnType === includeReturnType))
return this._hash;
var hash = "$" + JSIL.HashTypeArgumentArray(this.argumentTypes, this.context);
if ((this.returnType !== null) && (includeReturnType !== false)) {
hash += "=" + JSIL.HashTypeArgumentArray([this.returnType], this.context);
} else {
if (includeReturnType !== false)
hash += "=void";
}
this._hash = hash;
this._hashIncludesReturnType = includeReturnType;
return hash;
};
JSIL.MethodSignature.prototype.get_IsClosed = function () {
if (this.returnType && (this.returnType.__IsClosed__ === false))
return false;
for (var i = 0, l = this.argumentTypes.length; i < l; i++) {
var at = this.argumentTypes[i];
if (at.__IsClosed__ === false)
return false;
}
return true;
};
Object.defineProperty(JSIL.MethodSignature.prototype, "GenericSuffix", {
configurable: false,
enumerable: true,
get: JSIL.MethodSignature.prototype.get_GenericSuffix
});
Object.defineProperty(JSIL.MethodSignature.prototype, "Hash", {
configurable: false,
enumerable: true,
get: JSIL.MethodSignature.prototype.get_Hash
});
Object.defineProperty(JSIL.MethodSignature.prototype, "IsClosed", {
configurable: false,
enumerable: true,
get: JSIL.MethodSignature.prototype.get_IsClosed
});
JSIL.ConstructorSignature = function (type, argumentTypes, context) {
this._lastKeyName = "<null>";
this._lastKey = "<null>";
this._hash = null;
this._typeObject = null;
this.context = context || $private;
this.type = type;
if (!JSIL.IsArray(argumentTypes)) {
if (argumentTypes !== null) {
var argumentTypesString = typeof(argumentTypes) + " " + String(argumentTypes);
JSIL.RuntimeError("ArgumentTypes must be an array or null, was: " + argumentTypesString);
} else
this.argumentTypes = $jsilcore.ArrayNull;
} else {
this.argumentTypes = argumentTypes;
}
};
JSIL.ConstructorSignature.prototype = JSIL.CreatePrototypeObject(JSIL.SignatureBase.prototype);
JSIL.SetLazyValueProperty(JSIL.ConstructorSignature.prototype, "Construct", function () { return this.$MakeConstructMethod(); }, true);
JSIL.ConstructorSignature.prototype.get_Type = function () {
if (this._typeObject !== null)
return this._typeObject;
return this._typeObject = this.ResolveTypeReference(this.type)[1];
};
JSIL.ConstructorSignature.prototype.get_Hash = function (includeReturnType) {
if (this._hash !== null)
return this._hash;
return this._hash = "$" + JSIL.HashTypeArgumentArray(this.argumentTypes, this.context) + "=void";
};
JSIL.ConstructorSignature.prototype.$MakeBoundConstructor = function (argumentNames) {
var typeObject = this.get_Type();
var publicInterface = typeObject.__PublicInterface__;
var closure = {};
var body = [];
var proto = publicInterface.prototype;
closure.fieldInitializer = JSIL.GetFieldInitializer(typeObject);
body.push("fieldInitializer(this);");
var ctorKey = "_ctor";
if (typeObject.__IsStruct__ && argumentNames.length === 0) {
} else {
ctorKey = this.GetNamedKey("_ctor", true);
if (!proto[ctorKey]) {
if (!proto["_ctor"])
JSIL.RuntimeError("No method named '_ctor' found");
else
ctorKey = "_ctor";
}
JSIL.MethodSignature.$EmitInvocation(
body, "this['" + ctorKey + "']", null,
"return ", argumentNames
);
}
var result = JSIL.CreateNamedFunction(
typeObject.__FullName__ + "." + ctorKey,
argumentNames,
body.join("\r\n"),
closure
);
result.prototype = proto;
return result;
};
JSIL.ConstructorSignature.prototype.$MakeConstructMethod = function () {
var typeObject = this.get_Type();
var publicInterface = typeObject.__PublicInterface__;
var argumentTypes = this.argumentTypes;
if (typeObject.__IsClosed__ === false)
return function () {
JSIL.RuntimeError("Cannot create an instance of an open type");
};
else if (typeObject.IsInterface)
return function () {
JSIL.RuntimeError("Cannot create an instance of an interface");
};
var closure = {
typeObject: typeObject,
publicInterface: publicInterface
};
var body = [];
var argumentNames = [];
for (var i = 0, l = argumentTypes.length; i < l; i++) {
var argumentName = "arg" + i;
argumentNames.push(argumentName);
}
JSIL.RunStaticConstructors(publicInterface, typeObject);
if (typeObject.__IsNativeType__) {
closure.ctor = publicInterface.prototype["_ctor"];
JSIL.MethodSignature.$EmitInvocation(
body, "ctor.call", "publicInterface",
"return ", argumentTypes
);
} else {
closure.constructor = this.$MakeBoundConstructor(
argumentNames
);
JSIL.MethodSignature.$EmitInvocation(
body, "new constructor", null,
"return ", argumentTypes
);
}
var result = JSIL.CreateNamedFunction(
"ConstructorSignature.Construct$" + argumentTypes.length,
argumentNames,
body.join("\r\n"),
closure
);
return result;
};
JSIL.ConstructorSignature.prototype.toString = function () {
var signature;
signature = this.get_Type().toString(this) + "::.ctor (";
for (var i = 0; i < this.argumentTypes.length; i++) {
signature += this.ResolveTypeReference(this.argumentTypes[i])[1].toString(this);
if (i < this.argumentTypes.length - 1)
signature += ", "
}
signature += ")";
return signature;
};
JSIL.ResolvedMethodSignature = function (methodSignature, key, returnType, argumentTypes) {
this.methodSignature = methodSignature;
this.key = key;
this.returnType = returnType;
this.argumentTypes = argumentTypes;
JSIL.ValidateArgumentTypes(argumentTypes);
};
JSIL.ResolvedMethodSignature.prototype.ResolvePositionalGenericParameter = function (genericParameterValues, parameter) {
if (
(typeof (parameter) === "object") &&
(parameter !== null) &&
(Object.getPrototypeOf(parameter) === JSIL.PositionalGenericParameter.prototype)
) {
return genericParameterValues[parameter.index] || null;
} else {
return parameter;
}
};
JSIL.ResolvedMethodSignature.prototype.ResolvePositionalGenericParameters = function (genericParameterValues) {
var returnType = this.ResolvePositionalGenericParameter(genericParameterValues, this.returnType);
var argumentTypes = [];
var resolvedAnyArguments = false;
for (var i = 0, l = this.argumentTypes.length; i < l; i++) {
var argumentType = this.argumentTypes[i];
argumentType = this.ResolvePositionalGenericParameter(genericParameterValues, argumentType);
argumentTypes.push(argumentType);
if (argumentType !== this.argumentTypes[i]);
resolvedAnyArguments = true;
}
if ((returnType !== this.returnType) || resolvedAnyArguments)
return new JSIL.ResolvedMethodSignature(
this.methodSignature,
this.key,
returnType,
argumentTypes
);
else
return this;
};
JSIL.ResolvedMethodSignature.prototype.toString = function () {
return this.methodSignature.toString.apply(this.methodSignature, arguments);
};
JSIL.InterfaceMethod = function (typeObject, methodName, signature, parameterInfo) {
this.typeObject = typeObject;
this.variantGenericArguments = JSIL.$FindVariantGenericArguments(typeObject);
this.methodName = methodName;
if (signature) {
// Important so ICs don't get mixed up.
this.signature = signature.Clone(true);
} else {
// FIXME: Why the hell does this happen?
this.signature = null;
}
this.parameterInfo = parameterInfo;
this.qualifiedName = JSIL.$GetSignaturePrefixForType(typeObject) + this.methodName;
this.variantInvocationCandidateCache = JSIL.CreateDictionaryObject(null);
this.fallbackMethod = JSIL.$PickFallbackMethodForInterfaceMethod(typeObject, methodName, signature);
JSIL.SetLazyValueProperty(this, "methodKey", function () {
return this.signature.GetNamedKey(this.qualifiedName, true);
});
};
JSIL.SetLazyValueProperty(JSIL.InterfaceMethod.prototype, "Call", function () { return this.$MakeCallMethod(); }, true);
JSIL.InterfaceMethod.prototype.Rebind = function (newTypeObject, newSignature) {
var result = new JSIL.InterfaceMethod(newTypeObject, this.methodName, newSignature, this.parameterInfo);
result.fallbackMethod = this.fallbackMethod;
return result;
};
JSIL.InterfaceMethod.prototype.GetVariantInvocationCandidates = function (thisReference) {
var cache = this.variantInvocationCandidateCache;
var typeId = thisReference.__ThisTypeId__;
var result = cache[typeId];
if (typeof (result) === "undefined") {
cache[typeId] = result = JSIL.$GenerateVariantInvocationCandidates(
this.typeObject, this.signature, this.qualifiedName, this.variantGenericArguments, JSIL.GetType(thisReference)
);
}
return result;
};
JSIL.InterfaceMethod.prototype.MethodLookupFailed = function (thisReference) {
var variantInvocationCandidates = this.GetVariantInvocationCandidates(thisReference);
var errorString = "Method '" + this.signature.toString(this.methodName) + "' of interface '" +
this.typeObject.__FullName__ + "' is not implemented by object " +
thisReference + "\n";
if (variantInvocationCandidates) {
errorString += "(Looked for key(s): '";
errorString += this.methodKey + "'";
for (var i = 0, l = variantInvocationCandidates.length; i < l; i++) {
var candidate = variantInvocationCandidates[i];
errorString += ", \n'" + candidate + "'";
}
errorString += ")";
} else {
errorString += "(Looked for key '" + this.methodKey + "')";
}
JSIL.RuntimeError(errorString);
};
JSIL.InterfaceMethod.prototype.LookupMethod = function (thisReference, name) {
var methodKey;
if (this.variantGenericArguments.length > 0) {
methodKey = this.LookupVariantMethodKey(thisReference);
} else {
methodKey = this.methodKey;
}
var result = thisReference[methodKey];
if (!result)
this.MethodLookupFailed(thisReference);
return result;
};
JSIL.InterfaceMethod.prototype.LookupVariantMethodKey = function (thisReference) {
var variantInvocationCandidates = this.GetVariantInvocationCandidates(thisReference);
if (variantInvocationCandidates) {
for (var i = 0, l = variantInvocationCandidates.length; i < l; i++) {
var candidate = variantInvocationCandidates[i];
var variantResult = thisReference[candidate];
if (variantResult)
return candidate;
}
}
return this.methodKey;
};
JSIL.InterfaceMethod.prototype.$MakeCallMethod = function () {
if (this.typeObject.__IsClosed__ && this.signature.IsClosed) {
var callType =
(this.variantGenericArguments.length > 0)
? "CallVariantInterface"
: "CallInterface";
var fallbackMethod = this.fallbackMethod;
Object.defineProperty(
this, "fallbackMethod",
{
value: fallbackMethod,
writable: false,
writeable: false,
configurable: false
}
);
return this.signature.$MakeCallMethod(callType, this.methodKey, fallbackMethod);
} else {
return function () {
JSIL.RuntimeError("Cannot invoke method '" + this.methodName + "' of open generic interface '" + this.typeObject.__FullName__ + "'");
};
}
};
JSIL.InterfaceMethod.prototype.toString = function () {
// HACK: This makes it possible to do
// MethodSignature.CallVirtual(IFoo.Method, thisReference)
return this.qualifiedName;
};
JSIL.$GetSignaturePrefixForType = function (typeObject) {
if (typeObject.IsInterface) {
if (typeObject.__OpenType__)
return "I" + typeObject.__OpenType__.__TypeId__ + "$";
else
return "I" + typeObject.__TypeId__ + "$";
} else {
return "";
}
};
//
// System.Type.cs
//
// Author:
// Rodrigo Kumpera <[email protected]>
//
//
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
//
// 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.
//
JSIL.TypeNameParseState = function (input, fromPosition) {
this.input = input;
this.pos = fromPosition;
};
Object.defineProperty(JSIL.TypeNameParseState.prototype, "eof", {
get: function () {
return this.pos >= this.input.length;
}
});
Object.defineProperty(JSIL.TypeNameParseState.prototype, "current", {
get: function () {
return this.input[this.pos];
}
});
JSIL.TypeNameParseState.prototype.substr = function (start, count) {
return this.input.substr(start, count);
};
JSIL.TypeNameParseState.prototype.moveNext = function () {
this.pos += 1;
return (this.pos < this.input.length);
};
JSIL.TypeNameParseState.prototype.skipWhitespace = function () {
var length = this.input.length;
while ((this.pos < length) && (this.current === ' '))
this.pos += 1;
};
JSIL.TypeNameParseResult = function () {
this.type = null;
this.assembly = null;
this.genericArguments = [];
this.arraySpec = [];
this.pointerLevel = 0;
this.isByRef = false;
this.parseEndedAt = null;
};
Object.defineProperty(JSIL.TypeNameParseResult.prototype, "isArray", {
get: function () {
return this.arraySpec.length > 0;
}
});
JSIL.TypeNameParseResult.prototype.addName = function (name) {
if (!this.type)
this.type = name;
else
this.type += "+" + name;
};
JSIL.TypeNameParseResult.prototype.addArray = function (array) {
this.arraySpec.push(array);
};
JSIL.ParseTypeNameImpl = function (input, fromPosition, isRecursive, allowQualifiedNames) {
var state = new JSIL.TypeNameParseState(input, fromPosition);
var inModifiers = false;
state.skipWhitespace();
var startPosition = state.pos;
var result = new JSIL.TypeNameParseResult();
while (state.moveNext()) {
switch (state.current) {
case '+':
result.addName(state.substr(startPosition, state.pos - startPosition));
startPosition = state.pos + 1;
break;
case ',':
case ']':
result.addName(state.substr(startPosition, state.pos - startPosition));
startPosition = state.pos + 1;
inModifiers = true;
if (isRecursive && !allowQualifiedNames) {
result.parseEndedAt = state.pos;
return result;
}
break;
case '&':
case '*':
case '[':
if (isRecursive && (state.current !== '['))
JSIL.RuntimeError("Generic argument must be by-value and not a pointer");
result.addName(state.substr(startPosition, state.pos - startPosition));
startPosition = state.pos + 1;
inModifiers = true;
break;
}
if (inModifiers)
break;
}
if (startPosition < state.pos)
result.addName(state.substr(startPosition, state.pos - startPosition));
if (!inModifiers) {
result.parseEndedAt = state.pos;
return result;
}
state.pos -= 1;
while (state.moveNext()) {
switch (state.current) {
case '&':
if (result.isByRef)
JSIL.RuntimeError("Too many &s");
result.isByRef = true;
break;
case '*':
if (result.isByRef)
JSIL.RuntimeError("Can't have a pointer to a byref type");
result.pointerLevel += 1;
break;
case ',':
if (isRecursive) {
var length = state.input.length, end = state.pos;
while (end < length && state.input[end] !== ']')
end += 1;
if (end >= length)
JSIL.RuntimeError("Unmatched '['");
result.assembly = state.substr(state.pos + 1, end - state.pos - 1).trim();
state.pos = end + 1;
result.parseEndedAt = state.pos;
return result;
}
result.assembly = state.substr(state.pos + 1).trim();
state.pos = length;
break;
case '[':
if (result.isByRef)
JSIL.RuntimeError("ByRef qualifier must be last part of type");
state.pos += 1;
if (state.pos >= length)
JSIL.RuntimeError("Invalid array/generic spec");
state.skipWhitespace();
var sch = state.current;
if (
(sch !== ',') &&
(sch !== '*') &&
(sch !== ']')
) {
//generic args
if (result.isArray)
throw new ArgumentException ("generic args after array spec", "typeName");
while (!state.eof) {
state.skipWhitespace();
var aqn = state.current === '[';
if (aqn)
state.moveNext();
var subspec = JSIL.ParseTypeNameImpl(state.input, state.pos, true, aqn);
state.pos = subspec.parseEndedAt;
result.genericArguments.push(subspec);
if (state.eof)
JSIL.RuntimeError("Invalid generic args spec");
if (state.current === ']')
break;
else if (state.current === ',')
state.moveNext();
else
JSIL.RuntimeError("Invalid generic args separator");
}
if (state.eof || (state.current !== ']'))
JSIL.RuntimeError("Invalid generic args spec");
} else {
//array spec
var dimensions = 1, bound = false;
while (!state.eof && (state.current !== ']')) {
if (state.current === '*') {
if (bound)
JSIL.RuntimeError("Array spec has too many bound dimensions");
bound = true;
} else if (state.current !== ',') {
JSIL.RuntimeError("Invalid character in array spec");
} else {
dimensions += 1;
}
state.moveNext();
state.skipWhitespace();
}
if (state.current !== ']')
JSIL.RuntimeError("Invalid array spec");
if ((dimensions > 1) && bound)
JSIL.RuntimeError("Invalid array spec: Multi-dimensional array can't be bound");
result.addArray({
dimensions: dimensions,
bound: bound
});
}
break;
case ']':
if (isRecursive) {
result.parseEndedAt = state.pos;
return result;
}
JSIL.RuntimeError("Unmatched ']'");
default:
JSIL.RuntimeError("Invalid type spec");
}
}
return result;
};
JSIL.ParseTypeName = function (name) {
return JSIL.ParseTypeNameImpl(name, 0, false, true);
};
JSIL.GetTypeInternal = function (parsedTypeName, defaultContext, throwOnFail) {
var context = null;
if (parsedTypeName.assembly !== null)
context = JSIL.GetAssembly(parsedTypeName.assembly, true);
if (context === null)
context = defaultContext;
var ga = null;
if (parsedTypeName.genericArguments !== null) {
ga = new Array(parsedTypeName.genericArguments.length);
for (var i = 0, l = ga.length; i < l; i++) {
ga[i] = JSIL.GetTypeInternal(parsedTypeName.genericArguments[i], defaultContext, false);
if (ga[i] === null) {
if (throwOnFail)
JSIL.RuntimeError("Unable to resolve generic argument '" + parsedTypeName.genericArguments[i].type + "'");
else
return null;
}
}
}
return JSIL.GetTypeFromAssembly(context, parsedTypeName.type, ga, throwOnFail);
};
JSIL.GetTypeFromAssembly = function (assembly, typeName, genericArguments, throwOnFail) {
var resolved, result = null;
var publicInterface = assembly.__PublicInterface__ || assembly;
assembly = publicInterface.__Assembly__;
resolved = JSIL.ResolveName(publicInterface, typeName, true, throwOnFail === true);
if (resolved === null)
return null;
if (resolved.exists()) {
result = resolved.get();
if (JSIL.IsArray(genericArguments) && (genericArguments.length > 0))
result = result.Of.apply(result, genericArguments);
} else if (throwOnFail) {
throw new System.TypeLoadException("The type '" + typeName + "' could not be found in the assembly '" + assembly.toString() + "'.");
}
if (result !== null)
return result.__Type__;
else
return null;
};
JSIL.GetTypesFromAssembly = function (assembly) {
var publicInterface = assembly.__PublicInterface__ || assembly;
assembly = publicInterface.__Assembly__;
var result = [];
var types = publicInterface.$typesByName;
for (var k in types) {
var typeFunction = types[k];
var publicInterface = typeFunction(false);
var type = publicInterface.__Type__;
result.push(type);
}
return result;
};
JSIL.$CreateInstanceOfTypeTable = JSIL.CreateDictionaryObject(null);
JSIL.CreateInstanceOfTypeRecordSet = function (type) {
this.records = JSIL.CreateDictionaryObject(null);
};
JSIL.CreateInstanceOfTypeRecord = function (
type, publicInterface,
constructorName, constructor,
specialValue
) {
JSIL.RunStaticConstructors(publicInterface, type);
var closure = JSIL.CreateDictionaryObject(null);
var constructorBody = [];
this.type = type;
this.constructorName = constructorName;
this.constructor = constructor;
this.specialValue = specialValue;
this.argumentlessInstanceConstructor = null;
// FIXME: I think this runs the field initializer twice? :(
var fi = JSIL.GetFieldInitializer(type);
if (fi) {
closure.fieldInitializer = fi;
constructorBody.push("fieldInitializer(this);");
}
if ((constructorName === null) && (constructor === null)) {
} else {
if (type.__IsStruct__) {
this.argumentlessInstanceConstructor = JSIL.CreateNamedFunction(
type.__FullName__ + ".CreateInstanceOfType$NoArguments",
[],
constructorBody.join("\r\n"),
closure
);
this.argumentlessInstanceConstructor.prototype = publicInterface.prototype;
} else {
constructorBody.push("if ((typeof (argv) === 'undefined') || (argv === null)) argv = [];");
}
if (constructor) {
closure.actualConstructor = constructor;
constructorBody.push("return actualConstructor.apply(this, argv);");
}
}
this.instanceConstructor = JSIL.CreateNamedFunction(
type.__FullName__ + ".CreateInstanceOfType",
["argv"],
constructorBody.join("\r\n"),
closure
);
this.instanceConstructor.prototype = publicInterface.prototype;
};
JSIL.CreateInstanceOfType$CacheMiss = function (type, constructorName, constructorArguments, recordSet) {
if (!recordSet)
recordSet = JSIL.$CreateInstanceOfTypeTable[type.__TypeId__] =
new JSIL.CreateInstanceOfTypeRecordSet(type);
var publicInterface = type.__PublicInterface__;
var record = null;
if (type.__IsNativeType__) {
var specialValue = JSIL.DefaultValue(type);
record = new JSIL.CreateInstanceOfTypeRecord(
type, publicInterface, null, null, specialValue
);
} else if (typeof (constructorName) === "string") {
var constructor = publicInterface.prototype[constructorName];
if (!constructor)
JSIL.RuntimeError("Type '" + type.__FullName__ + "' does not have a constructor named '" + constructorName + "'");
record = new JSIL.CreateInstanceOfTypeRecord(
type, publicInterface, constructorName, constructor, null
);
} else if (typeof (constructorName) === "function") {
record = new JSIL.CreateInstanceOfTypeRecord(
type, publicInterface, constructorName, constructorName, null
);
} else {
record = new JSIL.CreateInstanceOfTypeRecord(
type, publicInterface, null, null, null
);
}
if (type.__IsClosed__ === false)
JSIL.RuntimeError("Cannot create an instance of an open type");
else if (type.IsInterface)
JSIL.RuntimeError("Cannot create an instance of an interface");
recordSet.records[constructorName] = record;
return JSIL.CreateInstanceOfType$CacheHit(type, record, constructorArguments);
};
JSIL.CreateInstanceOfType$CacheHit = function (type, record, constructorArguments) {
if (type.__IsNativeType__) {
// Native types need to be constructed differently.
if (record.specialValue !== null)
return record.specialValue;
else
return record.constructor.apply(record.constructor, constructorArguments);
} else {
if (
(constructorArguments === null) ||
(constructorArguments === undefined) ||
(constructorArguments.length === 0)
) {
if (record.argumentlessInstanceConstructor !== null)
return new (record.argumentlessInstanceConstructor)();
else
return new (record.instanceConstructor)($jsilcore.ArrayNull);
} else {
return new (record.instanceConstructor)(constructorArguments);
}
}
};
JSIL.CreateInstanceOfType = function (type, $constructorName, $constructorArguments) {
var constructorName = null, constructorArguments = null;
if (arguments.length < 2)
constructorName = "_ctor";
else
constructorName = $constructorName;
if (arguments.length < 3)
constructorArguments = null;
else
constructorArguments = $constructorArguments;
var recordSet = JSIL.$CreateInstanceOfTypeTable[type.__TypeId__] || null;
if (recordSet) {
var record = recordSet.records[constructorName] || null;
if (record) {
return JSIL.CreateInstanceOfType$CacheHit(type, record, constructorArguments);
} else {
return JSIL.CreateInstanceOfType$CacheMiss(type, constructorName, constructorArguments, recordSet);
}
} else {
return JSIL.CreateInstanceOfType$CacheMiss(type, constructorName, constructorArguments, null);
}
};
$jsilcore.BindingFlags = {
Default: 0,
IgnoreCase: 1,
DeclaredOnly: 2,
Instance: 4,
Static: 8,
Public: 16,
NonPublic: 32,
FlattenHierarchy: 64,
InvokeMethod: 256,
CreateInstance: 512,
GetField: 1024,
SetField: 2048,
GetProperty: 4096,
SetProperty: 8192,
PutDispProperty: 16384,
PutRefDispProperty: 32768,
ExactBinding: 65536,
SuppressChangeType: 131072,
OptionalParamBinding: 262144,
IgnoreReturn: 16777216,
$Flags: function () {
var result = 0;
for (var i = 0; i < arguments.length; i++) {
result |= $jsilcore.BindingFlags[arguments[i]];
}
return result;
}
};
// Ensures that all the type's members have associated MemberInfo instances and returns them.
JSIL.GetReflectionCache = function (typeObject) {
if (typeof (typeObject) === "undefined")
return null;
if (typeObject === null)
return null;
var cache = typeObject.__ReflectionCache__;
if (JSIL.IsArray(cache))
return cache;
var members = typeObject.__Members__;
if (!JSIL.IsArray(members))
return null;
cache = typeObject.__ReflectionCache__ = [];
var makeTypeInstance = function (type) {
// Construct the appropriate subclass of MemberInfo
var parsedTypeName = JSIL.ParseTypeName("System.Reflection." + type);
var infoType = JSIL.GetTypeInternal(parsedTypeName, $jsilcore, true);
var info = JSIL.CreateInstanceOfType(infoType, null);
/*
// Don't trigger type initialization machinery
// FIXME: This will break if any of the memberinfo types rely on static constructors.
var infoType = JSIL.GetTypeByName("System.Reflection." + type, $jsilcore);
var info = Object.create(infoType.prototype);
*/
// HACK: Makes it possible to tell what type a member is trivially
JSIL.SetValueProperty(info, "__MemberType__", type);
return info;
};
for (var i = 0, l = members.length; i < l; i++) {
var member = members[i];
if (!member)
continue;
var type = member.type;
var descriptor = member.descriptor;
var data = member.data;
var info = makeTypeInstance(type);
info._typeObject = typeObject;
info._data = data;
info._descriptor = descriptor;
info.__Attributes__ = member.attributes;
info.__Overrides__ = member.overrides;
cache.push(info);
}
return cache;
};
// Scans the specified type (and its base types, as necessary) to retrieve all the MemberInfo instances appropriate for a request.
// If any BindingFlags are specified in flags they are applied as filters to limit the number of members returned.
// If memberType is specified and is the short name of a MemberInfo subclass like 'FieldInfo', only members of that type are returned.
JSIL.GetMembersInternal = function (typeObject, flags, memberType, name) {
var result = [];
var bindingFlags = $jsilcore.BindingFlags;
var allMethodsIncludingSpecialNames = (memberType === "$AllMethods");
var methodOrConstructor = (memberType === "$MethodOrConstructor") || allMethodsIncludingSpecialNames;
var allowInherited = ((flags & bindingFlags.DeclaredOnly) == 0) &&
// FIXME: WTF is going on here?
!typeObject.IsInterface;
var publicOnly = (flags & bindingFlags.Public) != 0;
var nonPublicOnly = (flags & bindingFlags.NonPublic) != 0;
if (publicOnly && nonPublicOnly)
publicOnly = nonPublicOnly = false;
// FIXME: Is this right?
else if (!publicOnly && !nonPublicOnly)
return result;
var staticOnly = (flags & bindingFlags.Static) != 0;
var instanceOnly = (flags & bindingFlags.Instance) != 0;
if (staticOnly && instanceOnly)
staticOnly = instanceOnly = false;
var members = [];
var target = typeObject;
while (target !== null) {
var targetMembers = JSIL.GetReflectionCache(target);
if (targetMembers === null)
break;
members = targetMembers.concat(members);
if (!allowInherited)
break;
target = target.__BaseType__;
}
for (var i = 0, l = members.length; i < l; i++) {
var member = members[i];
// HACK: Reflection never seems to enumerate static constructors. This is probably because
// it doesn't make any sense to invoke them explicitly anyway, and they don't have arguments...
if (
!allMethodsIncludingSpecialNames &&
member._descriptor.Static &&
member._descriptor.SpecialName &&
member._descriptor.Name.indexOf("cctor") >= 0
)
continue;
if (publicOnly && !member._descriptor.Public)
continue;
else if (nonPublicOnly && member._descriptor.Public)
continue;
if (staticOnly && !member._descriptor.Static)
continue;
else if (instanceOnly && member._descriptor.Static)
continue;
var currentMemberType = member.__ThisType__.__ShortName__;
if (methodOrConstructor) {
if (
(currentMemberType != "MethodInfo") &&
(currentMemberType != "ConstructorInfo")
)
continue;
} else if ((typeof (memberType) === "string") && (memberType != currentMemberType)) {
continue;
}
if ((typeof (name) === "string") && (name != member._descriptor.Name)) {
continue;
}
result.push(member);
}
return result;
};
JSIL.AnyValueType = JSIL.AnyType = {
__TypeId__: "any",
CheckType: function (value) {
return true;
}
};
JSIL.ApplyCollectionInitializer = function (target, values) {
for (var i = 0, l = values.length; i < l; i++)
target.Add.apply(target, values[i]);
};
JSIL.StructEquals = function Struct_Equals (lhs, rhs) {
if (lhs === rhs)
return true;
if ((rhs === null) || (rhs === undefined))
return false;
var thisType = lhs.__ThisType__;
var comparer = thisType.__Comparer__;
if (comparer === $jsilcore.FunctionNotInitialized)
comparer = thisType.__Comparer__ = JSIL.$MakeStructComparer(thisType, thisType.__PublicInterface__);
return comparer(lhs, rhs);
};
JSIL.DefaultValueInternal = function (typeObject, typePublicInterface) {
var fullName = typeObject.__FullName__;
if (fullName === "System.Char") {
return "\0";
} else if (fullName === "System.Boolean") {
return false;
} else if (typeObject.__IsReferenceType__) {
return null;
} else if (typeObject.__IsNumeric__) {
return 0;
} else if (typeObject.__IsEnum__) {
return typePublicInterface[typeObject.__ValueToName__[0]];
} else {
return new typePublicInterface();
}
};
JSIL.DefaultValue = function (type) {
var typeObject, typePublicInterface;
if (!type)
JSIL.RuntimeError("No type passed into DefaultValue");
if (typeof (type.__Type__) === "object") {
typeObject = type.__Type__;
typePublicInterface = type;
} else if (typeof (type.__PublicInterface__) !== "undefined") {
typeObject = type;
typePublicInterface = type.__PublicInterface__;
}
if (typeObject && typePublicInterface) {
return JSIL.DefaultValueInternal(typeObject, typePublicInterface);
} else {
// Handle stupid special cases
if ((type === Object) || (type === Array) || (type === String))
return null;
else if (type === Number)
return 0;
JSIL.RuntimeError("Invalid type passed into DefaultValue: " + String(type));
}
};
JSIL.Array.GetElements = function (array) {
if (Object.getPrototypeOf(array) === JSIL.MultidimensionalArray.prototype)
return array._items;
else if (JSIL.IsArray(array))
return array;
else
JSIL.RuntimeError("Argument is not an array");
};
JSIL.Array.$EraseImplementations = JSIL.CreateDictionaryObject(null);
// Creating a unique implementation of Erase for every element type
// allows JITs to optimize it more aggressively by making ICs monomorphic
JSIL.Array.$GetEraseImplementation = function (elementTypeObject, elementTypePublicInterface) {
var result = JSIL.Array.$EraseImplementations[elementTypeObject.__TypeId__];
if (!result) {
var body = [
"length = length | 0;",
"startIndex = startIndex | 0;",
"",
"if (length > elements.length)",
" JSIL.RuntimeError('Length out of range');",
""
];
if (elementTypeObject.__IsNativeType__) {
body.push("var defaultValue = JSIL.DefaultValueInternal(elementTypeObject, elementTypePublicInterface);");
} else if (elementTypeObject.__IsEnum__) {
body.push("var defaultValue = elementTypePublicInterface.$Cast(0);");
} else if (!elementTypeObject.__IsStruct__) {
body.push("var defaultValue = null;");
}
body.push("");
body.push("for (var i = 0; i < length; i = (i + 1) | 0)");
if (elementTypeObject.__IsStruct__) {
body.push(" elements[(i + startIndex) | 0] = new elementTypePublicInterface();");
} else {
body.push(" elements[(i + startIndex) | 0] = defaultValue;");
}
result = JSIL.CreateNamedFunction(
elementTypeObject.__FullName__ + "[].Erase",
["elements", "startIndex", "length"],
body.join("\n"),
{
elementTypeObject: elementTypeObject,
elementTypePublicInterface: elementTypePublicInterface
}
);
JSIL.Array.$EraseImplementations[elementTypeObject.__TypeId__] = result;
}
return result;
};
// startIndex and length are optional
JSIL.Array.Erase = function Array_Erase (array, elementType, startIndex, length) {
var elementTypeObject, elementTypePublicInterface;
if (typeof (elementType.__Type__) === "object") {
elementTypeObject = elementType.__Type__;
elementTypePublicInterface = elementType;
} else if (typeof (elementType.__PublicInterface__) !== "undefined") {
elementTypeObject = elementType;
elementTypePublicInterface = elementType.__PublicInterface__;
}
var elements = JSIL.Array.GetElements(array);
if (typeof (startIndex) !== "number")
startIndex = 0;
startIndex = startIndex | 0;
if (typeof (length) !== "number")
length = elements.length - startIndex;
length = length | 0;
var impl = JSIL.Array.$GetEraseImplementation(elementTypeObject, elementTypePublicInterface);
impl(elements, startIndex, length);
};
JSIL.Array.New = function Array_New (elementType, sizeOrInitializer) {
var elementTypeObject = null, elementTypePublicInterface = null;
if (typeof (elementType.__Type__) === "object") {
elementTypeObject = elementType.__Type__;
elementTypePublicInterface = elementType;
} else if (typeof (elementType.__PublicInterface__) !== "undefined") {
elementTypeObject = elementType;
elementTypePublicInterface = elementType.__PublicInterface__;
}
var result = null, size = 0;
var initializerIsArray = JSIL.IsArray(sizeOrInitializer);
if (initializerIsArray) {
size = sizeOrInitializer.length;
} else {
size = Number(sizeOrInitializer);
}
var typedArrayCtor = JSIL.GetTypedArrayConstructorForElementType(elementTypeObject, false);
if (typedArrayCtor) {
result = new (typedArrayCtor)(size);
} else {
result = new Array(size);
}
if (initializerIsArray) {
// If non-numeric, assume array initializer
for (var i = 0; i < sizeOrInitializer.length; i++)
result[i] = sizeOrInitializer[i];
} else if (!typedArrayCtor) {
JSIL.Array.Erase(result, elementType);
}
return result;
};
JSIL.Array.Clone = function (array) {
if (JSIL.IsTypedArray(array)) {
var ctor = Object.getPrototypeOf(array).constructor;
return new ctor(array);
} else if (Object.getPrototypeOf(array) === JSIL.MultidimensionalArray.prototype) {
return new JSIL.MultidimensionalArray(array._type, array._dimensions, array._items);
} else if (JSIL.IsArray(array)) {
return Array.prototype.slice.call(array);
} else {
JSIL.RuntimeError("Invalid array");
}
};
JSIL.Array.CopyTo = function (source, destination, destinationIndex) {
if (JSIL.IsTypedArray(destination)) {
destination.set(source, destinationIndex);
return;
}
var srcArray = JSIL.Array.GetElements(source);
var destArray = JSIL.Array.GetElements(destination);
var size = Math.min(srcArray.length, destArray.length);
for (var i = 0; i < size; i++)
destArray[i + destinationIndex] = srcArray[i];
};
JSIL.Array.ShallowCopy = function (destination, source) {
JSIL.Array.CopyTo(source, destination, 0);
};
$jsilcore.CheckDelegateType = function (value) {
if (value === null)
return false;
return (
(typeof (value) === "function") ||
(typeof (value) === "object")
) && (value.__ThisType__ === this);
};
JSIL.MakeDelegate = function (fullName, isPublic, genericArguments, methodSignature, pInvokeInfo) {
var assembly = $private;
var localName = JSIL.GetLocalName(fullName);
var callStack = null;
if (typeof (printStackTrace) === "function")
callStack = printStackTrace();
var creator = function CreateDelegate () {
var delegateType;
delegateType = JSIL.GetTypeByName("System.MulticastDelegate", $jsilcore).__Type__;
var typeObject = JSIL.$MakeTypeObject(fullName);
typeObject.__Context__ = assembly;
JSIL.SetValueProperty(typeObject, "__BaseType__", delegateType);
JSIL.SetValueProperty(typeObject, "__FullName__", fullName);
typeObject.__CallStack__ = callStack;
typeObject.__Interfaces__ = [];
typeObject.__IsDelegate__ = true;
JSIL.SetValueProperty(typeObject, "__IsReferenceType__", true);
typeObject.__AssignableTypes__ = null;
typeObject.__IsEnum__ = false;
typeObject.__IsValueType__ = false;
typeObject.__IsByRef__ = false;
typeObject.__TypeInitialized__ = false;
JSIL.FillTypeObjectGenericArguments(typeObject, genericArguments);
var staticClassObject = typeObject.__PublicInterface__ = JSIL.CreateSingletonObject(JSIL.StaticClassPrototype);
staticClassObject.__Type__ = typeObject;
staticClassObject.prototype = JSIL.CreatePrototypeObject($jsilcore.System.MulticastDelegate.prototype);
var toStringImpl = function DelegateType_ToString () {
return this.__ThisType__.toString();
};
var pinImpl = function Delegate_Pin () {
this.__pinnedPointer__ =
System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate$b1(
this.__ThisType__
)(
this
);
};
var unpinImpl = function Delegate_Unpin () {
this.__pinnedPointer__ = null;
};
var asIntPtrImpl = function Delegate_AsIntPtr () {
if (this.__pinnedPointer__)
return this.__pinnedPointer__;
else
JSIL.RuntimeErrorFormat("Delegate of type {0} is not pinned and cannot be packed/marshalled", [this.__ThisType__]);
};
JSIL.SetValueProperty(staticClassObject, "CheckType", $jsilcore.CheckDelegateType.bind(typeObject));
JSIL.SetValueProperty(staticClassObject, "New", function (object, method, methodInfoResolver) {
if ((typeof (method) === "undefined") &&
(typeof (object) === "function")
) {
method = object;
object = null;
if (method.__ThisType__ === typeObject)
return method;
else
JSIL.RuntimeError("Single delegate argument passed to Delegate.New, but types don't match");
}
if (typeof (method) !== "function") {
JSIL.RuntimeError("Non-function passed to Delegate.New");
}
if (method.__IsMembrane__)
method = method.__Unwrap__();
var resultDelegate = function Delegate_Invoke () {
return method.apply(object, arguments);
};
JSIL.SetValueProperty(resultDelegate, "__ThisType__", this.__Type__);
JSIL.SetValueProperty(resultDelegate, "toString", toStringImpl);
JSIL.SetValueProperty(resultDelegate, "__object__", object);
JSIL.SetValueProperty(resultDelegate, "__method__", method);
JSIL.SetValueProperty(resultDelegate, "__isMulticast__", false);
JSIL.SetValueProperty(resultDelegate, "Invoke", method);
JSIL.SetValueProperty(resultDelegate, "get_Method", this.__Type__.__PublicInterface__.prototype.get_Method);
JSIL.SetValueProperty(resultDelegate, "__methodInfoResolver__", methodInfoResolver);
// FIXME: Move these off the object to reduce cost of constructing delegates
JSIL.SetValueProperty(resultDelegate, "$pin", pinImpl);
JSIL.SetValueProperty(resultDelegate, "$unpin", unpinImpl);
JSIL.SetValueProperty(resultDelegate, "$asIntPtr", asIntPtrImpl);
resultDelegate.__isMethodInfoResolved__ = false;
return resultDelegate;
});
JSIL.SetTypeId(
typeObject, staticClassObject, JSIL.AssignTypeId(assembly, fullName)
);
if (typeObject.__GenericArguments__.length > 0) {
staticClassObject.Of$NoInitialize = $jsilcore.$MakeOf$NoInitialize(staticClassObject);
staticClassObject.Of = $jsilcore.$MakeOf(staticClassObject);
typeObject.__IsClosed__ = false;
typeObject.__OfCache__ = {};
} else {
typeObject.__IsClosed__ = true;
typeObject.__AssignableFromTypes__ = {};
}
JSIL.MakeCastMethods(staticClassObject, typeObject, "delegate");
if (methodSignature) {
var ib = new JSIL.InterfaceBuilder(assembly, typeObject, staticClassObject);
ib.Method({Static:false , Public:true }, "Invoke",
methodSignature,
function() {return this.__method__.apply(this, arguments);});
typeObject.__Signature__ = methodSignature;
} else {
typeObject.__Signature__ = null;
}
if (pInvokeInfo) {
typeObject.__PInvokeInfo__ = pInvokeInfo;
} else {
typeObject.__PInvokeInfo__ = null;
}
return staticClassObject;
};
JSIL.RegisterName(fullName, assembly, isPublic, creator);
};
JSIL.StringToByteArray = function (text) {
var result = JSIL.Array.New(System.Byte, text.length);
for (var i = 0, l = text.length; i < l; i++)
result[i] = text.charCodeAt(i) & 0xFF;
return result;
};
JSIL.StringToCharArray = function (text) {
var result = JSIL.Array.New(System.Char, text.length);
for (var i = 0, l = text.length; i < l; i++)
result[i] = text[i];
return result;
};
JSIL.$equalsSignature = null;
JSIL.GetEqualsSignature = function () {
if (JSIL.$equalsSignature === null)
JSIL.$equalsSignature = new JSIL.MethodSignature("System.Boolean", ["System.Object"], [], $jsilcore);
return JSIL.$equalsSignature;
}
JSIL.ObjectEquals = function (lhs, rhs) {
if ((lhs === null) || (rhs === null))
return lhs === rhs;
if (lhs === rhs)
return true;
switch (typeof (lhs)) {
case "string":
case "number":
return lhs == rhs;
break;
case "object":
var key = JSIL.GetEqualsSignature().GetNamedKey("Object_Equals", true);
var fn = lhs[key];
if (fn)
return fn.call(lhs, rhs);
break;
}
return false;
};
JSIL.CompareValues = function (lhs, rhs) {
if (lhs > rhs)
return 1;
else if (lhs < rhs)
return -1;
else
return 0;
};
var $nextHashCode = 0;
var $hashCodeWeakMap = null;
if (typeof (WeakMap) !== "undefined") {
$hashCodeWeakMap = new WeakMap();
JSIL.HashCodeInternal = function (obj) {
var hc = $hashCodeWeakMap.get(obj);
if (!hc) {
hc = (++$nextHashCode) | 0;
$hashCodeWeakMap.set(obj, hc);
}
return hc;
};
} else {
JSIL.HashCodeInternal = function (obj) {
var hc = obj.__HashCode__;
if (!hc)
hc = obj.__HashCode__ = (++$nextHashCode) | 0;
return hc;
};
}
JSIL.ObjectHashCode = function (obj) {
var type = typeof obj;
if (type === "object") {
if (obj.GetHashCode)
return (obj.GetHashCode() | 0);
return JSIL.HashCodeInternal(obj);
} else {
// FIXME: Not an integer. Gross.
return String(obj);
}
};
// MemberwiseClone if parameter is struct, otherwise do nothing.
JSIL.CloneParameter = function (parameterType, value) {
if (!parameterType)
JSIL.RuntimeError("Undefined parameter type");
if (
parameterType.__IsStruct__ &&
(parameterType.__IsNullable__ !== true) &&
// We have to check this because of some tricky semantic corner cases :/
(value !== null)
) {
return value.MemberwiseClone();
} else
return value;
};
JSIL.Nullable_Value = function (n) {
if (n === null)
throw new System.InvalidOperationException("Nullable has no value");
else
return n;
};
JSIL.Nullable_ValueOrDefault = function (n, defaultValue) {
if (n === null)
return defaultValue;
else
return n;
};
JSIL.Nullable_Cast = function (n, targetType) {
if (n === null)
return null;
else
return targetType.$Cast(n);
};
JSIL.GetMemberAttributes = function (memberInfo, inherit, attributeType, result) {
var tType = $jsilcore.System.Type;
var memberType = memberInfo.GetType().get_FullName();
if (inherit) {
if (memberType !== "System.Type")
throw new System.NotImplementedException("Inherited attributes only supported for types");
if (!result)
result = [];
var currentType = memberInfo;
while (currentType && currentType.GetType) {
JSIL.GetMemberAttributes(currentType, false, attributeType, result);
currentType = currentType.__BaseType__;
}
return result;
}
var attributes = memberInfo.__CachedAttributes__;
if (!attributes) {
attributes = memberInfo.__CachedAttributes__ = [];
var attributeRecords = memberInfo.__Attributes__;
if (attributeRecords) {
for (var i = 0, l = attributeRecords.length; i < l; i++) {
var record = attributeRecords[i];
var recordType = record.GetType();
var instance = record.Construct();
attributes.push(instance);
}
}
}
if (!result)
result = [];
for (var i = 0, l = attributes.length; i < l; i++) {
var attribute = attributes[i];
if (attributeType && !tType.op_Equality(attributeType, attribute.GetType()))
continue;
result.push(attributes[i]);
}
return result;
};
var $blobBuilderInfo = {
initialized: false,
retainedBlobs: []
};
JSIL.InitBlobBuilder = function () {
if ($blobBuilderInfo.initialized)
return;
var blobBuilder = window.WebKitBlobBuilder || window.mozBlobBuilder || window.MSBlobBuilder || window.BlobBuilder;
$blobBuilderInfo.hasObjectURL = (typeof (window.URL) !== "undefined") && (typeof (window.URL.createObjectURL) === "function");
$blobBuilderInfo.hasBlobBuilder = Boolean(blobBuilder);
$blobBuilderInfo.blobBuilder = blobBuilder;
$blobBuilderInfo.hasBlobCtor = false;
$blobBuilderInfo.applyIEHack = navigator.userAgent.indexOf("Trident/") >= 0;
try {
var blob = new Blob();
$blobBuilderInfo.hasBlobCtor = Boolean(blob);
} catch (exc) {
}
if (navigator.userAgent.indexOf("Firefox/14.") >= 0) {
JSIL.Host.logWriteLine("Your browser is outdated and has a serious bug. Please update to a newer version.");
$blobBuilderInfo.hasBlobBuilder = false;
$blobBuilderInfo.hasBlobCtor = false;
}
}
JSIL.GetObjectURLForBytes = function (bytes, mimeType) {
JSIL.InitBlobBuilder();
if (!$blobBuilderInfo.hasObjectURL)
JSIL.RuntimeError("Object URLs not available");
else if (!("Uint8Array" in window))
JSIL.RuntimeError("Typed arrays not available");
var blob = null;
if (Object.getPrototypeOf(bytes) !== Uint8Array.prototype)
JSIL.RuntimeError("bytes must be a Uint8Array");
try {
if ($blobBuilderInfo.hasBlobCtor) {
blob = new Blob([bytes], { type: mimeType });
}
} catch (exc) {
}
if (!blob) {
try {
if ($blobBuilderInfo.hasBlobBuilder) {
var bb = new $blobBuilderInfo.blobBuilder();
bb.append(bytes.buffer);
blob = bb.getBlob(mimeType);
}
} catch (exc) {
}
}
if (!blob)
JSIL.RuntimeError("Blob API broken or not available");
if ($blobBuilderInfo.applyIEHack)
$blobBuilderInfo.retainedBlobs.push(blob);
return window.URL.createObjectURL(blob);
}
JSIL.BinarySearch = function (T, array, start, count, value, comparer) {
if (!Array.isArray(array))
throw new System.Exception("An array must be provided");
if (start < 0)
throw new System.ArgumentOutOfRangeException("start");
else if (start >= array.length)
throw new System.ArgumentOutOfRangeException("start");
else if (count < 0)
throw new System.ArgumentOutOfRangeException("count");
else if ((start + count) > array.length)
throw new System.ArgumentOutOfRangeException("count");
if (comparer === null)
comparer = System.Collections.Generic.Comparer$b1.Of(T).get_Default();
var low = start, high = start + count - 1, pivot;
while (low <= high) {
pivot = (low + (high - low) / 2) | 0;
var order = comparer.Compare(array[pivot], value);
if (order === 0)
return pivot;
else if (order < 0)
low = pivot + 1;
else
high = pivot - 1;
}
return ~low;
};
JSIL.ResolveGenericExternalMethods = function (publicInterface, typeObject) {
var externalMethods = typeObject.__ExternalMethods__;
if (!externalMethods)
return;
var result = typeObject.__ExternalMethods__ = new Array(externalMethods.length);
for (var i = 0, l = result.length; i < l; i++)
result[i] = JSIL.$ResolveGenericMethodSignature(typeObject, externalMethods[i], publicInterface) || externalMethods[i];
};
JSIL.FreezeImmutableObject = function (object) {
// Object.freeze and Object.seal make reads *slower* in modern versions of Chrome and older versions of Firefox.
if (jsilConfig.enableFreezeAndSeal === true)
Object.freeze(object);
};
JSIL.GetTypedArrayConstructorForElementType = function (typeObject, byteFallback) {
if (!typeObject)
JSIL.RuntimeError("typeObject was null");
var result = typeObject.__TypedArray__ || null;
if (!result && byteFallback) {
if (typeObject.__IsStruct__)
result = $jsilcore.System.Byte.__TypedArray__ || null;
}
return result;
};
JSIL.ResolveGenericMemberSignatures = function (publicInterface, typeObject) {
var members = typeObject.__Members__;
if (!JSIL.IsArray(members))
return;
members = typeObject.__Members__ = Array.prototype.slice.call(members);
var resolveContext = typeObject.__IsStatic__ ? publicInterface : publicInterface.prototype;
for (var i = 0, l = members.length; i < l; i++) {
var member = members[i];
var descriptor = member.descriptor;
var data = member.data;
if (!data)
continue;
var signature = data.signature;
if (!signature)
continue;
var resolvedSignature = JSIL.$ResolveGenericMethodSignature(
typeObject, signature, resolveContext
);
if (!resolvedSignature)
continue;
var newData = JSIL.CreateDictionaryObject(data);
if (!newData.genericSignature)
newData.genericSignature = signature;
newData.signature = resolvedSignature;
var newMember = new JSIL.MemberRecord(member.type, member.descriptor, newData, member.attributes, member.overrides);
members[i] = newMember;
}
};
JSIL.TypeReferenceToName = function (typeReference) {
var result = null;
if (
typeof (typeReference) === "string"
) {
return typeReference;
} else if (
typeof (typeReference) === "object"
) {
if (typeReference === null)
JSIL.RuntimeError("Null type reference");
if (Object.getPrototypeOf(typeReference) === JSIL.TypeRef.prototype)
return typeReference.toName();
}
if (typeof (typeReference.__Type__) === "object") {
return typeReference.__Type__.toString();
} else {
return typeReference.toString();
}
};
JSIL.FillTypeObjectGenericArguments = function (typeObject, argumentNames) {
var names = [];
var variances = [];
if (argumentNames) {
if (!JSIL.IsArray(argumentNames))
JSIL.RuntimeError("Generic argument names must be undefined or an array");
for (var i = 0, l = argumentNames.length; i < l; i++) {
var variance = {
"in": false,
"out": false
};
var argumentName = argumentNames[i];
var tokens = argumentName.trim().split(" ");
for (var j = 0; j < tokens.length - 1; j++) {
switch (tokens[j]) {
case "in":
variance.in = true;
break;
case "out":
variance.out = true;
break;
default:
JSIL.RuntimeError("Invalid generic argument modifier: " + tokens[j]);
}
}
variances.push(variance);
names.push(tokens[tokens.length - 1].trim());
}
}
typeObject.__GenericArguments__ = names;
typeObject.__GenericArgumentVariance__ = variances;
};
JSIL.GetTypeAndBases = function (typeObject) {
// FIXME: Memoize the result of this function?
var result = [typeObject];
JSIL.$EnumBasesOfType(typeObject, result);
return result;
};
JSIL.$EnumBasesOfType = function (typeObject, resultList) {
var currentType = typeObject;
while (currentType) {
var baseRef = currentType.__BaseType__;
if (!baseRef)
break;
var base = JSIL.ResolveTypeReference(baseRef, currentType.__Context__)[1];
if (base)
resultList.push(base);
currentType = base;
}
};
JSIL.GetInterfacesImplementedByType = function (typeObject, walkInterfaceBases, allowDuplicates, includeDistance) {
// FIXME: Memoize the result of this function?
if (arguments.length < 3)
JSIL.RuntimeError("3 arguments expected");
var typeAndBases = JSIL.GetTypeAndBases(typeObject);
var result = [];
var distanceList = [];
// Walk in reverse to match the behavior of JSIL.Internal.TypeInfo.AllInterfacesRecursive
typeAndBases.reverse();
for (var i = 0, l = typeAndBases.length; i < l; i++) {
var typeObject = typeAndBases[i];
var distance = (typeAndBases.length - i - 1);
JSIL.$EnumInterfacesImplementedByTypeExcludingBases(
typeObject, result, distanceList, walkInterfaceBases, allowDuplicates, distance
);
}
if (includeDistance)
return {
interfaces: result,
distances: distanceList
};
else
return result;
};
JSIL.$EnumInterfacesImplementedByTypeExcludingBases = function (typeObject, resultList, distanceList, walkInterfaceBases, allowDuplicates, distance) {
if (arguments.length !== 6)
JSIL.RuntimeError("6 arguments expected");
var interfaces = typeObject.__Interfaces__;
var toEnumerate = [];
if (interfaces && interfaces.length) {
for (var i = 0, l = interfaces.length; i < l; i++) {
var ifaceRef = interfaces[i];
var iface = JSIL.ResolveTypeReference(ifaceRef, typeObject.__Context__)[1];
if (!iface)
continue;
var alreadyAdded = resultList.indexOf(iface) >= 0;
if (!alreadyAdded || allowDuplicates) {
resultList.push(iface);
if (distanceList)
distanceList.push(distance);
}
if (!alreadyAdded && walkInterfaceBases)
toEnumerate.push(iface);
}
}
for (var i = 0, l = toEnumerate.length; i < l; i++) {
var iface = toEnumerate[i];
JSIL.$EnumInterfacesImplementedByTypeExcludingBases(iface, resultList, distanceList, walkInterfaceBases, allowDuplicates, distance + 1);
}
};
JSIL.$FindMatchingInterfacesThroughVariance = function (expectedInterfaceObject, actualTypeObject, variantParameters) {
// FIXME: Memoize the result of this function?
var result = [];
var trace = 0;
var record = function (distance, iface) {
this.distance = distance;
this.interface = iface;
};
record.prototype.toString = function () {
return "<" + this.interface.toString() + " (distance " + this.distance + ")>";
};
// We have to scan exhaustively through all the interfaces implemented by this type
// We turn on distance tracking, so the interface records are [distance, interface] instead of interface objects.
var obj = JSIL.GetInterfacesImplementedByType(actualTypeObject, true, false, true);
var interfaces = obj.interfaces;
var distances = obj.distances;
if (trace >= 2)
System.Console.WriteLine("Type {0} implements {1} interface(s): [ {2} ]", actualTypeObject.__FullName__, interfaces.length, interfaces.join(", "));
var openExpected = expectedInterfaceObject.__OpenType__;
if (!openExpected || !openExpected.IsInterface)
JSIL.RuntimeError("Expected interface object must be a closed generic interface type");
// Scan for interfaces that could potentially match through variance
for (var i = 0, l = interfaces.length; i < l; i++) {
var iface = interfaces[i];
var distance = distances[i];
var openIface = iface.__OpenType__;
// Variance only applies to closed generic interface types... I think.
if (!openIface || !openIface.IsInterface)
continue;
if (openIface !== openExpected)
continue;
var ifaceResult = true;
check_parameters:
for (var j = 0; j < variantParameters.length; j++) {
var vp = variantParameters[j];
var lhs = expectedInterfaceObject.__GenericArgumentValues__[vp.index];
var rhs = iface.__GenericArgumentValues__[vp.index];
var parameterResult = true;
var foundIndex = -1;
if (vp.in) {
if (rhs.IsInterface) {
var interfacesLhs = JSIL.GetInterfacesImplementedByType(lhs, true, true);
foundIndex = interfacesLhs.indexOf(rhs);
} else {
var typeAndBasesLhs = JSIL.GetTypeAndBases(lhs);
foundIndex = typeAndBasesLhs.indexOf(rhs);
}
if (foundIndex < 0)
ifaceResult = parameterResult = false;
}
if (vp.out) {
if (lhs.IsInterface) {
var interfacesRhs = JSIL.GetInterfacesImplementedByType(rhs, true, true);
foundIndex = interfacesRhs.indexOf(lhs);
} else {
var typeAndBasesRhs = JSIL.GetTypeAndBases(rhs);
foundIndex = typeAndBasesRhs.indexOf(lhs);
}
if (foundIndex < 0)
ifaceResult = parameterResult = false;
}
if (trace >= 1)
System.Console.WriteLine(
"Variance check {4}{5}{0}: {1} <-> {2} === {3}",
vp.name, lhs, rhs, parameterResult,
vp.in ? "in " : "", vp.out ? "out " : ""
);
}
if (ifaceResult)
result.push(new record(distance, iface));
}
return result;
};
JSIL.CheckInterfaceVariantEquality = function (expectedInterfaceObject, actualTypeObject, variantParameters) {
// FIXME: Memoize the result of this function?
var matchingInterfaces = JSIL.$FindMatchingInterfacesThroughVariance(expectedInterfaceObject, actualTypeObject, variantParameters);
return matchingInterfaces.length > 0;
};
JSIL.$FindVariantGenericArguments = function (typeObject) {
var result = [];
var argumentVariances = typeObject.__GenericArgumentVariance__;
if (!argumentVariances)
return result;
for (var i = 0, l = argumentVariances.length; i < l; i++) {
var variance = argumentVariances[i];
if (variance.in || variance.out) {
var vp = JSIL.CreateDictionaryObject(variance);
vp.name = typeObject.__GenericArguments__[i];
vp.index = i;
result.push(vp);
}
}
return result;
};
JSIL.WrapCastMethodsForInterfaceVariance = function (typeObject, isFunction, asFunction) {
var trace = false;
var result = {
"is": isFunction,
"as": asFunction
};
var variantParameters = JSIL.$FindVariantGenericArguments(typeObject);
if (variantParameters.length === 0) {
if (trace)
System.Console.WriteLine("None of interface {0}'s parameters are variant", typeObject.__FullName__);
return result;
}
result.is = function Is_VariantInterface (value) {
var result = isFunction(value);
if (trace)
System.Console.WriteLine("({0} is {1}) == {2}", value, typeObject.__FullName__, result);
if (!result)
result = JSIL.CheckInterfaceVariantEquality(typeObject, JSIL.GetType(value), variantParameters);
if (trace)
System.Console.WriteLine("({0} is {1}) == {2}", value, typeObject.__FullName__, result);
return result;
};
result.as = function As_VariantInterface (value) {
var result = asFunction(value);
if (trace && !result)
System.Console.WriteLine("{0} as {1} failed", value, typeObject.__FullName__);
if (!result) {
if (JSIL.CheckInterfaceVariantEquality(typeObject, JSIL.GetType(value), variantParameters))
result = value;
if (trace)
System.Console.WriteLine("{0} as {1} variantly {2}", value, typeObject.__FullName__, result ? "succeeded" : "failed");
}
return result;
};
return result;
};
JSIL.$GenerateVariantInvocationCandidates = function (interfaceObject, signature, qualifiedMethodName, variantGenericArguments, thisReferenceType) {
var trace = false;
var matchingInterfaces = JSIL.$FindMatchingInterfacesThroughVariance(interfaceObject, thisReferenceType, variantGenericArguments);
if (trace)
System.Console.WriteLine("Matching interfaces in candidate generator: [ {0} ]", matchingInterfaces.join(", "));
if (!matchingInterfaces.length)
return null;
else if (!signature.openSignature) {
// FIXME: Is this right?
return null;
}
var result = [];
// Sort the interfaces by distance, in increasing order.
// This is necessary for the implementation-selection behavior used by the CLR in cases where
// there are multiple candidates due to variance. See issue #445.
matchingInterfaces.sort(function (lhs, rhs) {
return JSIL.CompareValues(lhs.distance, rhs.distance);
});
generate_candidates:
for (var i = 0, l = matchingInterfaces.length; i < l; i++) {
var record = matchingInterfaces[i];
// FIXME: This is incredibly expensive.
var variantSignature = JSIL.$ResolveGenericMethodSignature(
record.interface, signature.openSignature, record.interface.__PublicInterface__
);
var candidate = variantSignature.GetNamedKey(qualifiedMethodName, true);
if (trace)
System.Console.WriteLine("Candidate (distance {0}): {1}", record.distance, candidate);
result.push(candidate);
}
return result;
};
JSIL.$GetStringEnumerator = function () {
return JSIL.GetEnumerator(this, $jsilcore.System.Char.__Type__, true);
};
$jsilcore.$GetArrayEnumeratorImplementations = {};
JSIL.$GetEnumeratorFallback = function (interfaceTypeObject, signature, thisReference) {
if (typeof (thisReference) === "string") {
return JSIL.$GetStringEnumerator;
} else if (JSIL.IsArray(thisReference)) {
var enumeratorTypeArgument = $jsilcore.System.Object.__Type__;
if (interfaceTypeObject.IsGenericType) {
enumeratorTypeArgument = interfaceTypeObject.__GenericArgumentValues__[0];
}
var key = enumeratorTypeArgument.__TypeId__;
var result = $jsilcore.$GetArrayEnumeratorImplementations[key];
if (!result) {
$jsilcore.$GetArrayEnumeratorImplementations[key] = result = function () {
return JSIL.GetEnumerator(this, enumeratorTypeArgument, true);
};
}
return result;
} else {
JSIL.RuntimeError("Object of type '" + JSIL.GetType(thisReference) + "' has no implementation of " + signature.toString("GetEnumerator"));
}
};
// FIXME: This can probably be replaced with compiler and/or runtime intelltypeigence
// to create interface overlays for strings, just like arrays.
JSIL.$PickFallbackMethodForInterfaceMethod = function (interfaceObject, methodName, signature) {
// HACK: Ensures that you can enumerate the chars of a JS string or array in cases where they lack an overlay.
if (
(
(interfaceObject.__FullName__ === "System.Collections.Generic.IEnumerable`1") ||
(interfaceObject.__FullName__ === "System.Collections.IEnumerable")
) && (methodName === "GetEnumerator")
) {
return JSIL.$GetEnumeratorFallback;
}
return null;
};
JSIL.$DoTypesMatch = function (expected, type) {
if (expected === null)
return (type === null);
if (expected === type)
return true;
if (expected.__FullName__ === "System.Array")
return type.__IsArray__;
if (expected instanceof JSIL.PositionalGenericParameter && type instanceof JSIL.PositionalGenericParameter && expected.index === type.index)
return true;
return false;
}
JSIL.$FilterMethodsByArgumentTypes = function (methods, argumentTypes, returnType) {
var trace = false;
var l = methods.length;
for (var i = 0; i < l; i++) {
var remove = false;
var method = methods[i];
var parameterInfos = $jsilcore.$MethodGetParameters(method);
if (parameterInfos.length !== argumentTypes.length) {
if (trace)
console.log("Dropping because wrong argcount", argumentTypes.length, parameterInfos.length);
remove = true;
} else {
for (var j = 0; j < argumentTypes.length; j++) {
var argumentType = argumentTypes[j];
var argumentTypeB = parameterInfos[j].get_ParameterType();
if (!JSIL.$DoTypesMatch(argumentType, argumentTypeB)) {
if (trace)
console.log("Dropping because arg mismatch", argumentType.__FullName__, argumentTypeB.__FullName__);
remove = true;
break;
}
}
}
if (typeof (returnType) !== "undefined") {
// FIXME: Do a more complete assignability check
if (!JSIL.$DoTypesMatch(returnType, method.get_ReturnType())) {
if (trace)
console.log("Dropping because wrong return type", returnType.__FullName__, method.get_ReturnType().__FullName__);
remove = true;
}
}
if (remove) {
methods[i] = methods[l - 1];
l -= 1;
i -= 1;
}
}
methods.length = l;
};
JSIL.$GetMethodImplementation = function (method, target) {
var isStatic = method._descriptor.Static;
var isInterface = method._typeObject.IsInterface;
var key = null;
if (isInterface)
key = method._descriptor.EscapedName;
else if (method._data.signature)
key = method._data.signature.GetNamedKey(method._descriptor.EscapedName, true);
else
key = method._data.mangledName || method._descriptor.EscapedName;
var genericArgumentValues = method._data.signature.genericArgumentValues;
var publicInterface = method._typeObject.__PublicInterface__;
var context = isStatic || isInterface
? publicInterface
: publicInterface.prototype;
var result = context[key] || null;
if (isInterface) {
if (!result.signature.IsClosed)
JSIL.RuntimeError("Generic method is not closed");
}
// 1. Generic
if (genericArgumentValues && genericArgumentValues.length) {
// 1.1 Generic static
if (isStatic) {
// Return an invoker that concats generic arguments and arglist and invokes
// static generic method implementation directly.
return function () {
var fullArgumentList = genericArgumentValues.concat(Array.prototype.slice.call(arguments));
return result.apply(
publicInterface, fullArgumentList
);
};
// 1.2 Generic instance (interface)
} else if (result instanceof JSIL.InterfaceMethod) {
// Return an invoker that specifies the generic arguments and passes in rest
return function () {
return result.Call.apply(result,
[this, genericArgumentValues].concat(Array.prototype.slice.call(arguments))
);
};
// 1.3 Generic instance (non-interface)
} else {
// Return an invoker that concats generic arguments and arglist and invokes
// generic method implementation directly.
return function () {
var fullArgumentList = genericArgumentValues.concat(Array.prototype.slice.call(arguments));
return result.apply(
this, fullArgumentList
);
};
}
// 2. Non-generic
// 2.1 Non-generic instance (interface)
} else if (result instanceof JSIL.InterfaceMethod) {
// Wrap the interface method invoker since it expects a generic arguments parameter.
return function (methodArgs) {
return result.Call(this, null, methodArgs);
};
}
if (!result) {
debugger;
}
// 2.2 Non-generic instance (non-interface)
// 2.3 Non-generic static
return result;
};
JSIL.$FindMethodBodyInTypeChain = function (typeObject, isStatic, key, recursive) {
var typeChain = [];
var currentType = typeObject;
while (currentType) {
if (currentType.__PublicInterface__)
typeChain.push(currentType.__PublicInterface__);
if (currentType.__OpenType__ && currentType.__OpenType__.__PublicInterface__)
typeChain.push(currentType.__OpenType__.__PublicInterface__);
if (recursive)
currentType = currentType.__BaseType__;
else
break;
}
for (var i = 0, l = typeChain.length; i < l; i++) {
currentType = typeChain[i];
var target = isStatic ? currentType : currentType.prototype;
var method = target[key];
if (typeof (method) === "function")
return method;
}
return null;
};
JSIL.$IgnoredPrototypeMembers = [
];
JSIL.$IgnoredPublicInterfaceMembers = [
"__Type__", "__TypeId__", "__ThisType__", "__TypeInitialized__", "__IsClosed__", "prototype",
"Of", "toString", "__FullName__", "__OfCache__", "Of$NoInitialize",
"GetType", "__ReflectionCache__", "__Members__", "__ThisTypeId__",
"__RanCctors__", "__RanFieldInitializers__", "__PreInitMembrane__",
"__FieldList__", "__Comparer__", "__Marshaller__", "__Unmarshaller__",
"__UnmarshalConstructor__", "__ElementProxyConstructor__", "__IsNativeType__"
];
JSIL.$CopyMembersIndirect = function (target, source, ignoredNames, recursive) {
if (!source)
JSIL.RuntimeError("No source provided for copy");
if (source.__ThisType__ && (source.__ThisType__.__FullName__.indexOf("ArrayEnumerator") >= 0)) {
// debugger;
}
// FIXME: for ( in ) is deoptimized in V8. Maybe use Object.keys(), or type metadata?
for (var k in source) {
if (ignoredNames.indexOf(k) !== -1)
continue;
if (!recursive && !source.hasOwnProperty(k))
continue;
if (target.hasOwnProperty(k))
continue;
JSIL.MakeIndirectProperty(target, k, source);
}
};
JSIL.$CopyInterfaceMethods = function (interfaceList, target) {
var imProto = JSIL.InterfaceMethod.prototype;
var makeGetter = function (src, key) {
return function () {
return src[key];
};
};
for (var i = 0, l = interfaceList.length; i < l; i++) {
var ifaceRef = interfaceList[i];
var iface = JSIL.ResolveTypeReference(ifaceRef)[0];
for (var k in iface) {
if (!Object.prototype.hasOwnProperty.call(iface, k))
continue;
if (Object.prototype.hasOwnProperty.call(target, k))
continue;
JSIL.SetLazyValueProperty(target, k, makeGetter(iface, k));
}
}
};
JSIL.SetEntryPoint = function (assembly, typeRef, methodName, methodSignature) {
if (JSIL.$EntryPoints[assembly.__AssemblyId__])
JSIL.RuntimeError("Assembly already has an entry point");
JSIL.$EntryPoints[assembly.__AssemblyId__] =
[assembly, typeRef, methodName, methodSignature];
};
JSIL.GetEntryPoint = function (assembly) {
var entryPoint = JSIL.$EntryPoints[assembly.__AssemblyId__];
if (!entryPoint)
return null;
var entryTypePublicInterface = JSIL.ResolveTypeReference(entryPoint[1])[0];
var methodName = entryPoint[2];
var methodSignature = entryPoint[3];
return {
thisReference: entryTypePublicInterface,
method: methodSignature.LookupMethod(entryTypePublicInterface, methodName)
};
};
JSIL.InvokeEntryPoint = function (assembly, args) {
var dict = JSIL.GetEntryPoint(assembly);
if (!dict)
JSIL.RuntimeError("Assembly has no entry point");
if (!args)
args = [];
return dict.method.apply(dict.thisReference, args);
};
JSIL.ThrowNullReferenceException = function () {
throw new System.NullReferenceException();
};
JSIL.RuntimeError = function (text) {
throw new Error(text);
};
JSIL.RuntimeErrorFormat = function (format, values) {
var text = JSIL.$FormatStringImpl(format, values);
throw new Error(text);
};
JSIL.WarningFormat = function (format, values) {
var text = JSIL.$FormatStringImpl(format, values);
JSIL.Host.warning(text);
};
JSIL.ValidateArgumentTypes = function (types) {
for (var i = 0, l = types.length; i < l; i++) {
var item = types[i];
if (
(typeof (item) === "string") ||
(typeof (item) === "number") ||
(typeof (item) === "undefined") ||
(item === null)
) {
JSIL.RuntimeError("Argument type list must only contain type objects: " + JSON.stringify(item));
}
}
};
JSIL.GetMethodInfo = function(typeObject, name, signature, isStatic, methodGenericParameters){
var methods = JSIL.GetMembersInternal(
typeObject.__Type__, $jsilcore.BindingFlags.$Flags("DeclaredOnly", "Public", "NonPublic", isStatic ? "Static" : "Instance"), "$AllMethods", name
);
for (var i = 0, l = methods.length; i < l; i++) {
var method = methods[i];
if (method._data.signature.Hash == signature.Hash){
if (JSIL.IsArray(methodGenericParameters)) {
var genericParameterTypes = [];
for (var i = 0, l = methodGenericParameters.length; i < l; i++) {
genericParameterTypes.push(methodGenericParameters[i].get().__Type__);
}
return method.MakeGenericMethod(genericParameterTypes);
}
return method;
}
}
return null;
};
JSIL.GetFieldInfo = function(typeObject, name, isStatic){
var fields = JSIL.GetMembersInternal(
typeObject.__Type__, $jsilcore.BindingFlags.$Flags("DeclaredOnly", "Public", "NonPublic", isStatic ? "Static" : "Instance"), "FieldInfo", name
);
if (fields.length == 1) {
return fields[0];
}
return null;
};
// index alignment valueFormat escape
JSIL.$FormatRegex = new RegExp("{([0-9]*)(?:,([-0-9]*))?(?::([^}]*))?}|{{|}}|{|}", "g");
JSIL.$FormatStringImpl = function (format, values) {
if ((arguments.length !== 2) || !JSIL.IsArray(values))
JSIL.RuntimeError("JSIL.$FormatStringImpl expects (formatString, [value0, value1, ...])");
var match = null;
var matcher = function (match, index, alignment, valueFormat, offset, str) {
if (match === "{{")
return "{";
else if (match === "}}")
return "}";
else if ((match === "{") || (match === "}"))
throw new System.FormatException("Input string was not in a correct format.");
index = parseInt(index);
var value = values[index];
if (alignment || valueFormat) {
return JSIL.NumberToFormattedString(value, alignment, valueFormat);
} else {
if (typeof (value) === "boolean") {
if (value)
return "True";
else
return "False";
} else if (value === null) {
return "";
} else {
return String(value);
}
}
};
return format.replace(JSIL.$FormatRegex, matcher);
};
JSIL.Array.IndexOf = function (array, count, value) {
for (var i = 0, l = count; i < l; i++) {
if (JSIL.ObjectEquals(array[i], value))
return i;
}
return -1;
}; | Libraries/JSIL.Core.js | "use strict";
if (typeof (JSIL) === "undefined")
throw new Error("JSIL.js must be loaded first");
if (typeof(JSIL.SuppressInterfaceWarnings) === "undefined")
JSIL.SuppressInterfaceWarnings = true;
JSIL.ReadOnlyPropertyWriteWarnings = false;
if (typeof(JSIL.ThrowOnUnimplementedExternals) === "undefined")
JSIL.ThrowOnUnimplementedExternals = false;
if (typeof(JSIL.ThrowOnStaticCctorError) === "undefined")
JSIL.ThrowOnStaticCctorError = false;
JSIL.WarnAboutGenericResolveFailures = false;
JSIL.StructFormatWarnings = false;
JSIL.$NextAssemblyId = 0;
JSIL.PrivateNamespaces = {};
JSIL.AssemblyShortNames = {};
var $private = null;
// FIXME: Why does this slightly deopt global performance vs. Object.create? Object.create should be worse.
JSIL.$CreateCrockfordObject = function (prototype) {
if (!prototype && (prototype !== null))
JSIL.RuntimeError("Prototype not specified");
// FIXME: Generate this with a better name?
function crockfordobject () {
};
crockfordobject.prototype = prototype || null;
return new crockfordobject();
};
JSIL.CreateDictionaryObject = function (prototype) {
if (!prototype && (prototype !== null))
JSIL.RuntimeError("Prototype not specified");
return Object.create(prototype);
};
JSIL.CreateSingletonObject = function (prototype) {
return JSIL.CreateDictionaryObject(prototype);
};
JSIL.CreatePrototypeObject = function (prototype) {
// HACK: Nesting may protect type information
// return JSIL.CreateDictionaryObject(JSIL.CreateDictionaryObject(prototype));
// Not faster though. Probably because of the longer prototype chain.
return JSIL.CreateDictionaryObject(prototype);
};
JSIL.CreateInstanceObject = function (prototype) {
if (!prototype && (prototype !== null))
JSIL.RuntimeError("Prototype not specified");
return Object.create(prototype);
};
JSIL.HasOwnPropertyRecursive = function (target, name) {
while (!target.hasOwnProperty(name)) {
target = Object.getPrototypeOf(target);
if ((typeof (target) === "undefined") || (target === null))
return false;
}
return target.hasOwnProperty(name);
};
JSIL.GetOwnPropertyDescriptorRecursive = function (target, name) {
while (!target.hasOwnProperty(name)) {
target = Object.getPrototypeOf(target);
if ((typeof (target) === "undefined") || (target === null))
return null;
}
return Object.getOwnPropertyDescriptor(target, name);
};
JSIL.SetValueProperty = function (target, key, value, enumerable, readOnly) {
var descriptor = {
configurable: true,
enumerable: !(enumerable === false)
};
if (readOnly === false) {
descriptor.value = value;
descriptor.writable = descriptor.writeable = !readOnly;
} else {
if (JSIL.ReadOnlyPropertyWriteWarnings) {
descriptor.get = function () {
return value;
};
descriptor.set = function () {
JSIL.RuntimeError("Attempt to write to read-only property '" + key + "'!");
};
} else {
descriptor.value = value;
descriptor.writable = descriptor.writeable = false;
}
}
Object.defineProperty(target, key, descriptor);
};
JSIL.DefineLazyDefaultProperty = function (target, key, getDefault) {
var isInitialized = false;
var defaultValue;
var descriptor = {
configurable: true,
enumerable: true
};
var cleanup = function () {
var currentDescriptor = Object.getOwnPropertyDescriptor(target, key);
// Someone could have replaced us with a new property. If so, don't trample
// over them.
if (
currentDescriptor &&
(currentDescriptor.get === descriptor.get) &&
(currentDescriptor.set === descriptor.set)
)
Object.defineProperty(target, key, {
configurable: true,
enumerable: true,
writable: true,
value: target[key]
});
};
var initIfNeeded = function (self) {
if (!isInitialized) {
isInitialized = true;
defaultValue = getDefault.call(self);
cleanup();
}
};
var getter = function LazyDefaultProperty_Get () {
initIfNeeded(this);
// HACK: We could return defaultValue here, but that would ignore cases where the initializer overwrote the default.
// The cctor for a static array field containing values is an example of this (issue #234)
var currentDescriptor = Object.getOwnPropertyDescriptor(target, key);
if (currentDescriptor.value)
return currentDescriptor.value;
else if (currentDescriptor.get !== descriptor.get)
return this[key];
else
return defaultValue;
};
var setter = function LazyDefaultProperty_Set (value) {
var setterDesc = {
configurable: true,
enumerable: true,
writable: true,
value: value
};
initIfNeeded(this);
// Overwrite the defaultValue so that any getter calls
// still return the correct result.
defaultValue = value;
// We *NEED* to update the field after we run the initializer,
// not before! If we update it before the initializer may overwrite
// it, and worse still, the initializer may not be expecting to see
// the write yet.
Object.defineProperty(
this, key, setterDesc
);
return value;
};
descriptor.get = getter;
descriptor.set = setter;
Object.defineProperty(target, key, descriptor);
};
JSIL.SetLazyValueProperty = function (target, key, getValue, onPrototype, readOnly) {
var isInitialized = false;
var descriptor = {
configurable: true,
enumerable: true,
};
if (onPrototype) {
var cleanup = function (value) {
JSIL.SetValueProperty(this, key, value, true, readOnly);
};
var getter = function LazyValueProperty_Get () {
var value = getValue.call(this);
cleanup.call(this, value);
return value;
};
descriptor.get = getter;
} else {
var value;
var cleanup = function () {
var currentDescriptor = Object.getOwnPropertyDescriptor(target, key);
// Someone could have replaced us with a new property. If so, don't trample
// over them.
if (
currentDescriptor &&
(currentDescriptor.get === descriptor.get)
) {
JSIL.SetValueProperty(target, key, value, true, readOnly);
} else {
return;
}
};
var getter = function LazyValueProperty_Get () {
if (!isInitialized) {
value = getValue.call(this);
if (!isInitialized) {
isInitialized = true;
cleanup.call(this);
}
}
return value;
};
descriptor.get = getter;
}
Object.defineProperty(target, key, descriptor);
};
JSIL.$NextTypeId = 0;
JSIL.$NextDispatcherId = 0;
JSIL.$AssignedTypeIds = {};
JSIL.$GenericParameterTypeIds = {};
JSIL.$PublicTypes = {};
JSIL.$PublicTypeAssemblies = {};
JSIL.$PrivateTypeAssemblies = {};
JSIL.$EntryPoints = {};
JSIL.$SpecialTypeObjects = {};
JSIL.$SpecialTypePrototypes = {};
JSIL.$MakeSpecialType = function (name, typeObjectBase, prototypeBase) {
var typeObject = Object.create(typeObjectBase);
JSIL.$SpecialTypeObjects[name] = typeObject;
var prototype = null;
if (prototypeBase)
prototype = JSIL.$MakeSpecialPrototype(name, prototypeBase);
return {
typeObject: typeObject,
prototype: prototype
};
};
JSIL.$MakeSpecialPrototype = function (name, prototypeBase) {
var prototype = Object.create(prototypeBase);
JSIL.$SpecialTypePrototypes[name] = prototype;
return prototype;
};
JSIL.$GetSpecialType = function (name) {
return {
typeObject: JSIL.$SpecialTypeObjects[name] || null,
prototype: JSIL.$SpecialTypePrototypes[name] || null
};
};
( function () {
JSIL.TypeObjectPrototype = Object.create(null);
// FIXME: It's gross that methods are split between this and System.Type externals.
JSIL.TypeObjectPrototype.toString = function () {
return JSIL.GetTypeName(this, true);
};
JSIL.TypeObjectPrototype.get_Assembly = function() {
return this.__Context__.__Assembly__;
};
JSIL.TypeObjectPrototype.get_BaseType = function() {
return this.__BaseType__;
};
JSIL.TypeObjectPrototype.get_Namespace = function() {
// FIXME: Probably wrong for nested types.
return JSIL.GetParentName(this.__FullNameWithoutArguments__ || this.__FullName__);
};
JSIL.TypeObjectPrototype.get_Name = function() {
return JSIL.GetLocalName(this.__FullNameWithoutArguments__ || this.__FullName__);
};
JSIL.TypeObjectPrototype.get_FullName = function() {
if (this.get_IsGenericType() && !this.get_IsGenericTypeDefinition()) {
var result = this.__FullNameWithoutArguments__;
result += "[";
var ga = this.__GenericArgumentValues__;
for (var i = 0, l = ga.length; i < l; i++) {
var type = ga[i];
result += "[" + type.get_AssemblyQualifiedName() + "]";
}
result += "]";
return result;
} else {
return this.__FullName__;
}
};
JSIL.TypeObjectPrototype.get_AssemblyQualifiedName = function() {
return this.get_FullName() + ", " + this.get_Assembly().toString();
};
JSIL.TypeObjectPrototype.get_IsEnum = function() {
return this.__IsEnum__;
};
JSIL.TypeObjectPrototype.get_ContainsGenericParameters = function() {
return this.__IsClosed__ === false;
};
JSIL.TypeObjectPrototype.get_IsGenericType = function() {
return (this.__OpenType__ !== undefined || this.__IsClosed__ === false) && !(this instanceof JSIL.GenericParameter);
};
JSIL.TypeObjectPrototype.get_IsGenericTypeDefinition = function() {
return this.__IsClosed__ === false && this.__GenericArgumentValues__ === undefined && !(this instanceof JSIL.GenericParameter);
};
JSIL.TypeObjectPrototype.get_IsValueType = function() {
return this.__IsValueType__;
};
JSIL.TypeObjectPrototype.get_IsArray = function() {
return this.__IsArray__;
};
JSIL.TypeObjectPrototype.get_IsGenericParameter = function() {
return false;
};
JSIL.TypeObjectPrototype.get_IsByRef = function() {
return this.__IsByRef__;
};
JSIL.TypeObjectPrototype.get_IsInterface = function() {
// FIXME: I think Object.DefineProperty might mess with us here. Should probably rename the backing value to __IsInterface__.
return this.IsInterface;
};
var systemObjectPrototype = JSIL.$MakeSpecialPrototype("System.Object", Object.prototype);
var memberInfoPrototype = JSIL.$MakeSpecialPrototype("System.Reflection.MemberInfo", systemObjectPrototype);
var systemTypePrototype = JSIL.$MakeSpecialPrototype("System.Type", memberInfoPrototype);
var typeInfoPrototype = JSIL.$MakeSpecialPrototype("System.Reflection.TypeInfo", systemTypePrototype);
var runtimeTypePrototype = JSIL.$MakeSpecialPrototype("System.RuntimeType", typeInfoPrototype);
var dict = JSIL.$MakeSpecialType("System.RuntimeType", runtimeTypePrototype, null);
var runtimeType = dict.typeObject;
for (var k in JSIL.TypeObjectPrototype)
runtimeType[k] = JSIL.TypeObjectPrototype[k];
JSIL.SetValueProperty(runtimeType, "__IsReferenceType__", true);
runtimeType.IsInterface = false;
runtimeType.__IsEnum__ = false;
runtimeType.__ThisType__ = runtimeType;
runtimeType.__TypeInitialized__ = false;
runtimeType.__LockCount__ = 0;
JSIL.SetValueProperty(runtimeType, "__FullName__", "System.RuntimeType");
JSIL.SetValueProperty(runtimeType, "__ShortName__", "RuntimeType");
var assemblyPrototype = JSIL.$MakeSpecialPrototype("System.Reflection.Assembly", systemObjectPrototype);
dict = JSIL.$MakeSpecialType("System.Reflection.RuntimeAssembly", runtimeTypePrototype, assemblyPrototype);
var runtimeAssembly = dict.typeObject;
JSIL.SetValueProperty(runtimeAssembly, "__IsReferenceType__", true);
runtimeAssembly.IsInterface = false;
runtimeAssembly.__IsEnum__ = false;
runtimeAssembly.__ThisType__ = runtimeType;
runtimeAssembly.__ThisTypeId__ = runtimeType.__TypeId__;
runtimeAssembly.__TypeInitialized__ = false;
runtimeAssembly.__LockCount__ = 0;
JSIL.SetValueProperty(runtimeAssembly, "__FullName__", "System.Reflection.RuntimeAssembly");
JSIL.SetValueProperty(runtimeAssembly, "__ShortName__", "RuntimeAssembly");
} )();
JSIL.SetTypeId = function (typeObject, publicInterface, prototype, value) {
if (!value)
value = prototype;
if (typeof (value) !== "string")
JSIL.RuntimeError("Type IDs must be strings");
JSIL.SetValueProperty(typeObject, "__TypeId__", value);
JSIL.SetValueProperty(publicInterface, "__TypeId__", value);
if (arguments.length === 4)
JSIL.SetValueProperty(prototype, "__ThisTypeId__", value);
}
JSIL.AssignTypeId = function (assembly, typeName) {
if (JSIL.EscapeName)
typeName = JSIL.EscapeName(typeName);
if (typeof (assembly.__AssemblyId__) === "undefined")
JSIL.RuntimeError("Invalid assembly context");
if (typeof (JSIL.$PublicTypeAssemblies[typeName]) !== "undefined") {
assembly = JSIL.$PublicTypeAssemblies[typeName];
} else if (typeof (JSIL.$PrivateTypeAssemblies[typeName]) !== "undefined") {
assembly = JSIL.$PrivateTypeAssemblies[typeName];
}
var key = assembly.__AssemblyId__ + "$" + typeName;
var result = JSIL.$AssignedTypeIds[key];
if (typeof (result) !== "string")
result = JSIL.$AssignedTypeIds[key] = String(++(JSIL.$NextTypeId));
return result;
};
JSIL.DeclareAssembly = function (assemblyName) {
var existing = JSIL.GetAssembly(assemblyName, true);
if ((existing !== null) && (existing.__Declared__))
JSIL.RuntimeError("Assembly '" + assemblyName + "' already declared.");
var result = JSIL.GetAssembly(assemblyName, false);
JSIL.SetValueProperty(result, "__Declared__", true);
$private = result;
return result;
};
JSIL.GetAssembly = function (assemblyName, requireExisting) {
var existing = JSIL.PrivateNamespaces[assemblyName];
if (typeof (existing) !== "undefined")
return existing;
var shortName = assemblyName;
var commaPos = shortName.indexOf(",");
if (commaPos >= 0)
shortName = shortName.substr(0, commaPos);
if (typeof (JSIL.AssemblyShortNames[shortName]) !== "undefined") {
var existingFullName = JSIL.AssemblyShortNames[shortName];
if ((existingFullName !== null) && (commaPos <= 0)) {
existing = JSIL.PrivateNamespaces[existingFullName];
if (typeof (existing) !== "undefined")
return existing;
} else if (commaPos >= 0) {
// Multiple assemblies with the same short name, so disable the mapping.
JSIL.AssemblyShortNames[shortName] = null;
}
} else if (commaPos >= 0) {
JSIL.AssemblyShortNames[shortName] = assemblyName;
}
if (requireExisting)
return null;
var isMscorlib = (shortName === "mscorlib") || (assemblyName.indexOf("mscorlib,") === 0);
var isSystem = (shortName === "System") || (assemblyName.indexOf("System,") === 0);
var isSystemCore = (shortName === "System.Core") || (assemblyName.indexOf("System.Core,") === 0);
var isSystemXml = (shortName === "System.Xml") || (assemblyName.indexOf("System.Xml,") === 0);
var isJsilMeta = (shortName === "JSIL.Meta") || (assemblyName.indexOf("JSIL.Meta,") === 0);
// Create a new private global namespace for the new assembly
var template = {};
// Ensure that BCL private namespaces inherit from the JSIL namespace.
if (isMscorlib || isSystem || isSystemCore || isSystemXml || isJsilMeta)
template = $jsilcore;
var result = JSIL.CreateSingletonObject(template);
var assemblyId;
// Terrible hack to assign the mscorlib and JSIL.Core types the same IDs
if (isMscorlib) {
assemblyId = $jsilcore.__AssemblyId__;
} else {
assemblyId = ++JSIL.$NextAssemblyId;
}
var makeReflectionAssembly = function () {
var proto = JSIL.$GetSpecialType("System.Reflection.RuntimeAssembly").prototype;
var reflectionAssembly = Object.create(proto);
JSIL.SetValueProperty(reflectionAssembly, "__PublicInterface__", result);
JSIL.SetValueProperty(reflectionAssembly, "__FullName__", assemblyName);
return reflectionAssembly;
};
JSIL.SetValueProperty(result, "__Declared__", false);
JSIL.SetLazyValueProperty(result, "__Assembly__", makeReflectionAssembly);
JSIL.SetValueProperty(result, "__AssemblyId__", assemblyId, false);
JSIL.SetValueProperty(result, "TypeRef",
function (name, ga) {
return new JSIL.TypeRef(result, name, ga);
}, false
);
JSIL.SetValueProperty(result, "toString",
function Assembly_ToString () {
return "<" + assemblyName + " Public Interface>";
}
);
JSIL.SetValueProperty(result, "$typesByName", {}, false);
JSIL.PrivateNamespaces[assemblyName] = result;
return result;
};
var $jsilcore = JSIL.DeclareAssembly("JSIL.Core");
(function () {
JSIL.$SpecialTypePrototypes["System.RuntimeType"].__ThisTypeId__ =
JSIL.$SpecialTypeObjects["System.RuntimeType"].__TypeId__ =
JSIL.AssignTypeId($jsilcore, "System.RuntimeType");
})();
// Using these constants instead of 'null' turns some call sites from dimorphic to monomorphic in SpiderMonkey's
// type inference engine.
$jsilcore.ArrayNotInitialized = ["ArrayNotInitialized"];
$jsilcore.ArrayNull = [];
$jsilcore.FunctionNotInitialized = function () { throw new Error("FunctionNotInitialized"); };
$jsilcore.FunctionNull = function () { };
JSIL.Memoize = function Memoize (value) {
if (typeof (value) === "undefined")
JSIL.RuntimeError("Memoized value is undefined");
return function MemoizedValue () {
return value;
};
};
JSIL.PreInitMembrane = function (target, initializer) {
if (typeof (initializer) !== "function")
JSIL.RuntimeError("initializer is not a function");
if (
(typeof (target) !== "object") &&
(typeof (target) !== "function")
)
JSIL.RuntimeError("target must be an object or function");
if (target.__PreInitMembrane__)
JSIL.RuntimeError("object already has a membrane");
this.target = target;
this.target.__PreInitMembrane__ = this;
this.hasRunInitializer = false;
this.hasRunCleanup = false;
this.initializer = initializer;
this.cleanupList = [];
this.aliasesByKey = {};
this.propertiesToRebind = [];
// Function.bind is too slow to rely on in a hot path function like these
var self = this;
var _maybeInit = Object.getPrototypeOf(this).maybeInit;
var _cleanup = Object.getPrototypeOf(this).cleanup;
this.maybeInit = function bound_maybeInit () {
_maybeInit.call(self);
};
this.cleanup = function bound_cleanup () {
return _cleanup.call(self);
};
};
JSIL.PreInitMembrane.prototype.checkForUseAfterCleanup = function () {
if (this.hasRunCleanup)
JSIL.RuntimeError("Membrane in use after cleanup");
};
JSIL.PreInitMembrane.prototype.maybeInit = function () {
if (this.hasRunCleanup && this.hasRunInitializer) {
// HACK for #651
// JSIL.RuntimeError("maybeInit called after init and cleanup");
}
if (!this.hasRunInitializer) {
this.hasRunInitializer = true;
this.initializer();
}
if (!this.hasRunCleanup) {
this.cleanup();
}
};
JSIL.PreInitMembrane.prototype.rebindProperties = function () {
for (var i = 0, l = this.propertiesToRebind.length; i < l; i++) {
var propertyName = this.propertiesToRebind[i];
var descriptor = Object.getOwnPropertyDescriptor(this.target, propertyName);
if (!descriptor)
continue;
var doRebind = false;
if (descriptor.get && descriptor.get.__IsMembrane__) {
descriptor.get = this.target[descriptor.get.__OriginalKey__];
doRebind = true;
}
if (descriptor.set && descriptor.set.__IsMembrane__) {
descriptor.set = this.target[descriptor.set.__OriginalKey__];
doRebind = true;
}
if (doRebind) {
Object.defineProperty(this.target, propertyName, descriptor);
}
};
};
JSIL.PreInitMembrane.prototype.cleanup = function () {
this.hasRunCleanup = true;
for (var i = 0, l = this.cleanupList.length; i < l; i++) {
var cleanupFunction = this.cleanupList[i];
cleanupFunction();
}
this.rebindProperties();
this.initializer = null;
this.cleanupList = null;
this.aliasesByKey = null;
this.target.__PreInitMembrane__ = null;
// this.propertiesToRebind = null;
// this.target = null;
return true;
};
JSIL.PreInitMembrane.prototype.defineField = function (key, getInitialValue) {
this.checkForUseAfterCleanup();
var needToGetFieldValue = true;
var fieldValue;
var target = this.target;
this.cleanupList.push(function PreInitField_Cleanup () {
if (needToGetFieldValue) {
needToGetFieldValue = false;
fieldValue = getInitialValue();
}
Object.defineProperty(target, key, {
configurable: true,
enumerable: true,
writable: true,
value: fieldValue
});
});
var maybeInit = this.maybeInit;
var getter = function PreInitField_Get () {
maybeInit();
if (needToGetFieldValue) {
needToGetFieldValue = false;
fieldValue = getInitialValue();
}
return fieldValue;
}
var setter = function PreInitField_Set (value) {
needToGetFieldValue = false;
fieldValue = value;
return value;
};
Object.defineProperty(
target, key, {
configurable: true,
enumerable: true,
get: getter,
set: setter
}
);
};
JSIL.PreInitMembrane.prototype.defineMethod = function (key, fnGetter) {
this.checkForUseAfterCleanup();
var aliasesByKey = this.aliasesByKey;
var actualFn = $jsilcore.FunctionNotInitialized;
var target = this.target;
var membrane;
this.cleanupList.push(function PreInitMethod_Cleanup () {
if (actualFn === $jsilcore.FunctionNotInitialized)
actualFn = fnGetter();
if (target[key].__IsMembrane__)
JSIL.SetValueProperty(target, key, actualFn);
var aliases = aliasesByKey[key];
if (aliases) {
for (var i = 0, l = aliases.length; i < l; i++) {
var alias = aliases[i];
if (target[alias].__IsMembrane__)
JSIL.SetValueProperty(target, alias, actualFn);
}
}
// delete this.aliasesByKey[key];
});
var maybeInit = this.maybeInit;
membrane = function PreInitMethod_Invoke () {
maybeInit();
if (actualFn === $jsilcore.FunctionNotInitialized)
actualFn = fnGetter();
return actualFn.apply(this, arguments);
};
membrane.__Membrane__ = this;
membrane.__IsMembrane__ = true;
membrane.__OriginalKey__ = key;
membrane.__Unwrap__ = function () {
maybeInit();
if (actualFn === $jsilcore.FunctionNotInitialized)
actualFn = fnGetter();
return actualFn;
};
JSIL.SetValueProperty(target, key, membrane);
};
JSIL.PreInitMembrane.prototype.defineMethodAlias = function (key, alias) {
this.checkForUseAfterCleanup();
var aliases = this.aliasesByKey[key];
if (!aliases)
aliases = this.aliasesByKey[key] = [];
aliases.push(alias);
};
JSIL.PreInitMembrane.prototype.registerPropertyForRebind = function (key) {
this.checkForUseAfterCleanup();
this.propertiesToRebind.push(key);
};
JSIL.DefinePreInitField = function (target, key, getInitialValue, initializer) {
var membrane = target.__PreInitMembrane__;
if (!membrane)
membrane = new JSIL.PreInitMembrane(target, initializer);
membrane.defineField(key, getInitialValue);
};
JSIL.DefinePreInitMethod = function (target, key, fnGetter, initializer) {
var membrane = target.__PreInitMembrane__;
if (!membrane)
membrane = new JSIL.PreInitMembrane(target, initializer);
membrane.defineMethod(key, fnGetter);
};
JSIL.DefinePreInitMethodAlias = function (target, alias, originalMethod) {
if (!originalMethod.__IsMembrane__)
JSIL.RuntimeError("Method is not a membrane");
var membrane = originalMethod.__Membrane__;
membrane.defineMethodAlias(originalMethod.__OriginalKey__, alias);
};
JSIL.RebindPropertyAfterPreInit = function (target, propertyName) {
var membrane = target.__PreInitMembrane__;
if (!membrane)
membrane = new JSIL.PreInitMembrane(target, initializer);
membrane.registerPropertyForRebind(propertyName);
};
$jsilcore.SystemObjectInitialized = false;
$jsilcore.RuntimeTypeInitialized = false;
$jsilcore.TypedArrayToType = {};
JSIL.AssemblyCollection = function (obj) {
var makeGetter = function (assemblyName) {
return function GetAssemblyFromCollection () {
var state = JSIL.GetAssembly(assemblyName, true);
return state;
};
};
for (var k in obj) {
JSIL.SetLazyValueProperty(
this, k, makeGetter(obj[k])
);
}
};
JSIL.Name = function (name, context) {
if (typeof (context) !== "string") {
if (context.__FullName__)
context = context.__FullName__;
else
context = String(context);
}
this.humanReadable = context + "." + String(name);
this.key = JSIL.EscapeName(context) + "$" + JSIL.EscapeName(String(name));
};
JSIL.Name.prototype.get = function (target) {
return target[this.key];
};
JSIL.Name.prototype.set = function (target, value) {
target[this.key] = value;
return value;
};
JSIL.Name.prototype.defineProperty = function (target, decl) {
Object.defineProperty(
target, this.key, decl
);
};
JSIL.Name.prototype.toString = function () {
return this.humanReadable;
};
JSIL.SplitRegex = /[\.]/g;
JSIL.UnderscoreRegex = /[\.\/\+]/g;
JSIL.AngleGroupRegex = /\<([^<>]*)\>/g;
JSIL.EscapedNameCharacterRegex = /[\.\/\+\`\~\:\<\>\(\)\{\}\[\]\@\-\=\?\!\*\ \&\,\|\']/g;
JSIL.EscapeName = function (name) {
if ((!name) || (typeof (name) !== "string"))
throw new Error("EscapeName only accepts a string");
// FIXME: It sucks that this has to manually duplicate the C# escape logic.
name = name.replace(JSIL.AngleGroupRegex, function (match, group1) {
return "$l" + group1.replace(JSIL.UnderscoreRegex, "_") + "$g";
});
// HACK: Using a regex here to try to avoid generating huge rope strings in v8
name = name.replace(JSIL.EscapedNameCharacterRegex, function (match) {
var ch = match[0];
switch (ch) {
case ".":
case "/":
case "+":
return "_";
case "`":
return "$b";
case "~":
return "$t";
case ":":
return "$co";
case "<":
return "$l";
case ">":
return "$g";
case "(":
return "$lp";
case ")":
return "$rp";
case "{":
return "$lc";
case "}":
return "$rc";
case "[":
return "$lb";
case "]":
return "$rb";
case "@":
return "$at";
case "-":
return "$da";
case "=":
return "$eq";
case " ":
return "$sp";
case "?":
return "$qu";
case "!":
return "$ex";
case "*":
return "$as";
case "&":
return "$am";
case ",":
return "$cm";
case "|":
return "$vb";
case "'":
return "$q";
}
var chIndex = ch.charCodeAt(0);
if ((chIndex < 32) || (chIndex >= 127)) {
// FIXME: Padding?
return "$" + ch.toString(16);
}
return ch;
});
return name;
};
JSIL.GetParentName = function (name) {
var parts = JSIL.SplitName(name);
return name.substr(0, name.length - (parts[parts.length - 1].length + 1));
};
JSIL.GetLocalName = function (name) {
var parts = JSIL.SplitName(name);
return parts[parts.length - 1];
};
JSIL.SplitName = function (name) {
if (typeof (name) !== "string")
JSIL.Host.abort(new Error("Not a name: " + name));
var escapedName = name.replace(JSIL.AngleGroupRegex, function (match, group1) {
return "$l" + group1.replace(JSIL.UnderscoreRegex, "_") + "$g";
});
return escapedName.split(JSIL.SplitRegex);
};
JSIL.ResolvedName = function (parent, parentName, key, allowInheritance) {
this.parent = parent;
this.parentName = parentName;
this.key = key;
this.allowInheritance = allowInheritance;
};
JSIL.ResolvedName.prototype.exists = function (allowInheritance) {
if (this.allowInheritance && (allowInheritance !== false))
return (this.key in this.parent);
else
return this.parent.hasOwnProperty(this.key);
};
JSIL.ResolvedName.prototype.get = function () {
return this.parent[this.key];
};
JSIL.ResolvedName.prototype.set = function (value) {
JSIL.SetValueProperty(this.parent, this.key, value);
return value;
};
JSIL.ResolvedName.prototype.setLazy = function (getter) {
JSIL.SetLazyValueProperty(this.parent, this.key, getter);
};
JSIL.ResolvedName.prototype.define = function (declaration) {
Object.defineProperty(this.parent, this.key, declaration);
var descriptor = Object.getOwnPropertyDescriptor(this.parent, this.key);
if (declaration.value) {
if (descriptor.value != declaration.value)
JSIL.RuntimeError("Failed to define property '" + this.key + "'.");
} else if (declaration.get) {
if (descriptor.get != declaration.get)
JSIL.RuntimeError("Failed to define property '" + this.key + "'.");
}
};
JSIL.ResolveName = function (root, name, allowInheritance, throwOnFail) {
var parts = JSIL.SplitName(name);
var current = root;
if (typeof (root) === "undefined")
JSIL.RuntimeError("Invalid search root");
var makeError = function (_key, _current) {
var namespaceName;
if (_current === JSIL.GlobalNamespace)
namespaceName = "<global>";
else {
try {
namespaceName = _current.toString();
} catch (e) {
namespaceName = "<unknown>";
}
}
return new Error("Could not find the name '" + _key + "' in the namespace '" + namespaceName + "'.");
};
for (var i = 0, l = parts.length - 1; i < l; i++) {
var key = JSIL.EscapeName(parts[i]);
if (!(key in current)) {
if (throwOnFail !== false)
throw makeError(key, current);
else
return null;
}
if (!allowInheritance) {
if (!current.hasOwnProperty(key)) {
if (throwOnFail !== false)
throw makeError(key, current);
else
return null;
}
}
var next = current[key];
current = next;
}
var localName = parts[parts.length - 1];
return new JSIL.ResolvedName(
current, name.substr(0, name.length - (localName.length + 1)),
JSIL.EscapeName(localName), allowInheritance
);
};
// Must not be used to construct type or interact with members. Only to get a reference to the type for access to type information.
JSIL.GetTypeByName = function (name, assembly) {
if (name.indexOf("!!") === 0)
JSIL.RuntimeError("Positional generic method parameter '" + name + "' cannot be resolved by GetTypeByName.");
if (assembly !== undefined) {
var tbn = assembly.$typesByName;
if (typeof (tbn) === "object") {
var typeFunction = tbn[name];
if (typeof (typeFunction) === "function")
return typeFunction(false);
} else {
JSIL.Host.warning("Invalid assembly reference passed to GetTypeByName: " + assembly);
}
}
var key = JSIL.EscapeName(name);
var typeFunction = JSIL.$PublicTypes[key];
if (typeof (typeFunction) !== "function")
JSIL.RuntimeError("Type '" + name + "' has not been defined.");
return typeFunction(false);
};
JSIL.DefineTypeName = function (name, getter, isPublic) {
if (typeof (getter) !== "function")
JSIL.RuntimeError("Definition for type name '" + name + "' is not a function");
if (isPublic) {
var key = JSIL.EscapeName(name);
var existing = JSIL.$PublicTypes[key];
var existingAssembly = JSIL.$PublicTypeAssemblies[key];
if ((typeof (existing) === "function") && (existingAssembly !== $jsilcore)) {
JSIL.$PublicTypes[key] = function AmbiguousPublicTypeReference () {
JSIL.RuntimeError("Type '" + name + "' has multiple public definitions. You must access it through a specific assembly.");
};
if (existingAssembly != undefined) {
JSIL.WarningFormat(
"Public type '{0}' defined twice: {1} and {2}",
[name, existingAssembly.toString(), $private.toString()]
);
delete JSIL.$PublicTypeAssemblies[key];
} else {
JSIL.WarningFormat(
"Public type '{0}' defined more than twice: {1} and several other assemblies",
[name, $private.toString()]
);
}
} else {
JSIL.$PublicTypes[key] = getter;
JSIL.$PublicTypeAssemblies[key] = $private;
}
} else if ($private == $jsilcore) {
var key = JSIL.EscapeName(name);
JSIL.$PrivateTypeAssemblies[key] = $private;
} else {
var key = JSIL.EscapeName(name);
var existing = JSIL.$PrivateTypeAssemblies[key];
if (existing !== undefined){
if (existing != $jsilcore) {
JSIL.WarningFormat(
"Private type '{0}' with external implementation defined more than twice: '{1}'" +
[$private.toString(), existing.toString()]
);
}
JSIL.$PrivateTypeAssemblies[key] = $private;
}
}
var existing = $private.$typesByName[name];
if (typeof (existing) === "function")
JSIL.RuntimeError("Type '" + name + "' has already been defined.");
$private.$typesByName[name] = getter;
};
JSIL.DeclareNamespace = function (name, sealed) {
if (typeof (sealed) === "undefined")
sealed = true;
var toStringImpl = function Namespace_ToString () {
return name;
};
var resolved = JSIL.ResolveName(JSIL.GlobalNamespace, name, true);
if (!resolved.exists())
resolved.define({
enumerable: true,
configurable: !sealed,
value: {
__FullName__: name,
toString: toStringImpl
}
});
var resolved = JSIL.ResolveName($private, name, true);
if (!resolved.exists())
resolved.define({
enumerable: true,
configurable: !sealed,
value: {
__FullName__: name,
toString: toStringImpl
}
});
};
JSIL.DeclareNamespace("System");
JSIL.DeclareNamespace("System.Collections");
JSIL.DeclareNamespace("System.Collections.Generic");
JSIL.DeclareNamespace("System.Text");
JSIL.DeclareNamespace("System.Threading");
JSIL.DeclareNamespace("System.Globalization");
JSIL.DeclareNamespace("System.Runtime");
JSIL.DeclareNamespace("System.Runtime.InteropServices");
JSIL.DeclareNamespace("System.Reflection");
JSIL.DeclareNamespace("JSIL");
JSIL.DeclareNamespace("JSIL.Array");
JSIL.DeclareNamespace("JSIL.Delegate");
JSIL.DeclareNamespace("JSIL.MulticastDelegate");
JSIL.DeclareNamespace("JSIL.Dynamic");
// Hack
JSIL.DeclareNamespace("Property");
// Implemented in JSIL.Host.js
JSIL.DeclareNamespace("JSIL.Host", false);
JSIL.UnmaterializedReference = function (targetExpression) {
JSIL.Host.abort(new Error("A reference to expression '" + targetExpression + "' could not be translated."));
};
JSIL.UntranslatableNode = function (nodeType) {
JSIL.Host.abort(new Error("An ILAst node of type " + nodeType + " could not be translated."));
};
JSIL.UntranslatableFunction = function (functionName) {
return function UntranslatableFunctionInvoked () {
JSIL.Host.abort(new Error("The function '" + functionName + "' could not be translated."));
};
};
JSIL.UntranslatableInstruction = function (instruction, operand) {
if (typeof (operand) !== "undefined")
JSIL.Host.abort(new Error("A MSIL instruction of type " + instruction + " with an operand of type " + operand + " could not be translated."));
else
JSIL.Host.abort(new Error("A MSIL instruction of type " + instruction + " could not be translated."));
};
JSIL.IgnoredType = function (typeName) {
JSIL.Host.abort(new Error("An attempt was made to reference the type '" + typeName + "', but it was explicitly ignored during translation."));
};
JSIL.IgnoredMember = function (memberName) {
JSIL.Host.abort(new Error("An attempt was made to reference the member '" + memberName + "', but it was explicitly ignored during translation."));
};
JSIL.UnknownMember = function (memberName) {
JSIL.Host.abort(new Error("An attempt was made to reference the member '" + memberName + "', but it has no type information."));
};
JSIL.$UnimplementedExternalError = function (err) {
if (typeof err === "string") {
if (arguments.length === 2)
err = JSIL.$FormatStringImpl(err, arguments[1]);
else if (arguments.length > 2)
JSIL.RuntimeError("$UnimplementedExternalError only accepts (errString), (error), or (errString, [value0, value1, ...])");
err = new Error(err);
}
var msg = err.message;
if (typeof (err.stack) !== "undefined") {
if (err.stack.indexOf(err.toString()) === 0)
msg = err.stack;
else
msg += "\n" + err.stack;
}
JSIL.Host.warning(msg);
if (JSIL.ThrowOnUnimplementedExternals) {
JSIL.Host.abort(err);
}
}
JSIL.$ExternalMemberWarningFormat =
"The external method '{0}' of type '{1}' has not been implemented.";
JSIL.$ExternalMemberInheritedWarningFormat =
"The external method '{0}' of type '{1}' has not been implemented; calling inherited method.";
JSIL.MakeExternalMemberStub = function (namespaceName, getMemberName, inheritedMember) {
var state = {
warningCount: 0
};
var result;
if (typeof (inheritedMember) === "function") {
result = function ExternalMemberStub () {
if (state.warningCount < 1) {
JSIL.WarningFormat(
JSIL.$ExternalMemberInheritedWarningFormat,
[getMemberName.call(this), namespaceName]
);
state.warningCount += 1;
}
return Function.prototype.apply.call(inheritedMember, this, arguments);
};
} else {
result = function ExternalMemberStub () {
if (state.warningCount > 3)
return;
var fmtArgs = [getMemberName.call(this), namespaceName];
if (JSIL.ThrowOnUnimplementedExternals)
throw new Error(
JSIL.$FormatStringImpl(
JSIL.$ExternalMemberWarningFormat, fmtArgs
)
);
else
JSIL.WarningFormat(
JSIL.$ExternalMemberWarningFormat, fmtArgs
);
state.warningCount += 1;
};
}
result.__IsPlaceholder__ = true;
return result;
};
JSIL.MemberRecord = function (type, descriptor, data, attributes, overrides) {
this.type = type;
this.descriptor = descriptor;
this.data = data;
this.attributes = attributes;
this.overrides = overrides;
};
JSIL.AttributeRecord = function (context, type, getConstructorArguments, initializer) {
this.context = context;
this.type = type;
this.getConstructorArguments = getConstructorArguments;
this.initializer = initializer;
};
JSIL.OverrideRecord = function (interfaceNameOrReference, interfaceMemberName) {
if (
(
(typeof (interfaceNameOrReference) !== "string") &&
(typeof (interfaceNameOrReference) !== "object")
) || !interfaceNameOrReference
) {
JSIL.RuntimeError("Override must specify interface name or typeref");
}
this.interfaceNameOrReference = interfaceNameOrReference;
this.interfaceMemberName = interfaceMemberName;
};
JSIL.AttributeRecord.prototype.GetType = function () {
if (this.resolvedType)
return this.resolvedType;
var resolvedType = JSIL.ResolveTypeReference(this.type, this.context)[1];
if (!resolvedType)
JSIL.RuntimeError("Failed to resolve attribute type '" + this.type + "'")
return this.resolvedType = resolvedType;
};
JSIL.AttributeRecord.prototype.Construct = function () {
var resolvedType = this.GetType();
var constructorArguments;
if (this.getConstructorArguments)
this.constructorArguments = constructorArguments = this.getConstructorArguments();
else
this.constructorArguments = constructorArguments = [];
var instance = JSIL.CreateInstanceOfType(resolvedType, "_ctor", constructorArguments);
return instance;
};
JSIL.RawMethodRecord = function (name, isStatic) {
this.name = name;
this.isStatic = isStatic;
};
JSIL.ImplementExternals = function (namespaceName, externals) {
if (typeof (namespaceName) !== "string") {
JSIL.Host.abort(new Error("ImplementExternals expected name of namespace"));
return;
}
var trace = false;
var context = $private;
var queue = JSIL.ExternalsQueue[namespaceName];
if (!JSIL.IsArray(queue)) {
JSIL.ExternalsQueue[namespaceName] = queue = [];
}
var obj = JSIL.AllImplementedExternals[namespaceName];
if (typeof (obj) !== "object") {
JSIL.AllImplementedExternals[namespaceName] = obj = {};
}
if (obj.__IsInitialized__) {
JSIL.Host.abort(new Error("Type '" + namespaceName + "' already initialized"));
return;
}
if (typeof (externals) !== "function") {
if (trace)
JSIL.WarningFormat("Old-style ImplementExternals call for '{0}' ignored!", [namespaceName]);
return;
}
// Deferring the execution of externals functions is important in case they reference
// other types or assemblies.
queue.push(function ImplementExternalsImpl () {
var typeId = JSIL.AssignTypeId(context, namespaceName);
var typeObject = {
__Members__: [],
__RawMethods__: [],
__TypeId__: typeId,
__FullName__: namespaceName
};
var publicInterface = {
prototype: {
__TypeId__: typeId
},
__TypeId__: typeId
};
var ib = new JSIL.InterfaceBuilder(context, typeObject, publicInterface);
externals(ib);
var prefix = "instance$";
var m = typeObject.__Members__;
for (var i = 0; i < m.length; i++) {
var member = m[i];
var type = member.type;
var descriptor = member.descriptor;
var data = member.data;
var name = data.mangledName || descriptor.EscapedName;
var target = descriptor.Static ? publicInterface : publicInterface.prototype;
if (typeof (data.constant) !== "undefined") {
obj[descriptor.EscapedName + "$constant"] = data.constant;
} else if (data.mangledName) {
obj[descriptor.Static ? data.mangledName : prefix + data.mangledName] = [member, target[name]];
}
}
var rm = typeObject.__RawMethods__;
for (var i = 0; i < rm.length; i++) {
var rawMethod = rm[i];
var suffix = "$raw";
if (rawMethod.isStatic) {
obj[rawMethod.name + suffix] = [null, publicInterface[rawMethod.name]];
} else {
obj[prefix + rawMethod.name + suffix] = [null, publicInterface.prototype[rawMethod.name]];
}
}
});
};
JSIL.QueueTypeInitializer = function (type, initializer) {
if (type.__TypeInitialized__) {
initializer(type);
} else {
type.__Initializers__.push(initializer);
}
};
JSIL.Initialize = function () {
// Seal all registered names so that their static constructors run on use
var arn = JSIL.AllRegisteredNames;
for (var i = 0, l = arn.length; i < l; i++)
arn[i].sealed = true;
// Necessary because we can't rely on membranes for these types.
JSIL.InitializeType($jsilcore.System.RuntimeType);
JSIL.InitializeType($jsilcore.System.Reflection.RuntimeAssembly);
JSIL.InitializeType($jsilcore.System.Object);
};
JSIL.GenericParameter = function (name, context) {
var key;
this.name = new JSIL.Name(name, context);
this.covariant = false;
this.contravariant = false;
if (typeof (context) === "string") {
key = JSIL.EscapeName(String(context)) + "$" + JSIL.EscapeName(String(name));
} else if (typeof (context.__TypeId__) === "undefined") {
JSIL.RuntimeError("Invalid context for generic parameter");
} else {
key = context.__TypeId__ + "$" + JSIL.EscapeName(String(name));
}
if (typeof (JSIL.$GenericParameterTypeIds[key]) === "undefined") {
var typeId = String(++JSIL.$NextTypeId);
JSIL.$GenericParameterTypeIds[key] = typeId;
JSIL.SetValueProperty(this, "__TypeId__", typeId);
} else {
JSIL.SetValueProperty(this, "__TypeId__", JSIL.$GenericParameterTypeIds[key]);
}
JSIL.SetValueProperty(this, "__ShortName__", name);
JSIL.SetValueProperty(this, "__FullName__", this.name.humanReadable);
};
JSIL.GenericParameter.prototype = Object.create(JSIL.TypeObjectPrototype);
JSIL.GenericParameter.prototype.in = function () {
this.contravariant = true;
return this;
};
JSIL.GenericParameter.prototype.out = function () {
this.covariant = true;
return this;
};
JSIL.GenericParameter.prototype.get = function (context) {
if (!context) {
JSIL.RuntimeError("No context provided when resolving generic parameter '" + this.name + "'");
return JSIL.AnyType;
}
return this.name.get(context);
};
JSIL.GenericParameter.prototype.toString = function () {
var result = "<GP ";
if (this.contravariant)
result += "in ";
if (this.covariant)
result += "out ";
result += this.name.humanReadable + ">";
return result;
};
JSIL.GenericParameter.prototype.get_IsGenericParameter = function () {
return true;
};
JSIL.GenericParameter.prototype.get_Name = function () {
return this.name.humanReadable;
};
JSIL.GenericParameter.prototype.__IsClosed__ = false;
JSIL.PositionalGenericParameter = function (name, context) {
this.index = parseInt(name.substr(2));
JSIL.SetValueProperty(this, "__TypeId__", name);
this.__Context__ = context || $jsilcore;
var fullNameDecl = {
configurable: true,
enumerable: true,
get: this.getFullName
};
Object.defineProperty(this, "__FullName__", fullNameDecl);
Object.defineProperty(this, "__FullNameWithoutArguments__", fullNameDecl);
};
JSIL.PositionalGenericParameter.prototype = Object.create(JSIL.TypeObjectPrototype);
JSIL.PositionalGenericParameter.prototype.getFullName = function () {
return "!!" + this.index;
};
JSIL.PositionalGenericParameter.prototype.get = function (context) {
if ((typeof (context) !== "object") && (typeof (context) !== "function")) {
JSIL.RuntimeError("No context provided when resolving generic method parameter #" + this.index);
return JSIL.AnyType;
}
JSIL.RuntimeError("Not implemented");
};
JSIL.PositionalGenericParameter.prototype.toString = function (context) {
if (
(typeof (context) === "object") && (context !== null) &&
(Object.getPrototypeOf(context) === JSIL.MethodSignature.prototype)
) {
return context.genericArgumentNames[this.index];
}
return "<Generic Method Parameter #" + this.index + ">";
};
JSIL.PositionalGenericParameter.prototype.get_IsGenericParameter = function () {
return true;
};
JSIL.PositionalGenericParameter.prototype.get_Name = function () {
return "!!" + this.index;
};
JSIL.PositionalGenericParameter.prototype.__IsClosed__ = false;
JSIL.NamespaceRef = function (context, namespace) {
if (arguments.length === 1) {
this.context = null;
this.namespace = arguments[0];
} else if (arguments.length === 2) {
this.context = context;
this.namespace = namespace;
} else {
JSIL.RuntimeError("Invalid argument count");
}
this.cachedReference = null;
};
JSIL.NamespaceRef.prototype.toString = function () {
var result = null;
result = "ref namespace " + this.namespace;
return result;
};
JSIL.NamespaceRef.prototype.get = function () {
if (this.cachedReference !== null)
return this.cachedReference;
var result = JSIL.ResolveName(this.context, this.namespace, true);
if (!result.exists())
JSIL.RuntimeError("The name '" + this.namespace + "' does not exist.");
this.cachedReference = result.get();
return this.cachedReference;
};
JSIL.NamespaceRef.prototype.TypeRef = function (name, genericArguments) {
return new JSIL.TypeRef(this, name, genericArguments);
};
JSIL.TypeRef = function (context, name, genericArguments) {
if (arguments.length === 1) {
this.context = null;
this.typeName = null;
this.genericArguments = null;
this.cachedReference = arguments[0];
} else {
if (typeof (name) === "string") {
this.context = context;
this.typeName = name;
this.genericArguments = genericArguments || $jsilcore.ArrayNull;
this.cachedReference = null;
} else {
JSIL.Host.abort(new Error("Invalid type reference: " + name + " in context " + context));
}
}
if (JSIL.IsArray(this.genericArguments)) {
for (var i = 0, l = this.genericArguments.length; i < l; i++) {
var ga = this.genericArguments[i];
if (typeof (ga) === "undefined")
JSIL.RuntimeError("Undefined passed as generic argument #" + i);
else if (ga === null)
JSIL.RuntimeError("Null passed as generic argument #" + i);
}
}
};
JSIL.TypeRef.prototype.getAssembly = function () {
if (
this.context &&
Object.getPrototypeOf(this.context) === JSIL.NamespaceRef.prototype
)
return this.context.context;
else
return this.context;
};
JSIL.TypeRef.prototype.getContext = function () {
if (
this.context &&
Object.getPrototypeOf(this.context) === JSIL.NamespaceRef.prototype
)
return this.context.get();
else
return this.context;
};
JSIL.TypeRef.prototype.getTypeName = function () {
if (
this.context &&
Object.getPrototypeOf(this.context) === JSIL.NamespaceRef.prototype
)
return this.context.namespace + "." + this.typeName;
else
return this.typeName;
};
JSIL.TypeRef.prototype.toString = function () {
var result = null;
if (this.typeName === null)
result = "ref " + JSIL.GetTypeName(this.cachedReference);
else
result = "ref " + this.getTypeName();
if (this.genericArguments && this.genericArguments.length) {
result += "[";
for (var i = 0, l = this.genericArguments.length; i < l; i++) {
result += this.genericArguments[i].toString();
if (i < (l - 1))
result += ", ";
}
result += "]";
}
return result;
};
JSIL.TypeRef.prototype.toName = function () {
var result = null;
if (this.typeName === null)
result = JSIL.GetTypeName(this.cachedReference);
else
result = this.getTypeName();
// HACK: System.Array[T] -> T[]
if (
(this.getTypeName() === "System.Array") &&
this.genericArguments &&
this.genericArguments.length
) {
return JSIL.TypeReferenceToName(this.genericArguments[0]) + "[]";
}
if (this.genericArguments && this.genericArguments.length) {
result += "[";
for (var i = 0, l = this.genericArguments.length; i < l; i++) {
result += JSIL.TypeReferenceToName(this.genericArguments[i]);
if (i < (l - 1))
result += ", ";
}
result += "]";
}
return result;
};
JSIL.TypeRef.prototype.getTypeId = function () {
if (this.cachedReference !== null)
return this.cachedReference.__TypeId__;
else {
var result = JSIL.AssignTypeId(this.getAssembly(), this.getTypeName());
if (this.genericArguments.length > 0) {
result += "[";
result += JSIL.HashTypeArgumentArray(this.genericArguments, this.getAssembly());
result += "]";
// print(result);
}
return result;
}
};
JSIL.TypeRef.prototype.bindGenericArguments = function (unbound) {
if (this.genericArguments.length > 0) {
var ga = this.genericArguments;
for (var i = 0, l = ga.length; i < l; i++) {
var arg = ga[i];
if (typeof (arg) === "string") {
if (arg.indexOf("!!") === 0) {
ga[i] = arg = new JSIL.PositionalGenericParameter(arg, this.getContext());
} else {
ga[i] = arg = new JSIL.TypeRef(this.context, arg);
}
}
if (typeof (arg) === "object" && Object.getPrototypeOf(arg) === JSIL.TypeRef.prototype) {
ga[i] = arg = arg.get(true);
}
}
return unbound.Of$NoInitialize.apply(unbound, ga);
}
return unbound;
};
JSIL.TypeRef.prototype.getNoInitialize = function () {
if (this.cachedReference !== null)
return this.cachedReference;
var result = JSIL.GetTypeByName(this.getTypeName(), this.getAssembly());
result = this.bindGenericArguments(result);
return result;
};
JSIL.TypeRef.prototype.get = function (allowPartiallyConstructed) {
if (this.cachedReference !== null)
return this.cachedReference;
if (allowPartiallyConstructed === true) {
var inFlight = $jsilcore.InFlightObjectConstructions[this.getTypeName()];
if (inFlight)
return inFlight.publicInterface;
}
var result = JSIL.ResolveName(this.getContext(), this.typeName, true);
if (!result.exists())
JSIL.RuntimeError("The name '" + this.typeName + "' does not exist.");
this.cachedReference = result.get();
try {
this.cachedReference = this.bindGenericArguments(this.cachedReference);
} catch (exc) {
var err = new Error("Failed to bind generic arguments for typeRef '" + this.toString() + "': " + String(exc));
err.innerException = exc;
throw err;
}
return this.cachedReference;
};
JSIL.TypeRef.prototype.genericParameter = function (name) {
return new JSIL.GenericParameter(name, this.getTypeName());
};
JSIL.AllRegisteredNames = [];
JSIL.AllImplementedExternals = {};
JSIL.ExternalsQueue = {};
// FIXME: Used to prevent cycles in type cachers from causing problems. Not sure if this is right.
$jsilcore.SuppressRecursiveConstructionErrors = 0;
// HACK: So we can allow a class's base class to include itself as a generic argument. :/
$jsilcore.InFlightObjectConstructions = JSIL.CreateDictionaryObject(null);
JSIL.RegisterName = function (name, privateNamespace, isPublic, creator, initializer) {
var privateName = JSIL.ResolveName(privateNamespace, name, true);
if (isPublic)
var publicName = JSIL.ResolveName(JSIL.GlobalNamespace, name, true);
var localName = JSIL.GetLocalName(name);
var existingInSameAssembly = JSIL.ResolveName(privateNamespace, name, false, false);
if (existingInSameAssembly && existingInSameAssembly.exists(false)) {
JSIL.DuplicateDefinitionWarning(name, false, existingInSameAssembly.get().__CallStack__ || null, privateNamespace);
return;
}
var state = {
creator: creator,
initializer: initializer,
sealed: false,
value: null,
constructing: false,
name: name
};
JSIL.AllRegisteredNames.push(state);
var getter = function RegisterName_getter (unseal) {
var result;
try {
if (state.constructing) {
if (($jsilcore.SuppressRecursiveConstructionErrors > 0) && state.value) {
JSIL.WarningFormat(
"Ignoring recursive construction of type '{0}'.",
[name]
);
return state.value;
} else {
var err = new Error("Recursive construction of type '" + name + "' detected.");
state.value = err;
throw err;
}
}
if (typeof (state.creator) === "function") {
state.constructing = true;
var cf = state.creator;
try {
result = cf();
if ((result === null) || ((typeof (result) !== "object") && (typeof (result) !== "function"))) {
var err = new Error("Invalid result from type creator for type '" + name + "'");
state.value = err;
throw err;
}
state.value = result;
} catch (exc) {
JSIL.Host.abort(exc);
} finally {
state.creator = null;
state.constructing = false;
}
} else {
result = state.value;
if (
(result === null) ||
(
(typeof (result) !== "object") &&
(typeof (result) !== "function")
)
) {
var err = new Error("Type initialization failed for type '" + name + "'");
state.value = err;
throw err;
}
}
if (typeof (state.initializer) === "function") {
var ifn = state.initializer;
state.constructing = true;
var setThisType = null;
try {
setThisType = ifn(result);
if (typeof(setThisType) === "function")
setThisType(result);
} catch (exc) {
JSIL.Host.abort(exc);
} finally {
state.initializer = null;
state.constructing = false;
}
}
if (typeof (unseal) !== "boolean") {
unseal = true;
}
if (state.sealed && unseal) {
state.sealed = false;
JSIL.InitializeType(result);
privateName.define({ value: result });
if (isPublic)
publicName.define({ value: result });
}
} finally {
}
return result;
};
privateName.setLazy(getter);
if (isPublic)
publicName.setLazy(getter);
JSIL.DefineTypeName(name, getter, isPublic);
// V8 closure leaks yaaaaaay
creator = null;
initializer = null;
};
JSIL.FixupPrototype = function (prototype, baseTypeObject, typeObject, typeName, isReferenceType) {
JSIL.SetValueProperty(prototype, "__ThisType__", typeObject);
JSIL.SetValueProperty(prototype, "__ThisTypeId__", typeObject.__TypeId__);
JSIL.SetValueProperty(prototype, "__BaseType__", baseTypeObject);
JSIL.SetValueProperty(prototype, "__ShortName__", JSIL.GetLocalName(typeName));
JSIL.SetValueProperty(prototype, "__FullName__", typeName);
JSIL.SetValueProperty(prototype, "__IsReferenceType__", Boolean(isReferenceType));
};
JSIL.MakeProto = function (baseType, typeObject, typeName, isReferenceType, assembly) {
var _ = JSIL.ResolveTypeReference(baseType, assembly);
var baseTypePublicInterface = _[0];
var baseTypeObject = _[1];
if (baseTypePublicInterface === Object)
baseTypeObject = null;
var prototype = JSIL.$GetSpecialType(typeName).prototype;
if (!prototype)
prototype = JSIL.CreatePrototypeObject(baseTypePublicInterface.prototype);
JSIL.FixupPrototype(prototype, baseTypeObject, typeObject, typeName, isReferenceType);
return prototype;
};
JSIL.MakeNumericType = function (baseType, typeName, isIntegral, typedArrayName) {
var typeArgs = {
BaseType: baseType,
Name: typeName,
GenericArguments: $jsilcore.ArrayNull,
IsReferenceType: false,
IsPublic: true,
ConstructorAcceptsManyArguments: false
};
JSIL.MakeType(typeArgs, function ($) {
$.SetValue("__IsNumeric__", true);
$.SetValue("__IsIntegral__", isIntegral);
$.SetValue("__IsNativeType__", true);
if (typedArrayName) {
var typedArrayCtorExists = false;
var checkFn = new Function("return typeof (" + typedArrayName + ") !== \"undefined\"");
var getFn = new Function("return " + typedArrayName);
try {
typedArrayCtorExists = checkFn();
} catch (exc) {
}
if (typedArrayCtorExists) {
$.SetValue("__TypedArray__", getFn());
var ctor = getFn();
var key = ctor.name || String(ctor);
$jsilcore.TypedArrayToType[key] = typeName;
} else
$.SetValue("__TypedArray__", null);
} else {
$.SetValue("__TypedArray__", null);
}
var castSpecialType;
if (typeName === "System.Char") {
castSpecialType = "char";
} else if (typeName == "System.Boolean") {
castSpecialType = "bool";
} else if (isIntegral) {
castSpecialType = "integer";
} else {
castSpecialType = "number";
}
JSIL.MakeCastMethods(
$.publicInterface, $.typeObject, castSpecialType
);
$.RawMethod(
true, "$OverflowCheck",
function OverflowCheck (value) {
var minValue = $.publicInterface.MinValue;
var maxValue = $.publicInterface.MaxValue;
if ((value < minValue) || (value > maxValue))
throw new System.OverflowException("Arithmetic operation resulted in an overflow.");
if ($.publicInterface.name == "System_Char") {
return String.fromCharCode((value.charCodeAt(0) | 0));
}
return (value | 0);
}
);
});
};
JSIL.MakeIndirectProperty = function (target, key, source) {
var hasValue = false, state;
var getter = function GetIndirectProperty () {
if (hasValue)
return state;
else
return source[key];
};
var setter = function SetIndirectProperty (value) {
hasValue = true;
return state = value;
};
Object.defineProperty(target, key, {
configurable: true,
enumerable: true,
get: getter,
set: setter
});
};
// FIXME: The $...Internal version returns null if no resolution was necessary,
// which isn't quite as convenient. This is still pretty ugly.
JSIL.ResolveGenericTypeReference = function (obj, context) {
var result = JSIL.$ResolveGenericTypeReferenceInternal(obj, context);
if (result === null)
return obj;
return result;
};
JSIL.$ResolveGenericTypeReferenceInternal = function (obj, context) {
if ((typeof (obj) !== "object") || (obj === null))
return null;
if (Object.getPrototypeOf(obj) === JSIL.GenericParameter.prototype) {
var result = obj.get(context);
if (
(typeof (result) === "undefined") ||
(result === null)
) {
if (JSIL.WarnAboutGenericResolveFailures) {
var errorText = "Failed to resolve generic parameter " + String(obj);
JSIL.Host.warning(errorText);
}
return null;
}
if (result === obj)
throw new System.InvalidOperationException("Cannot pass a generic parameter as its own value");
var result2 = JSIL.$ResolveGenericTypeReferenceInternal(result, context);
if (!result2)
return result;
else
return result2;
} else if (Object.getPrototypeOf(obj) === JSIL.TypeRef.prototype) {
var resolvedGa = [];
var anyChanges = false;
for (var i = 0, l = obj.genericArguments.length; i < l; i++) {
var unresolved = obj.genericArguments[i];
var resolved = JSIL.$ResolveGenericTypeReferenceInternal(unresolved, context);
if (resolved !== null) {
resolvedGa[i] = resolved;
anyChanges = true;
} else
resolvedGa[i] = unresolved;
}
if (anyChanges)
return new JSIL.TypeRef(obj.context, obj.getTypeName(), resolvedGa);
else
return null;
} else if (obj.__IsClosed__ === false) {
if (obj.__IsArray__) {
var elementType = JSIL.$ResolveGenericTypeReferenceInternal(obj.__ElementType__, context);
if (elementType !== null)
return System.Array.Of(elementType);
return null;
}
var ga = obj.__GenericArguments__ || $jsilcore.ArrayNull;
if (ga.length < 1)
return null;
var openType = obj.__OpenType__;
if (typeof (openType) !== "object")
return null;
var openPublicInterface = openType.__PublicInterface__;
var existingParameters = obj.__GenericArgumentValues__ || $jsilcore.ArrayNull;
var closedParameters = new Array(existingParameters.length);
for (var i = 0; i < closedParameters.length; i++) {
closedParameters[i] = JSIL.$ResolveGenericTypeReferenceInternal(
existingParameters[i], context
);
if (!closedParameters[i]) {
if (
(Object.getPrototypeOf(existingParameters[i]) === JSIL.GenericParameter.prototype) ||
(existingParameters[i].__IsClosed__ === false)
) {
if (JSIL.WarnAboutGenericResolveFailures)
JSIL.WarningFormat(
"Failed to resolve generic parameter #{0} of type reference '{1}'.",
[i, obj.toString()]
);
return null;
}
closedParameters[i] = existingParameters[i];
}
}
var result = openPublicInterface.Of.apply(openPublicInterface, closedParameters);
return result.__Type__;
}
return null;
};
JSIL.FoundGenericParameter = function (name, value) {
this.name = name;
this.value = value;
};
JSIL.FindGenericParameters = function (obj, type, resultList) {
// Walk through our base types and identify any unresolved generic parameters.
// This produces a list of parameters that need new values assigned in the target prototype.
if ((typeof (obj) !== "object") && (typeof (obj) !== "function"))
JSIL.RuntimeError("Cannot resolve generic parameters of non-object");
var currentType = type;
while ((typeof(currentType) !== "undefined") && (currentType !== null)) {
var localGa = currentType.__GenericArguments__ || $jsilcore.ArrayNull;
var localFullName = currentType.__FullNameWithoutArguments__ || currentType.__FullName__;
for (var i = 0, l = localGa.length; i < l; i++) {
var key = localGa[i];
var qualifiedName = new JSIL.Name(key, localFullName);
var value = qualifiedName.get(obj);
if ((typeof (value) === "object") && (value !== null)) {
if ((Object.getPrototypeOf(value) === JSIL.GenericParameter.prototype) || (!value.__IsClosed__)) {
resultList.push(new JSIL.FoundGenericParameter(qualifiedName, value));
}
}
}
currentType = currentType.__BaseType__;
if (
(typeof(currentType) === "object") &&
(currentType !== null) &&
(Object.getPrototypeOf(currentType) === JSIL.TypeRef.prototype)
)
currentType = currentType.get().__Type__;
}
};
JSIL.ResolveTypeReference = function (typeReference, context) {
var result = null;
if (
typeof (typeReference) === "undefined"
) {
JSIL.RuntimeError("Undefined type reference");
} else if (
typeof (typeReference) === "string"
) {
if (typeReference.indexOf("!!") === 0) {
result = new JSIL.PositionalGenericParameter(typeReference, context);
} else {
if (
(typeof (context) === "object") && (context !== null) &&
(Object.getPrototypeOf(context) === JSIL.MethodSignature.prototype)
) {
result = JSIL.GetTypeByName(typeReference, context.context);
} else {
result = JSIL.GetTypeByName(typeReference, context);
}
}
} else if (
typeof (typeReference) === "object"
) {
if (typeReference === null)
JSIL.RuntimeError("Null type reference");
if (Object.getPrototypeOf(typeReference) === JSIL.TypeRef.prototype)
result = typeReference.get();
else
result = typeReference;
} else if (
typeof (typeReference) === "function"
) {
result = typeReference;
} else {
result = typeReference;
}
if (typeof (result.__Type__) === "object") {
return [result, result.__Type__];
} else if (
typeof (result.__PublicInterface__) !== "undefined"
) {
return [result.__PublicInterface__, result];
} else {
return [result, result];
}
};
JSIL.ResolveTypeArgument = function (typeArg, context) {
var result = JSIL.ResolveTypeReference(typeArg, context)[1];
if (typeof (result) === "undefined")
JSIL.RuntimeError("Undefined passed as type argument");
else if (result === null)
JSIL.RuntimeError("Null passed as type argument");
return result;
};
JSIL.ResolveTypeArgumentArray = function (typeArgs, context) {
var resolvedArguments = typeArgs;
// Ensure that each argument is the public interface of a type (not the type object or a type reference)
for (var i = 0, l = resolvedArguments.length; i < l; i++)
resolvedArguments[i] = JSIL.ResolveTypeArgument(typeArgs[i], context);
return resolvedArguments;
};
JSIL.$GetTypeIDForHash = function (typeReference, context) {
var trType = typeof (typeReference);
var typeId;
if (trType === "undefined") {
JSIL.RuntimeError("Undefined passed as type argument");
} else if (typeReference === null) {
JSIL.RuntimeError("Null passed as type argument");
} else if (typeId = typeReference.__TypeId__) {
return typeId;
} else if (
trType === "string"
) {
if (typeReference.indexOf("!!") === 0) {
return typeReference;
} else {
if (typeof (context) === "undefined")
JSIL.RuntimeError("Context required");
return JSIL.AssignTypeId(context, typeReference);
}
} else if (
trType === "object"
) {
if (Object.getPrototypeOf(typeReference) === JSIL.TypeRef.prototype)
return typeReference.getTypeId();
}
JSIL.RuntimeError("Type missing type ID");
};
JSIL.HashTypeArgumentArray = function (typeArgs, context) {
if (typeArgs.length <= 0)
return "void";
var cacheKey = null;
for (var i = 0, l = typeArgs.length; i < l; i++) {
var typeId = JSIL.$GetTypeIDForHash(typeArgs[i], context);
if (i === 0)
cacheKey = typeId;
else
cacheKey += "," + typeId;
}
return cacheKey;
};
$jsilcore.$Of$NoInitialize = function () {
// This whole function would be 100x simpler if you could provide a prototype when constructing a function. Javascript sucks so much.
var staticClassObject = this;
var typeObject = this.__Type__;
var ga = typeObject.__GenericArguments__;
if (arguments.length != ga.length)
JSIL.RuntimeError("Invalid number of generic arguments for type '" + JSIL.GetTypeName(this) + "' (got " + arguments.length + ", expected " + ga.length + ")");
var cacheKey = JSIL.HashTypeArgumentArray(arguments, typeObject.__Context__);
var ofCache = typeObject.__OfCache__;
// If we do not return the same exact closed type instance from every call to Of(...), derivation checks will fail
var result = ofCache[cacheKey];
if (result)
return result;
var resolvedArguments = JSIL.ResolveTypeArgumentArray(
Array.prototype.slice.call(arguments)
);
var gaNames = typeObject.__GenericArgumentNames__;
if (!JSIL.IsArray(gaNames)) {
typeObject.__GenericArgumentNames__ = gaNames = [];
for (var i = 0; i < ga.length; i++)
gaNames[i] = new JSIL.Name(ga[i], typeObject.__FullName__);
}
var unresolvedBaseType;
if (typeObject.IsInterface)
// HACK
unresolvedBaseType = $jsilcore.System.Object.__Type__;
else
unresolvedBaseType = typeObject.__BaseType__;
var resolvedBaseType = unresolvedBaseType;
var resolveContext = null;
if (staticClassObject.prototype) {
resolveContext = JSIL.CreatePrototypeObject(staticClassObject.prototype);
} else {
resolveContext = JSIL.CreateSingletonObject(null);
}
for (var i = 0; i < resolvedArguments.length; i++) {
gaNames[i].set(resolveContext, resolvedArguments[i]);
}
// We need to resolve any generic arguments contained in the base type so that the base type of a closed generic type is also closed.
// thus, given Derived<T> : Base<T> and Base<U> : Object, Derived<int>.BaseType must be Base<int>, not Base<U>.
resolvedBaseType = JSIL.$ResolveGenericTypeReferenceInternal(resolvedBaseType, resolveContext);
if (!resolvedBaseType) {
resolvedBaseType = unresolvedBaseType;
}
JSIL.$ResolveGenericTypeReferences(typeObject, resolvedArguments);
var resultTypeObject = JSIL.CreateSingletonObject(typeObject);
// Since .Of() will now be called even for open types, we need to ensure that we flag
// the type as open if it has any unresolved generic parameters.
var isClosed = true;
for (var i = 0, l = arguments.length; i < l; i++) {
if (Object.getPrototypeOf(resolvedArguments[i]) === JSIL.GenericParameter.prototype)
isClosed = false;
else if (resolvedArguments[i].__IsClosed__ === false)
isClosed = false;
}
resultTypeObject.__IsClosed__ = isClosed;
var constructor;
if (typeObject.IsInterface) {
constructor = function Interface__ctor () {
JSIL.RuntimeError("Cannot construct an instance of an interface");
};
} else if (typeObject.__IsNullable__ === true) {
constructor = function Nullable__ctor () {
JSIL.RuntimeError("Cannot construct an instance of Nullable");
};
} else {
constructor = JSIL.MakeTypeConstructor(resultTypeObject, typeObject.__MaxConstructorArguments__);
}
JSIL.SetValueProperty(resultTypeObject, "__PublicInterface__", result = constructor);
resultTypeObject.__OpenType__ = typeObject;
JSIL.SetValueProperty(resultTypeObject, "__BaseType__", resolvedBaseType);
result.__Type__ = resultTypeObject;
resultTypeObject.__RenamedMethods__ = JSIL.CreateDictionaryObject(typeObject.__RenamedMethods__ || null);
// Prevents recursion when Of is called indirectly during initialization of the new closed type
ofCache[cacheKey] = result;
if (staticClassObject.prototype) {
// Given Derived<T> : Base<T> and Base<U> : Object, the prototype of Derived<T> instances must have this chain:
// Derived<T> -> Base<T> -> Object, not:
// Derived<T> -> Derived -> Base<U> -> Object
var basePrototype = resolvedBaseType.__PublicInterface__.prototype;
var resultPrototype = JSIL.CreatePrototypeObject(basePrototype);
result.prototype = resultPrototype;
JSIL.$CopyMembersIndirect(resultPrototype, staticClassObject.prototype, JSIL.$IgnoredPrototypeMembers, false);
var genericParametersToResolve = [];
JSIL.FindGenericParameters(result.prototype, resultTypeObject, genericParametersToResolve);
for (var i = 0; i < genericParametersToResolve.length; i++) {
var qualifiedName = genericParametersToResolve[i].name;
var value = genericParametersToResolve[i].value;
var resolved = JSIL.$ResolveGenericTypeReferenceInternal(value, resolveContext);
if (resolved !== null) {
// console.log(qualifiedName.humanReadable, " ", value, " -> ", resolved);
qualifiedName.defineProperty(
result.prototype, {
value: resolved,
enumerable: true,
configurable: true
}
);
}
}
}
JSIL.$CopyMembersIndirect(result, staticClassObject, JSIL.$IgnoredPublicInterfaceMembers, true);
var fullName = typeObject.__FullName__ + "[";
for (var i = 0; i < resolvedArguments.length; i++) {
if (i > 0)
fullName += ",";
var arg = resolvedArguments[i];
var stringified = arg.__FullName__; // || String(arg);
if (!stringified)
JSIL.RuntimeError("No name for generic argument #" + i + " to closed form of type " + typeObject.__FullName__);
fullName += stringified;
}
fullName += "]";
var typeId = typeObject.__TypeId__ + "[";
for (var i = 0; i < resolvedArguments.length; i++) {
if (i > 0)
typeId += ",";
typeId += resolvedArguments[i].__TypeId__;
}
typeId += "]";
JSIL.SetTypeId(result, resultTypeObject, typeId);
resultTypeObject.__ReflectionCache__ = null;
resultTypeObject.__GenericArgumentValues__ = resolvedArguments;
resultTypeObject.__FullNameWithoutArguments__ = typeObject.__FullName__;
JSIL.SetValueProperty(resultTypeObject, "__FullName__", fullName);
JSIL.SetValueProperty(resultTypeObject, "toString",
function GenericType_ToString () {
return JSIL.GetTypeName(this, true);
}
);
JSIL.SetValueProperty(result, "toString",
function GenericTypePublicInterface_ToString () {
return "<" + this.__Type__.__FullName__ + " Public Interface>";
}
);
result.__Self__ = result;
if (typeof (result.prototype) !== "undefined") {
JSIL.SetValueProperty(result.prototype, "__ThisType__", resultTypeObject);
JSIL.SetValueProperty(result.prototype, "__ThisTypeId__", resultTypeObject.__TypeId__);
JSIL.SetValueProperty(result.prototype, "__FullName__", fullName);
}
// This is important: It's possible for recursion to cause the initializer to run while we're defining properties.
// We prevent this from happening by forcing the initialized state to true.
resultTypeObject.__TypeInitialized__ = true;
// Resolve any generic parameter references in the interfaces this type implements.
var interfaces = resultTypeObject.__Interfaces__ = [];
var sourceInterfaces = typeObject.__Interfaces__;
var writeGenericArgument = function (key, name, resolvedArgument) {
var getter = function GetGenericArgument () {
return name.get(this);
}
var decl = {
configurable: true,
enumerable: true,
value: resolvedArgument
};
var getterDecl = {
configurable: true,
enumerable: true,
get: getter
};
name.defineProperty(result, decl);
if (key)
Object.defineProperty(result, key, getterDecl);
if (result.prototype) {
name.defineProperty(result.prototype, decl);
if (key)
Object.defineProperty(result.prototype, key, getterDecl);
}
};
for (var i = 0, l = sourceInterfaces.length; i < l; i++) {
var unresolvedInterface = sourceInterfaces[i];
var resolvedInterface = JSIL.$ResolveGenericTypeReferenceInternal(unresolvedInterface, resolveContext);
if (resolvedInterface === null)
resolvedInterface = unresolvedInterface;
// It's possible there are duplicates in the interface list.
if (interfaces.indexOf(resolvedInterface) >= 0)
continue;
interfaces.push(resolvedInterface);
if (resolvedInterface !== unresolvedInterface) {
var resolvedInterfaceTypeObj = JSIL.ResolveTypeReference(resolvedInterface)[1];
var names = resolvedInterfaceTypeObj.__OpenType__.__GenericArgumentNames__;
for (var j = 0, l2 = names.length; j < l2; j++) {
var name = names[j];
var value = resolvedInterfaceTypeObj.__GenericArgumentValues__[j];
writeGenericArgument(null, name, value);
}
}
}
for (var i = 0, l = resolvedArguments.length; i < l; i++) {
var key = ga[i];
var escapedKey = JSIL.EscapeName(key);
var name = new JSIL.Name(key, resultTypeObject.__FullNameWithoutArguments__);
writeGenericArgument(escapedKey, name, resolvedArguments[i]);
}
if (typeObject.IsInterface)
JSIL.CopyObjectValues(resolveContext, result.prototype, false);
if (isClosed) {
resultTypeObject.__AssignableFromTypes__ = {};
JSIL.ResolveGenericMemberSignatures(result, resultTypeObject);
JSIL.RenameGenericMethods(result, resultTypeObject);
JSIL.RebindRawMethods(result, resultTypeObject);
JSIL.FixupFieldTypes(result, resultTypeObject);
JSIL.ResolveGenericExternalMethods(result, resultTypeObject);
} else {
resultTypeObject.__OfCache__ = {};
}
JSIL.MakeCastMethods(result, resultTypeObject, typeObject.__CastSpecialType__);
// Force the initialized state back to false
resultTypeObject.__TypeInitialized__ = false;
return result;
};
$jsilcore.$MakeOf$NoInitialize = function (publicInterface) {
var fn = $jsilcore.$Of$NoInitialize;
return function Of$NoInitialize_bound () {
return fn.apply(publicInterface, arguments);
};
};
$jsilcore.$MakeOf = function (publicInterface) {
var typeObject = publicInterface.__Type__;
var typeName = typeObject.__FullName__;
return JSIL.CreateNamedFunction(
typeName + ".Of", [],
"var result = publicInterface.Of$NoInitialize.apply(publicInterface, arguments);\r\n" +
"// If the outer type is initialized, initialize the inner type.\r\n" +
"if (!result.__Type__.__TypeInitialized__ && typeObject.__TypeInitialized__)\r\n" +
" JSIL.InitializeType(result);\r\n" +
"return result;",
{
publicInterface: publicInterface,
typeObject: typeObject
}
);
};
JSIL.StaticClassPrototype = {};
JSIL.StaticClassPrototype.toString = function () {
return JSIL.GetTypeName(JSIL.GetType(this), true);
};
JSIL.$ResolveGenericMethodSignature = function (typeObject, signature, resolveContext) {
var returnType = [signature.returnType];
var argumentTypes = Array.prototype.slice.call(signature.argumentTypes);
var genericArgumentNames = signature.genericArgumentNames;
var changed = JSIL.$ResolveGenericTypeReferences(resolveContext, returnType);
changed = JSIL.$ResolveGenericTypeReferences(resolveContext, argumentTypes) || changed;
if (changed)
return new JSIL.MethodSignature(returnType[0], argumentTypes, genericArgumentNames, typeObject.__Context__, signature);
/*
if (!signature.IsClosed) {
console.log("Resolving failed for open signature", signature, "with context", resolveContext);
}
*/
return null;
};
// Static RawMethods need to be rebound so that their 'this' reference is the publicInterface
// of the type object.
JSIL.RebindRawMethods = function (publicInterface, typeObject) {
var rm = typeObject.__RawMethods__;
var isGeneric = typeObject.__OpenType__;
if (JSIL.IsArray(rm)) {
for (var i = 0; i < rm.length; i++) {
var item = rm[i];
var methodName = item.name;
if (item.isStatic) {
var method = publicInterface[methodName];
// FIXME: Stop using Function.bind here, it's slow
var boundMethod = method.bind(publicInterface);
JSIL.SetValueProperty(publicInterface, methodName, boundMethod);
}
}
}
// Rebind CheckType for delegate types so that it uses the new closed delegate type
if (typeObject.__IsDelegate__) {
JSIL.SetValueProperty(
publicInterface, "CheckType",
$jsilcore.CheckDelegateType.bind(typeObject)
);
}
}
// Any methods with generic parameters as their return type or argument type(s) must be renamed
// after the generic type is closed; otherwise overload resolution will fail to locate them because
// the method signature won't match.
// We also need to copy any methods without generic parameters over from the open version of the type's prototype.
JSIL.RenameGenericMethods = function (publicInterface, typeObject) {
var members = typeObject.__Members__;
if (!JSIL.IsArray(members))
return;
members = typeObject.__Members__ = Array.prototype.slice.call(members);
var resolveContext = typeObject.__IsStatic__ ? publicInterface : publicInterface.prototype;
var rm = typeObject.__RenamedMethods__;
var trace = false;
var throwOnFail = false;
var isInterface = typeObject.IsInterface;
_loop:
for (var i = 0, l = members.length; i < l; i++) {
var member = members[i];
switch (member.type) {
case "MethodInfo":
case "ConstructorInfo":
break;
default:
continue _loop;
}
var descriptor = member.descriptor;
var data = member.data;
var signature = data.signature;
var genericSignature = data.genericSignature;
var unqualifiedName = descriptor.EscapedName;
var oldName = data.mangledName;
var target = descriptor.Static ? publicInterface : publicInterface.prototype;
if (isInterface) {
var oldObject = publicInterface[unqualifiedName];
if (!oldObject)
JSIL.RuntimeError("Failed to find unrenamed generic interface method");
if (!signature.IsClosed) {
genericSignature = signature;
signature = JSIL.$ResolveGenericMethodSignature(
typeObject, genericSignature, resolveContext
);
if (!signature) {
if (throwOnFail) {
JSIL.RuntimeError("Failed to resolve generic signature", genericSignature);
} else {
signature = genericSignature;
}
}
}
var newObject = oldObject.Rebind(typeObject, signature);
JSIL.SetValueProperty(publicInterface, unqualifiedName, newObject);
if (trace)
console.log(typeObject.__FullName__ + ": " + unqualifiedName + " rebound");
} else {
// If the method is already renamed, don't bother trying to rename it again.
// Renaming it again would clobber the rename target with null.
if (typeof (rm[oldName]) !== "undefined") {
if (trace)
console.log(typeObject.__FullName__ + ": " + oldName + " not found");
continue;
}
if ((genericSignature !== null) && (genericSignature.get_Hash() != signature.get_Hash())) {
var newName = signature.GetNamedKey(descriptor.EscapedName, true);
var methodReference = JSIL.$FindMethodBodyInTypeChain(typeObject, descriptor.Static, oldName, false);
if (!methodReference)
JSIL.RuntimeError("Failed to find unrenamed generic method");
typeObject.__RenamedMethods__[oldName] = newName;
delete target[oldName];
JSIL.SetValueProperty(target, newName, methodReference);
if (trace)
console.log(typeObject.__FullName__ + ": " + oldName + " -> " + newName);
}
}
}
};
JSIL.FixupFieldTypes = function (publicInterface, typeObject) {
var members = typeObject.__Members__;
if (!JSIL.IsArray(members))
return;
var members = typeObject.__Members__ = Array.prototype.slice.call(members);
var resolveContext = publicInterface.prototype;
var rm = typeObject.__RenamedMethods__;
var trace = false;
var resolvedFieldTypeRef, resolvedFieldType;
_loop:
for (var i = 0, l = members.length; i < l; i++) {
var member = members[i];
if (member.type !== "FieldInfo")
continue _loop;
var descriptor = member.descriptor;
var data = member.data;
var fieldType = data.fieldType;
resolvedFieldTypeRef = JSIL.$ResolveGenericTypeReferenceInternal(fieldType, resolveContext);
if (resolvedFieldTypeRef !== null)
resolvedFieldType = JSIL.ResolveTypeReference(resolvedFieldTypeRef, typeObject.__Context__)[1];
else
resolvedFieldType = fieldType;
var newData = JSIL.CreateDictionaryObject(data);
newData.fieldType = resolvedFieldType;
members[i] = new JSIL.MemberRecord(member.type, member.descriptor, newData, member.attributes, member.overrides);
}
};
JSIL.InstantiateProperties = function (publicInterface, typeObject) {
var originalTypeObject = typeObject;
var recursed = false;
while ((typeof (typeObject) !== "undefined") && (typeObject !== null)) {
var currentPublicInterface = typeObject.__PublicInterface__;
var ps = typeObject.__Properties__;
if (JSIL.IsArray(ps)) {
var typeShortName = typeObject.__ShortName__;
for (var i = 0, l = ps.length; i < l; i++) {
var property = ps[i];
var isStatic = property[0];
var name = property[1];
var isVirtual = property[2];
var methodSource = publicInterface;
if (isStatic)
JSIL.InterfaceBuilder.MakeProperty(typeShortName, name, publicInterface, methodSource, recursed);
else
JSIL.InterfaceBuilder.MakeProperty(typeShortName, name, publicInterface.prototype, methodSource.prototype, recursed);
}
}
typeObject = typeObject.__BaseType__;
recursed = true;
}
};
$jsilcore.CanFixUpEnumInterfaces = false;
JSIL.FixupInterfaces = function (publicInterface, typeObject) {
var trace = false;
if (typeObject.__FullName__ === "System.Enum") {
if (!$jsilcore.CanFixUpEnumInterfaces)
return;
else
/* trace = true */;
}
// FIXME: Is this right? I think it might be. We don't actually use the types,
// just use their type objects as tokens for comparisons.
if (typeObject.__IsFixingUpInterfaces__)
return;
if (typeObject.IsInterface)
return;
// This is the table of interfaces that is used by .Overrides' numeric indices.
var indexedInterfaceTable = JSIL.GetInterfacesImplementedByType(typeObject, false, false);
// This is the table of every interface we actually implement (exhaustively).
var interfaces = JSIL.GetInterfacesImplementedByType(typeObject, true, false);
if (!interfaces.length)
return;
typeObject.__IsFixingUpInterfaces__ = true;
var context = typeObject.__Context__;
var typeName = typeObject.__FullName__;
var missingMembers = [];
var ambiguousMembers = [];
var typeMembers = JSIL.GetMembersInternal(typeObject, $jsilcore.BindingFlags.$Flags("Instance", "NonPublic", "Public"));
var resolveContext = typeObject.__IsStatic__ ? publicInterface : publicInterface.prototype;
__interfaces__:
for (var i = 0, l = interfaces.length; i < l; i++) {
var iface = interfaces[i];
if (typeof (iface) === "undefined") {
JSIL.WarningFormat(
"Type '{0}' implements an undefined interface.",
[typeName]
);
continue __interfaces__;
} else if (typeof (iface) === "string") {
var resolved = JSIL.ResolveName(
context, iface, true
);
if (resolved.exists())
iface = resolved.get();
else {
JSIL.WarningFormat(
"Type '{0}' implements an undefined interface named '{1}'.",
[typeName, iface]
);
interfaces[i] = null;
continue __interfaces__;
}
} else if ((typeof (iface) === "object") && (typeof (iface.get) === "function")) {
var resolvedGenericInterface = JSIL.$ResolveGenericTypeReferenceInternal(iface, resolveContext);
try {
if (resolvedGenericInterface)
iface = resolvedGenericInterface.get();
else
iface = iface.get();
} catch (exc) {
JSIL.WarningFormat(
"Type '{0}' implements an interface named '{1}' that could not be resolved: {2}",
[typeName, String(iface.getTypeName() || iface), exc]
);
interfaces[i] = null;
continue __interfaces__;
}
}
if (typeof (iface.__Type__) === "object")
iface = iface.__Type__;
interfaces[i] = iface;
var ifaceName = iface.__FullNameWithoutArguments__ || iface.__FullName__;
var ifaceLocalName = JSIL.GetLocalName(ifaceName);
if (iface.IsInterface !== true) {
JSIL.Host.warning("Type " + ifaceName + " is not an interface.");
continue __interfaces__;
}
// In cases where an interface method (IInterface_MethodName) is implemented by a regular method
// (MethodName), we make a copy of the regular method with the name of the interface method, so
// that attempts to directly invoke the interface method will still work.
var members = JSIL.GetMembersInternal(
iface,
$jsilcore.BindingFlags.$Flags("DeclaredOnly", "Instance", "NonPublic", "Public")
);
var proto = publicInterface.prototype;
var escapedLocalName = JSIL.EscapeName(ifaceLocalName);
var hasOwn = function (name) {
return Object.prototype.hasOwnProperty.call(proto, name);
};
var hasNonPlaceholder = function (obj, name) {
var value = obj[name];
if ((typeof (value) === "undefined") ||
(value === null))
return false;
if (value.__IsPlaceholder__)
return false;
return true;
}
__members__:
for (var j = 0; j < members.length; j++) {
var member = members[j];
var qualifiedName = JSIL.$GetSignaturePrefixForType(iface) + member._descriptor.EscapedName;
var signature = member._data.signature || null;
var signatureQualifiedName = null;
if (signature) {
signatureQualifiedName = signature.GetNamedKey(qualifiedName, true);
}
if (signature
&& hasNonPlaceholder(proto, signatureQualifiedName)
&& hasOwn(signatureQualifiedName)
)
continue;
if (
hasNonPlaceholder(proto, qualifiedName)
&& hasOwn(qualifiedName)
)
continue;
var isMissing = false, isAmbiguous = false;
switch (member.__MemberType__) {
case "MethodInfo":
case "ConstructorInfo":
// FIXME: Match signatures
var matchingMethods = typeObject.$GetMatchingInstanceMethods(
member.get_Name(), member.GetParameterTypes(), member.get_ReturnType()
);
if (matchingMethods.length === 0) {
isMissing = true;
} else if (matchingMethods.length > 1) {
isAmbiguous = true;
} else {
var implementation = matchingMethods[0];
var sourceQualifiedName = implementation._data.signature.GetNamedKey(
implementation._descriptor.EscapedName, true
);
if (trace)
console.log(typeName + "::" + signatureQualifiedName + " (" + iface + ") = " + sourceQualifiedName);
JSIL.SetLazyValueProperty(
proto, signatureQualifiedName,
JSIL.MakeInterfaceMemberGetter(proto, sourceQualifiedName)
);
}
break;
default:
// FIXME: Not implemented
break;
}
if (isMissing)
missingMembers.push(signatureQualifiedName || qualifiedName);
else if (isAmbiguous)
ambiguousMembers.push(signatureQualifiedName || qualifiedName);
}
if (interfaces.indexOf(iface) < 0)
interfaces.push(iface);
}
// Now walk all the members defined in the typeObject itself, and see if any of them explicitly override
// an interface member (.overrides in IL, .Overrides() in JS)
for (var i = 0; i < typeMembers.length; i++) {
var member = typeMembers[i];
var overrides = member.__Overrides__;
if (!overrides || !overrides.length)
continue;
if (member._data.isExternal) {
if (trace)
console.log("Skipping external method '" + member._descriptor.EscapedName + "'");
continue;
}
for (var j = 0; j < overrides.length; j++) {
var override = overrides[j];
var iface = null;
switch (typeof (override.interfaceNameOrReference)) {
case "object":
iface = JSIL.ResolveTypeReference(override.interfaceNameOrReference)[1];
break;
case "string":
// Search for interfaces that have an exact name match.
// Doing this first ensures that "IFoo" does not match "IFoo`1" if "IFoo" is also in the list..
var matchingInterfaces = interfaces.filter(function (iface) {
return iface.__FullName__ === override.interfaceNameOrReference;
});
// If we didn't find any exact matches, search for a prefix match.
// This ensures that we can write something like 'IList`1' to match 'System.Collections.Generic.IList`1' if we are super lazy and terrible.
if (matchingInterfaces.length === 0)
matchingInterfaces = interfaces.filter(function (iface) {
return iface.__FullName__.indexOf(override.interfaceNameOrReference) >= 0;
});
if (matchingInterfaces.length > 1) {
// TODO: Enable this warning?
/*
JSIL.RuntimeError(
"Member '" + member._descriptor.EscapedName +
"' overrides interface '" + override.interfaceNameOrReference +
"' but " + matchingInterfaces.length + " interfaces match that name: \r\n" +
"\r\n".join(matchingInterfaces)
);
*/
iface = matchingInterfaces[0];
} else if (matchingInterfaces.length === 0) {
iface = null;
} else {
iface = matchingInterfaces[0];
}
break;
}
if (!iface)
JSIL.RuntimeErrorFormat(
"Member '{0}::{1}' overrides nonexistent interface member '{2}::{3}'",
[
typeObject.__FullName__, member._descriptor.EscapedName,
override.interfaceNameOrReference, override.interfaceMemberName
]
);
var interfaceQualifiedName = JSIL.$GetSignaturePrefixForType(iface) + JSIL.EscapeName(override.interfaceMemberName);
var key = member._data.signature.GetNamedKey(interfaceQualifiedName, true);
var missingIndex = missingMembers.indexOf(key);
if (missingIndex >= 0)
missingMembers.splice(missingIndex, 1);
if (trace) {
console.log("Overrides set " + typeName + "::" + key + " (#" + override.interfaceNameOrReference + "=" + iface + ") = " + member._descriptor.EscapedName);
}
// Important: This may overwrite an existing member with this key, from an automatic interface fixup
// like 'Foo.GetEnumerator' -> 'Foo.Ixx$GetEnumerator'.
// This is desirable because an explicit override (via .Overrides) should always trump automatic
// overrides via name/signature matching.
JSIL.SetLazyValueProperty(proto, key, JSIL.MakeInterfaceMemberGetter(proto, member._descriptor.EscapedName));
}
}
if (missingMembers.length > 0) {
if ((JSIL.SuppressInterfaceWarnings !== true) || trace)
JSIL.Host.warning("Type '" + typeObject.__FullName__ + "' is missing implementation of interface member(s): " + missingMembers.join(", "));
}
if (ambiguousMembers.length > 0) {
if ((JSIL.SuppressInterfaceWarnings !== true) || trace)
JSIL.Host.warning("Type '" + typeObject.__FullName__ + "' has ambiguous implementation of interface member(s): " + ambiguousMembers.join(", "));
}
typeObject.__IsFixingUpInterfaces__ = false;
};
$jsilcore.BuildingFieldList = new Array();
JSIL.GetFieldList = function (typeObject) {
var fl = typeObject.__FieldList__;
if (fl === $jsilcore.ArrayNotInitialized) {
fl = $jsilcore.BuildingFieldList;
fl = JSIL.$BuildFieldList(typeObject);
} else if (fl === $jsilcore.BuildingFieldList) {
JSIL.RuntimeError("Recursive invocation of GetFieldList on type " + typeObject.__FullName__);
}
if ((fl === $jsilcore.ArrayNull) || (!JSIL.IsArray(fl)))
return $jsilcore.ArrayNull;
return fl;
};
JSIL.EscapeJSIdentifier = function (identifier) {
var nameRe = /[^A-Za-z_0-9\$]/g;
return JSIL.EscapeName(identifier).replace(nameRe, "_");
};
JSIL.GetObjectKeys = function (obj) {
// This is a .NET object, so return the names of any public fields/properties.
if (obj && obj.GetType) {
var typeObject = obj.GetType();
var bindingFlags = $jsilcore.BindingFlags.$Flags("Instance", "Public");
var fields = JSIL.GetMembersInternal(typeObject, bindingFlags, "FieldInfo");
var properties = JSIL.GetMembersInternal(typeObject, bindingFlags, "PropertyInfo");
var result = [];
for (var i = 0, l = fields.length; i < l; i++)
result.push(fields[i].get_Name());
for (var i = 0, l = properties.length; i < l; i++)
result.push(properties[i].get_Name());
return result;
} else {
return Object.keys(obj);
}
};
JSIL.CreateNamedFunction = function (name, argumentNames, body, closure) {
var result = null, keys = null, closureArgumentList = null;
if (closure) {
keys = JSIL.GetObjectKeys(closure);
closureArgumentList = new Array(keys.length);
for (var i = 0, l = keys.length; i < l; i++)
closureArgumentList[i] = closure[keys[i]];
}
var constructor = JSIL.CreateRebindableNamedFunction(name, argumentNames, body, closure);
result = constructor.apply(null, closureArgumentList);
return result;
};
JSIL.CreateRebindableNamedFunction = function (name, argumentNames, body, closure) {
var uriRe = /[\<\>\+\/\\\.]/g;
var strictPrefix = "\"use strict\";\r\n";
var uriPrefix = "//# sourceURL=jsil://closure/" + name + "\r\n";
var escapedFunctionIdentifier = JSIL.EscapeJSIdentifier(name);
var rawFunctionText = "function " + escapedFunctionIdentifier + "(" +
argumentNames.join(", ") +
") {\r\n" +
body +
"\r\n};\r\n";
var lineBreakRE = /\r(\n?)/g;
rawFunctionText =
uriPrefix + strictPrefix +
rawFunctionText.replace(lineBreakRE, "\r\n ") +
" return " + escapedFunctionIdentifier + ";\r\n";
var result = null, keys = null;
if (closure) {
keys = JSIL.GetObjectKeys(closure).concat([rawFunctionText]);
} else {
keys = [rawFunctionText];
}
result = Function.apply(Function, keys);
return result;
};
JSIL.FormatMemberAccess = function (targetExpression, memberName) {
// Can't reuse a global instance because .test mutates the RegExp. JavaScript is stupid.
var shortMemberRegex = /^[_a-zA-Z][a-zA-Z_0-9]*$/g;
if (typeof (memberName) !== "string")
JSIL.RuntimeError("Member name must be a string");
if (shortMemberRegex.test(memberName)) {
return targetExpression + "." + memberName;
} else {
return targetExpression + "['" + memberName + "']";
}
};
JSIL.MakeFieldInitializer = function (typeObject, returnNamedFunction) {
var fl = JSIL.GetFieldList(typeObject);
if ((fl.length < 1) && returnNamedFunction)
return $jsilcore.FunctionNull;
var prototype = typeObject.__PublicInterface__.prototype;
var body = [];
var targetArgName = returnNamedFunction ? "target" : "this";
var initializerClosure = null;
if (typeObject.__IsUnion__) {
var sizeBytes = typeObject.__NativeSize__;
body.push(JSIL.FormatMemberAccess(targetArgName, "$backingStore") + " = new Uint8Array(" + sizeBytes + ");");
// HACK: Generate accessors for the (now missing) fields that hit our backing store
JSIL.$GenerateUnionAccessors(typeObject, fl, body, targetArgName);
} else {
var types = {};
var defaults = {};
for (var i = 0, l = fl.length; i < l; i++) {
var field = fl[i];
if ((field.type === typeObject) && (field.isStruct)) {
JSIL.Host.warning("Ignoring self-typed struct field " + field.name);
continue;
}
var key = "f" + i.toString();
if (field.isStruct) {
if (field.type.__IsNullable__) {
body.push(JSIL.FormatMemberAccess(targetArgName, field.name) + " = null;");
} else {
body.push(JSIL.FormatMemberAccess(targetArgName, field.name) + " = new types." + key + "();");
types[key] = field.type.__PublicInterface__;
}
} else if (field.type.__IsNativeType__ && field.type.__IsNumeric__) {
// This is necessary because JS engines are incredibly dumb about figuring out the actual type(s)
// an object's field slots should be.
var defaultValueString;
if (field.type.__FullName__ === "System.Boolean") {
defaultValueString = "(false)";
} else if (field.type.__FullName__ === "System.Char") {
defaultValueString = "('\\0')";
} else if (field.type.__IsIntegral__) {
defaultValueString = "(0 | 0)";
} else {
defaultValueString = "(+0.0)";
}
body.push(JSIL.FormatMemberAccess(targetArgName, field.name) + " = " + defaultValueString + ";");
} else {
body.push(JSIL.FormatMemberAccess(targetArgName, field.name) + " = defaults." + key + ";");
if (typeof (field.defaultValueExpression) === "function") {
// FIXME: This wants a this-reference?
defaults[key] = field.defaultValueExpression();
} else if (field.defaultValueExpression) {
defaults[key] = field.defaultValueExpression;
} else {
defaults[key] = JSIL.DefaultValue(field.type);
}
}
}
initializerClosure = {
types: types,
defaults: defaults
};
}
if (returnNamedFunction) {
var boundFunction = JSIL.CreateNamedFunction(
typeObject.__FullName__ + ".InitializeFields",
["target"],
body.join("\r\n"),
initializerClosure
);
boundFunction.__ThisType__ = typeObject;
JSIL.SetValueProperty(boundFunction, "__ThisTypeId__", typeObject.__TypeId__);
return boundFunction;
} else {
return [body, initializerClosure];
}
};
JSIL.GetFieldInitializer = function (typeObject) {
var fi = typeObject.__FieldInitializer__;
if (fi === $jsilcore.FunctionNotInitialized)
typeObject.__FieldInitializer__ = fi = JSIL.MakeFieldInitializer(typeObject, true);
return fi;
};
JSIL.InitializeInstanceFields = function (instance, typeObject) {
var fi = JSIL.GetFieldInitializer(typeObject);
if (fi === $jsilcore.FunctionNull)
return;
fi(instance);
};
JSIL.CopyObjectValues = function (source, target, allowOverwrite) {
for (var k in source) {
if (!Object.prototype.hasOwnProperty.call(source, k))
continue;
if (allowOverwrite === false) {
if (k in target)
continue;
}
target[k] = source[k];
}
};
JSIL.CopyMembers = function (source, target) {
var thisType = source.__ThisType__;
var copier = thisType.__MemberCopier__;
if (copier === $jsilcore.FunctionNotInitialized)
copier = thisType.__MemberCopier__ = JSIL.$MakeMemberCopier(thisType, thisType.__PublicInterface__);
copier(source, target);
};
JSIL.$MakeComparerCore = function (typeObject, context, body) {
var fields = JSIL.GetFieldList(typeObject);
if (context.prototype.__CompareMembers__) {
context.comparer = context.prototype.__CompareMembers__;
body.push(" return context.comparer(lhs, rhs);");
} else {
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
var fieldType = field.type;
if (fieldType.__IsNumeric__ || fieldType.__IsEnum__) {
body.push(" if (" + JSIL.FormatMemberAccess("lhs", field.name) + " !== " + JSIL.FormatMemberAccess("rhs", field.name) + ")");
} else {
body.push(" if (!JSIL.ObjectEquals(" + JSIL.FormatMemberAccess("lhs", field.name) + ", " + JSIL.FormatMemberAccess("rhs", field.name) + "))");
}
body.push(" return false;");
}
body.push(" return true;");
}
}
JSIL.$MakeStructComparer = function (typeObject, publicInterface) {
var prototype = publicInterface.prototype;
var context = {
prototype: prototype
};
var body = [];
JSIL.$MakeComparerCore(typeObject, context, body);
return JSIL.CreateNamedFunction(
typeObject.__FullName__ + ".StructComparer",
["lhs", "rhs"],
body.join("\r\n")
);
};
JSIL.$MakeCopierCore = function (typeObject, context, body, resultVar) {
var fields = JSIL.GetFieldList(typeObject);
if (typeObject.__IsUnion__) {
var nativeSize = typeObject.__NativeSize__;
body.push(" " + resultVar + ".$backingStore = new Uint8Array(" + nativeSize + ");");
JSIL.$EmitMemcpyIntrinsic(body, resultVar + ".$backingStore", "source.$backingStore", 0, 0, nativeSize);
} else if (context.prototype.__CopyMembers__) {
context.copier = context.prototype.__CopyMembers__;
body.push(" context.copier(source, " + resultVar + ");");
} else {
for (var i = 0; i < fields.length; i++) {
// FIXME
var field = fields[i];
var isStruct = field.isStruct;
// Type-hint the assignments
var isChar = field.type.__FullName__ === "System.Char";
var isBool = field.type.__FullName__ === "System.Boolean";
var isInteger = field.type.__IsNumeric__ && field.type.__IsIntegral__ && !isChar && !isBool;
var isFloat = field.type.__IsNumeric__ && !field.type.__IsIntegral__ && !isChar && !isBool;
var line = " " + JSIL.FormatMemberAccess(resultVar, field.name) + " = ";
if (isFloat)
line += "+(";
line += JSIL.FormatMemberAccess("source", field.name);
if (isStruct)
line += ".MemberwiseClone();"
else if (isInteger)
line += " | 0;";
else if (isFloat)
line += ");";
else
line += ";"
body.push(line);
}
}
};
JSIL.$MakeMemberCopier = function (typeObject, publicInterface) {
var prototype = publicInterface.prototype;
var context = {
prototype: prototype
};
var body = [];
JSIL.$MakeCopierCore(typeObject, context, body, "result");
return JSIL.CreateNamedFunction(
typeObject.__FullName__ + ".MemberCopier",
["source", "result"],
body.join("\r\n")
);
};
JSIL.$MakeMemberwiseCloner = function (typeObject, publicInterface) {
var prototype = publicInterface.prototype;
var context = {
prototype: prototype
};
var body = ["// Copy constructor"];
JSIL.$MakeCopierCore(typeObject, context, body, "this");
var subtypeRe = /[\+\/]/g;
var nameRe = /[^A-Za-z_0-9]/g;
var uri = typeObject.__FullName__.replace(subtypeRe, ".");
var constructor = JSIL.CreateNamedFunction(
typeObject.__FullName__ + ".CopyConstructor",
["source"],
body.join("\r\n"),
{
context: context
}
);
constructor.prototype = prototype;
var memberwiseCloner = JSIL.CreateNamedFunction(
typeObject.__FullName__ + ".MemberwiseClone",
[],
"return new clone(this);",
{
clone: constructor
}
);
return memberwiseCloner;
};
JSIL.$BuildFieldList = function (typeObject) {
if (typeObject.__IsClosed__ === false)
return;
var isUnion = false;
var bindingFlags = $jsilcore.BindingFlags.$Flags("Instance", "NonPublic", "Public");
var fields = JSIL.GetMembersInternal(
typeObject, bindingFlags, "FieldInfo"
);
var fl = typeObject.__FieldList__ = [];
var fieldOffset = 0;
var customPacking = typeObject.__CustomPacking__ | 0;
$fieldloop:
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
var fieldType = field._data.fieldType;
var didGenericResolve = false;
while (fieldType && (Object.getPrototypeOf(fieldType) === JSIL.GenericParameter.prototype)) {
didGenericResolve = true;
var fieldTypeRef = fieldType;
fieldType = JSIL.$ResolveGenericTypeReferenceInternal(fieldType, typeObject.__PublicInterface__.prototype);
if (!fieldType) {
JSIL.Host.warning(
"Could not resolve open generic parameter '" + fieldTypeRef.name +
"' when building field list for type '" + typeObject.__FullName__ + "'"
);
continue $fieldloop;
}
}
if (!didGenericResolve) {
fieldType = JSIL.ResolveTypeReference(fieldType, typeObject.__Context__)[1];
}
if ((typeof (fieldType) === "undefined") || (fieldType === null))
JSIL.RuntimeError("Invalid field type");
// Native types may derive from System.ValueType but we can't treat them as structs.
var isStruct = (fieldType.__IsStruct__ || false) && (!fieldType.__IsNativeType__);
var fieldSize = JSIL.GetNativeSizeOf(fieldType, true);
var fieldAlignment = JSIL.GetNativeAlignmentOf(fieldType, true);
// StructLayout.Pack seems to only be able to eliminate extra space between fields,
// not add extra space as one might also expect.
if (customPacking && (customPacking < fieldAlignment)) {
if (JSIL.StructFormatWarnings) {
if (fieldAlignment !== customPacking)
JSIL.WarningFormat("Custom packing for field {0}.{1} is non-native for JavaScript", [typeObject.__FullName__, field._descriptor.Name]);
}
fieldAlignment = customPacking;
}
var actualFieldOffset = fieldOffset;
if (typeof (field._data.offset) === "number") {
if (typeObject.__ExplicitLayout__)
actualFieldOffset = field._data.offset;
else if (JSIL.StructFormatWarnings)
JSIL.WarningFormat("Ignoring offset for field {0}.{1} because {0} does not have explicit layout", [typeObject.__FullName__, field.descriptor.Name]);
} else if (fieldAlignment > 0) {
actualFieldOffset = (((fieldOffset + (fieldAlignment - 1)) / fieldAlignment) | 0) * fieldAlignment;
}
var fieldRecord = {
name: field._descriptor.Name,
type: fieldType,
isStruct: isStruct,
defaultValueExpression: field._data.defaultValueExpression,
offsetBytes: actualFieldOffset,
sizeBytes: fieldSize,
alignmentBytes: fieldAlignment
};
if (fieldSize > 0) {
// Scan through preceding fields to see if we overlap any of them.
for (var j = 0; j < fl.length; j++) {
var priorRecord = fl[j];
var start = priorRecord.offsetBytes;
var end = start + priorRecord.sizeBytes;
var myInclusiveEnd = actualFieldOffset + fieldSize - 1;
if (
(
(actualFieldOffset < end) &&
(actualFieldOffset >= start)
) ||
(
(myInclusiveEnd < end) &&
(myInclusiveEnd >= start)
)
) {
if (JSIL.StructFormatWarnings)
JSIL.WarningFormat("Field {0}.{1} overlaps field {0}.{2}.", [typeObject.__FullName__, fieldRecord.name, priorRecord.name]);
fieldRecord.overlapsOtherFields = true;
isUnion = true;
}
}
}
if (!field.IsStatic)
fl.push(fieldRecord);
if (fieldSize >= 0)
fieldOffset = actualFieldOffset + fieldSize;
}
// Sort fields by name so that we get a predictable initialization order.
fl.sort(function (lhs, rhs) {
return JSIL.CompareValues(lhs.name, rhs.name);
})
if (isUnion && !typeObject.__ExplicitLayout__)
JSIL.RuntimeError("Non-explicit-layout structure appears to be a union: " + typeObject.__FullName__);
Object.defineProperty(typeObject, "__IsUnion_BackingStore__", {
value: isUnion,
configurable: true,
enumerable: false
});
return fl;
};
JSIL.$ResolveGenericTypeReferences = function (context, types) {
var result = false;
for (var i = 0; i < types.length; i++) {
var resolved = JSIL.$ResolveGenericTypeReferenceInternal(types[i], context);
if (resolved !== null) {
// console.log("ga[" + i + "] " + types[i] + " -> " + resolved);
types[i] = resolved;
result = true;
}
}
return result;
};
JSIL.$MakeAnonymousMethod = function (target, body) {
if (typeof (body) !== "function")
JSIL.RuntimeError("body must be a function");
var key = "$$" + (++JSIL.$NextDispatcherId).toString(16);
Object.defineProperty(
target, key, {
value: body,
writable: false,
configurable: true,
enumerable: false
}
);
if (body.__IsMembrane__)
JSIL.DefinePreInitMethodAlias(target, key, body);
return key;
};
JSIL.MethodSetByGenericArgumentCount = function () {
this.dict = {};
this.count = 0;
};
JSIL.MethodSetByGenericArgumentCount.prototype.get = function (argumentCount) {
var result = this.dict[argumentCount];
if (!result)
result = this.dict[argumentCount] = new JSIL.MethodSetByArgumentCount(this, argumentCount);
return result;
};
JSIL.MethodSetByArgumentCount = function (genericSet, genericCount) {
this.genericSet = genericSet;
this.genericCount = genericCount;
this.dict = {};
this.count = 0;
};
JSIL.MethodSetByArgumentCount.prototype.get = function (argumentCount) {
var result = this.dict[argumentCount];
if (!result) {
result = this.dict[argumentCount] = new JSIL.MethodSet(this, argumentCount);
}
return result;
};
JSIL.MethodSet = function (argumentSet, argumentCount) {
this.argumentSet = argumentSet;
this.argumentCount = argumentCount;
this.list = [];
this.count = 0;
};
JSIL.MethodSet.prototype.add = function (signature) {
this.list.push(signature);
this.count += 1;
this.argumentSet.count += 1;
this.argumentSet.genericSet.count += 1;
};
JSIL.$MakeMethodGroup = function (typeObject, isStatic, target, renamedMethods, methodName, methodEscapedName, overloadSignatures) {
var typeName = typeObject.__FullName__;
var methodFullName = typeName + "." + methodName;
var makeDispatcher, makeGenericArgumentGroup;
var makeMethodMissingError = function (signature) {
return "Method not found: " + signature.toString(methodFullName);
};
var makeNoMatchFoundError = function (group) {
var text = group.count + " candidate(s) for method invocation:";
for (var i = 0; i < group.count; i++) {
text += "\n" + group.list[i].toString(methodFullName);
}
return new Error(text);
};
// If the method group contains only a single method, we call this to fetch the method implementation
// and then use that as the method group.
var makeSingleMethodGroup = function (id, group, offset) {
var singleMethod = group.list[0];
var key = singleMethod.GetNamedKey(methodEscapedName, true);
var unrenamedKey = key;
if (typeof (renamedMethods[key]) === "string")
key = renamedMethods[key];
var method = JSIL.$FindMethodBodyInTypeChain(typeObject, isStatic, key, false);
if (typeof (method) !== "function") {
JSIL.Host.warning(makeMethodMissingError(singleMethod));
var stub = function MissingMethodInvoked () {
JSIL.RuntimeError(makeMethodMissingError(singleMethod));
};
return JSIL.$MakeAnonymousMethod(target, stub);
} else {
// We need to manufacture an anonymous name for the method
// So that overload dispatch can invoke it using 'this.x' syntax instead
// of using thisType['x']
// return key;
return JSIL.$MakeAnonymousMethod(target, method);
}
};
// For methods with generic arguments we figure out whether there are multiple options for the generic
// argument dispatcher, and bind the appropriate generic method dispatcher.
makeGenericArgumentGroup = function (id, group, offset) {
var groupDispatcher = makeDispatcher(id, group, offset);
var genericArgumentCount = offset;
var stub = JSIL.$MakeGenericMethodBinder(groupDispatcher, methodFullName, genericArgumentCount, group.dict);
return JSIL.$MakeAnonymousMethod(target, stub);
};
// For methods with multiple candidate signatures that all have the same number of arguments, we do
// dynamic dispatch at runtime on each invocation by comparing the types of the actual argument
// values against the expected type objects for each signature, in order to select the right
// method to call.
var makeMultipleMethodGroup = function (id, group, offset) {
// [resolvedSignatures, differentReturnTypeError]
var isResolved = false;
var resolvedGroup = null;
// Take the method signature(s) in this group and resolve all their type references.
// We do this once and cache it since type reference resolution takes time.
var getResolvedGroup = function GetResolvedGroup () {
if (isResolved)
return resolvedGroup;
var result = [];
for (var i = 0; i < group.count; i++) {
var groupEntry = group.list[i];
// FIXME: Do we still need generic logic here?
var typeObject = JSIL.GetType(target);
var resolveContext = target;
var resolvedGeneric = JSIL.$ResolveGenericMethodSignature(typeObject, groupEntry, resolveContext);
if (resolvedGeneric != null)
result[i] = resolvedGeneric.Resolve(methodEscapedName);
else
result[i] = groupEntry.Resolve(methodEscapedName);
}
isResolved = true;
return (resolvedGroup = result);
};
var stub = function OverloadedMethod_InvokeDynamic () {
var argc = arguments.length;
var resolvedGroup = getResolvedGroup();
// If resolving the group fails, it will return null.
if (resolvedGroup === null)
throw makeNoMatchFoundError(group);
var genericDispatcherKey = null;
scan_methods:
for (var i = 0, l = resolvedGroup.length; i < l; i++) {
var resolvedMethod = resolvedGroup[i];
// We've got a generic dispatcher for a generic method with N generic arguments.
// Store it to use as a fallback if none of the normal overloads match.
if (typeof (resolvedMethod) === "string") {
genericDispatcherKey = resolvedMethod;
continue;
}
var argTypes = resolvedMethod.argumentTypes;
var numGenericArguments = argc - argTypes.length;
var resolvedGenericMethod = resolvedMethod;
// If the method signature has any generic arguments, resolve any positional generic parameters
// referenced in the method signature. If we don't do this those types will just be "!!0" etc
if (numGenericArguments > 0) {
var genericArguments = Array.prototype.slice.call(arguments, 0, numGenericArguments);
resolvedGenericMethod = resolvedMethod.ResolvePositionalGenericParameters(genericArguments);
argTypes = resolvedGenericMethod.argumentTypes;
}
// Check the types of the passed in argument values against the types expected for
// this particular signature. Note that we use the resolved generic version so that
// any positional generic parameters are used for type matching.
for (var j = 0; j < argc; j++) {
var expectedType = argTypes[j];
var arg = arguments[j + offset];
if ((typeof (expectedType) === "undefined") || (expectedType === null)) {
// Specific types, like generic parameters, resolve to null or undefined.
} else if (expectedType.__IsReferenceType__ && (arg === null)) {
// Null is a valid value for any reference type.
} else if (!expectedType.$Is(arg)) {
continue scan_methods;
}
}
// Find the method implementation. Note that we don't use the key generated from the
// resolved generic version, because the actual method key contains !!0 etc.
var foundOverload = target[resolvedMethod.key];
if (typeof (foundOverload) !== "function") {
JSIL.RuntimeError(makeMethodMissingError(resolvedMethod));
} else {
return foundOverload.apply(this, arguments);
}
}
// None of the normal overloads matched, but if we found a generic dispatcher, call that.
// This isn't quite right, but the alternative (check to see if the arg is System.Type) is
// worse since it would break for methods that actually take Type instances as arguments.
if (genericDispatcherKey !== null) {
return this[genericDispatcherKey].apply(this, arguments);
}
throw makeNoMatchFoundError(group);
};
return JSIL.$MakeAnonymousMethod(target, stub);
};
makeDispatcher = function (id, g, offset) {
var body = [];
var maxArgumentCount = 0;
body.push(" var argc = arguments.length | 0;");
var methodKey = null;
var gProto = Object.getPrototypeOf(g);
var cases = [];
for (var k in g.dict) {
if (!g.dict.hasOwnProperty(k))
continue;
var argumentCount = parseInt(k) + offset;
if (isNaN(argumentCount))
throw new Error();
maxArgumentCount = Math.max(maxArgumentCount, argumentCount);
var caseDesc = {
key: argumentCount
};
var group = g.dict[k];
if (gProto === JSIL.MethodSetByGenericArgumentCount.prototype) {
methodKey = makeGenericArgumentGroup(id + "`" + k, group, group.genericCount + offset);
} else if (gProto === JSIL.MethodSetByArgumentCount.prototype) {
if (group.count > 1) {
methodKey = makeMultipleMethodGroup(id, group, offset);
} else {
methodKey = makeSingleMethodGroup(id, group, offset);
}
}
var invocation = " return this." + methodKey + "(";
for (var ai = 0; ai < argumentCount; ai++) {
if (ai !== 0)
invocation += ", ";
invocation += "arg" + ai.toString();
}
invocation += ");";
caseDesc.code = invocation;
cases.push(caseDesc);
}
JSIL.$MakeOptimizedNumericSwitch(
body, "argc", cases,
" JSIL.RuntimeError('No overload of ' + name + ' can accept ' + (argc - offset) + ' argument(s).')"
);
var bodyText = body.join("\r\n");
var formalArgumentNames = [];
for (var ai = 0; ai < maxArgumentCount; ai++)
formalArgumentNames.push("arg" + ai.toString());
var boundDispatcher = JSIL.CreateNamedFunction(
id, formalArgumentNames,
bodyText,
{
name: methodName,
offset: offset
}
);
return JSIL.$MakeAnonymousMethod(target, boundDispatcher);
};
var methodSet = new JSIL.MethodSetByGenericArgumentCount();
for (var i = 0, l = overloadSignatures.length; i < l; i++) {
var signature = overloadSignatures[i];
var argumentCount = signature.argumentTypes.length;
var gaCount = signature.genericArgumentNames.length;
var genargcSet = methodSet.get(gaCount);
var argcSet = genargcSet.get(argumentCount);
argcSet.add(signature);
}
var gaKeys = Object.keys(methodSet.dict);
// For method groups with no generic arguments, skip creating a generic argument dispatcher.
if ((gaKeys.length === 1) && (gaKeys[0] == 0)) {
// If there's only one method definition, don't generate a dispatcher at all.
// This ensures that if our implementation uses JS varargs, it works.
if (methodSet.count === 1) {
var theSet = methodSet.dict[0];
var theMethodList = theSet.dict[Object.keys(theSet.dict)[0]];
return makeSingleMethodGroup(methodFullName, theMethodList, 0);
} else {
return makeDispatcher(methodFullName, methodSet.dict[0], 0);
}
} else {
return makeDispatcher(methodFullName, methodSet, 0);
}
};
JSIL.$ApplyMemberHiding = function (typeObject, memberList, resolveContext) {
if (memberList.length < 1)
return;
// This is called during type system initialization, so we can't rely on any of MemberInfo's
// properties or methods - we need to access the data members directly.
var comparer = function (lhs, rhs) {
var lhsCount = lhs._data.signature.argumentTypes.length;
var rhsCount = rhs._data.signature.argumentTypes.length;
// Group by argument count.
var result = JSIL.CompareValues(lhsCount, rhsCount);
// Sub-cluster by hash (the hash encodes argument types, etc.)
if (result === 0) {
var lhsHash = lhs._data.signature.get_Hash();
var rhsHash = rhs._data.signature.get_Hash();
result = JSIL.CompareValues(lhsHash, rhsHash);
}
// Non-placeholders override placeholders.
if (result === 0)
result = JSIL.CompareValues(
lhs._data.isPlaceholder ? 1 : 0,
rhs._data.isPlaceholder ? 1 : 0
);
// Non-externals override externals.
if (result === 0)
result = JSIL.CompareValues(
lhs._data.isExternal ? 1 : 0,
rhs._data.isExternal ? 1 : 0
);
// A derived type's methods override inherited methods.
if (result === 0)
result = -JSIL.CompareValues(
lhs._typeObject.__InheritanceDepth__,
rhs._typeObject.__InheritanceDepth__
);
return result;
};
// Sort the member list by method signature hash, then by whether they are external
// placeholders, then by inheritance depth.
// This produces a list of 'signature groups' (methods with the same signature), and
// the first method in each signature group is the most-derived (hides the rest).
// This also ensures that external placeholders will not overwrite non-placeholder
// methods unless they are all that remains (in which case the most-derived one will
// win).
memberList.sort(comparer);
var originalCount = memberList.length;
var currentSignatureHash = null;
var currentArgumentCount = null;
var currentGroupStart;
var groupUpdate = function (i, memberSignature) {
var argumentCount = memberSignature.argumentTypes.length;
var memberSignatureHash = memberSignature.get_Hash();
if (
(currentArgumentCount === null) ||
(currentSignatureHash === null) ||
(currentArgumentCount != argumentCount) ||
(
(currentSignatureHash != memberSignatureHash) &&
// *Every* method with zero arguments is a part of a group, no matter what.
// They will automatically sort into one group because they all start with '$void='
(currentArgumentCount !== 0)
)
) {
// New group
currentArgumentCount = argumentCount;
currentSignatureHash = memberSignatureHash;
currentGroupStart = i;
return false;
} else {
return true;
}
};
var trace = false;
var traceOut = function () {
if ((typeof(console) !== "undefined") && console.log)
console.log.apply(console, arguments);
else
print.apply(null, arguments);
};
var memberName = memberList[0]._descriptor.Name;
// Sweep through the member list and replace any hidden members with null.
for (var i = 0, l = memberList.length; i < l; i++) {
var member = memberList[i];
var memberSignature = member._data.signature;
var isHidden = groupUpdate(i, memberSignature);
if (isHidden) {
var hidingMember = memberList[currentGroupStart];
if (trace) {
var localMemberName =
member._typeObject.__FullName__ +
"." + member._descriptor.Name;
var hidingMemberName =
hidingMember._typeObject.__FullName__ +
"." + hidingMember._descriptor.Name;
var memberSuffix = "", hidingMemberSuffix = "";
if (member._data.isPlaceholder)
memberSuffix = " (placeholder)";
else if (member._data.isExternal)
memberSuffix = " (external)";
if (hidingMember._data.isPlaceholder)
hidingMemberSuffix = " (placeholder)";
else if (hidingMember._data.isExternal)
hidingMemberSuffix = " (external)";
traceOut(
memberName + ": Purged " +
localMemberName + memberSuffix +
" because it is hidden by " +
hidingMemberName + hidingMemberSuffix
);
}
memberList[i] = null;
}
}
// Perform a second pass through the member list and shrink it to eliminate the nulls.
for (var i = originalCount - 1; i >= 0; i--) {
var member = memberList[i];
if (member === null)
memberList.splice(i, 1);
}
if ((trace) && (originalCount != memberList.length)) {
traceOut("Shrank method group from " + originalCount + " item(s) to " + memberList.length);
}
};
JSIL.$CreateMethodMembranes = function (typeObject, publicInterface) {
var maybeRunCctors = function MaybeRunStaticConstructors () {
JSIL.RunStaticConstructors(publicInterface, typeObject);
};
var makeReturner = function (value) {
return function () { return value; };
};
var bindingFlags = $jsilcore.BindingFlags.$Flags("NonPublic", "Public");
var methods = JSIL.GetMembersInternal(
typeObject, bindingFlags, "$MethodOrConstructor"
);
// We need to ensure that all the mangled method names have membranes applied.
// This can't be done before now due to generic types.
for (var i = 0, l = methods.length; i < l; i++) {
var method = methods[i];
var isStatic = method._descriptor.Static;
// FIXME: I'm not sure this is right for open generic methods.
// I think it might be looking up the old open form of the method signature
// instead of the closed form.
var key = method._data.signature.GetNamedKey(method._descriptor.EscapedName, true);
var useMembrane = isStatic &&
($jsilcore.cctorKeys.indexOf(method._descriptor.Name) < 0) &&
($jsilcore.cctorKeys.indexOf(method._descriptor.EscapedName) < 0);
if (useMembrane) {
var originalFunction = publicInterface[key];
if (typeof (originalFunction) !== "function") {
// throw new Error("No function with key '" + key + "' found");
continue;
}
JSIL.DefinePreInitMethod(
publicInterface, key, makeReturner(originalFunction), maybeRunCctors
);
}
}
};
JSIL.$GroupMethodsByName = function (methods) {
var methodsByName = {};
for (var i = 0, l = methods.length; i < l; i++) {
var method = methods[i];
var key = (method._descriptor.Static ? "static" : "instance") + "$" + method._descriptor.EscapedName;
var methodList = methodsByName[key];
if (!JSIL.IsArray(methodList))
methodList = methodsByName[key] = [];
// Don't add duplicate copies of the same method to the method list.
if (methodList.indexOf(method) < 0)
methodList.push(method);
}
return methodsByName;
};
JSIL.$BuildMethodGroups = function (typeObject, publicInterface, forceLazyMethodGroups) {
// This is called during type system initialization, so we can't rely on any of MemberInfo's
// properties or methods - we need to access the data members directly.
var instanceMethods = JSIL.GetMembersInternal(
typeObject, $jsilcore.BindingFlags.$Flags("Instance", "Public", "NonPublic"), "MethodInfo"
);
var constructors = JSIL.GetMembersInternal(
typeObject, $jsilcore.BindingFlags.$Flags("DeclaredOnly", "Instance", "Public", "NonPublic"), "ConstructorInfo"
);
var staticMethods = JSIL.GetMembersInternal(
typeObject, $jsilcore.BindingFlags.$Flags("DeclaredOnly", "Static", "Public", "NonPublic"), "$AllMethods"
);
var methods = staticMethods.concat(instanceMethods).concat(constructors);
var renamedMethods = typeObject.__RenamedMethods__ || {};
var trace = false;
var active = true;
// Set to true to enable lazy method group construction. This increases
// javascript heap size but improves startup performance.
var lazyMethodGroups = true || (forceLazyMethodGroups === true);
var printedTypeName = false;
var resolveContext = publicInterface.prototype;
// Group up all the methods by name in preparation for building the method groups
var methodsByName = JSIL.$GroupMethodsByName(methods);
for (var key in methodsByName) {
var methodList = methodsByName[key];
JSIL.$ApplyMemberHiding(typeObject, methodList, resolveContext);
}
var record = function (distance, signature) {
this.distance = distance;
this.signature = signature;
};
var typesHiearchy = JSIL.GetTypeAndBases(typeObject);
for (var key in methodsByName) {
var methodList = methodsByName[key];
var methodName = methodList[0]._descriptor.Name;
var methodEscapedName = methodList[0]._descriptor.EscapedName;
var isStatic = methodList[0]._descriptor.Static;
var signature = methodList[0]._data.signature;
var entriesToSort = [];
for (var i = 0, l = methodList.length; i < l; i++) {
var method = methodList[i];
entriesToSort.push(new record(typesHiearchy.indexOf(method._typeObject), method._data.signature));
}
entriesToSort.sort(function (lhs, rhs) {
return JSIL.CompareValues(lhs.distance, rhs.distance);
});
var entries = [];
var numZeroArgEntries = 0;
for (var i = 0, l = entriesToSort.length; i < l; i++) {
var method = entriesToSort[i];
entries.push(method.signature);
if (method.signature.argumentTypes.length === 0) {
numZeroArgEntries += 1;
}
}
if (numZeroArgEntries > 1) {
throw new Error(
"Method '" + methodName + "' has more than one zero-argument overload"
);
}
var target = isStatic ? publicInterface : publicInterface.prototype;
if (
target.hasOwnProperty(methodEscapedName) &&
(typeof (target[methodEscapedName]) === "function") &&
(target[methodEscapedName].__IsPlaceholder__ !== true)
) {
if (trace) {
console.log("Not overwriting " + typeObject.__FullName__ + "." + methodEscapedName);
}
continue;
}
// We defer construction of the actual method group dispatcher(s) until the first
// time the method is used. This reduces the up-front cost of BuildMethodGroups
// and reduces the amount of memory used for methods that are never invoked via
// dynamic dispatch.
var makeMethodGroupGetter = function (
target, isStatic, renamedMethods, methodName, methodEscapedName, entries
) {
var key = null;
return function GetMethodGroup () {
if (key === null) {
key = JSIL.$MakeMethodGroup(
typeObject, isStatic, target, renamedMethods, methodName, methodEscapedName, entries
);
}
var methodGroupTarget = target[key];
if (methodGroupTarget.__IsMembrane__)
JSIL.DefinePreInitMethodAlias(target, methodEscapedName, methodGroupTarget);
return methodGroupTarget;
};
};
if (trace) {
console.log(typeObject.__FullName__ + "[" + methodEscapedName + "] = ", getter);
}
if (active) {
var getter = makeMethodGroupGetter(
target, isStatic, renamedMethods, methodName, methodEscapedName, entries
);
if (lazyMethodGroups) {
JSIL.SetLazyValueProperty(
target, methodEscapedName, getter
);
} else {
JSIL.SetValueProperty(
target, methodEscapedName, getter()
);
}
}
}
};
JSIL.BuildTypeList = function (type, publicInterface) {
var myTypeId = type.__TypeId__;
var typeList = type.__AssignableTypes__ = {};
var context = type.__Context__;
var toVisit = [];
var current = type;
while ((typeof (current) === "object") && (current !== null)) {
toVisit.push(current);
current = current.__BaseType__;
}
while (toVisit.length > 0) {
current = toVisit.shift();
var id = current.__TypeId__;
typeList[id] = true;
if (typeof(current.__AssignableFromTypes__) !== "undefined")
current.__AssignableFromTypes__[myTypeId] = true;
var interfaces = current.__Interfaces__;
if (JSIL.IsArray(interfaces)) {
for (var i = 0; i < interfaces.length; i++) {
var ifaceRef = interfaces[i];
// This should have already generated a warning in FixupInterfaces.
if (ifaceRef === null)
continue;
var iface = JSIL.ResolveTypeReference(ifaceRef, context)[1];
toVisit.push(iface);
}
}
}
};
$jsilcore.cctorKeys = ["_cctor", "_cctor2", "_cctor3", "_cctor4", "_cctor5"];
JSIL.InitializeType = function (type) {
var classObject = type, typeObject = type;
if (typeof (type) === "undefined")
JSIL.RuntimeError("Type is null");
else if (typeof (type.__PublicInterface__) !== "undefined")
classObject = type.__PublicInterface__;
else if (typeof (type.__Type__) === "object")
typeObject = type.__Type__;
else
return;
if (typeObject.__TypeInitialized__ || false)
return;
// Not entirely correct, but prevents recursive type initialization
typeObject.__TypeInitialized__ = true;
if (typeObject.__IsClosed__) {
var forceLazyMethodGroups = false;
// We need to ensure that method groups for BCL classes are always lazy
// because otherwise, initializing the method groups may rely on the classes themselves
if (typeObject.__FullName__.indexOf("System.") === 0)
forceLazyMethodGroups = true;
if (typeObject.IsInterface !== true) {
JSIL.$CreateMethodMembranes(typeObject, classObject);
JSIL.$BuildMethodGroups(typeObject, classObject, forceLazyMethodGroups);
}
JSIL.InitializeFields(classObject, typeObject);
JSIL.InstantiateProperties(classObject, typeObject);
if (typeObject.IsInterface !== true) {
JSIL.QueueTypeInitializer(typeObject, function () {
JSIL.FixupInterfaces(classObject, typeObject);
});
JSIL.RebindRawMethods(classObject, typeObject);
}
if (!typeObject.__IsStatic__) {
JSIL.BuildTypeList(typeObject, classObject);
}
if (
classObject.prototype &&
(typeof (classObject.prototype) === "object") &&
// HACK: We need to use a special implementation for System.Object.MemberwiseClone,
// since when called explicitly it acts 'virtually' (conforms to the instance type)
// (issue #146)
(typeObject.__FullName__ !== "System.Object")
) {
JSIL.SetLazyValueProperty(
classObject.prototype, "MemberwiseClone", function () {
return JSIL.$MakeMemberwiseCloner(typeObject, classObject);
}
);
}
if (classObject.__PreInitMembrane__)
classObject.__PreInitMembrane__.maybeInit();
if (classObject.prototype && classObject.prototype.__PreInitMembrane__)
classObject.prototype.__PreInitMembrane__.maybeInit();
} else {
// console.log("Type '" + typeObject.__FullName__ + "' is open so not initializing");
}
// Any closed forms of the type, if it's an open type, should be initialized too.
if (typeof (typeObject.__OfCache__) !== "undefined") {
var oc = typeObject.__OfCache__;
for (var k in oc) {
if (!oc.hasOwnProperty(k))
continue;
JSIL.InitializeType(oc[k]);
}
}
if (
(typeof (type.__BaseType__) !== "undefined") &&
(type.__BaseType__ !== null)
) {
JSIL.InitializeType(type.__BaseType__);
}
};
JSIL.$InvokeStaticConstructor = function (staticConstructor, typeObject, classObject) {
if (JSIL.ThrowOnStaticCctorError) {
staticConstructor.call(classObject);
} else {
try {
staticConstructor.call(classObject);
} catch (e) {
typeObject.__StaticConstructorError__ = e;
JSIL.Host.warning("Unhandled exception in static constructor for type " + JSIL.GetTypeName(typeObject) + ":");
JSIL.Host.warning(e);
}
}
}
JSIL.RunStaticConstructors = function (classObject, typeObject) {
var base = typeObject.__BaseType__;
if (base && base.__PublicInterface__)
JSIL.RunStaticConstructors(base.__PublicInterface__, base);
JSIL.InitializeType(typeObject);
if (typeObject.__RanCctors__)
return;
typeObject.__RanCctors__ = true;
// Run any queued initializers for the type
var ti = typeObject.__Initializers__ || $jsilcore.ArrayNull;
while (ti.length > 0) {
var initializer = ti.unshift();
if (typeof (initializer) === "function")
initializer(classObject);
};
// If the type is closed, invoke its static constructor(s)
for (var i = 0; i < $jsilcore.cctorKeys.length; i++) {
var key = $jsilcore.cctorKeys[i];
var cctor = classObject[key];
if (typeof (cctor) === "function")
JSIL.$InvokeStaticConstructor(cctor, typeObject, classObject);
}
};
JSIL.InitializeFields = function (classObject, typeObject) {
var typeObjects = [];
var to = typeObject;
while (to) {
typeObjects.push(to);
to = to.__BaseType__;
}
// Run the initializers in reverse order, so we start with the base class
// and work our way up, just in case derived initializers overwrite stuff
// that was put in place by base initializers.
for (var i = typeObjects.length - 1; i >= 0; i--) {
var to = typeObjects[i];
var fi = to.__FieldInitializers__;
if (fi) {
for (var j = 0, l = fi.length; j < l; j++)
fi[j](classObject, to.__PublicInterface__, typeObject, to);
}
}
}
JSIL.ShadowedTypeWarning = function (fullName) {
JSIL.Host.abort(new Error("Type " + fullName + " is shadowed by another type of the same name."));
};
JSIL.DuplicateDefinitionWarning = function (fullName, isPublic, definedWhere, inAssembly) {
var message = (isPublic ? "Public" : "Private") + " type '" + fullName + "' is already defined";
if (inAssembly)
message += " in assembly '" + inAssembly + "'";
if (definedWhere && (definedWhere !== null)) {
message += ".\r\nPreviously defined at:\r\n ";
message += definedWhere.join("\r\n ");
}
JSIL.Host.abort(new Error(message));
};
JSIL.GetFunctionName = function (fn) {
return fn.name || fn.__name__ || "unknown";
};
JSIL.ApplyExternals = function (publicInterface, typeObject, fullName) {
var queue = JSIL.ExternalsQueue[fullName];
if (JSIL.IsArray(queue)) {
while (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
var externals = JSIL.AllImplementedExternals[fullName];
var instancePrefix = "instance$";
var rawSuffix = "$raw";
var constantSuffix = "$constant";
var hasPrototype = typeof (publicInterface.prototype) === "object";
var prototype = hasPrototype ? publicInterface.prototype : null;
for (var k in externals) {
if (!externals.hasOwnProperty(k))
continue;
if (k === "__IsInitialized__")
continue;
var target = publicInterface;
var key = k;
var isRaw = false, isStatic;
if (key.indexOf(instancePrefix) === 0) {
isStatic = false;
if (hasPrototype) {
key = key.replace(instancePrefix, "");
target = prototype;
} else {
JSIL.Host.warning("Type '" + fullName + "' has no prototype to apply instance externals to.");
continue;
}
} else {
isStatic = true;
}
if (key.indexOf(rawSuffix) > 0) {
key = key.replace(rawSuffix, "");
isRaw = true;
}
if (key.indexOf(constantSuffix) > 0) {
JSIL.SetValueProperty(target, key.replace(constantSuffix, ""), externals[k]);
continue;
}
var external = externals[k];
if (!Array.isArray(external))
continue;
var member = external[0];
var value = external[1];
if (member !== null) {
if (Object.getPrototypeOf(member) !== JSIL.MemberRecord.prototype)
JSIL.RuntimeError("Invalid prototype");
typeObject.__Members__.push(member);
}
if (isRaw) {
var rawRecord = new JSIL.RawMethodRecord(key, isStatic);
typeObject.__RawMethods__.push(rawRecord);
}
JSIL.SetValueProperty(target, key, value);
}
if (externals) {
externals.__IsInitialized__ = true;
} else {
JSIL.AllImplementedExternals[fullName] = {
__IsInitialized__: true
};
}
};
JSIL.MakeExternalType = function (fullName, isPublic) {
if (typeof (isPublic) === "undefined")
JSIL.Host.abort(new Error("Must specify isPublic"));
var assembly = $private;
var state = {
hasValue: false
};
var getter = function GetExternalType () {
if (state.hasValue)
return state.value;
else
JSIL.Host.abort(new Error("The external type '" + fullName + "' has not been implemented."));
};
var setter = function SetExternalType (newValue) {
state.value = newValue;
state.hasValue = true;
};
var definition = {
get: getter, set: setter,
configurable: true, enumerable: true
};
var privateName = JSIL.ResolveName(assembly, fullName, false);
if (!privateName.exists())
privateName.define(definition);
if (isPublic) {
var publicName = JSIL.ResolveName(JSIL.GlobalNamespace, fullName, true);
if (!publicName.exists())
publicName.define(definition);
}
};
JSIL.GetCorlib = function () {
return JSIL.GetAssembly("mscorlib", true) || $jsilcore;
};
$jsilcore.$GetRuntimeType = function () {
// Initializing System.Object forms a cyclical dependency through RuntimeType.
return JSIL.$GetSpecialType("System.RuntimeType").typeObject;
};
JSIL.$MakeTypeObject = function (fullName) {
var runtimeType = $jsilcore.$GetRuntimeType();
var result = Object.create(runtimeType.__PublicInterface__.prototype);
return result;
};
JSIL.MakeStaticClass = function (fullName, isPublic, genericArguments, initializer) {
if (typeof (isPublic) === "undefined")
JSIL.Host.abort(new Error("Must specify isPublic"));
var assembly = $private;
var localName = JSIL.GetLocalName(fullName);
var callStack = null;
if (typeof (printStackTrace) === "function")
callStack = printStackTrace();
var memberBuilder = new JSIL.MemberBuilder($private);
var attributes = memberBuilder.attributes;
var typeObject, staticClassObject;
var creator = function CreateStaticClassObject () {
typeObject = JSIL.$MakeTypeObject(fullName);
JSIL.SetValueProperty(typeObject, "__Context__", assembly);
JSIL.SetValueProperty(typeObject, "__FullName__", fullName);
JSIL.SetValueProperty(typeObject, "__ShortName__", localName);
JSIL.SetValueProperty(typeObject, "__BaseType__", null);
typeObject.__ReflectionCache__ = null;
typeObject.__CallStack__ = callStack;
typeObject.__InheritanceDepth__ = 1;
typeObject.__IsStatic__ = true;
typeObject.__Properties__ = [];
typeObject.__Initializers__ = [];
typeObject.__Interfaces__ = [];
typeObject.__Members__ = [];
typeObject.__ExternalMethods__ = [];
typeObject.__RenamedMethods__ = {};
typeObject.__RawMethods__ = [];
typeObject.__TypeInitialized__ = false;
JSIL.FillTypeObjectGenericArguments(typeObject, genericArguments);
typeObject.__Attributes__ = attributes;
typeObject.IsInterface = false;
staticClassObject = JSIL.CreateSingletonObject(JSIL.StaticClassPrototype);
staticClassObject.__Type__ = typeObject;
var typeId = JSIL.AssignTypeId(assembly, fullName);
JSIL.SetTypeId(typeObject, staticClassObject, typeId);
JSIL.SetValueProperty(typeObject, "__PublicInterface__", staticClassObject);
if (typeObject.__GenericArguments__.length > 0) {
staticClassObject.Of$NoInitialize = $jsilcore.$MakeOf$NoInitialize(staticClassObject);
staticClassObject.Of = $jsilcore.$MakeOf(staticClassObject);
typeObject.__IsClosed__ = false;
typeObject.__OfCache__ = {};
} else {
typeObject.__IsClosed__ = true;
}
for (var i = 0, l = typeObject.__GenericArguments__.length; i < l; i++) {
var ga = typeObject.__GenericArguments__[i];
var name = new JSIL.Name(ga, fullName);
JSIL.SetValueProperty(staticClassObject, ga, name);
}
JSIL.ApplyExternals(staticClassObject, typeObject, fullName);
JSIL.SetValueProperty(staticClassObject, "toString", function StaticClass_toString () {
return "<" + fullName + " Public Interface>";
});
return staticClassObject;
};
var wrappedInitializer = null;
if (initializer) {
wrappedInitializer = function (to) {
var interfaceBuilder = new JSIL.InterfaceBuilder(assembly, to.__Type__, to);
return initializer(interfaceBuilder);
};
}
JSIL.RegisterName(fullName, assembly, isPublic, creator, wrappedInitializer);
return memberBuilder;
};
JSIL.$ActuallyMakeCastMethods = function (publicInterface, typeObject, specialType) {
if (!typeObject)
JSIL.RuntimeError("Null type object");
if (!publicInterface)
JSIL.RuntimeError("Null public interface");
JSIL.InitializeType(publicInterface);
var castFunction, asFunction, isFunction;
var customCheckOnly = false;
var checkMethod = publicInterface.CheckType || null;
var typeId = typeObject.__TypeId__;
var assignableFromTypes = typeObject.__AssignableFromTypes__ || {};
typeObject.__CastSpecialType__ = specialType;
var typeName = JSIL.GetTypeName(typeObject);
var throwCastError = function (value) {
throw new System.InvalidCastException("Unable to cast object of type '" + JSIL.GetTypeName(JSIL.GetType(value)) + "' to type '" + typeName + "'.");
};
var throwInvalidAsError = function (value) {
throw new System.InvalidCastException("It is invalid to use 'as' to cast values to this type.");
};
var isIEnumerable = typeName.indexOf(".IEnumerable") >= 0;
var isICollection = typeName.indexOf(".ICollection") >= 0;
var isIList = typeName.indexOf(".IList") >= 0;
var isPointer = typeName.indexOf("JSIL.Pointer") === 0;
var isInterface = typeObject.IsInterface || false;
// HACK: Handle casting arrays to IEnumerable by creating an overlay.
if (isIEnumerable || isICollection || isIList) {
checkMethod = function Check_ArrayInterface (value) {
// FIXME: IEnumerable<int>.Is(float[]) will return true.
if (JSIL.IsArray(value))
return true;
// Fallback to default check logic
return false;
};
} else if (isPointer) {
var expectedElementTypeId = typeObject.__GenericArgumentValues__[0].__TypeId__;
checkMethod = function Check_IsPointer (value) {
var isPointer = value.__IsPointer__ || false;
if (isPointer) {
var matches = value.elementType.__TypeId__ === expectedElementTypeId;
return matches;
} else {
return false;
}
};
}
if (checkMethod) {
isFunction = JSIL.CreateNamedFunction(
typeName + ".$Is",
["expression", "bypassCustomCheckMethod"],
"if (!bypassCustomCheckMethod && checkMethod(expression))\r\n" +
" return true;\r\n" +
"if (expression) {\r\n" +
" var expressionTypeId = expression.__ThisTypeId__;\r\n" +
" return (expressionTypeId === typeId) || (!!assignableFromTypes[expressionTypeId]);\r\n" +
"} else\r\n" +
" return false;\r\n",
{
typeId: typeId,
assignableFromTypes: assignableFromTypes,
checkMethod: checkMethod
}
);
} else {
isFunction = JSIL.CreateNamedFunction(
typeName + ".$Is",
["expression"],
"if (expression) {\r\n" +
" var expressionTypeId = expression.__ThisTypeId__;\r\n" +
" return (expressionTypeId === typeId) || (!!assignableFromTypes[expressionTypeId]);\r\n" +
"} else\r\n" +
" return false;\r\n",
{
typeId: typeId,
assignableFromTypes: assignableFromTypes,
}
);
}
if (checkMethod) {
asFunction = JSIL.CreateNamedFunction(
typeName + ".$As",
["expression"],
"if (checkMethod(expression))\r\n" +
" return expression;\r\n" +
"else if (expression) {\r\n" +
" var expressionTypeId = expression.__ThisTypeId__;\r\n" +
" if ((expressionTypeId === typeId) || (!!assignableFromTypes[expressionTypeId]))\r\n" +
" return expression;\r\n" +
"}\r\n\r\n" +
"return null;\r\n",
{
typeId: typeId,
assignableFromTypes: assignableFromTypes,
checkMethod: checkMethod
}
);
} else {
asFunction = JSIL.CreateNamedFunction(
typeName + ".$As",
["expression"],
"if (expression) {\r\n" +
" var expressionTypeId = expression.__ThisTypeId__;\r\n" +
" if ((expressionTypeId === typeId) || (!!assignableFromTypes[expressionTypeId]))\r\n" +
" return expression;\r\n" +
"}\r\n\r\n" +
"return null;\r\n",
{
typeId: typeId,
assignableFromTypes: assignableFromTypes,
}
);
}
castFunction = function Cast (expression) {
if (isFunction(expression))
return expression;
else if (expression === null)
return null;
else
throwCastError(expression);
};
var integerCastFunction = function Cast_Integer (expression) {
if (typeof (expression) === "number") {
var max = publicInterface.MaxValue | 0;
var result = (expression | 0) & max;
return result;
} else if (expression === false) {
return 0;
} else if (expression === true) {
return 1;
} else if (
expression.__ThisType__ &&
expression.__ThisType__.__IsEnum__
) {
return expression.value;
} else
throwCastError(expression);
};
var numericCastFunction = function Cast_Number (expression) {
if (typeof (expression) === "number") {
return expression;
} else if (expression === false) {
return 0;
} else if (expression === true) {
return 1;
} else
throwCastError(expression);
};
var int64CastFunction = function Cast_Int64_Impl (expression) {
if (expression === false)
return System.Int64.Zero;
else if (expression === true)
return System.Int64.One;
else if (typeof (expression) === "number")
return System.Int64.FromNumber(expression);
else if (checkMethod(expression))
return expression;
else
throwCastError(expression);
};
switch (specialType) {
case "enum":
customCheckOnly = true;
asFunction = throwInvalidAsError;
var castCache = [];
var valueToName = typeObject.__ValueToName__;
var populateCastCache = function (value) {
value |= 0;
var name = valueToName[value] || null;
if (name !== null)
return publicInterface[name];
return publicInterface.$MakeValue(value, null);
};
castFunction = function Cast_Enum (value) {
value |= 0;
var result = castCache[value] || null;
if (result === null)
result = castCache[value] = populateCastCache(value);
return result;
};
break;
case "delegate":
var _isFunction = isFunction;
isFunction = function Is_Delegate (expression) {
return _isFunction(expression) || (typeof (expression) === "function");
};
var _asFunction = asFunction;
asFunction = function As_Delegate (expression) {
var result = _asFunction(expression);
if ((result === null) && (typeof (expression) === "function"))
result = expression;
return result;
};
break;
case "array":
// Allow casting array interface overlays back to appropriate array types
var _isFunction = isFunction;
isFunction = function Is_Array (expression) {
return _isFunction(expression) || (
expression &&
expression.$overlayToArray &&
expression.$overlayToArray(typeObject)
);
};
var _asFunction = asFunction;
asFunction = function As_Array (expression) {
var result = _asFunction(expression);
if ((result === null) && (expression && expression.$overlayToArray))
result = expression.$overlayToArray(typeObject);
return result;
};
castFunction = function CastArray (expression) {
if (_isFunction(expression))
return expression;
if (expression && expression.$overlayToArray) {
var overlayArray = expression.$overlayToArray(typeObject);
if (overlayArray)
return overlayArray;
}
throwCastError(expression);
};
break;
case "char":
customCheckOnly = true;
asFunction = throwInvalidAsError;
break;
case "integer":
customCheckOnly = true;
asFunction = throwInvalidAsError;
castFunction = integerCastFunction;
break;
case "number":
customCheckOnly = true;
asFunction = throwCastError;
castFunction = numericCastFunction;
break;
case "int64":
customCheckOnly = true;
asFunction = throwCastError;
castFunction = function Cast_Int64 (expression) {
return int64CastFunction(expression);
};
break;
}
if (checkMethod && customCheckOnly) {
isFunction = checkMethod;
asFunction = function As_Checked (expression) {
if (checkMethod(expression))
return expression;
else
return null;
};
}
if (isIEnumerable || isICollection || isIList) {
var innerAsFunction = asFunction;
var innerCastFunction = castFunction;
var createOverlay = function Overlay_ArrayInterface (value) {
if (JSIL.IsArray(value)) {
var tElement = $jsilcore.System.Object.__Type__;
if (typeObject.__GenericArguments__.length === 1)
tElement = typeObject.__GenericArgumentValues__[0];
var tOverlay = JSIL.ArrayInterfaceOverlay.Of(tElement);
return new tOverlay(value);
}
return value;
};
asFunction = function As_ArrayInterface (value) {
// FIXME: I think the order of these function calls should be reversed.
return createOverlay(innerAsFunction(value));
};
castFunction = function Cast_ArrayInterface (value) {
// FIXME: I think the order of these function calls should be reversed.
return createOverlay(innerCastFunction(value));
};
}
if (isInterface) {
var wrappedFunctions = JSIL.WrapCastMethodsForInterfaceVariance(typeObject, isFunction, asFunction);
isFunction = wrappedFunctions.is;
asFunction = wrappedFunctions.as;
}
return {
Cast: castFunction,
As: asFunction,
Is: isFunction
}
};
JSIL.MakeCastMethods = function (publicInterface, typeObject, specialType) {
var state = null;
var doLazyInitialize = function () {
if (state === null)
state = JSIL.$ActuallyMakeCastMethods(publicInterface, typeObject, specialType);
};
var getIsMethod = function () {
doLazyInitialize();
return state.Is;
}
var getAsMethod = function () {
doLazyInitialize();
return state.As;
}
var getCastMethod = function () {
doLazyInitialize();
return state.Cast;
}
JSIL.SetLazyValueProperty(publicInterface, "$Is", getIsMethod);
JSIL.SetLazyValueProperty(typeObject, "$Is", getIsMethod);
JSIL.SetLazyValueProperty(publicInterface, "$As", getAsMethod);
JSIL.SetLazyValueProperty(typeObject, "$As", getAsMethod);
JSIL.SetLazyValueProperty(publicInterface, "$Cast", getCastMethod);
JSIL.SetLazyValueProperty(typeObject, "$Cast", getCastMethod);
};
JSIL.MakeTypeAlias = function (sourceAssembly, fullName) {
var context = $private;
var tbn = sourceAssembly.$typesByName;
Object.defineProperty(
context.$typesByName, fullName, {
configurable: false,
enumerable: true,
get: function () {
return tbn[fullName];
}
}
);
if (sourceAssembly.__AssemblyId__ === context.__AssemblyId__) {
// HACK: This is a recursive type alias, so don't define the name alias.
// We still want to leave the typesByName logic above intact since the two aliases have separate assembly
// objects, and thus separate typesByName lists, despite sharing an assembly id.
return;
}
var privateName = JSIL.ResolveName(context, fullName, true);
var sourcePrivateName = null;
var getter = function TypeAlias_getter () {
if (!sourcePrivateName)
sourcePrivateName = JSIL.ResolveName(sourceAssembly, fullName, true);
var result = sourcePrivateName.get();
if (!result)
JSIL.RuntimeError("Type alias for '" + fullName + "' points to a nonexistent type");
return result;
};
privateName.setLazy(getter);
};
JSIL.$MakeOptimizedNumericSwitch = function (output, variableName, cases, defaultCase) {
// TODO: For large numbers of cases, do a divide-and-conquer search to reduce number of comparisons, like:
// if (x > b) {
// if (x === c) casec else if (x === d) cased else casedefault
// } else {
// if (x === a) casea else if (x === b) caseb else casedefault
// }
// switch statements appear to generate better code in JS runtimes now. Neat!
var useIfStatements = false;
if (useIfStatements) {
for (var i = 0, l = cases.length; i < l; i++) {
var caseDesc = cases[i];
if (i === 0)
output.push("if (" + variableName + " === " + caseDesc.key + ") {");
else
output.push("} else if (" + variableName + " === " + caseDesc.key + ") {");
output.push(" " + caseDesc.code);
}
if (defaultCase) {
output.push("} else {");
output.push(" " + defaultCase);
}
output.push("}");
} else {
output.push("switch (" + variableName + ") {");
for (var i = 0, l = cases.length; i < l; i++) {
var caseDesc = cases[i];
output.push(" case " + caseDesc.key + ":");
output.push(" " + caseDesc.code);
output.push(" break;");
}
if (defaultCase) {
output.push(" default:");
output.push(" " + defaultCase);
output.push(" break;");
}
output.push("}");
}
};
JSIL.MakeTypeConstructor = function (typeObject, maxConstructorArguments) {
if (typeObject.__IsClosed__ === false) {
return function () {
JSIL.RuntimeError("Cannot create an instance of an open type");
};
}
var ctorClosure = {
typeObject: typeObject,
fieldInitializer: $jsilcore.FunctionNotInitialized,
isTypeInitialized: false
};
var ctorBody = [];
var argumentNames = [];
ctorBody.push("if (!isTypeInitialized) {");
ctorBody.push(" JSIL.RunStaticConstructors(typeObject.__PublicInterface__, typeObject);");
ctorBody.push(" fieldInitializer = JSIL.GetFieldInitializer(typeObject);");
ctorBody.push(" isTypeInitialized = true;");
ctorBody.push("}");
ctorBody.push("");
ctorBody.push("fieldInitializer(this);");
ctorBody.push("");
// Only generate specialized dispatch if we know the number of arguments.
if (typeof (maxConstructorArguments) === "number") {
var numPositionalArguments = maxConstructorArguments | 0;
ctorBody.push("var argc = arguments.length | 0;");
var cases = [
{ key: 0, code: (typeObject.__IsStruct__ ? "return;" : "return this._ctor();") }
];
for (var i = 1; i < (numPositionalArguments + 1); i++)
argumentNames.push("arg" + (i - 1));
for (var i = 1; i < (numPositionalArguments + 1); i++) {
var line = "return this._ctor(";
for (var j = 0, jMax = Math.min(argumentNames.length, i); j < jMax; j++) {
line += argumentNames[j];
if (j == jMax - 1)
line += ");";
else
line += ", ";
}
cases.push({ key: i, code: line });
}
JSIL.$MakeOptimizedNumericSwitch(
ctorBody, "argc", cases,
"JSIL.RuntimeError('Too many arguments passed to constructor; expected 0 - " + maxConstructorArguments + ", got ' + arguments.length);"
);
} else if (typeObject.__IsStruct__) {
ctorBody.push("if (arguments.length === 0)");
ctorBody.push(" return;");
ctorBody.push("else");
ctorBody.push(" return this._ctor.apply(this, arguments);");
} else {
ctorBody.push("return this._ctor.apply(this, arguments);");
}
var result = JSIL.CreateNamedFunction(
typeObject.__FullName__, argumentNames,
ctorBody.join("\r\n"),
ctorClosure
);
return result;
};
JSIL.MakeType = function (typeArgs, initializer) {
var baseType = typeArgs.BaseType || null;
var fullName = typeArgs.Name || null;
var isReferenceType = Boolean(typeArgs.IsReferenceType);
var isPublic = Boolean(typeArgs.IsPublic);
var genericArguments = typeArgs.GenericParameters || $jsilcore.ArrayNull;
var maxConstructorArguments = typeArgs.MaximumConstructorArguments;
if (typeof (isPublic) === "undefined")
JSIL.Host.abort(new Error("Must specify isPublic"));
var assembly = $private;
var localName = JSIL.GetLocalName(fullName);
var memberBuilder = new JSIL.MemberBuilder($private);
var attributes = memberBuilder.attributes;
var stack = null;
if (typeof (printStackTrace) === "function")
stack = printStackTrace();
var typeObject, staticClassObject;
var createTypeObject = function CreateTypeObject () {
var runtimeType;
runtimeType = $jsilcore.$GetRuntimeType(assembly, fullName);
// We need to make the type object we're constructing available early on, in order for
// recursive generic base classes to work.
typeObject = JSIL.$GetSpecialType(fullName).typeObject;
if (!typeObject)
typeObject = JSIL.CreateSingletonObject(runtimeType);
// Needed for basic bookkeeping to function correctly.
typeObject.__Context__ = assembly;
JSIL.SetValueProperty(typeObject, "__FullName__", fullName);
JSIL.SetValueProperty(typeObject, "__ShortName__", localName);
typeObject.__ReflectionCache__ = null;
// Without this, the generated constructor won't behave correctly for 0-argument construction
typeObject.__IsStruct__ = !isReferenceType;
var ctorFunction = null;
if (genericArguments && genericArguments.length) {
ctorFunction = function OpenType () {
JSIL.RuntimeError("Cannot create an instance of open generic type '" + fullName + "'");
};
} else {
ctorFunction = JSIL.MakeTypeConstructor(typeObject, maxConstructorArguments);
}
staticClassObject = ctorFunction;
JSIL.SetValueProperty(typeObject, "__PublicInterface__", staticClassObject);
JSIL.SetValueProperty(staticClassObject, "__Type__", typeObject);
typeObject.__MaxConstructorArguments__ = maxConstructorArguments;
var typeId = JSIL.AssignTypeId(assembly, fullName);
JSIL.SetTypeId(typeObject, staticClassObject, typeId);
// FIXME: This should probably be a per-assembly dictionary to work right in the case of name collisions.
$jsilcore.InFlightObjectConstructions[fullName] = {
fullName: fullName,
typeObject: typeObject,
publicInterface: staticClassObject
};
if (fullName !== "System.Object") {
JSIL.SetValueProperty(typeObject, "__BaseType__", JSIL.ResolveTypeReference(baseType, assembly)[1]);
var baseTypeName = typeObject.__BaseType__.__FullName__ || baseType.toString();
var baseTypeInterfaces = typeObject.__BaseType__.__Interfaces__ || $jsilcore.ArrayNull;
// HACK: We can't do this check before creating the constructor, because recursion. UGH.
typeObject.__IsStruct__ = typeObject.__IsStruct__ && (baseTypeName === "System.ValueType");
typeObject.__InheritanceDepth__ = (typeObject.__BaseType__.__InheritanceDepth__ || 0) + 1;
typeObject.__Interfaces__ = Array.prototype.slice.call(baseTypeInterfaces);
typeObject.__ExternalMethods__ = Array.prototype.slice.call(typeObject.__BaseType__.__ExternalMethods__ || $jsilcore.ArrayNull);
typeObject.__RenamedMethods__ = JSIL.CreateDictionaryObject(typeObject.__BaseType__.__RenamedMethods__ || null);
} else {
JSIL.SetValueProperty(typeObject, "__BaseType__", null);
typeObject.__IsStruct__ = false;
typeObject.__InheritanceDepth__ = 0;
typeObject.__Interfaces__ = [];
typeObject.__ExternalMethods__ = [];
typeObject.__RenamedMethods__ = JSIL.CreateDictionaryObject(null);
}
typeObject.__IsArray__ = false;
typeObject.__IsNullable__ = fullName.indexOf("System.Nullable`1") === 0;
typeObject.__FieldList__ = $jsilcore.ArrayNotInitialized;
typeObject.__FieldInitializer__ = $jsilcore.FunctionNotInitialized;
typeObject.__MemberCopier__ = $jsilcore.FunctionNotInitialized;
typeObject.__Comparer__ = $jsilcore.FunctionNotInitialized;
typeObject.__Marshaller__ = $jsilcore.FunctionNotInitialized;
typeObject.__Unmarshaller__ = $jsilcore.FunctionNotInitialized;
typeObject.__UnmarshalConstructor__ = $jsilcore.FunctionNotInitialized;
typeObject.__ElementProxyConstructor__ = $jsilcore.FunctionNotInitialized;
typeObject.__Properties__ = [];
typeObject.__Initializers__ = [];
typeObject.__TypeInitialized__ = false;
typeObject.__IsNativeType__ = false;
typeObject.__AssignableTypes__ = null;
typeObject.__AssignableFromTypes__ = {};
JSIL.SetValueProperty(typeObject, "__IsReferenceType__", isReferenceType);
typeObject.__LockCount__ = 0;
typeObject.__Members__ = [];
// FIXME: I'm not sure this is right. See InheritedExternalStubError.cs
typeObject.__Attributes__ = attributes;
typeObject.__RanCctors__ = false;
typeObject.__RawMethods__ = [];
JSIL.FillTypeObjectGenericArguments(typeObject, genericArguments);
typeObject.IsInterface = false;
typeObject.__IsValueType__ = !isReferenceType;
typeObject.__IsByRef__ = false;
typeObject.__CustomPacking__ = typeArgs.Pack;
// Packings of 16 or more are silently ignored by the windows .NET runtime.
if (typeObject.__CustomPacking__ >= 16)
typeObject.__CustomPacking__ = 0;
typeObject.__CustomSize__ = typeArgs.SizeBytes;
typeObject.__ExplicitLayout__ = typeArgs.ExplicitLayout;
typeObject.__SequentialLayout__ = typeArgs.SequentialLayout;
// Lazily initialize struct's native size and alignment properties
if (typeObject.__IsStruct__) {
JSIL.SetLazyValueProperty(
typeObject, "__NativeAlignment__",
JSIL.ComputeNativeAlignmentOfStruct.bind(null, typeObject)
);
JSIL.SetLazyValueProperty(
typeObject, "__NativeSize__",
JSIL.ComputeNativeSizeOfStruct.bind(null, typeObject)
);
JSIL.SetLazyValueProperty(
typeObject, "__IsUnion__",
function () {
JSIL.GetFieldList(typeObject);
return typeObject.__IsUnion_BackingStore__;
}
);
}
if (stack !== null)
typeObject.__CallStack__ = stack;
var inited = false;
JSIL.SetValueProperty(staticClassObject, "toString", function TypePublicInterface_ToString () {
return "<" + fullName + " Public Interface>";
});
JSIL.SetValueProperty(typeObject, "toString", function Type_ToString () {
return JSIL.GetTypeName(this, true);
});
staticClassObject.prototype = JSIL.MakeProto(baseType, typeObject, fullName, false, assembly);
if (typeObject.__GenericArguments__.length > 0) {
staticClassObject.Of$NoInitialize = $jsilcore.$MakeOf$NoInitialize(staticClassObject);
staticClassObject.Of = $jsilcore.$MakeOf(staticClassObject);
typeObject.__IsClosed__ = false;
typeObject.__OfCache__ = {};
} else {
typeObject.__IsClosed__ = (baseType.__IsClosed__ !== false);
}
if (fullName === "System.Object") {
typeObject._IsAssignableFrom = function (typeOfValue) {
return true;
};
} else {
typeObject._IsAssignableFrom = function (typeOfValue) {
return typeOfValue.__AssignableTypes__[this.__TypeId__] === true;
};
}
for (var i = 0, l = typeObject.__GenericArguments__.length; i < l; i++) {
var ga = typeObject.__GenericArguments__[i];
var name = new JSIL.Name(ga, fullName);
var escapedKey = JSIL.EscapeName(ga);
JSIL.SetValueProperty(staticClassObject, escapedKey, name);
}
JSIL.ApplyExternals(staticClassObject, typeObject, fullName);
JSIL.MakeCastMethods(staticClassObject, typeObject, null);
delete $jsilcore.InFlightObjectConstructions[fullName];
return staticClassObject;
};
var state = null;
var getTypeObject = function GetTypeObject () {
if (state === null) {
state = createTypeObject();
}
return state;
};
var wrappedInitializer = null;
if (initializer) {
var makeWrappedInitializer = function (i, a) {
return function (to) {
var interfaceBuilder = new JSIL.InterfaceBuilder(a, to.__Type__, to);
return i(interfaceBuilder);
};
};
wrappedInitializer = makeWrappedInitializer(initializer, assembly);
}
JSIL.RegisterName(fullName, assembly, isPublic, getTypeObject, wrappedInitializer);
// Goddamn V8 closure leaks UGH JESUS
initializer = null;
wrappedInitializer = null;
return memberBuilder;
};
JSIL.MakeClass = function (baseType, fullName, isPublic, genericArguments, initializer) {
var typeArgs = {
BaseType: baseType,
Name: fullName,
GenericParameters: genericArguments,
IsReferenceType: true,
IsPublic: isPublic,
ConstructorAcceptsManyArguments: true
};
return JSIL.MakeType(typeArgs, initializer);
};
JSIL.MakeStruct = function (baseType, fullName, isPublic, genericArguments, initializer) {
var typeArgs = {
BaseType: baseType,
Name: fullName,
GenericParameters: genericArguments,
IsReferenceType: false,
IsPublic: isPublic,
ConstructorAcceptsManyArguments: true
};
return JSIL.MakeType(typeArgs, initializer);
};
JSIL.MakeInterface = function (fullName, isPublic, genericArguments, initializer, interfaces) {
var assembly = $private;
var localName = JSIL.GetLocalName(fullName);
if (typeof (initializer) !== "function") {
JSIL.RuntimeError("Non-function initializer passed to MakeInterface");
}
var callStack = null;
if (typeof (printStackTrace) === "function")
callStack = printStackTrace();
var memberBuilder = new JSIL.MemberBuilder(fullName);
var attributes = memberBuilder.attributes;
var creator = function CreateInterface () {
var publicInterface = new Object();
JSIL.SetValueProperty(publicInterface, "toString", function InterfacePublicInterface_ToString () {
return "<" + fullName + " Public Interface>";
});
var typeObject = JSIL.$MakeTypeObject(fullName);
publicInterface.prototype = null;
publicInterface.__Type__ = typeObject;
JSIL.SetValueProperty(typeObject, "__PublicInterface__", publicInterface);
JSIL.SetValueProperty(typeObject, "__BaseType__", null);
typeObject.__CallStack__ = callStack;
JSIL.SetTypeId(typeObject, publicInterface, JSIL.AssignTypeId(assembly, fullName));
typeObject.__Members__ = [];
typeObject.__RenamedMethods__ = {};
JSIL.SetValueProperty(typeObject, "__ShortName__", localName);
typeObject.__Context__ = $private;
JSIL.SetValueProperty(typeObject, "__FullName__", fullName);
typeObject.__TypeInitialized__ = false;
if (interfaces && interfaces.length) {
// FIXME: This seems wrong.
// JSIL.$CopyInterfaceMethods(interfaces, publicInterface);
}
JSIL.FillTypeObjectGenericArguments(typeObject, genericArguments);
JSIL.SetValueProperty(typeObject, "__IsReferenceType__", true);
typeObject.__AssignableTypes__ = null;
typeObject.IsInterface = true;
typeObject.__Attributes__ = attributes;
typeObject.__Interfaces__ = interfaces || [];
var interfaceBuilder = new JSIL.InterfaceBuilder(assembly, typeObject, publicInterface, "interface");
initializer(interfaceBuilder);
if (typeObject.__GenericArguments__.length > 0) {
publicInterface.Of$NoInitialize = $jsilcore.$MakeOf$NoInitialize(publicInterface);
publicInterface.Of = $jsilcore.$MakeOf(publicInterface);
typeObject.__IsClosed__ = false;
typeObject.__OfCache__ = {};
} else {
typeObject.__IsClosed__ = true;
typeObject.__AssignableFromTypes__ = {};
}
typeObject._IsAssignableFrom = function (typeOfValue) {
return typeOfValue.__AssignableTypes__[this.__TypeId__] === true;
};
JSIL.MakeCastMethods(publicInterface, typeObject, "interface");
return publicInterface;
};
JSIL.RegisterName(fullName, $private, isPublic, creator);
return memberBuilder;
};
JSIL.EnumValue = function (m) {
JSIL.RuntimeError("Cannot create an abstract instance of an enum");
};
JSIL.EnumValue.prototype = JSIL.CreatePrototypeObject(null);
JSIL.EnumValue.prototype.GetType = function () {
return this.__ThisType__;
};
JSIL.EnumValue.prototype.GetHashCode = function () {
return this.value;
};
JSIL.EnumValue.prototype.toString = function () {
if (!this.stringified) {
if (this.isFlags) {
var enumType = this.__ThisType__;
var publicInterface = enumType.__PublicInterface__;
var names = enumType.__Names__;
var result = [];
for (var i = 0, l = names.length; i < l; i++) {
var name = names[i];
var nameValue = publicInterface[name].value;
if (nameValue === this.value) {
result.push(name);
} else if (nameValue) {
if ((this.value & nameValue) === nameValue)
result.push(name);
}
}
if (result.length === 0)
this.stringified = this.value.toString();
else
this.stringified = result.join(", ");
} else {
this.stringified = this.value.toString();
}
}
return this.stringified;
};
JSIL.EnumValue.prototype.valueOf = function () {
return this.value;
}
/* old arglist: fullName, isPublic, members, isFlagsEnum */
JSIL.MakeEnum = function (_descriptor, _members) {
var descriptor, members;
if (arguments.length !== 2) {
descriptor = {
FullName: arguments[0],
IsPublic: arguments[1],
IsFlags: arguments[3] || false,
BaseType: $jsilcore.TypeRef("System.Int32")
};
members = arguments[2];
} else {
descriptor = _descriptor;
members = _members;
}
if (!descriptor || !members)
JSIL.RuntimeError("Invalid arguments");
var localName = JSIL.GetLocalName(descriptor.FullName);
var callStack = null;
if (typeof (printStackTrace) === "function")
callStack = printStackTrace();
var context = $private;
var typeObject, publicInterface;
var creator = function CreateEnum () {
publicInterface = function Enum__ctor () {
JSIL.RuntimeError("Cannot construct an instance of an enum");
};
typeObject = JSIL.$MakeTypeObject(descriptor.FullName);
publicInterface.prototype = JSIL.CreatePrototypeObject($jsilcore.System.Enum.prototype);
publicInterface.__Type__ = typeObject;
JSIL.SetValueProperty(typeObject, "__PublicInterface__", publicInterface);
JSIL.SetValueProperty(typeObject, "__BaseType__", $jsilcore.System.Enum.__Type__);
typeObject.__Context__ = context;
typeObject.__CallStack__ = callStack;
JSIL.SetValueProperty(typeObject, "__FullName__", descriptor.FullName);
typeObject.__IsArray__ = false;
typeObject.__IsEnum__ = true;
typeObject.__IsByRef__ = false;
typeObject.__IsValueType__ = true;
JSIL.SetValueProperty(typeObject, "__IsReferenceType__", false);
typeObject.__IsClosed__ = true;
typeObject.__TypeInitialized__ = false;
if (descriptor.BaseType) {
typeObject.__StorageType__ = JSIL.ResolveTypeReference(descriptor.BaseType)[1];
} else {
typeObject.__StorageType__ = $jsilcore.System.Int32.__Type__;
}
var typeId = JSIL.AssignTypeId(context, descriptor.FullName);
JSIL.SetValueProperty(typeObject, "__TypeId__", typeId);
JSIL.SetValueProperty(publicInterface, "__TypeId__", typeId);
typeObject.__IsFlagsEnum__ = descriptor.IsFlags;
// HACK to ensure that enum types implement the interfaces System.Enum does.
typeObject.__Interfaces__ = typeObject.__BaseType__.__Interfaces__;
var enumTypeId = JSIL.AssignTypeId($jsilcore, "System.Enum");
typeObject.__AssignableTypes__ = {};
typeObject.__AssignableTypes__[typeObject.__TypeId__] = true;
typeObject.__AssignableTypes__[enumTypeId] = true;
typeObject.__AssignableFromTypes__ = {};
typeObject.__AssignableFromTypes__[typeObject.__TypeId__] = true;
typeObject.__ValueToName__ = [];
typeObject.__Names__ = [];
JSIL.SetValueProperty(typeObject, "toString", function Type_ToString () {
return JSIL.GetTypeName(this, true);
});
JSIL.SetValueProperty(publicInterface, "toString", function Type_ToString () {
return "<" + descriptor.FullName + " Public Interface>";
});
typeObject.Of$NoInitialize = function () {
return typeObject;
};
typeObject.Of = function () {
return typeObject;
};
if (descriptor.IsFlags) {
publicInterface.$Flags = function FlagsEnum_Flags () {
var argc = arguments.length;
var resultValue = 0;
for (var i = 0; i < argc; i++) {
var flagName = arguments[i];
resultValue = resultValue | publicInterface[flagName].value;
}
return publicInterface.$MakeValue(resultValue, null);
};
} else {
publicInterface.$Flags = function Enum_Flags () {
JSIL.RuntimeError("Enumeration is not a flags enumeration.");
};
}
typeObject.CheckType = function Enum_CheckType (v) {
if (v.__ThisType__ === typeObject)
return true;
return false;
};
var valueType = publicInterface.$Value = JSIL.CreateNamedFunction(
descriptor.FullName,
["value", "name"],
"this.value = value;\r\n" +
"this.stringified = this.name = name;\r\n"
);
var valueProto = valueType.prototype = publicInterface.prototype;
// Copy members from EnumValue.prototype since we have to derive from System.Enum
for (var k in JSIL.EnumValue.prototype) {
JSIL.MakeIndirectProperty(valueProto, k, JSIL.EnumValue.prototype);
}
JSIL.SetValueProperty(
valueProto, "isFlags", descriptor.IsFlags
);
JSIL.SetValueProperty(
valueProto, "__ThisType__", typeObject
);
JSIL.SetValueProperty(
valueProto, "__ThisTypeId__", typeObject.__TypeId__
);
// Because there's no way to change the behavior of ==,
// we need to ensure that all calls to $MakeValue for a given value
// return the same instance.
// FIXME: Memory leak! Weak references would help here, but TC39 apparently thinks
// hiding GC behavior from developers is more important than letting them control
// memory usage.
var valueCache = JSIL.CreateDictionaryObject(null);
var fixedUpEnumInterfaces = false;
var maybeFixUpInterfaces = function () {
// HACK: Letting System.Enum's interfaces get fixed up normally causes a cycle.
if (!fixedUpEnumInterfaces) {
fixedUpEnumInterfaces = true;
if (!$jsilcore.CanFixUpEnumInterfaces) {
$jsilcore.CanFixUpEnumInterfaces = true;
JSIL.FixupInterfaces($jsilcore.System.Enum, $jsilcore.System.Enum.__Type__);
JSIL.RunStaticConstructors(publicInterface, typeObject);
JSIL.FixupInterfaces(publicInterface, typeObject);
}
}
};
publicInterface.$MakeValue = function (value, name) {
maybeFixUpInterfaces();
var result = valueCache[value];
if (!result)
result = valueCache[value] = new valueType(value, name);
return result;
};
return publicInterface;
};
var initializer = function ($) {
var asm = JSIL.GetAssembly("mscorlib", true) || $jsilcore;
if (!asm)
JSIL.RuntimeError("mscorlib not found!");
var enumType = JSIL.GetTypeFromAssembly(asm, "System.Enum");
var prototype = JSIL.CreatePrototypeObject(enumType.__PublicInterface__.prototype);
JSIL.SetValueProperty(prototype, "__BaseType__", enumType);
JSIL.SetValueProperty(prototype, "__ShortName__", localName);
JSIL.SetValueProperty(prototype, "__FullName__", descriptor.FullName);
JSIL.SetValueProperty($, "__BaseType__", enumType);
$.prototype = prototype;
var ib = new JSIL.InterfaceBuilder(context, typeObject, publicInterface);
for (var key in members) {
if (!members.hasOwnProperty(key))
continue;
var value = members[key];
if (typeof (value) === "function")
continue;
value = Math.floor(value);
$.__Type__.__Names__.push(key);
$.__Type__.__ValueToName__[value] = key;
var makeGetter = function (key, value) {
return function () {
return $.$MakeValue(value, key);
}
};
JSIL.SetLazyValueProperty($, key, makeGetter(key, value));
var memberDescriptor = ib.ParseDescriptor({Public: true, Static: true}, key);
var mb = new JSIL.MemberBuilder(context);
var data = {
fieldType: $.__Type__,
constant: value
};
ib.PushMember("FieldInfo", memberDescriptor, data, mb);
}
// FIXME: This is doing FixupInterfaces on Enum every time instead of on the specific enum type.
// Should be harmless, but...?
// JSIL.FixupInterfaces(enumType.__PublicInterface__, enumType);
JSIL.MakeCastMethods($, $.__Type__, "enum");
};
JSIL.RegisterName(descriptor.FullName, $private, descriptor.IsPublic, creator, initializer);
};
JSIL.MakeInterfaceMemberGetter = function (thisReference, name) {
return function GetInterfaceMember () {
return thisReference[name];
};
};
JSIL.CheckDerivation = function (haystack, needle) {
var proto = haystack;
while (proto !== null) {
if (proto === needle)
return true;
if (typeof (proto) !== "object")
return false;
proto = Object.getPrototypeOf(proto);
}
return false;
};
JSIL.IsArray = function (value) {
if (value === null)
return false;
else if (Array.isArray(value))
return true;
if (JSIL.IsTypedArray(value))
return true;
return false;
};
JSIL.AreTypedArraysSupported = function () {
return (typeof (ArrayBuffer) !== "undefined");
}
JSIL.IsTypedArray = function (value) {
if ((typeof (value) === "object") && value && value.buffer) {
if (typeof (ArrayBuffer) !== "undefined") {
if (Object.getPrototypeOf(value.buffer) === ArrayBuffer.prototype)
return true;
}
}
return false;
}
JSIL.IsSystemArray = function (value) {
if (JSIL.IsArray(value))
return true;
if (!value)
return false;
var valueType = value.__ThisType__;
if (valueType)
return valueType.__IsArray__;
else
return JSIL.GetType(value).__IsArray__;
};
JSIL.GetBaseType = function (typeObject) {
var result = typeObject.__BaseType__;
if (typeof (result) === "string")
result = JSIL.ResolveName(typeObject.__Context__, result, true);
if ((typeof (result) !== "undefined") && (typeof (result.get) === "function"))
result = result.get();
if ((typeof (result) !== "undefined") && (typeof (result.__Type__) === "object"))
result = result.__Type__;
return result;
};
JSIL.GetType = function (value) {
var type = typeof (value);
if (value === null)
return null;
else if (type === "undefined")
return null;
if ((type === "object") || (type === "function")) {
var tt;
if (tt = value.__ThisType__)
return tt;
else if (value.GetType)
return value.GetType();
else if (JSIL.IsTypedArray(value))
return JSIL.$GetTypeForTypedArray(value);
else if (JSIL.IsArray(value))
return System.Array.__Type__;
else
return System.Object.__Type__;
} else if (type === "string") {
return System.String.__Type__;
} else if (type === "number") {
if (value === (value | 0))
return System.Int32.__Type__;
else
return System.Double.__Type__;
} else if (type === "boolean") {
return System.Boolean.__Type__;
} else {
return System.Object.__Type__;
}
};
JSIL.$GetTypeForTypedArray = function (value) {
var proto = Object.getPrototypeOf(value);
var typeName = proto.constructor.name || String(proto.constructor);
var typeKey = $jsilcore.TypedArrayToType[typeName];
if (typeKey) {
// HACK: Construct an array type given the element type we know about for this typed array constructor.
var parsedTypeName = JSIL.ParseTypeName(typeKey);
var elementType = JSIL.GetTypeInternal(parsedTypeName, $jsilcore, true);
var arrayType = System.Array.Of(elementType).__Type__;
return arrayType;
}
// Who knows what happened, just return System.Array.
return System.Array.__Type__;
};
// type may be a a type object, a type public interface, or an instance of a type.
JSIL.GetTypeName = function (type, dotNetTypeToString) {
if (type === null)
return "System.Object";
if (typeof (type) === "string")
return "System.String";
var typeObject = null;
if (type.__PublicInterface__)
typeObject = type;
else if (type.__Type__)
typeObject = type.__Type__;
else if (type.__ThisType__)
typeObject = type.__ThisType__;
if (typeObject) {
var result = typeObject.__FullName__;
// Emulate the exact behavior of Type.ToString in .NET
if (dotNetTypeToString && !typeObject.__IsClosed__) {
result = typeObject.__FullNameWithoutArguments__ || typeObject.__FullName__;
result += "[";
var ga = typeObject.__GenericArguments__;
var gav = typeObject.__GenericArgumentValues__;
for (var i = 0, l = ga.length; i < l; i++) {
if (gav && gav[i]) {
result += gav[i].__ShortName__;
} else {
result += ga[i];
}
if (i < (l - 1))
result += ",";
}
result += "]";
}
return result;
}
var result;
if (typeof (type.prototype) !== "undefined")
result = type.prototype.__FullName__;
if (typeof (result) === "undefined")
result = typeof (type);
if (typeof (result) !== "string")
result = "unknown type";
return result;
};
JSIL.Coalesce = function (lhs, rhs) {
if (lhs == null)
return rhs;
else
return lhs;
};
JSIL.Dynamic.Cast = function (value, expectedType) {
return value;
};
JSIL.$MakeGenericMethodBinder = function (groupDispatcher, methodFullName, genericArgumentCount, argumentCounts) {
var body = [];
var maxArgumentCount = 0;
var normalArgumentNames = [];
var normalArgumentList = "";
var binderArgumentNames = [];
var binderArgumentList = "";
var closure = {
dispatcherKey: groupDispatcher,
methodFullName: methodFullName
};
for (var i = 0; i < genericArgumentCount; i++) {
binderArgumentNames.push("genericArg" + i);
binderArgumentList += binderArgumentNames[i];
if (i !== (genericArgumentCount - 1))
binderArgumentList += ", ";
}
for (var k in argumentCounts)
maxArgumentCount = Math.max(maxArgumentCount, k | 0);
for (var i = 0; i < maxArgumentCount; i++) {
normalArgumentNames.push("arg" + i);
normalArgumentList += normalArgumentNames[i];
if (i !== (maxArgumentCount - 1))
normalArgumentList += ", ";
}
/*
result.call = function BoundGenericMethod_Call (thisReference) {
// concat doesn't work on the raw 'arguments' value :(
var invokeArguments = genericArguments.concat(
Array.prototype.slice.call(arguments, 1)
);
return body.apply(thisReference, invokeArguments);
};
result.apply = function BoundGenericMethod_Apply (thisReference, invokeArguments) {
// This value might be an Arguments object instead of an array.
invokeArguments = genericArguments.concat(
Array.prototype.slice.call(invokeArguments)
);
return body.apply(thisReference, invokeArguments);
};
return result;
*/
// The user might pass in a public interface instead of a type object, so map that to the type object.
for (var i = 0; i < genericArgumentCount; i++) {
var varName = binderArgumentNames[i];
body.push("if (" + varName + " && " + varName + ".__Type__)");
body.push(" " + varName + " = " + varName + ".__Type__");
}
var innerDispatchCode = [" switch (argc) {"];
for (var k in argumentCounts) {
var localArgCount = k | 0;
innerDispatchCode.push(" case " + localArgCount + ":");
innerDispatchCode.push(" return dispatcher.call(");
innerDispatchCode.push(" thisReference,");
innerDispatchCode.push(" " + binderArgumentList + (
(localArgCount !== 0)
? ", "
: ""
)
);
for (var i = 0; i < localArgCount; i++) {
innerDispatchCode.push(
" " + normalArgumentNames[i] + (
(i === localArgCount - 1)
? ""
: ", "
)
);
}
innerDispatchCode.push(" );");
}
innerDispatchCode.push(" default:");
innerDispatchCode.push(" JSIL.RuntimeError('Unexpected argument count');");
innerDispatchCode.push(" }");
body.push("");
body.push("var outerThis = this;");
body.push("var dispatcher = this[dispatcherKey];");
body.push("");
body.push("var result = function BoundGenericMethod_Invoke (");
body.push(" " + normalArgumentList);
body.push(") {");
body.push(" var thisReference = outerThis;");
body.push(" var argc = arguments.length | 0;");
body.push(" ");
body.push.apply(body, innerDispatchCode);
body.push("};");
body.push("");
body.push("result.call = function BoundGenericMethod_Call (");
body.push(
" thisReference" + (
(maxArgumentCount !== 0)
? ", "
: ""
) + normalArgumentList
);
body.push(") {");
body.push(" var argc = ((arguments.length | 0) - 1) | 0;");
body.push(" ");
body.push.apply(body, innerDispatchCode);
body.push("};");
body.push("");
body.push("result.apply = function BoundGenericMethod_Apply (");
body.push(" thisReference, $arguments");
body.push(") {");
body.push(" var argc = $arguments.length | 0;");
body.push(" ");
body.push(" switch (argc) {");
for (var k in argumentCounts) {
var localArgCount = k | 0;
body.push(" case " + localArgCount + ":");
body.push(" return dispatcher.call(");
body.push(" thisReference,");
body.push(" " + binderArgumentList + (
(localArgCount !== 0)
? ", "
: ""
)
);
for (var i = 0; i < localArgCount; i++) {
body.push(
" $arguments[" + i + "]" + (
(i === localArgCount - 1)
? ""
: ", "
)
);
}
body.push(" );");
}
body.push(" default:");
body.push(" JSIL.RuntimeError('Unexpected argument count');");
body.push(" }");
body.push("};");
body.push("");
body.push("return result;");
var result = JSIL.CreateNamedFunction(
methodFullName + "`" + genericArgumentCount + ".BindGenericArguments[" + maxArgumentCount + "]",
binderArgumentNames,
body.join("\r\n"),
closure
);
return result;
};
JSIL.MemberBuilder = function (context) {
this.context = context;
this.attributes = [];
this.overrides = [];
this.parameterInfo = {};
};
JSIL.MemberBuilder.prototype.Attribute = function (attributeType, getConstructorArguments, initializer) {
var record = new JSIL.AttributeRecord(this.context, attributeType, getConstructorArguments, initializer);
this.attributes.push(record);
// Allows call chaining for multiple attributes
return this;
};
JSIL.MemberBuilder.prototype.Overrides = function (interfaceNameOrReference, interfaceMemberName) {
var record = new JSIL.OverrideRecord(interfaceNameOrReference, interfaceMemberName);
this.overrides.push(record);
return this;
};
JSIL.MemberBuilder.prototype.Parameter = function (index, name, attributes) {
this.parameterInfo[index] = {
name: name,
attributes: attributes || null
};
return this;
};
JSIL.InterfaceBuilder = function (context, typeObject, publicInterface, builderMode) {
this.context = context;
this.typeObject = typeObject;
this.publicInterface = publicInterface;
if (Object.getPrototypeOf(typeObject) === Object.prototype) {
// HACK: Handle the fact that ImplementExternals doesn't pass us a real type object.
this.namespace = this.typeObject.__FullName__;
} else {
this.namespace = JSIL.GetTypeName(typeObject);
}
this.externals = JSIL.AllImplementedExternals[this.namespace];
if (typeof (this.externals) !== "object")
this.externals = JSIL.AllImplementedExternals[this.namespace] = {};
this.builderMode = builderMode || "class";
this._genericParameterCache = {};
var selfRef = typeObject;
var gaNames = typeObject.__GenericArguments__;
if (gaNames && gaNames.length > 0) {
var genericArgs = [];
for (var i = 0, l = gaNames.length; i < l; i++) {
var gpName = gaNames[i];
var gp = new JSIL.GenericParameter(gpName, this.namespace);
genericArgs.push(gp);
this._genericParameterCache[gpName] = gp;
}
selfRef = new JSIL.TypeRef(context, this.namespace, genericArgs);
}
Object.defineProperty(this, "Type", {
configurable: false,
enumerable: true,
value: selfRef
});
Object.defineProperty(this, "prototype", {
configurable: false,
enumerable: false,
get: function () {
JSIL.RuntimeError("Old-style use of $.prototype");
}
});
this.DefineTypeAliases(
JSIL.GetCorlib, [
"System.Byte", "System.UInt16", "System.UInt32", "System.UInt64",
"System.SByte", "System.Int16", "System.Int32", "System.Int64",
"System.Single", "System.Double", "System.String", "System.Object",
"System.Boolean", "System.Char", "System.IntPtr", "System.UIntPtr"
]
);
this.memberDescriptorPrototype = {
Static: false,
Public: false,
SpecialName: false,
Name: null,
toString: function () {
return "<" + this.Name + " Descriptor>";
}
};
this.anonymousMemberCount = 0;
};
JSIL.InterfaceBuilder.prototype.DefineTypeAliases = function (getAssembly, names) {
var asm = null;
var makeGetter = function (name) {
return function GetTypeAlias () {
if (asm === null)
asm = getAssembly();
return asm.TypeRef(name);
};
};
for (var i = 0; i < names.length; i++) {
var name = names[i];
var key = JSIL.GetLocalName(name);
JSIL.SetLazyValueProperty(
this, key, makeGetter(name)
);
}
};
JSIL.InterfaceBuilder.prototype.toString = function () {
return "<Interface Builder for " + this.namespace + ">";
};
JSIL.InterfaceBuilder.prototype.GenericParameter = function (name) {
var result = this._genericParameterCache[name];
if (!result)
result = this._genericParameterCache[name] = new JSIL.GenericParameter(name, this.namespace);
return result;
};
JSIL.InterfaceBuilder.prototype.SetValue = function (key, value) {
var descriptor = {
configurable: true,
enumerable: true,
value: value
};
Object.defineProperty(this.publicInterface, key, descriptor);
Object.defineProperty(this.typeObject, key, descriptor);
if (typeof (this.publicInterface.prototype) !== "undefined")
Object.defineProperty(this.publicInterface.prototype, key, descriptor);
};
JSIL.InterfaceBuilder.prototype.ParseDescriptor = function (descriptor, name, signature) {
if (name === null) {
name = "anonymous$" + this.anonymousMemberCount;
this.anonymousMemberCount += 1;
}
var result = JSIL.CreateDictionaryObject(this.memberDescriptorPrototype);
var escapedName = JSIL.EscapeName(name);
result.Static = descriptor.Static || false;
result.Public = descriptor.Public || false;
result.Virtual = descriptor.Virtual || false;
result.ReadOnly = descriptor.ReadOnly || false;
if (this.builderMode === "interface") {
// HACK: Interfaces have different default visibility than classes, so enforce that.
result.Public = descriptor.Public = true;
result.Static = descriptor.Static = false;
}
result.Name = name;
result.EscapedName = escapedName;
if (
signature &&
signature.genericArgumentNames &&
signature.genericArgumentNames.length
) {
result.EscapedName += "$b" + signature.genericArgumentNames.length;
}
result.SpecialName = (name == ".ctor") || (name == "_ctor") ||
(name.indexOf(".cctor") === 0) ||
(name.indexOf("_cctor") === 0) ||
(name.indexOf("op_") === 0);
JSIL.SetValueProperty(
result, "Target",
(result.Static || this.typeObject.IsInterface) ? this.publicInterface : this.publicInterface.prototype,
false
);
return result;
};
JSIL.InterfaceBuilder.prototype.PushMember = function (type, descriptor, data, memberBuilder, forExternal) {
var members = this.typeObject.__Members__;
if (!JSIL.IsArray(members))
this.typeObject.__Members__ = members = [];
// Simplify usage of member records by not requiring a null check on data
if (!data)
data = JSIL.CreateDictionaryObject(null);
// Throw if two members with identical signatures and names are added
if (data.signature) {
var includeReturnType =
descriptor.SpecialName;
var existingMembersWithSameNameAndSignature = members.filter(function (m) {
if (!m.data.signature)
return false;
var sig1 = m.data.signature.GetNamedKey(m.descriptor.EscapedName, includeReturnType);
var sig2 = data.signature.GetNamedKey(descriptor.EscapedName, includeReturnType);
return (sig1 == sig2);
});
if (existingMembersWithSameNameAndSignature.length > 0) {
if (forExternal) {
// No need to push this, the external is already implemented. Cool!
} else {
// This means that we accidentally implemented the same method twice, or something equally terrible.
var msgPrefix = includeReturnType ?
"A member with the signature '" :
"A member with the name and argument list '";
JSIL.RuntimeError(
msgPrefix + data.signature.toString(descriptor.EscapedName, includeReturnType) +
"' has already been declared in the type '" +
this.typeObject.__FullName__ + "'."
);
}
}
}
var record = new JSIL.MemberRecord(type, descriptor, data, memberBuilder.attributes, memberBuilder.overrides);
Array.prototype.push.call(members, record);
return members.length - 1;
};
JSIL.$PlacePInvokeMember = function (
target, memberName, signature, methodName, pInvokeInfo
) {
var newValue = null;
var existingValue = target[memberName];
if (existingValue) {
// JSIL.RuntimeError("PInvoke member " + memberName + " obstructed");
// Most likely explanation is that an external method took our place.
return;
}
var dllName = pInvokeInfo.Module;
var importedName = pInvokeInfo.EntryPoint || methodName;
var lookupThunk = function PInvokeLookupThunk () {
var module = JSIL.PInvoke.GetModule(dllName, false);
if (!module)
return (function MissingPInvokeModule () {
throw new System.DllNotFoundException("Unable to load DLL '" + dllName + "': The specified module could not be found.");
});
var methodImpl = JSIL.PInvoke.FindNativeMethod(module, importedName);
if (!methodImpl)
return (function MissingPInvokeEntryPoint () {
throw new System.EntryPointNotFoundException("Unable to find an entry point named '" + importedName + "' in DLL '" + dllName + "'.");
});
var wrapper = JSIL.PInvoke.CreateManagedToNativeWrapper(
module, methodImpl, memberName, signature, pInvokeInfo, null
);
return wrapper;
};
JSIL.SetLazyValueProperty(target, memberName, lookupThunk);
};
JSIL.InterfaceBuilder.prototype.PInvokeMethod = function (_descriptor, methodName, signature, pInvokeInfo) {
var descriptor = this.ParseDescriptor(_descriptor, methodName, signature);
var mangledName = signature.GetNamedKey(descriptor.EscapedName, true);
var prefix = "";
var fullName = this.namespace + "." + methodName;
if (!descriptor.Static)
JSIL.RuntimeError("PInvoke methods must be static: " + fullName);
if (!pInvokeInfo)
JSIL.RuntimeError("PInvoke methods must have PInvoke info");
if (!pInvokeInfo.Module)
JSIL.RuntimeError("PInvoke methods must have a module name");
JSIL.$PlacePInvokeMember(
descriptor.Target, mangledName, signature, methodName, pInvokeInfo
);
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember("MethodInfo", descriptor, {
signature: signature,
genericSignature: null,
mangledName: mangledName,
isExternal: true,
isPInvoke: true,
isPlaceholder: false,
isConstructor: false,
parameterInfo: memberBuilder.parameterInfo,
pInvokeInfo: pInvokeInfo
}, memberBuilder, true);
return memberBuilder;
};
JSIL.$PlaceExternalMember = function (
target, implementationSource, implementationPrefix,
memberName, namespace, getDisplayName
) {
var newValue = null;
var existingValue = target[memberName];
if (implementationSource.hasOwnProperty(implementationPrefix + memberName)) {
newValue = implementationSource[implementationPrefix + memberName][1];
} else if (!target.hasOwnProperty(memberName)) {
if (!getDisplayName)
getDisplayName = function () { return memberName; };
newValue = JSIL.MakeExternalMemberStub(namespace, getDisplayName, existingValue);
newValue.__PlaceholderFor__ = memberName;
}
if (newValue === null)
return;
if (existingValue === newValue)
return;
if (existingValue) {
// console.log("replacing '" + memberName + "':", existingValue, "\r\n with:", newValue);
}
JSIL.SetValueProperty(target, memberName, newValue);
};
JSIL.InterfaceBuilder.prototype.ExternalMembers = function (isInstance /*, ...names */) {
var impl = this.externals;
var prefix = isInstance ? "instance$" : "";
var target = this.publicInterface;
if (isInstance)
target = target.prototype;
for (var i = 1, l = arguments.length; i < l; i++) {
var memberName = arguments[i];
JSIL.$PlaceExternalMember(
target, impl, prefix, memberName, this.namespace, null
);
}
};
JSIL.InterfaceBuilder.prototype.Constant = function (_descriptor, name, value) {
var descriptor = this.ParseDescriptor(_descriptor, name);
var data = {
constant: value
};
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember("FieldInfo", descriptor, data, memberBuilder);
JSIL.SetValueProperty(this.publicInterface, descriptor.EscapedName, value);
return memberBuilder;
};
JSIL.InterfaceBuilder.MakeProperty = function (typeShortName, name, target, methodSource, recursed) {
var prop = {
configurable: true,
enumerable: true
};
var interfacePrefix = JSIL.GetParentName(name);
if (interfacePrefix.length)
interfacePrefix += ".";
var localName = JSIL.GetLocalName(name);
var getterName = JSIL.EscapeName(interfacePrefix + "get_" + localName);
var setterName = JSIL.EscapeName(interfacePrefix + "set_" + localName);
var getter = methodSource[getterName];
var setter = methodSource[setterName];
if (typeof (getter) === "function") {
prop["get"] = getter;
} else {
prop["get"] = function () {
JSIL.RuntimeError("Property is not readable");
};
}
if (typeof (setter) === "function") {
prop["set"] = setter;
} else {
prop["set"] = function () {
JSIL.RuntimeError("Property is not writable");
};
}
if (!prop.get && !prop.set) {
prop["get"] = prop["set"] = function () {
JSIL.RuntimeError("Property has no getter or setter: " + name + "\r\n looked for: " + getterName + " & " + setterName);
};
}
var escapedName = JSIL.EscapeName(name);
Object.defineProperty(target, escapedName, prop);
// HACK: Ensure that we do not override BaseType$Foo with a derived implementation of $Foo.
if (!recursed) {
var typeQualifiedName = JSIL.EscapeName(typeShortName + "$" + interfacePrefix + localName);
Object.defineProperty(target, typeQualifiedName, prop);
}
if ((getter && getter.__IsMembrane__) || (setter && setter.__IsMembrane__)) {
JSIL.RebindPropertyAfterPreInit(target, escapedName);
if (!recursed)
JSIL.RebindPropertyAfterPreInit(target, typeQualifiedName);
}
};
JSIL.InterfaceBuilder.prototype.Property = function (_descriptor, name, propertyType) {
var descriptor = this.ParseDescriptor(_descriptor, name);
if (this.typeObject.IsInterface) {
} else {
var props = this.typeObject.__Properties__;
props.push([descriptor.Static, name, descriptor.Virtual, propertyType]);
}
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember("PropertyInfo", descriptor, null, memberBuilder);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.GenericProperty = function (_descriptor, name, propertyType) {
var descriptor = this.ParseDescriptor(_descriptor, name);
var props = this.typeObject.__Properties__;
props.push([descriptor.Static, name, descriptor.Virtual, propertyType]);
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember("PropertyInfo", descriptor, null, memberBuilder);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.Event = function (_descriptor, name, eventType) {
var descriptor = this.ParseDescriptor(_descriptor, name);
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember("EventInfo", descriptor, null, memberBuilder);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.GenericEvent = function (_descriptor, name, eventType) {
var descriptor = this.ParseDescriptor(_descriptor, name);
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember("EventInfo", descriptor, null, memberBuilder);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.Field = function (_descriptor, fieldName, fieldType, defaultValueExpression) {
var descriptor = this.ParseDescriptor(_descriptor, fieldName);
var data = {
fieldType: fieldType,
defaultValueExpression: defaultValueExpression
};
if (typeof (_descriptor.Offset) === "number")
data.offset = _descriptor.Offset | 0;
var memberBuilder = new JSIL.MemberBuilder(this.context);
var fieldIndex = this.PushMember("FieldInfo", descriptor, data, memberBuilder);
// Instance fields have no special logic applied to the prototype or public interface.
// This is important because having default values or other magic on the prototype
// can impair the creation of dense memory layouts and consistent hidden classes/shapes.
if (!descriptor.Static) {
return memberBuilder;
}
var maybeRunCctors = this.maybeRunCctors;
var context = this.context;
var fieldCreator = function InitField (
fullyDerivedClassObject, classObject,
fullyDerivedTypeObject, typeObject
) {
var actualTarget = descriptor.Static ? classObject : fullyDerivedClassObject.prototype;
var maybeRunCctors = function MaybeRunStaticConstructors () {
JSIL.RunStaticConstructors(fullyDerivedClassObject, fullyDerivedTypeObject);
};
// If the field has already been initialized, don't overwrite it.
if (Object.getOwnPropertyDescriptor(actualTarget, descriptor.EscapedName))
return;
if (typeof (defaultValueExpression) === "function") {
JSIL.DefineLazyDefaultProperty(
actualTarget, descriptor.EscapedName,
function InitFieldDefaultExpression () {
if (descriptor.Static)
maybeRunCctors();
return data.defaultValue = defaultValueExpression(this);
}
);
} else if (typeof (defaultValueExpression) !== "undefined") {
if (descriptor.Static) {
JSIL.DefineLazyDefaultProperty(
actualTarget, descriptor.EscapedName,
function InitFieldDefaultExpression () {
if (descriptor.Static)
maybeRunCctors();
return data.defaultValue = defaultValueExpression;
}
);
} else {
actualTarget[descriptor.EscapedName] = data.defaultValue = defaultValueExpression;
}
} else {
var members = typeObject.__Members__;
var initFieldDefault = function InitFieldDefault () {
var actualFieldInfo = members[fieldIndex];
var actualFieldType = actualFieldInfo.data.fieldType;
var fieldTypeResolved;
if (actualFieldType.getNoInitialize) {
// FIXME: We can't use ResolveTypeReference here because it would initialize the field type, which can form a cycle.
// This means that when we create a default value for a struct type, we may create an instance of an uninitalized type
// or form a cycle anyway. :/
fieldTypeResolved = actualFieldType.getNoInitialize();
} else {
fieldTypeResolved = actualFieldType;
}
if (!fieldTypeResolved)
return;
else if (Object.getPrototypeOf(fieldTypeResolved) === JSIL.GenericParameter.prototype)
return;
return data.defaultValue = JSIL.DefaultValue(fieldTypeResolved);
};
if (
descriptor.Static
) {
JSIL.DefinePreInitField(
actualTarget, descriptor.EscapedName,
initFieldDefault, maybeRunCctors
);
} else {
JSIL.DefineLazyDefaultProperty(
actualTarget, descriptor.EscapedName,
initFieldDefault
);
}
}
};
var fi = this.typeObject.__FieldInitializers__;
if (!fi)
fi = this.typeObject.__FieldInitializers__ = [];
fi.push(fieldCreator);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.ExternalMethod = function (_descriptor, methodName, signature) {
var descriptor = this.ParseDescriptor(_descriptor, methodName, signature);
var mangledName = signature.GetNamedKey(descriptor.EscapedName, true);
var impl = this.externals;
var prefix = descriptor.Static ? "" : "instance$";
var memberValue = descriptor.Target[mangledName];
var newValue = null;
var isPlaceholder;
var fullName = this.namespace + "." + methodName;
{
var externalMethods = this.typeObject.__ExternalMethods__;
var externalMethodIndex = externalMethods.length;
// FIXME: Avoid doing this somehow?
externalMethods.push(signature);
var getName = function () {
var thisType = (this.__Type__ || this.__ThisType__);
var lateBoundSignature = thisType.__ExternalMethods__[externalMethodIndex];
// FIXME: Why is this necessary now when it wasn't before?
if (lateBoundSignature == null)
lateBoundSignature = signature;
return lateBoundSignature.toString(methodName);
};
}
JSIL.$PlaceExternalMember(
descriptor.Target, impl, prefix, mangledName, this.namespace, getName
);
var isConstructor = (descriptor.EscapedName === "_ctor");
var memberTypeName = isConstructor ? "ConstructorInfo" : "MethodInfo";
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember(memberTypeName, descriptor, {
signature: signature,
genericSignature: null,
mangledName: mangledName,
isExternal: true,
isPlaceholder: isPlaceholder,
isConstructor: isConstructor,
parameterInfo: memberBuilder.parameterInfo
}, memberBuilder, true);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.ExternalProperty = function (descriptor, propertyName, propertyType) {
this.ExternalMethod(
descriptor, "get_" + propertyName,
JSIL.MethodSignature.Return(propertyType)
);
this.ExternalMethod(
descriptor, "set_" + propertyName,
JSIL.MethodSignature.Action(propertyType)
);
return this.Property(descriptor, propertyName, propertyType);
};
JSIL.InterfaceBuilder.prototype.ExternalEvent = function (descriptor, eventName, eventType) {
this.ExternalMethod(
descriptor, "add_" + eventName,
JSIL.MethodSignature.Return(eventType)
);
this.ExternalMethod(
descriptor, "remove_" + eventName,
JSIL.MethodSignature.Action(eventType)
);
return this.Event(descriptor, eventName, eventType);
};
JSIL.InterfaceBuilder.prototype.RawMethod = function (isStatic, methodName, fn) {
methodName = JSIL.EscapeName(methodName);
if (typeof (fn) !== "function")
JSIL.RuntimeError("RawMethod only accepts function arguments");
JSIL.SetValueProperty(
isStatic ? this.publicInterface : this.publicInterface.prototype,
methodName, fn
);
var rawRecord = new JSIL.RawMethodRecord(methodName, isStatic);
this.typeObject.__RawMethods__.push(rawRecord);
};
JSIL.InterfaceBuilder.prototype.Method = function (_descriptor, methodName, signature, fn) {
var descriptor = this.ParseDescriptor(_descriptor, methodName, signature);
var mangledName = signature.GetNamedKey(descriptor.EscapedName, true);
var memberBuilder = new JSIL.MemberBuilder(this.context);
if (this.typeObject.IsInterface) {
var methodObject = new JSIL.InterfaceMethod(this.typeObject, descriptor.EscapedName, signature, memberBuilder.parameterInfo);
JSIL.SetValueProperty(descriptor.Target, mangledName, methodObject);
if (!descriptor.Target[descriptor.EscapedName])
JSIL.SetValueProperty(descriptor.Target, descriptor.EscapedName, methodObject);
} else {
if (typeof (fn) !== "function")
JSIL.RuntimeError("Method expected a function as 4th argument when defining '" + methodName + "'");
var fullName = this.namespace + "." + methodName;
JSIL.SetValueProperty(descriptor.Target, mangledName, fn);
}
var isConstructor = (descriptor.EscapedName === "_ctor");
var memberTypeName = isConstructor ? "ConstructorInfo" : "MethodInfo";
this.PushMember(memberTypeName, descriptor, {
signature: signature,
genericSignature: null,
mangledName: mangledName,
isExternal: false,
isConstructor: isConstructor,
parameterInfo: memberBuilder.parameterInfo
}, memberBuilder);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.MakeEventAccessors = function (_descriptor, name, type) {
var signature = JSIL.MethodSignature.Action(type);
function adder (value) {
var existingValue = this[name] || null;
var newValue = $jsilcore.$CombineDelegates(existingValue, value);
return this[name] = newValue;
};
function remover (value) {
var existingValue = this[name] || null;
var newValue = $jsilcore.$RemoveDelegate(existingValue, value);
return this[name] = newValue;
};
this.Method(_descriptor, "add_" + name, signature, adder);
this.Method(_descriptor, "remove_" + name, signature, remover);
};
JSIL.InterfaceBuilder.prototype.InheritBaseMethod = function (name, signature) {
var descriptor = this.ParseDescriptor({Public: true, Static: false}, name, signature);
var mangledName = signature.GetNamedKey(descriptor.EscapedName, true);
var fn = null;
fn = function InheritedBaseMethod_Invoke () {
var proto = Object.getPrototypeOf(this);
var baseMethod;
while (true) {
baseMethod = proto[mangledName];
if (baseMethod === fn)
proto = Object.getPrototypeOf(proto);
else
break;
}
if (typeof (baseMethod) === "function")
return baseMethod.apply(this, arguments);
else
JSIL.Host.warning("InheritBaseMethod() used but no method was found to inherit!");
};
JSIL.SetValueProperty(descriptor.Target, mangledName, fn);
var isConstructor = (descriptor.EscapedName === "_ctor");
var memberTypeName = isConstructor ? "ConstructorInfo" : "MethodInfo";
var memberBuilder = new JSIL.MemberBuilder(this.context);
this.PushMember(memberTypeName, descriptor, {
signature: signature,
genericSignature: null,
mangledName: mangledName,
isExternal: false,
isConstructor: isConstructor,
isInherited: true,
parameterInfo: memberBuilder.parameterInfo
}, memberBuilder);
return memberBuilder;
};
JSIL.InterfaceBuilder.prototype.InheritDefaultConstructor = function () {
this.InheritBaseMethod(".ctor", JSIL.MethodSignature.Void);
};
JSIL.InterfaceBuilder.prototype.ImplementInterfaces = function (/* ...interfacesToImplement */) {
var interfaces = this.typeObject.__Interfaces__;
if (typeof (interfaces) === "undefined")
JSIL.RuntimeError("Type has no interface list");
for (var i = 0; i < arguments.length; i++) {
var iface = arguments[i];
if (!iface)
JSIL.RuntimeError("Nonexistent interface passed to ImplementInterfaces");
interfaces.push(iface);
}
};
JSIL.SignatureBase = function () {
JSIL.RuntimeError("Abstract base class");
};
JSIL.SignatureBase.prototype.GetNamedKey$CacheMiss = function (name, includeReturnType) {
var result = name + "" + this.get_Hash(includeReturnType);
if (includeReturnType !== false) {
this._lastKeyName = null;
this._lastKey = result;
}
return result;
};
JSIL.SignatureBase.prototype.GetNamedKey = function (name, includeReturnType) {
if (!name)
return this.GetUnnamedKey(includeReturnType);
else if ((name === this._lastKeyName) && (includeReturnType !== false))
return this._lastKey;
return this.GetNamedKey$CacheMiss(name, includeReturnType);
};
JSIL.SignatureBase.prototype.GetUnnamedKey$CacheMiss = function (includeReturnType) {
var result = this.get_Hash(includeReturnType);
if (includeReturnType !== false) {
this._lastKeyName = null;
this._lastKey = result;
}
return result;
};
JSIL.SignatureBase.prototype.GetUnnamedKey = function (includeReturnType) {
if ((!this._lastKeyName) && (includeReturnType !== false))
return this._lastKey;
return this.GetUnnamedKey$CacheMiss(includeReturnType);
};
JSIL.SignatureBase.prototype.GetKey = function (name, includeReturnType) {
if (arguments.length === 2)
return this.GetNamedKey(name, includeReturnType);
else if (arguments.length === 1)
return this.GetNamedKey(name, true);
else
return this.GetUnnamedKey(true);
};
JSIL.SignatureBase.prototype.ResolveTypeReference = function (typeReference) {
return JSIL.ResolveTypeReference(typeReference, this);
};
JSIL.SignatureBase.prototype.LookupMethod = function (context, name) {
if (!context)
JSIL.RuntimeError("Attempting to invoke method named '" + name + "' on null/undefined object");
var key = this.GetNamedKey(name, true);
var method = context[key];
if (typeof (method) !== "function") {
var signature = this.toString(name);
JSIL.RuntimeError(
"No method with signature '" + signature +
"' defined in context '" + JSIL.GetTypeName(context) + "'"
);
}
return method;
};
JSIL.MethodSignature = function (returnType, argumentTypes, genericArgumentNames, context, openSignature, genericArgumentValues) {
this._lastKeyName = "<null>";
this._lastKey = "<null>";
this._genericSuffix = null;
this._hash = null;
this._hashIncludesReturnType = null;
this.context = context || $private;
this.returnType = returnType;
if (!JSIL.IsArray(argumentTypes)) {
if (argumentTypes !== null) {
var argumentTypesString = typeof(argumentTypes) + " " + String(argumentTypes);
JSIL.RuntimeError("ArgumentTypes must be an array or null, was: " + argumentTypesString);
} else
this.argumentTypes = $jsilcore.ArrayNull;
} else {
this.argumentTypes = argumentTypes;
}
if (JSIL.IsArray(genericArgumentNames))
this.genericArgumentNames = genericArgumentNames;
else
this.genericArgumentNames = $jsilcore.ArrayNull;
this.openSignature = openSignature || null;
if (JSIL.IsArray(genericArgumentValues)){
this.genericArgumentValues = genericArgumentValues;
}
this.recompileCount = 0;
this.useInlineCache = JSIL.MethodSignature.EnableInlineCaches;
this.inlineCacheEntries = [];
this.isInterfaceSignature = false;
};
JSIL.MethodSignature.prototype = JSIL.CreatePrototypeObject(JSIL.SignatureBase.prototype);
JSIL.MethodSignature.prototype.Clone = function (isInterfaceSignature) {
var result = new JSIL.MethodSignature(
this.returnType, this.argumentTypes, this.genericArgumentNames,
this.context, this.openSignature, this.genericArgumentValues
);
result.isInterfaceSignature = isInterfaceSignature;
return result;
};
JSIL.SetLazyValueProperty(JSIL.MethodSignature, "Void", function () {
return new JSIL.MethodSignature(null, null, null);
});
JSIL.MethodSignature.$returnCache = {};
JSIL.MethodSignature.$actionCache = {};
JSIL.MethodSignature.Return = function (returnType) {
var key = null;
if (!returnType)
JSIL.RuntimeError("Return type must be specified");
else if (Object.getPrototypeOf(returnType) === JSIL.TypeRef.prototype)
key = returnType.getTypeId();
else if (returnType.__TypeId__)
key = returnType.__TypeId__;
else
JSIL.RuntimeError("Unsupported return type format");
var result = JSIL.MethodSignature.$returnCache[key];
if (!result) {
result = new JSIL.MethodSignature(returnType, null, null);
JSIL.MethodSignature.$returnCache[key] = result;
}
return result;
};
JSIL.MethodSignature.Action = function (argumentType) {
var key = null;
if (!argumentType)
JSIL.RuntimeError("Argument type must be specified");
else if (Object.getPrototypeOf(argumentType) === JSIL.TypeRef.prototype)
key = argumentType.getTypeId();
else if (argumentType.__TypeId__)
key = argumentType.__TypeId__;
else
JSIL.RuntimeError("Unsupported argument type format");
var result = JSIL.MethodSignature.$actionCache[key];
if (!result) {
result = new JSIL.MethodSignature(null, [argumentType], null);
JSIL.MethodSignature.$actionCache[key] = result;
}
return result;
};
JSIL.SetLazyValueProperty(
JSIL.MethodSignature.prototype, "Call",
function () { return this.$MakeCallMethod("Call", null, null); }, true, false
);
JSIL.SetLazyValueProperty(
JSIL.MethodSignature.prototype, "CallStatic",
function () { return this.$MakeCallMethod("CallStatic", null, null); }, true, false
);
JSIL.SetLazyValueProperty(
JSIL.MethodSignature.prototype, "CallVirtual",
function () { return this.$MakeCallMethod("CallVirtual", null, null); }, true, false
);
JSIL.MethodSignature.prototype.Resolve = function (name) {
var argTypes = [];
var resolvedReturnType = null;
if (this.returnType !== null) {
resolvedReturnType = JSIL.ResolveTypeReference(this.returnType, this)[1];
}
for (var i = 0; i < this.argumentTypes.length; i++) {
argTypes[i] = JSIL.ResolveTypeReference(this.argumentTypes[i], this)[1];
}
return new JSIL.ResolvedMethodSignature(
this,
this.GetNamedKey(name, true),
resolvedReturnType,
argTypes
);
};
JSIL.MethodSignature.prototype.toString = function (name, includeReturnType) {
var signature;
if (includeReturnType === false) {
signature = "";
} else if (this.returnType !== null) {
signature = JSIL.TypeReferenceToName(this.returnType) + " ";
} else {
signature = "void ";
}
if (typeof (name) === "string") {
signature += name;
}
if (this.genericArgumentNames.length > 0) {
signature += "<";
for (var i = 0, l = this.genericArgumentNames.length; i < l; i++) {
if (i > 0)
signature += ", ";
signature += this.genericArgumentNames[i];
}
signature += "> (";
} else {
signature += "(";
}
for (var i = 0; i < this.argumentTypes.length; i++) {
signature += JSIL.TypeReferenceToName(this.argumentTypes[i]);
if (i < this.argumentTypes.length - 1)
signature += ", "
}
signature += ")";
return signature;
};
JSIL.MethodSignature.$EmitInvocation = function (
body, callText,
thisReferenceArg, prefix,
argumentTypes, genericArgumentNames,
isInterface, indentation
) {
var comma;
var needsBindingForm = false;
if (typeof (indentation) !== "string")
indentation = " ";
if (genericArgumentNames)
comma = (genericArgumentNames.length + argumentTypes.length) > 0 ? "," : "";
else
comma = argumentTypes.length > 0 ? "," : "";
body.push(indentation + prefix + callText + "(");
if (thisReferenceArg)
body.push(indentation + " " + thisReferenceArg + comma);
if (genericArgumentNames)
for (var i = 0, l = genericArgumentNames.length; i < l; i++) {
comma = ((i < (l - 1)) || (!needsBindingForm && argumentTypes.length > 0)) ? "," : "";
body.push(indentation + " ga[" + i + "]" + comma);
}
if (needsBindingForm)
body.push(indentation + ")(");
for (var i = 0, l = argumentTypes.length; i < l; i++) {
comma = (i < (l - 1)) ? "," : "";
body.push(indentation + " arg" + i + comma);
}
body.push(indentation + ");");
};
// Used as a global cache for generated invocation method bodies.
// Caching them reduces memory usage but probably ruins type info, so we're not
// going to do it by default.
if (false) {
JSIL.MethodSignature.$CallMethodCache = JSIL.CreateDictionaryObject(null);
} else {
JSIL.MethodSignature.$CallMethodCache = null;
}
// Control whether generated ICs check argument & generic argument counts.
// Shouldn't ever be necessary, but it's a useful debugging tool.
JSIL.MethodSignature.CheckArgumentCount = false;
JSIL.MethodSignature.CheckGenericArgumentCount = false;
JSIL.MethodSignature.EnableInlineCaches = true;
JSIL.MethodSignatureInlineCacheEntry = function (name, typeId, methodKey) {
this.name = name;
this.typeId = typeId;
this.methodKey = methodKey;
};
JSIL.MethodSignatureInlineCacheEntry.prototype.equals = function (name, typeId, methodKey) {
return (this.name === name) &&
(this.typeId === typeId) &&
(this.methodKey === methodKey);
};
JSIL.MethodSignature.prototype.$MakeInlineCacheBody = function (callMethodName, knownMethodKey, fallbackMethod) {
// Welcome to optimization hell! Enjoy your stay.
var returnType = this.returnType;
var argumentTypes = this.argumentTypes;
var genericArgumentNames = this.genericArgumentNames;
var argumentNames;
var methodLookupArg, thisReferenceArg;
var suffix;
var isInterfaceCall = false;
// We're generating an optimized inline cache or invocation thunk that handles
// method dispatch for four different types of calls. They are all similar.
switch (callMethodName) {
case "CallStatic":
// Invoking a specific static method of a given type. There's no this-reference.
// methodSource is the public interface of the type, we can call off it directly.
thisReferenceArg = methodLookupArg = "methodSource";
argumentNames = ["methodSource", "name", "ga"];
break;
case "Call":
// Invoking a specific method against a specific object instance.
thisReferenceArg = "thisReference";
methodLookupArg = "methodSource";
argumentNames = ["methodSource", "name", "ga", "thisReference"];
break;
case "CallVirtual":
// Invoking a specific virtual method of a specific object instance.
// The thisReference is the source of the method so we can call off it directly.
suffix = "Virtual";
thisReferenceArg = methodLookupArg = "thisReference";
argumentNames = ["name", "ga", "thisReference"];
break;
case "CallInterface":
case "CallVariantInterface":
// Interface calls that are non-variant don't need an IC. Their target is constant.
if (callMethodName === "CallInterface")
this.useInlineCache = false;
// Invoking an interface method against a this-reference.
// If the method is part of a variant generic interface, we need to do variant
// lookup. Otherwise, the name is constant and we can dispatch to it directly.
isInterfaceCall = true;
thisReferenceArg = methodLookupArg = "thisReference";
argumentNames = ["thisReference", "ga"];
break;
default:
JSIL.RuntimeError("Invalid callMethodName");
}
for (var i = 0, l = argumentTypes.length; i < l; i++) {
var argumentName = "arg" + i;
argumentNames.push(argumentName);
}
var requiredArgumentCount = argumentNames.length;
var argumentCheckOperator = "!==";
// HACK to allow simple 'method.call(x)' form for zero-argument, non-generic methods.
if ((genericArgumentNames.length === 0) && (argumentTypes.length === 0)) {
requiredArgumentCount = 1;
argumentCheckOperator = "<";
}
// We attempt to generate unique-enough and friendly names for our generated closures.
// These names make it clear what the IC is for and how many times it has been recompiled.
// The recompile count is important; otherwise some debuggers overwrite older compiles
// with new ones, making it confusing to debug.
this.recompileCount += 1;
var functionName = (isInterfaceCall ? "InterfaceMethod" : "MethodSignature") +
"." + callMethodName;
if (knownMethodKey && (callMethodName === "CallInterface")) {
// Generate straightforward closure names for non-variant interface methods.
functionName += "_" +
knownMethodKey;
} else {
functionName +=
"$" + genericArgumentNames.length +
"$" + argumentTypes.length;
}
if (this.useInlineCache)
functionName += "$inlineCache" + this.recompileCount;
var body = [];
// Check the # of provided arguments to detect an invalid invocation.
if (JSIL.MethodSignature.CheckArgumentCount) {
body.push("var argc = arguments.length | 0;");
body.push("if (argc " + argumentCheckOperator + " " + requiredArgumentCount + ")");
body.push(" JSIL.RuntimeError('" + requiredArgumentCount + " argument(s) required, ' + argc + ' provided.');");
}
// If the function accepts generic arguments, we need to do a check to ensure
// that the appropriate # of arguments were passed.
if (genericArgumentNames.length > 0) {
if (JSIL.MethodSignature.CheckGenericArgumentCount) {
body.push("if (!ga || ga.length !== " + genericArgumentNames.length + ")");
body.push(" JSIL.RuntimeError('Invalid number of generic arguments');");
}
body.push("JSIL.ResolveTypeArgumentArray(ga);");
body.push("");
} else {
// If it doesn't accept them, and we're in validation mode, insert a check.
// This wastes cycles normally so we don't always want to put it in there.
if (JSIL.MethodSignature.CheckGenericArgumentCount) {
body.push("if (ga && ga.length > 0)");
body.push(" JSIL.RuntimeError('Invalid number of generic arguments');");
body.push("");
}
}
var nameIdentifier = "name";
var thisReferenceExpression = null;
if (methodLookupArg !== thisReferenceArg)
thisReferenceExpression = thisReferenceArg;
var emitMissingMethodCheck = function (result, methodExpression, methodName, indentation) {
var errMethod =
indentation + " " +
(callMethodName === "CallStatic")
? "this.$StaticMethodNotFound("
: "this.$MethodNotFound(";
result.push(indentation + "if (!" + methodExpression + ")");
if (thisReferenceArg !== methodLookupArg)
result.push(errMethod + thisReferenceExpression + ", " + methodName + ");");
else
result.push(errMethod + thisReferenceArg + ", " + methodName + ");");
result.push(indentation);
};
// This is the path used for simple invocations - no IC, etc.
var emitDefaultInvocation = function (indentation, methodKeyToken) {
// For every invocation type other than Call, the this-reference will
// automatically bind thanks to JS call semantics.
var methodName = (callMethodName === "Call")
? methodLookupArg + "[" + methodKeyToken + "].call"
: methodLookupArg + "[" + methodKeyToken + "]";
if (fallbackMethod) {
body.push(indentation + " var methodReference = " + methodName + ";");
body.push(indentation + " if (!methodReference) {");
body.push(indentation + " methodReference = fallbackMethod(this.typeObject, this, thisReference)");
body.push(indentation + " }");
body.push("");
JSIL.MethodSignature.$EmitInvocation(
body, "methodReference.call", "thisReference",
(!!returnType) ? "return " : "",
argumentTypes, genericArgumentNames,
false, indentation + " "
);
} else {
emitMissingMethodCheck(body, methodName, methodKeyToken, "");
JSIL.MethodSignature.$EmitInvocation(
body, methodName, thisReferenceExpression,
(!!returnType) ? "return " : "",
argumentTypes, genericArgumentNames,
false, indentation
);
}
};
// The 'method key' used to find the method in the method source depends on
// the call scenario.
var getMethodKeyLookup = function () {
if (isInterfaceCall) {
if (callMethodName === "CallVariantInterface") {
return "this.LookupVariantMethodKey(thisReference)";
} else if (knownMethodKey) {
return "\"" + knownMethodKey + "\"";
} else {
return "this.methodKey";
}
} else {
return "this.GetNamedKey(name, true)";
}
};
// When an IC is enabled, if a cache miss occurs we update the IC before finally
// doing a typical invocation.
var emitCacheMissInvocation = function (indentation) {
// Interface ICs are keyed off the type ID of the this-reference.
// Non-interface ICs are keyed off method name.
var typeIdExpression =
isInterfaceCall
? "typeId"
: "null";
// Interface ICs live on the InterfaceMethod's signature.
var cacheMissMethod =
isInterfaceCall
? "this.signature.$InlineCacheMiss(this, '"
: "this.$InlineCacheMiss(this, '";
// Look up the actual method key, update the IC...
body.push(indentation + "var methodKey = " + getMethodKeyLookup() + ";");
body.push(
indentation + cacheMissMethod +
callMethodName + "', " +
nameIdentifier + ", " +
typeIdExpression + ", methodKey);"
);
// Then finally invoke.
emitDefaultInvocation(indentation, "methodKey");
};
if (this.useInlineCache) {
// Crazy inline cache nonsense time!
if (fallbackMethod)
JSIL.RuntimeError("Inline caching does not support fallback methods");
// Look up the type ID of the this-reference for interface calls. We'll be using it a lot.
if (isInterfaceCall) {
nameIdentifier = "null";
body.push("var typeId = thisReference.__ThisTypeId__;");
}
// Generate the lookup switch for the IC, along with IC management code.
for (var i = 0, l = this.inlineCacheEntries.length; i < l; i++) {
var entry = this.inlineCacheEntries[i];
// Check to see if the cache entry matches. Note that the condition depends
// on whether this is an interface method IC.
// FIXME: Can the key end up with a single quote in it, or a backslash?
var conditionExpression =
isInterfaceCall
? "\"" + entry.typeId + "\""
: "\"" + entry.name + "\"";
// So, you might be asking yourself... why a switch block keyed on the name?
// It's a good question. The first IC implementation built a name -> index
// dictionary, and looked up the name in the dictionary to choose the method
// to call. This was a performance improvement.
// The key observation, however, is that the value of these ICs is actually for
// inlining. If the call target is known, inlining can occur more easily,
// and once a method is inlining lots of cool new optimizations become possible.
// In an ideal world, *both* this IC *and* the call target will be inlined,
// so we want to design the IC to make this possible and make it *fast*.
// The old table lookup is not particularly optimizer-friendly. Even if it inlined
// the IC, it wouldn't have any easy way to know that the table lookup
// was constant.
// Replacing the table lookup with a switch (or if statements, even) keyed on
// the name/typeId means that once inlined, the IC looks like this:
//
// function ic (name /* = 'knownName' */, ...) {
// if (name === 'knownName' /* true */) {
// ...
// } else if (name === 'otherKnownName' /* false */) {
// ...
//
// Thanks to the inline, the JIT now has all the information it needs to
// *completely* optimize out the IC. It can kill all the false branch
// conditions and it's only left with the true branch - which calls a specific
// known method directly on the provided this-reference.
// In most scenarios the method name being passed into the IC is a constant,
// so it's fairly likely that inlining can happen and that it will optimize this way.
// Finally, in testing switch statements were not found to be any slower than
// if statements, so we generate an if statement. The generated code is denser
// and clearer, which is nice, and it makes it less work for the JIT to figure
// out that it can use a jump table or whatever it likes in the case where
// we aren't optimized out entirely.
if (i === 0) {
body.push(
"switch (" +
(isInterfaceCall
? "typeId"
: "name") +
") {"
);
}
body.push(
" case " + conditionExpression + ": "
);
// For every invocation type other than Call, the this-reference will
// automatically bind thanks to JS call semantics.
var methodName = (callMethodName === "Call")
? methodLookupArg + "['" + entry.methodKey + "'].call"
: methodLookupArg + "['" + entry.methodKey + "']";
emitMissingMethodCheck(body, methodName, "'" + entry.methodKey + "'", " ");
// This inline cache entry matches, so build an appropriate invocation.
JSIL.MethodSignature.$EmitInvocation(
body, methodName, thisReferenceExpression,
(!!returnType) ? "return " : "",
argumentTypes, genericArgumentNames,
false, " "
);
body.push(" break;");
body.push(" ");
}
if (this.inlineCacheEntries.length >= 1) {
body.push(" default: ");
emitCacheMissInvocation(" ");
body.push("}");
body.push("");
} else {
emitCacheMissInvocation("");
}
} else {
emitDefaultInvocation("", getMethodKeyLookup());
}
var joinedBody = body.join("\r\n");
var closure = null;
if (fallbackMethod)
closure = { fallbackMethod: fallbackMethod };
return JSIL.CreateNamedFunction(
functionName,
argumentNames,
joinedBody,
closure
);
};
JSIL.MethodSignature.prototype.$StaticMethodNotFound = function (publicInterface, methodName) {
JSIL.RuntimeErrorFormat(
"No static method with signature '{0}' found in context '{1}'", [
this.toString(methodName),
publicInterface
]
);
};
JSIL.MethodSignature.prototype.$MethodNotFound = function (thisReference, methodName) {
JSIL.RuntimeErrorFormat(
"No method with signature '{0}' found on instance '{1}'", [
this.toString(methodName),
thisReference
]
);
};
JSIL.MethodSignature.prototype.$MakeCallMethod = function (callMethodName, knownMethodKey, fallbackMethod) {
// FIXME: Is this correct? I think having all instances of a given unique signature
// share the same IC is probably correct.
var cacheKey = callMethodName + "$" + this.GetUnnamedKey(true);
if (JSIL.MethodSignature.$CallMethodCache) {
var cachedResult = JSIL.MethodSignature.$CallMethodCache[cacheKey];
if (cachedResult)
return cachedResult;
}
// Doing an IC with a fallback method in play is totally not worth the trouble.
// Fallback methods are an infrequently used hack anyway.
if (fallbackMethod)
this.useInlineCache = false;
var result = this.$MakeInlineCacheBody(callMethodName, knownMethodKey, fallbackMethod);
if (JSIL.MethodSignature.$CallMethodCache) {
JSIL.MethodSignature.$CallMethodCache[cacheKey] = result;
}
return result;
};
JSIL.MethodSignature.prototype.$InlineCacheMiss = function (target, callMethodName, name, typeId, methodKey) {
if (!this.useInlineCache)
return;
// FIXME: This might be too small.
var inlineCacheCapacity = 3;
var numEntries = this.inlineCacheEntries.length | 0;
if (numEntries >= inlineCacheCapacity) {
// Once the IC gets too large we convert it back to a simple invocation method.
// This is important since these ICs are only a big optimization if the JIT is
// able to inline them into the caller (so the conditionals become free).
// Making an IC too big will prevent inlining and at that point it's not gonna
// be particularly fast or worthwhile.
this.inlineCacheEntries = null;
this.useInlineCache = false;
this.$RecompileInlineCache(target, callMethodName);
} else {
for (var i = 0; i < numEntries; i++) {
var entry = this.inlineCacheEntries[i];
// Our caller is an expired inline cache function.
if (entry.equals(name, typeId, methodKey)) {
// Some bugs cause this to happen over and over so perf sucks.
// JSIL.RuntimeError("Inline cache miss w/ pending recompile.");
return;
}
}
// If we had a cache miss and the target doesn't have an entry, add it and recompile.
var newEntry = new JSIL.MethodSignatureInlineCacheEntry(name, typeId, methodKey);
this.inlineCacheEntries.push(newEntry);
this.$RecompileInlineCache(target, callMethodName);
}
};
JSIL.MethodSignature.prototype.$RecompileInlineCache = function (target, callMethodName) {
var cacheKey = callMethodName + "$" + this.GetUnnamedKey(true);
var newFunction = this.$MakeInlineCacheBody(callMethodName, target.methodKey || null);
if (JSIL.MethodSignature.$CallMethodCache) {
JSIL.MethodSignature.$CallMethodCache[cacheKey] = newFunction;
}
// HACK
var propertyName = this.isInterfaceSignature
? "Call"
: callMethodName;
// Once we've recompiled the inline cache, overwrite the old one on the target.
// Note that this is not 'this' because for interface methods, the IC is managed
// by their signature but lives on the interface method object instead.
JSIL.SetValueProperty(target, propertyName, newFunction);
};
JSIL.MethodSignature.prototype.get_GenericSuffix = function () {
if (this._genericSuffix !== null)
return this._genericSuffix;
if (this.genericArgumentNames.length > 0) {
return this._genericSuffix = "`" + this.genericArgumentNames.length.toString();
}
return this._genericSuffix = "";
};
JSIL.MethodSignature.prototype.get_Hash = function (includeReturnType) {
if ((this._hash !== null) && (this._hashIncludesReturnType === includeReturnType))
return this._hash;
var hash = "$" + JSIL.HashTypeArgumentArray(this.argumentTypes, this.context);
if ((this.returnType !== null) && (includeReturnType !== false)) {
hash += "=" + JSIL.HashTypeArgumentArray([this.returnType], this.context);
} else {
if (includeReturnType !== false)
hash += "=void";
}
this._hash = hash;
this._hashIncludesReturnType = includeReturnType;
return hash;
};
JSIL.MethodSignature.prototype.get_IsClosed = function () {
if (this.returnType && (this.returnType.__IsClosed__ === false))
return false;
for (var i = 0, l = this.argumentTypes.length; i < l; i++) {
var at = this.argumentTypes[i];
if (at.__IsClosed__ === false)
return false;
}
return true;
};
Object.defineProperty(JSIL.MethodSignature.prototype, "GenericSuffix", {
configurable: false,
enumerable: true,
get: JSIL.MethodSignature.prototype.get_GenericSuffix
});
Object.defineProperty(JSIL.MethodSignature.prototype, "Hash", {
configurable: false,
enumerable: true,
get: JSIL.MethodSignature.prototype.get_Hash
});
Object.defineProperty(JSIL.MethodSignature.prototype, "IsClosed", {
configurable: false,
enumerable: true,
get: JSIL.MethodSignature.prototype.get_IsClosed
});
JSIL.ConstructorSignature = function (type, argumentTypes, context) {
this._lastKeyName = "<null>";
this._lastKey = "<null>";
this._hash = null;
this._typeObject = null;
this.context = context || $private;
this.type = type;
if (!JSIL.IsArray(argumentTypes)) {
if (argumentTypes !== null) {
var argumentTypesString = typeof(argumentTypes) + " " + String(argumentTypes);
JSIL.RuntimeError("ArgumentTypes must be an array or null, was: " + argumentTypesString);
} else
this.argumentTypes = $jsilcore.ArrayNull;
} else {
this.argumentTypes = argumentTypes;
}
};
JSIL.ConstructorSignature.prototype = JSIL.CreatePrototypeObject(JSIL.SignatureBase.prototype);
JSIL.SetLazyValueProperty(JSIL.ConstructorSignature.prototype, "Construct", function () { return this.$MakeConstructMethod(); }, true);
JSIL.ConstructorSignature.prototype.get_Type = function () {
if (this._typeObject !== null)
return this._typeObject;
return this._typeObject = this.ResolveTypeReference(this.type)[1];
};
JSIL.ConstructorSignature.prototype.get_Hash = function (includeReturnType) {
if (this._hash !== null)
return this._hash;
return this._hash = "$" + JSIL.HashTypeArgumentArray(this.argumentTypes, this.context) + "=void";
};
JSIL.ConstructorSignature.prototype.$MakeBoundConstructor = function (argumentNames) {
var typeObject = this.get_Type();
var publicInterface = typeObject.__PublicInterface__;
var closure = {};
var body = [];
var proto = publicInterface.prototype;
closure.fieldInitializer = JSIL.GetFieldInitializer(typeObject);
body.push("fieldInitializer(this);");
var ctorKey = "_ctor";
if (typeObject.__IsStruct__ && argumentNames.length === 0) {
} else {
ctorKey = this.GetNamedKey("_ctor", true);
if (!proto[ctorKey]) {
if (!proto["_ctor"])
JSIL.RuntimeError("No method named '_ctor' found");
else
ctorKey = "_ctor";
}
JSIL.MethodSignature.$EmitInvocation(
body, "this['" + ctorKey + "']", null,
"return ", argumentNames
);
}
var result = JSIL.CreateNamedFunction(
typeObject.__FullName__ + "." + ctorKey,
argumentNames,
body.join("\r\n"),
closure
);
result.prototype = proto;
return result;
};
JSIL.ConstructorSignature.prototype.$MakeConstructMethod = function () {
var typeObject = this.get_Type();
var publicInterface = typeObject.__PublicInterface__;
var argumentTypes = this.argumentTypes;
if (typeObject.__IsClosed__ === false)
return function () {
JSIL.RuntimeError("Cannot create an instance of an open type");
};
else if (typeObject.IsInterface)
return function () {
JSIL.RuntimeError("Cannot create an instance of an interface");
};
var closure = {
typeObject: typeObject,
publicInterface: publicInterface
};
var body = [];
var argumentNames = [];
for (var i = 0, l = argumentTypes.length; i < l; i++) {
var argumentName = "arg" + i;
argumentNames.push(argumentName);
}
JSIL.RunStaticConstructors(publicInterface, typeObject);
if (typeObject.__IsNativeType__) {
closure.ctor = publicInterface.prototype["_ctor"];
JSIL.MethodSignature.$EmitInvocation(
body, "ctor.call", "publicInterface",
"return ", argumentTypes
);
} else {
closure.constructor = this.$MakeBoundConstructor(
argumentNames
);
JSIL.MethodSignature.$EmitInvocation(
body, "new constructor", null,
"return ", argumentTypes
);
}
var result = JSIL.CreateNamedFunction(
"ConstructorSignature.Construct$" + argumentTypes.length,
argumentNames,
body.join("\r\n"),
closure
);
return result;
};
JSIL.ConstructorSignature.prototype.toString = function () {
var signature;
signature = this.get_Type().toString(this) + "::.ctor (";
for (var i = 0; i < this.argumentTypes.length; i++) {
signature += this.ResolveTypeReference(this.argumentTypes[i])[1].toString(this);
if (i < this.argumentTypes.length - 1)
signature += ", "
}
signature += ")";
return signature;
};
JSIL.ResolvedMethodSignature = function (methodSignature, key, returnType, argumentTypes) {
this.methodSignature = methodSignature;
this.key = key;
this.returnType = returnType;
this.argumentTypes = argumentTypes;
JSIL.ValidateArgumentTypes(argumentTypes);
};
JSIL.ResolvedMethodSignature.prototype.ResolvePositionalGenericParameter = function (genericParameterValues, parameter) {
if (
(typeof (parameter) === "object") &&
(parameter !== null) &&
(Object.getPrototypeOf(parameter) === JSIL.PositionalGenericParameter.prototype)
) {
return genericParameterValues[parameter.index] || null;
} else {
return parameter;
}
};
JSIL.ResolvedMethodSignature.prototype.ResolvePositionalGenericParameters = function (genericParameterValues) {
var returnType = this.ResolvePositionalGenericParameter(genericParameterValues, this.returnType);
var argumentTypes = [];
var resolvedAnyArguments = false;
for (var i = 0, l = this.argumentTypes.length; i < l; i++) {
var argumentType = this.argumentTypes[i];
argumentType = this.ResolvePositionalGenericParameter(genericParameterValues, argumentType);
argumentTypes.push(argumentType);
if (argumentType !== this.argumentTypes[i]);
resolvedAnyArguments = true;
}
if ((returnType !== this.returnType) || resolvedAnyArguments)
return new JSIL.ResolvedMethodSignature(
this.methodSignature,
this.key,
returnType,
argumentTypes
);
else
return this;
};
JSIL.ResolvedMethodSignature.prototype.toString = function () {
return this.methodSignature.toString.apply(this.methodSignature, arguments);
};
JSIL.InterfaceMethod = function (typeObject, methodName, signature, parameterInfo) {
this.typeObject = typeObject;
this.variantGenericArguments = JSIL.$FindVariantGenericArguments(typeObject);
this.methodName = methodName;
if (signature) {
// Important so ICs don't get mixed up.
this.signature = signature.Clone(true);
} else {
// FIXME: Why the hell does this happen?
this.signature = null;
}
this.parameterInfo = parameterInfo;
this.qualifiedName = JSIL.$GetSignaturePrefixForType(typeObject) + this.methodName;
this.variantInvocationCandidateCache = JSIL.CreateDictionaryObject(null);
this.fallbackMethod = JSIL.$PickFallbackMethodForInterfaceMethod(typeObject, methodName, signature);
JSIL.SetLazyValueProperty(this, "methodKey", function () {
return this.signature.GetNamedKey(this.qualifiedName, true);
});
};
JSIL.SetLazyValueProperty(JSIL.InterfaceMethod.prototype, "Call", function () { return this.$MakeCallMethod(); }, true);
JSIL.InterfaceMethod.prototype.Rebind = function (newTypeObject, newSignature) {
var result = new JSIL.InterfaceMethod(newTypeObject, this.methodName, newSignature, this.parameterInfo);
result.fallbackMethod = this.fallbackMethod;
return result;
};
JSIL.InterfaceMethod.prototype.GetVariantInvocationCandidates = function (thisReference) {
var cache = this.variantInvocationCandidateCache;
var typeId = thisReference.__ThisTypeId__;
var result = cache[typeId];
if (typeof (result) === "undefined") {
cache[typeId] = result = JSIL.$GenerateVariantInvocationCandidates(
this.typeObject, this.signature, this.qualifiedName, this.variantGenericArguments, JSIL.GetType(thisReference)
);
}
return result;
};
JSIL.InterfaceMethod.prototype.MethodLookupFailed = function (thisReference) {
var variantInvocationCandidates = this.GetVariantInvocationCandidates(thisReference);
var errorString = "Method '" + this.signature.toString(this.methodName) + "' of interface '" +
this.typeObject.__FullName__ + "' is not implemented by object " +
thisReference + "\n";
if (variantInvocationCandidates) {
errorString += "(Looked for key(s): '";
errorString += this.methodKey + "'";
for (var i = 0, l = variantInvocationCandidates.length; i < l; i++) {
var candidate = variantInvocationCandidates[i];
errorString += ", \n'" + candidate + "'";
}
errorString += ")";
} else {
errorString += "(Looked for key '" + this.methodKey + "')";
}
JSIL.RuntimeError(errorString);
};
JSIL.InterfaceMethod.prototype.LookupMethod = function (thisReference, name) {
var methodKey;
if (this.variantGenericArguments.length > 0) {
methodKey = this.LookupVariantMethodKey(thisReference);
} else {
methodKey = this.methodKey;
}
var result = thisReference[methodKey];
if (!result)
this.MethodLookupFailed(thisReference);
return result;
};
JSIL.InterfaceMethod.prototype.LookupVariantMethodKey = function (thisReference) {
var variantInvocationCandidates = this.GetVariantInvocationCandidates(thisReference);
if (variantInvocationCandidates) {
for (var i = 0, l = variantInvocationCandidates.length; i < l; i++) {
var candidate = variantInvocationCandidates[i];
var variantResult = thisReference[candidate];
if (variantResult)
return candidate;
}
}
return this.methodKey;
};
JSIL.InterfaceMethod.prototype.$MakeCallMethod = function () {
if (this.typeObject.__IsClosed__ && this.signature.IsClosed) {
var callType =
(this.variantGenericArguments.length > 0)
? "CallVariantInterface"
: "CallInterface";
var fallbackMethod = this.fallbackMethod;
Object.defineProperty(
this, "fallbackMethod",
{
value: fallbackMethod,
writable: false,
writeable: false,
configurable: false
}
);
return this.signature.$MakeCallMethod(callType, this.methodKey, fallbackMethod);
} else {
return function () {
JSIL.RuntimeError("Cannot invoke method '" + this.methodName + "' of open generic interface '" + this.typeObject.__FullName__ + "'");
};
}
};
JSIL.InterfaceMethod.prototype.toString = function () {
// HACK: This makes it possible to do
// MethodSignature.CallVirtual(IFoo.Method, thisReference)
return this.qualifiedName;
};
JSIL.$GetSignaturePrefixForType = function (typeObject) {
if (typeObject.IsInterface) {
if (typeObject.__OpenType__)
return "I" + typeObject.__OpenType__.__TypeId__ + "$";
else
return "I" + typeObject.__TypeId__ + "$";
} else {
return "";
}
};
//
// System.Type.cs
//
// Author:
// Rodrigo Kumpera <[email protected]>
//
//
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
//
// 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.
//
JSIL.TypeNameParseState = function (input, fromPosition) {
this.input = input;
this.pos = fromPosition;
};
Object.defineProperty(JSIL.TypeNameParseState.prototype, "eof", {
get: function () {
return this.pos >= this.input.length;
}
});
Object.defineProperty(JSIL.TypeNameParseState.prototype, "current", {
get: function () {
return this.input[this.pos];
}
});
JSIL.TypeNameParseState.prototype.substr = function (start, count) {
return this.input.substr(start, count);
};
JSIL.TypeNameParseState.prototype.moveNext = function () {
this.pos += 1;
return (this.pos < this.input.length);
};
JSIL.TypeNameParseState.prototype.skipWhitespace = function () {
var length = this.input.length;
while ((this.pos < length) && (this.current === ' '))
this.pos += 1;
};
JSIL.TypeNameParseResult = function () {
this.type = null;
this.assembly = null;
this.genericArguments = [];
this.arraySpec = [];
this.pointerLevel = 0;
this.isByRef = false;
this.parseEndedAt = null;
};
Object.defineProperty(JSIL.TypeNameParseResult.prototype, "isArray", {
get: function () {
return this.arraySpec.length > 0;
}
});
JSIL.TypeNameParseResult.prototype.addName = function (name) {
if (!this.type)
this.type = name;
else
this.type += "+" + name;
};
JSIL.TypeNameParseResult.prototype.addArray = function (array) {
this.arraySpec.push(array);
};
JSIL.ParseTypeNameImpl = function (input, fromPosition, isRecursive, allowQualifiedNames) {
var state = new JSIL.TypeNameParseState(input, fromPosition);
var inModifiers = false;
state.skipWhitespace();
var startPosition = state.pos;
var result = new JSIL.TypeNameParseResult();
while (state.moveNext()) {
switch (state.current) {
case '+':
result.addName(state.substr(startPosition, state.pos - startPosition));
startPosition = state.pos + 1;
break;
case ',':
case ']':
result.addName(state.substr(startPosition, state.pos - startPosition));
startPosition = state.pos + 1;
inModifiers = true;
if (isRecursive && !allowQualifiedNames) {
result.parseEndedAt = state.pos;
return result;
}
break;
case '&':
case '*':
case '[':
if (isRecursive && (state.current !== '['))
JSIL.RuntimeError("Generic argument must be by-value and not a pointer");
result.addName(state.substr(startPosition, state.pos - startPosition));
startPosition = state.pos + 1;
inModifiers = true;
break;
}
if (inModifiers)
break;
}
if (startPosition < state.pos)
result.addName(state.substr(startPosition, state.pos - startPosition));
if (!inModifiers) {
result.parseEndedAt = state.pos;
return result;
}
state.pos -= 1;
while (state.moveNext()) {
switch (state.current) {
case '&':
if (result.isByRef)
JSIL.RuntimeError("Too many &s");
result.isByRef = true;
break;
case '*':
if (result.isByRef)
JSIL.RuntimeError("Can't have a pointer to a byref type");
result.pointerLevel += 1;
break;
case ',':
if (isRecursive) {
var length = state.input.length, end = state.pos;
while (end < length && state.input[end] !== ']')
end += 1;
if (end >= length)
JSIL.RuntimeError("Unmatched '['");
result.assembly = state.substr(state.pos + 1, end - state.pos - 1).trim();
state.pos = end + 1;
result.parseEndedAt = state.pos;
return result;
}
result.assembly = state.substr(state.pos + 1).trim();
state.pos = length;
break;
case '[':
if (result.isByRef)
JSIL.RuntimeError("ByRef qualifier must be last part of type");
state.pos += 1;
if (state.pos >= length)
JSIL.RuntimeError("Invalid array/generic spec");
state.skipWhitespace();
var sch = state.current;
if (
(sch !== ',') &&
(sch !== '*') &&
(sch !== ']')
) {
//generic args
if (result.isArray)
throw new ArgumentException ("generic args after array spec", "typeName");
while (!state.eof) {
state.skipWhitespace();
var aqn = state.current === '[';
if (aqn)
state.moveNext();
var subspec = JSIL.ParseTypeNameImpl(state.input, state.pos, true, aqn);
state.pos = subspec.parseEndedAt;
result.genericArguments.push(subspec);
if (state.eof)
JSIL.RuntimeError("Invalid generic args spec");
if (state.current === ']')
break;
else if (state.current === ',')
state.moveNext();
else
JSIL.RuntimeError("Invalid generic args separator");
}
if (state.eof || (state.current !== ']'))
JSIL.RuntimeError("Invalid generic args spec");
} else {
//array spec
var dimensions = 1, bound = false;
while (!state.eof && (state.current !== ']')) {
if (state.current === '*') {
if (bound)
JSIL.RuntimeError("Array spec has too many bound dimensions");
bound = true;
} else if (state.current !== ',') {
JSIL.RuntimeError("Invalid character in array spec");
} else {
dimensions += 1;
}
state.moveNext();
state.skipWhitespace();
}
if (state.current !== ']')
JSIL.RuntimeError("Invalid array spec");
if ((dimensions > 1) && bound)
JSIL.RuntimeError("Invalid array spec: Multi-dimensional array can't be bound");
result.addArray({
dimensions: dimensions,
bound: bound
});
}
break;
case ']':
if (isRecursive) {
result.parseEndedAt = state.pos;
return result;
}
JSIL.RuntimeError("Unmatched ']'");
default:
JSIL.RuntimeError("Invalid type spec");
}
}
return result;
};
JSIL.ParseTypeName = function (name) {
return JSIL.ParseTypeNameImpl(name, 0, false, true);
};
JSIL.GetTypeInternal = function (parsedTypeName, defaultContext, throwOnFail) {
var context = null;
if (parsedTypeName.assembly !== null)
context = JSIL.GetAssembly(parsedTypeName.assembly, true);
if (context === null)
context = defaultContext;
var ga = null;
if (parsedTypeName.genericArguments !== null) {
ga = new Array(parsedTypeName.genericArguments.length);
for (var i = 0, l = ga.length; i < l; i++) {
ga[i] = JSIL.GetTypeInternal(parsedTypeName.genericArguments[i], defaultContext, false);
if (ga[i] === null) {
if (throwOnFail)
JSIL.RuntimeError("Unable to resolve generic argument '" + parsedTypeName.genericArguments[i].type + "'");
else
return null;
}
}
}
return JSIL.GetTypeFromAssembly(context, parsedTypeName.type, ga, throwOnFail);
};
JSIL.GetTypeFromAssembly = function (assembly, typeName, genericArguments, throwOnFail) {
var resolved, result = null;
var publicInterface = assembly.__PublicInterface__ || assembly;
assembly = publicInterface.__Assembly__;
resolved = JSIL.ResolveName(publicInterface, typeName, true, throwOnFail === true);
if (resolved === null)
return null;
if (resolved.exists()) {
result = resolved.get();
if (JSIL.IsArray(genericArguments) && (genericArguments.length > 0))
result = result.Of.apply(result, genericArguments);
} else if (throwOnFail) {
throw new System.TypeLoadException("The type '" + typeName + "' could not be found in the assembly '" + assembly.toString() + "'.");
}
if (result !== null)
return result.__Type__;
else
return null;
};
JSIL.GetTypesFromAssembly = function (assembly) {
var publicInterface = assembly.__PublicInterface__ || assembly;
assembly = publicInterface.__Assembly__;
var result = [];
var types = publicInterface.$typesByName;
for (var k in types) {
var typeFunction = types[k];
var publicInterface = typeFunction(false);
var type = publicInterface.__Type__;
result.push(type);
}
return result;
};
JSIL.$CreateInstanceOfTypeTable = JSIL.CreateDictionaryObject(null);
JSIL.CreateInstanceOfTypeRecordSet = function (type) {
this.records = JSIL.CreateDictionaryObject(null);
};
JSIL.CreateInstanceOfTypeRecord = function (
type, publicInterface,
constructorName, constructor,
specialValue
) {
JSIL.RunStaticConstructors(publicInterface, type);
var closure = JSIL.CreateDictionaryObject(null);
var constructorBody = [];
this.type = type;
this.constructorName = constructorName;
this.constructor = constructor;
this.specialValue = specialValue;
this.argumentlessInstanceConstructor = null;
// FIXME: I think this runs the field initializer twice? :(
var fi = JSIL.GetFieldInitializer(type);
if (fi) {
closure.fieldInitializer = fi;
constructorBody.push("fieldInitializer(this);");
}
if ((constructorName === null) && (constructor === null)) {
} else {
if (type.__IsStruct__) {
this.argumentlessInstanceConstructor = JSIL.CreateNamedFunction(
type.__FullName__ + ".CreateInstanceOfType$NoArguments",
[],
constructorBody.join("\r\n"),
closure
);
this.argumentlessInstanceConstructor.prototype = publicInterface.prototype;
} else {
constructorBody.push("if ((typeof (argv) === 'undefined') || (argv === null)) argv = [];");
}
if (constructor) {
closure.actualConstructor = constructor;
constructorBody.push("return actualConstructor.apply(this, argv);");
}
}
this.instanceConstructor = JSIL.CreateNamedFunction(
type.__FullName__ + ".CreateInstanceOfType",
["argv"],
constructorBody.join("\r\n"),
closure
);
this.instanceConstructor.prototype = publicInterface.prototype;
};
JSIL.CreateInstanceOfType$CacheMiss = function (type, constructorName, constructorArguments, recordSet) {
if (!recordSet)
recordSet = JSIL.$CreateInstanceOfTypeTable[type.__TypeId__] =
new JSIL.CreateInstanceOfTypeRecordSet(type);
var publicInterface = type.__PublicInterface__;
var record = null;
if (type.__IsNativeType__) {
var specialValue = JSIL.DefaultValue(type);
record = new JSIL.CreateInstanceOfTypeRecord(
type, publicInterface, null, null, specialValue
);
} else if (typeof (constructorName) === "string") {
var constructor = publicInterface.prototype[constructorName];
if (!constructor)
JSIL.RuntimeError("Type '" + type.__FullName__ + "' does not have a constructor named '" + constructorName + "'");
record = new JSIL.CreateInstanceOfTypeRecord(
type, publicInterface, constructorName, constructor, null
);
} else if (typeof (constructorName) === "function") {
record = new JSIL.CreateInstanceOfTypeRecord(
type, publicInterface, constructorName, constructorName, null
);
} else {
record = new JSIL.CreateInstanceOfTypeRecord(
type, publicInterface, null, null, null
);
}
if (type.__IsClosed__ === false)
JSIL.RuntimeError("Cannot create an instance of an open type");
else if (type.IsInterface)
JSIL.RuntimeError("Cannot create an instance of an interface");
recordSet.records[constructorName] = record;
return JSIL.CreateInstanceOfType$CacheHit(type, record, constructorArguments);
};
JSIL.CreateInstanceOfType$CacheHit = function (type, record, constructorArguments) {
if (type.__IsNativeType__) {
// Native types need to be constructed differently.
if (record.specialValue !== null)
return record.specialValue;
else
return record.constructor.apply(record.constructor, constructorArguments);
} else {
if (
(constructorArguments === null) ||
(constructorArguments === undefined) ||
(constructorArguments.length === 0)
) {
if (record.argumentlessInstanceConstructor !== null)
return new (record.argumentlessInstanceConstructor)();
else
return new (record.instanceConstructor)($jsilcore.ArrayNull);
} else {
return new (record.instanceConstructor)(constructorArguments);
}
}
};
JSIL.CreateInstanceOfType = function (type, $constructorName, $constructorArguments) {
var constructorName = null, constructorArguments = null;
if (arguments.length < 2)
constructorName = "_ctor";
else
constructorName = $constructorName;
if (arguments.length < 3)
constructorArguments = null;
else
constructorArguments = $constructorArguments;
var recordSet = JSIL.$CreateInstanceOfTypeTable[type.__TypeId__] || null;
if (recordSet) {
var record = recordSet.records[constructorName] || null;
if (record) {
return JSIL.CreateInstanceOfType$CacheHit(type, record, constructorArguments);
} else {
return JSIL.CreateInstanceOfType$CacheMiss(type, constructorName, constructorArguments, recordSet);
}
} else {
return JSIL.CreateInstanceOfType$CacheMiss(type, constructorName, constructorArguments, null);
}
};
$jsilcore.BindingFlags = {
Default: 0,
IgnoreCase: 1,
DeclaredOnly: 2,
Instance: 4,
Static: 8,
Public: 16,
NonPublic: 32,
FlattenHierarchy: 64,
InvokeMethod: 256,
CreateInstance: 512,
GetField: 1024,
SetField: 2048,
GetProperty: 4096,
SetProperty: 8192,
PutDispProperty: 16384,
PutRefDispProperty: 32768,
ExactBinding: 65536,
SuppressChangeType: 131072,
OptionalParamBinding: 262144,
IgnoreReturn: 16777216,
$Flags: function () {
var result = 0;
for (var i = 0; i < arguments.length; i++) {
result |= $jsilcore.BindingFlags[arguments[i]];
}
return result;
}
};
// Ensures that all the type's members have associated MemberInfo instances and returns them.
JSIL.GetReflectionCache = function (typeObject) {
if (typeof (typeObject) === "undefined")
return null;
if (typeObject === null)
return null;
var cache = typeObject.__ReflectionCache__;
if (JSIL.IsArray(cache))
return cache;
var members = typeObject.__Members__;
if (!JSIL.IsArray(members))
return null;
cache = typeObject.__ReflectionCache__ = [];
var makeTypeInstance = function (type) {
// Construct the appropriate subclass of MemberInfo
var parsedTypeName = JSIL.ParseTypeName("System.Reflection." + type);
var infoType = JSIL.GetTypeInternal(parsedTypeName, $jsilcore, true);
var info = JSIL.CreateInstanceOfType(infoType, null);
/*
// Don't trigger type initialization machinery
// FIXME: This will break if any of the memberinfo types rely on static constructors.
var infoType = JSIL.GetTypeByName("System.Reflection." + type, $jsilcore);
var info = Object.create(infoType.prototype);
*/
// HACK: Makes it possible to tell what type a member is trivially
JSIL.SetValueProperty(info, "__MemberType__", type);
return info;
};
for (var i = 0, l = members.length; i < l; i++) {
var member = members[i];
if (!member)
continue;
var type = member.type;
var descriptor = member.descriptor;
var data = member.data;
var info = makeTypeInstance(type);
info._typeObject = typeObject;
info._data = data;
info._descriptor = descriptor;
info.__Attributes__ = member.attributes;
info.__Overrides__ = member.overrides;
cache.push(info);
}
return cache;
};
// Scans the specified type (and its base types, as necessary) to retrieve all the MemberInfo instances appropriate for a request.
// If any BindingFlags are specified in flags they are applied as filters to limit the number of members returned.
// If memberType is specified and is the short name of a MemberInfo subclass like 'FieldInfo', only members of that type are returned.
JSIL.GetMembersInternal = function (typeObject, flags, memberType, name) {
var result = [];
var bindingFlags = $jsilcore.BindingFlags;
var allMethodsIncludingSpecialNames = (memberType === "$AllMethods");
var methodOrConstructor = (memberType === "$MethodOrConstructor") || allMethodsIncludingSpecialNames;
var allowInherited = ((flags & bindingFlags.DeclaredOnly) == 0) &&
// FIXME: WTF is going on here?
!typeObject.IsInterface;
var publicOnly = (flags & bindingFlags.Public) != 0;
var nonPublicOnly = (flags & bindingFlags.NonPublic) != 0;
if (publicOnly && nonPublicOnly)
publicOnly = nonPublicOnly = false;
// FIXME: Is this right?
else if (!publicOnly && !nonPublicOnly)
return result;
var staticOnly = (flags & bindingFlags.Static) != 0;
var instanceOnly = (flags & bindingFlags.Instance) != 0;
if (staticOnly && instanceOnly)
staticOnly = instanceOnly = false;
var members = [];
var target = typeObject;
while (target !== null) {
var targetMembers = JSIL.GetReflectionCache(target);
if (targetMembers === null)
break;
members = targetMembers.concat(members);
if (!allowInherited)
break;
target = target.__BaseType__;
}
for (var i = 0, l = members.length; i < l; i++) {
var member = members[i];
// HACK: Reflection never seems to enumerate static constructors. This is probably because
// it doesn't make any sense to invoke them explicitly anyway, and they don't have arguments...
if (
!allMethodsIncludingSpecialNames &&
member._descriptor.Static &&
member._descriptor.SpecialName &&
member._descriptor.Name.indexOf("cctor") >= 0
)
continue;
if (publicOnly && !member._descriptor.Public)
continue;
else if (nonPublicOnly && member._descriptor.Public)
continue;
if (staticOnly && !member._descriptor.Static)
continue;
else if (instanceOnly && member._descriptor.Static)
continue;
var currentMemberType = member.__ThisType__.__ShortName__;
if (methodOrConstructor) {
if (
(currentMemberType != "MethodInfo") &&
(currentMemberType != "ConstructorInfo")
)
continue;
} else if ((typeof (memberType) === "string") && (memberType != currentMemberType)) {
continue;
}
if ((typeof (name) === "string") && (name != member._descriptor.Name)) {
continue;
}
result.push(member);
}
return result;
};
JSIL.AnyValueType = JSIL.AnyType = {
__TypeId__: "any",
CheckType: function (value) {
return true;
}
};
JSIL.ApplyCollectionInitializer = function (target, values) {
for (var i = 0, l = values.length; i < l; i++)
target.Add.apply(target, values[i]);
};
JSIL.StructEquals = function Struct_Equals (lhs, rhs) {
if (lhs === rhs)
return true;
if ((rhs === null) || (rhs === undefined))
return false;
var thisType = lhs.__ThisType__;
var comparer = thisType.__Comparer__;
if (comparer === $jsilcore.FunctionNotInitialized)
comparer = thisType.__Comparer__ = JSIL.$MakeStructComparer(thisType, thisType.__PublicInterface__);
return comparer(lhs, rhs);
};
JSIL.DefaultValueInternal = function (typeObject, typePublicInterface) {
var fullName = typeObject.__FullName__;
if (fullName === "System.Char") {
return "\0";
} else if (fullName === "System.Boolean") {
return false;
} else if (typeObject.__IsReferenceType__) {
return null;
} else if (typeObject.__IsNumeric__) {
return 0;
} else if (typeObject.__IsEnum__) {
return typePublicInterface[typeObject.__ValueToName__[0]];
} else {
return new typePublicInterface();
}
};
JSIL.DefaultValue = function (type) {
var typeObject, typePublicInterface;
if (!type)
JSIL.RuntimeError("No type passed into DefaultValue");
if (typeof (type.__Type__) === "object") {
typeObject = type.__Type__;
typePublicInterface = type;
} else if (typeof (type.__PublicInterface__) !== "undefined") {
typeObject = type;
typePublicInterface = type.__PublicInterface__;
}
if (typeObject && typePublicInterface) {
return JSIL.DefaultValueInternal(typeObject, typePublicInterface);
} else {
// Handle stupid special cases
if ((type === Object) || (type === Array) || (type === String))
return null;
else if (type === Number)
return 0;
JSIL.RuntimeError("Invalid type passed into DefaultValue: " + String(type));
}
};
JSIL.Array.GetElements = function (array) {
if (Object.getPrototypeOf(array) === JSIL.MultidimensionalArray.prototype)
return array._items;
else if (JSIL.IsArray(array))
return array;
else
JSIL.RuntimeError("Argument is not an array");
};
JSIL.Array.$EraseImplementations = JSIL.CreateDictionaryObject(null);
// Creating a unique implementation of Erase for every element type
// allows JITs to optimize it more aggressively by making ICs monomorphic
JSIL.Array.$GetEraseImplementation = function (elementTypeObject, elementTypePublicInterface) {
var result = JSIL.Array.$EraseImplementations[elementTypeObject.__TypeId__];
if (!result) {
var body = [
"length = length | 0;",
"startIndex = startIndex | 0;",
"",
"if (length > elements.length)",
" JSIL.RuntimeError('Length out of range');",
""
];
if (elementTypeObject.__IsNativeType__) {
body.push("var defaultValue = JSIL.DefaultValueInternal(elementTypeObject, elementTypePublicInterface);");
} else if (elementTypeObject.__IsEnum__) {
body.push("var defaultValue = elementTypePublicInterface.$Cast(0);");
} else if (!elementTypeObject.__IsStruct__) {
body.push("var defaultValue = null;");
}
body.push("");
body.push("for (var i = 0; i < length; i = (i + 1) | 0)");
if (elementTypeObject.__IsStruct__) {
body.push(" elements[(i + startIndex) | 0] = new elementTypePublicInterface();");
} else {
body.push(" elements[(i + startIndex) | 0] = defaultValue;");
}
result = JSIL.CreateNamedFunction(
elementTypeObject.__FullName__ + "[].Erase",
["elements", "startIndex", "length"],
body.join("\n"),
{
elementTypeObject: elementTypeObject,
elementTypePublicInterface: elementTypePublicInterface
}
);
JSIL.Array.$EraseImplementations[elementTypeObject.__TypeId__] = result;
}
return result;
};
// startIndex and length are optional
JSIL.Array.Erase = function Array_Erase (array, elementType, startIndex, length) {
var elementTypeObject, elementTypePublicInterface;
if (typeof (elementType.__Type__) === "object") {
elementTypeObject = elementType.__Type__;
elementTypePublicInterface = elementType;
} else if (typeof (elementType.__PublicInterface__) !== "undefined") {
elementTypeObject = elementType;
elementTypePublicInterface = elementType.__PublicInterface__;
}
var elements = JSIL.Array.GetElements(array);
if (typeof (startIndex) !== "number")
startIndex = 0;
startIndex = startIndex | 0;
if (typeof (length) !== "number")
length = elements.length - startIndex;
length = length | 0;
var impl = JSIL.Array.$GetEraseImplementation(elementTypeObject, elementTypePublicInterface);
impl(elements, startIndex, length);
};
JSIL.Array.New = function Array_New (elementType, sizeOrInitializer) {
var elementTypeObject = null, elementTypePublicInterface = null;
if (typeof (elementType.__Type__) === "object") {
elementTypeObject = elementType.__Type__;
elementTypePublicInterface = elementType;
} else if (typeof (elementType.__PublicInterface__) !== "undefined") {
elementTypeObject = elementType;
elementTypePublicInterface = elementType.__PublicInterface__;
}
var result = null, size = 0;
var initializerIsArray = JSIL.IsArray(sizeOrInitializer);
if (initializerIsArray) {
size = sizeOrInitializer.length;
} else {
size = Number(sizeOrInitializer);
}
var typedArrayCtor = JSIL.GetTypedArrayConstructorForElementType(elementTypeObject, false);
if (typedArrayCtor) {
result = new (typedArrayCtor)(size);
} else {
result = new Array(size);
}
if (initializerIsArray) {
// If non-numeric, assume array initializer
for (var i = 0; i < sizeOrInitializer.length; i++)
result[i] = sizeOrInitializer[i];
} else if (!typedArrayCtor) {
JSIL.Array.Erase(result, elementType);
}
return result;
};
JSIL.Array.Clone = function (array) {
if (JSIL.IsTypedArray(array)) {
var ctor = Object.getPrototypeOf(array).constructor;
return new ctor(array);
} else if (Object.getPrototypeOf(array) === JSIL.MultidimensionalArray.prototype) {
return new JSIL.MultidimensionalArray(array._type, array._dimensions, array._items);
} else if (JSIL.IsArray(array)) {
return Array.prototype.slice.call(array);
} else {
JSIL.RuntimeError("Invalid array");
}
};
JSIL.Array.CopyTo = function (source, destination, destinationIndex) {
if (JSIL.IsTypedArray(destination)) {
destination.set(source, destinationIndex);
return;
}
var srcArray = JSIL.Array.GetElements(source);
var destArray = JSIL.Array.GetElements(destination);
var size = Math.min(srcArray.length, destArray.length);
for (var i = 0; i < size; i++)
destArray[i + destinationIndex] = srcArray[i];
};
JSIL.Array.ShallowCopy = function (destination, source) {
JSIL.Array.CopyTo(source, destination, 0);
};
$jsilcore.CheckDelegateType = function (value) {
if (value === null)
return false;
return (
(typeof (value) === "function") ||
(typeof (value) === "object")
) && (value.__ThisType__ === this);
};
JSIL.MakeDelegate = function (fullName, isPublic, genericArguments, methodSignature, pInvokeInfo) {
var assembly = $private;
var localName = JSIL.GetLocalName(fullName);
var callStack = null;
if (typeof (printStackTrace) === "function")
callStack = printStackTrace();
var creator = function CreateDelegate () {
var delegateType;
delegateType = JSIL.GetTypeByName("System.MulticastDelegate", $jsilcore).__Type__;
var typeObject = JSIL.$MakeTypeObject(fullName);
typeObject.__Context__ = assembly;
JSIL.SetValueProperty(typeObject, "__BaseType__", delegateType);
JSIL.SetValueProperty(typeObject, "__FullName__", fullName);
typeObject.__CallStack__ = callStack;
typeObject.__Interfaces__ = [];
typeObject.__IsDelegate__ = true;
JSIL.SetValueProperty(typeObject, "__IsReferenceType__", true);
typeObject.__AssignableTypes__ = null;
typeObject.__IsEnum__ = false;
typeObject.__IsValueType__ = false;
typeObject.__IsByRef__ = false;
typeObject.__TypeInitialized__ = false;
JSIL.FillTypeObjectGenericArguments(typeObject, genericArguments);
var staticClassObject = typeObject.__PublicInterface__ = JSIL.CreateSingletonObject(JSIL.StaticClassPrototype);
staticClassObject.__Type__ = typeObject;
staticClassObject.prototype = JSIL.CreatePrototypeObject($jsilcore.System.MulticastDelegate.prototype);
var toStringImpl = function DelegateType_ToString () {
return this.__ThisType__.toString();
};
var pinImpl = function Delegate_Pin () {
this.__pinnedPointer__ =
System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate$b1(
this.__ThisType__
)(
this
);
};
var unpinImpl = function Delegate_Unpin () {
this.__pinnedPointer__ = null;
};
var asIntPtrImpl = function Delegate_AsIntPtr () {
if (this.__pinnedPointer__)
return this.__pinnedPointer__;
else
JSIL.RuntimeErrorFormat("Delegate of type {0} is not pinned and cannot be packed/marshalled", [this.__ThisType__]);
};
JSIL.SetValueProperty(staticClassObject, "CheckType", $jsilcore.CheckDelegateType.bind(typeObject));
JSIL.SetValueProperty(staticClassObject, "New", function (object, method, methodInfoResolver) {
if ((typeof (method) === "undefined") &&
(typeof (object) === "function")
) {
method = object;
object = null;
if (method.__ThisType__ === typeObject)
return method;
else
JSIL.RuntimeError("Single delegate argument passed to Delegate.New, but types don't match");
}
if (typeof (method) !== "function") {
JSIL.RuntimeError("Non-function passed to Delegate.New");
}
if (method.__IsMembrane__)
method = method.__Unwrap__();
var resultDelegate = function Delegate_Invoke () {
return method.apply(object, arguments);
};
JSIL.SetValueProperty(resultDelegate, "__ThisType__", this.__Type__);
JSIL.SetValueProperty(resultDelegate, "toString", toStringImpl);
JSIL.SetValueProperty(resultDelegate, "__object__", object);
JSIL.SetValueProperty(resultDelegate, "__method__", method);
JSIL.SetValueProperty(resultDelegate, "__isMulticast__", false);
JSIL.SetValueProperty(resultDelegate, "Invoke", method);
JSIL.SetValueProperty(resultDelegate, "get_Method", this.__Type__.__PublicInterface__.prototype.get_Method);
JSIL.SetValueProperty(resultDelegate, "__methodInfoResolver__", methodInfoResolver);
// FIXME: Move these off the object to reduce cost of constructing delegates
JSIL.SetValueProperty(resultDelegate, "$pin", pinImpl);
JSIL.SetValueProperty(resultDelegate, "$unpin", unpinImpl);
JSIL.SetValueProperty(resultDelegate, "$asIntPtr", asIntPtrImpl);
resultDelegate.__isMethodInfoResolved__ = false;
return resultDelegate;
});
JSIL.SetTypeId(
typeObject, staticClassObject, JSIL.AssignTypeId(assembly, fullName)
);
if (typeObject.__GenericArguments__.length > 0) {
staticClassObject.Of$NoInitialize = $jsilcore.$MakeOf$NoInitialize(staticClassObject);
staticClassObject.Of = $jsilcore.$MakeOf(staticClassObject);
typeObject.__IsClosed__ = false;
typeObject.__OfCache__ = {};
} else {
typeObject.__IsClosed__ = true;
typeObject.__AssignableFromTypes__ = {};
}
JSIL.MakeCastMethods(staticClassObject, typeObject, "delegate");
if (methodSignature) {
var ib = new JSIL.InterfaceBuilder(assembly, typeObject, staticClassObject);
ib.Method({Static:false , Public:true }, "Invoke",
methodSignature,
function() {return this.__method__.apply(this, arguments);});
typeObject.__Signature__ = methodSignature;
} else {
typeObject.__Signature__ = null;
}
if (pInvokeInfo) {
typeObject.__PInvokeInfo__ = pInvokeInfo;
} else {
typeObject.__PInvokeInfo__ = null;
}
return staticClassObject;
};
JSIL.RegisterName(fullName, assembly, isPublic, creator);
};
JSIL.StringToByteArray = function (text) {
var result = JSIL.Array.New(System.Byte, text.length);
for (var i = 0, l = text.length; i < l; i++)
result[i] = text.charCodeAt(i) & 0xFF;
return result;
};
JSIL.StringToCharArray = function (text) {
var result = JSIL.Array.New(System.Char, text.length);
for (var i = 0, l = text.length; i < l; i++)
result[i] = text[i];
return result;
};
JSIL.$equalsSignature = null;
JSIL.GetEqualsSignature = function () {
if (JSIL.$equalsSignature === null)
JSIL.$equalsSignature = new JSIL.MethodSignature("System.Boolean", ["System.Object"], [], $jsilcore);
return JSIL.$equalsSignature;
}
JSIL.ObjectEquals = function (lhs, rhs) {
if ((lhs === null) || (rhs === null))
return lhs === rhs;
if (lhs === rhs)
return true;
switch (typeof (lhs)) {
case "string":
case "number":
return lhs == rhs;
break;
case "object":
var key = JSIL.GetEqualsSignature().GetNamedKey("Object_Equals", true);
var fn = lhs[key];
if (fn)
return fn.call(lhs, rhs);
break;
}
return false;
};
JSIL.CompareValues = function (lhs, rhs) {
if (lhs > rhs)
return 1;
else if (lhs < rhs)
return -1;
else
return 0;
};
var $nextHashCode = 0;
var $hashCodeWeakMap = null;
if (typeof (WeakMap) !== "undefined") {
$hashCodeWeakMap = new WeakMap();
JSIL.HashCodeInternal = function (obj) {
var hc = $hashCodeWeakMap.get(obj);
if (!hc) {
hc = (++$nextHashCode) | 0;
$hashCodeWeakMap.set(obj, hc);
}
return hc;
};
} else {
JSIL.HashCodeInternal = function (obj) {
var hc = obj.__HashCode__;
if (!hc)
hc = obj.__HashCode__ = (++$nextHashCode) | 0;
return hc;
};
}
JSIL.ObjectHashCode = function (obj) {
var type = typeof obj;
if (type === "object") {
if (obj.GetHashCode)
return (obj.GetHashCode() | 0);
return JSIL.HashCodeInternal(obj);
} else {
// FIXME: Not an integer. Gross.
return String(obj);
}
};
// MemberwiseClone if parameter is struct, otherwise do nothing.
JSIL.CloneParameter = function (parameterType, value) {
if (!parameterType)
JSIL.RuntimeError("Undefined parameter type");
if (
parameterType.__IsStruct__ &&
(parameterType.__IsNullable__ !== true) &&
// We have to check this because of some tricky semantic corner cases :/
(value !== null)
) {
return value.MemberwiseClone();
} else
return value;
};
JSIL.Nullable_Value = function (n) {
if (n === null)
throw new System.InvalidOperationException("Nullable has no value");
else
return n;
};
JSIL.Nullable_ValueOrDefault = function (n, defaultValue) {
if (n === null)
return defaultValue;
else
return n;
};
JSIL.Nullable_Cast = function (n, targetType) {
if (n === null)
return null;
else
return targetType.$Cast(n);
};
JSIL.GetMemberAttributes = function (memberInfo, inherit, attributeType, result) {
var tType = $jsilcore.System.Type;
var memberType = memberInfo.GetType().get_FullName();
if (inherit) {
if (memberType !== "System.Type")
throw new System.NotImplementedException("Inherited attributes only supported for types");
if (!result)
result = [];
var currentType = memberInfo;
while (currentType && currentType.GetType) {
JSIL.GetMemberAttributes(currentType, false, attributeType, result);
currentType = currentType.__BaseType__;
}
return result;
}
var attributes = memberInfo.__CachedAttributes__;
if (!attributes) {
attributes = memberInfo.__CachedAttributes__ = [];
var attributeRecords = memberInfo.__Attributes__;
if (attributeRecords) {
for (var i = 0, l = attributeRecords.length; i < l; i++) {
var record = attributeRecords[i];
var recordType = record.GetType();
var instance = record.Construct();
attributes.push(instance);
}
}
}
if (!result)
result = [];
for (var i = 0, l = attributes.length; i < l; i++) {
var attribute = attributes[i];
if (attributeType && !tType.op_Equality(attributeType, attribute.GetType()))
continue;
result.push(attributes[i]);
}
return result;
};
var $blobBuilderInfo = {
initialized: false,
retainedBlobs: []
};
JSIL.InitBlobBuilder = function () {
if ($blobBuilderInfo.initialized)
return;
var blobBuilder = window.WebKitBlobBuilder || window.mozBlobBuilder || window.MSBlobBuilder || window.BlobBuilder;
$blobBuilderInfo.hasObjectURL = (typeof (window.URL) !== "undefined") && (typeof (window.URL.createObjectURL) === "function");
$blobBuilderInfo.hasBlobBuilder = Boolean(blobBuilder);
$blobBuilderInfo.blobBuilder = blobBuilder;
$blobBuilderInfo.hasBlobCtor = false;
$blobBuilderInfo.applyIEHack = navigator.userAgent.indexOf("Trident/") >= 0;
try {
var blob = new Blob();
$blobBuilderInfo.hasBlobCtor = Boolean(blob);
} catch (exc) {
}
if (navigator.userAgent.indexOf("Firefox/14.") >= 0) {
JSIL.Host.logWriteLine("Your browser is outdated and has a serious bug. Please update to a newer version.");
$blobBuilderInfo.hasBlobBuilder = false;
$blobBuilderInfo.hasBlobCtor = false;
}
}
JSIL.GetObjectURLForBytes = function (bytes, mimeType) {
JSIL.InitBlobBuilder();
if (!$blobBuilderInfo.hasObjectURL)
JSIL.RuntimeError("Object URLs not available");
else if (!("Uint8Array" in window))
JSIL.RuntimeError("Typed arrays not available");
var blob = null;
if (Object.getPrototypeOf(bytes) !== Uint8Array.prototype)
JSIL.RuntimeError("bytes must be a Uint8Array");
try {
if ($blobBuilderInfo.hasBlobCtor) {
blob = new Blob([bytes], { type: mimeType });
}
} catch (exc) {
}
if (!blob) {
try {
if ($blobBuilderInfo.hasBlobBuilder) {
var bb = new $blobBuilderInfo.blobBuilder();
bb.append(bytes.buffer);
blob = bb.getBlob(mimeType);
}
} catch (exc) {
}
}
if (!blob)
JSIL.RuntimeError("Blob API broken or not available");
if ($blobBuilderInfo.applyIEHack)
$blobBuilderInfo.retainedBlobs.push(blob);
return window.URL.createObjectURL(blob);
}
JSIL.BinarySearch = function (T, array, start, count, value, comparer) {
if (!Array.isArray(array))
throw new System.Exception("An array must be provided");
if (start < 0)
throw new System.ArgumentOutOfRangeException("start");
else if (start >= array.length)
throw new System.ArgumentOutOfRangeException("start");
else if (count < 0)
throw new System.ArgumentOutOfRangeException("count");
else if ((start + count) > array.length)
throw new System.ArgumentOutOfRangeException("count");
if (comparer === null)
comparer = System.Collections.Generic.Comparer$b1.Of(T).get_Default();
var low = start, high = start + count - 1, pivot;
while (low <= high) {
pivot = (low + (high - low) / 2) | 0;
var order = comparer.Compare(array[pivot], value);
if (order === 0)
return pivot;
else if (order < 0)
low = pivot + 1;
else
high = pivot - 1;
}
return ~low;
};
JSIL.ResolveGenericExternalMethods = function (publicInterface, typeObject) {
var externalMethods = typeObject.__ExternalMethods__;
if (!externalMethods)
return;
var result = typeObject.__ExternalMethods__ = new Array(externalMethods.length);
for (var i = 0, l = result.length; i < l; i++)
result[i] = JSIL.$ResolveGenericMethodSignature(typeObject, externalMethods[i], publicInterface) || externalMethods[i];
};
JSIL.FreezeImmutableObject = function (object) {
// Object.freeze and Object.seal make reads *slower* in modern versions of Chrome and older versions of Firefox.
if (jsilConfig.enableFreezeAndSeal === true)
Object.freeze(object);
};
JSIL.GetTypedArrayConstructorForElementType = function (typeObject, byteFallback) {
if (!typeObject)
JSIL.RuntimeError("typeObject was null");
var result = typeObject.__TypedArray__ || null;
if (!result && byteFallback) {
if (typeObject.__IsStruct__)
result = $jsilcore.System.Byte.__TypedArray__ || null;
}
return result;
};
JSIL.ResolveGenericMemberSignatures = function (publicInterface, typeObject) {
var members = typeObject.__Members__;
if (!JSIL.IsArray(members))
return;
members = typeObject.__Members__ = Array.prototype.slice.call(members);
var resolveContext = typeObject.__IsStatic__ ? publicInterface : publicInterface.prototype;
for (var i = 0, l = members.length; i < l; i++) {
var member = members[i];
var descriptor = member.descriptor;
var data = member.data;
if (!data)
continue;
var signature = data.signature;
if (!signature)
continue;
var resolvedSignature = JSIL.$ResolveGenericMethodSignature(
typeObject, signature, resolveContext
);
if (!resolvedSignature)
continue;
var newData = JSIL.CreateDictionaryObject(data);
if (!newData.genericSignature)
newData.genericSignature = signature;
newData.signature = resolvedSignature;
var newMember = new JSIL.MemberRecord(member.type, member.descriptor, newData, member.attributes, member.overrides);
members[i] = newMember;
}
};
JSIL.TypeReferenceToName = function (typeReference) {
var result = null;
if (
typeof (typeReference) === "string"
) {
return typeReference;
} else if (
typeof (typeReference) === "object"
) {
if (typeReference === null)
JSIL.RuntimeError("Null type reference");
if (Object.getPrototypeOf(typeReference) === JSIL.TypeRef.prototype)
return typeReference.toName();
}
if (typeof (typeReference.__Type__) === "object") {
return typeReference.__Type__.toString();
} else {
return typeReference.toString();
}
};
JSIL.FillTypeObjectGenericArguments = function (typeObject, argumentNames) {
var names = [];
var variances = [];
if (argumentNames) {
if (!JSIL.IsArray(argumentNames))
JSIL.RuntimeError("Generic argument names must be undefined or an array");
for (var i = 0, l = argumentNames.length; i < l; i++) {
var variance = {
"in": false,
"out": false
};
var argumentName = argumentNames[i];
var tokens = argumentName.trim().split(" ");
for (var j = 0; j < tokens.length - 1; j++) {
switch (tokens[j]) {
case "in":
variance.in = true;
break;
case "out":
variance.out = true;
break;
default:
JSIL.RuntimeError("Invalid generic argument modifier: " + tokens[j]);
}
}
variances.push(variance);
names.push(tokens[tokens.length - 1].trim());
}
}
typeObject.__GenericArguments__ = names;
typeObject.__GenericArgumentVariance__ = variances;
};
JSIL.GetTypeAndBases = function (typeObject) {
// FIXME: Memoize the result of this function?
var result = [typeObject];
JSIL.$EnumBasesOfType(typeObject, result);
return result;
};
JSIL.$EnumBasesOfType = function (typeObject, resultList) {
var currentType = typeObject;
while (currentType) {
var baseRef = currentType.__BaseType__;
if (!baseRef)
break;
var base = JSIL.ResolveTypeReference(baseRef, currentType.__Context__)[1];
if (base)
resultList.push(base);
currentType = base;
}
};
JSIL.GetInterfacesImplementedByType = function (typeObject, walkInterfaceBases, allowDuplicates, includeDistance) {
// FIXME: Memoize the result of this function?
if (arguments.length < 3)
JSIL.RuntimeError("3 arguments expected");
var typeAndBases = JSIL.GetTypeAndBases(typeObject);
var result = [];
var distanceList = [];
// Walk in reverse to match the behavior of JSIL.Internal.TypeInfo.AllInterfacesRecursive
typeAndBases.reverse();
for (var i = 0, l = typeAndBases.length; i < l; i++) {
var typeObject = typeAndBases[i];
var distance = (typeAndBases.length - i - 1);
JSIL.$EnumInterfacesImplementedByTypeExcludingBases(
typeObject, result, distanceList, walkInterfaceBases, allowDuplicates, distance
);
}
if (includeDistance)
return {
interfaces: result,
distances: distanceList
};
else
return result;
};
JSIL.$EnumInterfacesImplementedByTypeExcludingBases = function (typeObject, resultList, distanceList, walkInterfaceBases, allowDuplicates, distance) {
if (arguments.length !== 6)
JSIL.RuntimeError("6 arguments expected");
var interfaces = typeObject.__Interfaces__;
var toEnumerate = [];
if (interfaces && interfaces.length) {
for (var i = 0, l = interfaces.length; i < l; i++) {
var ifaceRef = interfaces[i];
var iface = JSIL.ResolveTypeReference(ifaceRef, typeObject.__Context__)[1];
if (!iface)
continue;
var alreadyAdded = resultList.indexOf(iface) >= 0;
if (!alreadyAdded || allowDuplicates) {
resultList.push(iface);
if (distanceList)
distanceList.push(distance);
}
if (!alreadyAdded && walkInterfaceBases)
toEnumerate.push(iface);
}
}
for (var i = 0, l = toEnumerate.length; i < l; i++) {
var iface = toEnumerate[i];
JSIL.$EnumInterfacesImplementedByTypeExcludingBases(iface, resultList, distanceList, walkInterfaceBases, allowDuplicates, distance + 1);
}
};
JSIL.$FindMatchingInterfacesThroughVariance = function (expectedInterfaceObject, actualTypeObject, variantParameters) {
// FIXME: Memoize the result of this function?
var result = [];
var trace = 0;
var record = function (distance, iface) {
this.distance = distance;
this.interface = iface;
};
record.prototype.toString = function () {
return "<" + this.interface.toString() + " (distance " + this.distance + ")>";
};
// We have to scan exhaustively through all the interfaces implemented by this type
// We turn on distance tracking, so the interface records are [distance, interface] instead of interface objects.
var obj = JSIL.GetInterfacesImplementedByType(actualTypeObject, true, false, true);
var interfaces = obj.interfaces;
var distances = obj.distances;
if (trace >= 2)
System.Console.WriteLine("Type {0} implements {1} interface(s): [ {2} ]", actualTypeObject.__FullName__, interfaces.length, interfaces.join(", "));
var openExpected = expectedInterfaceObject.__OpenType__;
if (!openExpected || !openExpected.IsInterface)
JSIL.RuntimeError("Expected interface object must be a closed generic interface type");
// Scan for interfaces that could potentially match through variance
for (var i = 0, l = interfaces.length; i < l; i++) {
var iface = interfaces[i];
var distance = distances[i];
var openIface = iface.__OpenType__;
// Variance only applies to closed generic interface types... I think.
if (!openIface || !openIface.IsInterface)
continue;
if (openIface !== openExpected)
continue;
var ifaceResult = true;
check_parameters:
for (var j = 0; j < variantParameters.length; j++) {
var vp = variantParameters[j];
var lhs = expectedInterfaceObject.__GenericArgumentValues__[vp.index];
var rhs = iface.__GenericArgumentValues__[vp.index];
var parameterResult = true;
var foundIndex = -1;
if (vp.in) {
if (rhs.IsInterface) {
var interfacesLhs = JSIL.GetInterfacesImplementedByType(lhs, true, true);
foundIndex = interfacesLhs.indexOf(rhs);
} else {
var typeAndBasesLhs = JSIL.GetTypeAndBases(lhs);
foundIndex = typeAndBasesLhs.indexOf(rhs);
}
if (foundIndex < 0)
ifaceResult = parameterResult = false;
}
if (vp.out) {
if (lhs.IsInterface) {
var interfacesRhs = JSIL.GetInterfacesImplementedByType(rhs, true, true);
foundIndex = interfacesRhs.indexOf(lhs);
} else {
var typeAndBasesRhs = JSIL.GetTypeAndBases(rhs);
foundIndex = typeAndBasesRhs.indexOf(lhs);
}
if (foundIndex < 0)
ifaceResult = parameterResult = false;
}
if (trace >= 1)
System.Console.WriteLine(
"Variance check {4}{5}{0}: {1} <-> {2} === {3}",
vp.name, lhs, rhs, parameterResult,
vp.in ? "in " : "", vp.out ? "out " : ""
);
}
if (ifaceResult)
result.push(new record(distance, iface));
}
return result;
};
JSIL.CheckInterfaceVariantEquality = function (expectedInterfaceObject, actualTypeObject, variantParameters) {
// FIXME: Memoize the result of this function?
var matchingInterfaces = JSIL.$FindMatchingInterfacesThroughVariance(expectedInterfaceObject, actualTypeObject, variantParameters);
return matchingInterfaces.length > 0;
};
JSIL.$FindVariantGenericArguments = function (typeObject) {
var result = [];
var argumentVariances = typeObject.__GenericArgumentVariance__;
if (!argumentVariances)
return result;
for (var i = 0, l = argumentVariances.length; i < l; i++) {
var variance = argumentVariances[i];
if (variance.in || variance.out) {
var vp = JSIL.CreateDictionaryObject(variance);
vp.name = typeObject.__GenericArguments__[i];
vp.index = i;
result.push(vp);
}
}
return result;
};
JSIL.WrapCastMethodsForInterfaceVariance = function (typeObject, isFunction, asFunction) {
var trace = false;
var result = {
"is": isFunction,
"as": asFunction
};
var variantParameters = JSIL.$FindVariantGenericArguments(typeObject);
if (variantParameters.length === 0) {
if (trace)
System.Console.WriteLine("None of interface {0}'s parameters are variant", typeObject.__FullName__);
return result;
}
result.is = function Is_VariantInterface (value) {
var result = isFunction(value);
if (trace)
System.Console.WriteLine("({0} is {1}) == {2}", value, typeObject.__FullName__, result);
if (!result)
result = JSIL.CheckInterfaceVariantEquality(typeObject, JSIL.GetType(value), variantParameters);
if (trace)
System.Console.WriteLine("({0} is {1}) == {2}", value, typeObject.__FullName__, result);
return result;
};
result.as = function As_VariantInterface (value) {
var result = asFunction(value);
if (trace && !result)
System.Console.WriteLine("{0} as {1} failed", value, typeObject.__FullName__);
if (!result) {
if (JSIL.CheckInterfaceVariantEquality(typeObject, JSIL.GetType(value), variantParameters))
result = value;
if (trace)
System.Console.WriteLine("{0} as {1} variantly {2}", value, typeObject.__FullName__, result ? "succeeded" : "failed");
}
return result;
};
return result;
};
JSIL.$GenerateVariantInvocationCandidates = function (interfaceObject, signature, qualifiedMethodName, variantGenericArguments, thisReferenceType) {
var trace = false;
var matchingInterfaces = JSIL.$FindMatchingInterfacesThroughVariance(interfaceObject, thisReferenceType, variantGenericArguments);
if (trace)
System.Console.WriteLine("Matching interfaces in candidate generator: [ {0} ]", matchingInterfaces.join(", "));
if (!matchingInterfaces.length)
return null;
else if (!signature.openSignature) {
// FIXME: Is this right?
return null;
}
var result = [];
// Sort the interfaces by distance, in increasing order.
// This is necessary for the implementation-selection behavior used by the CLR in cases where
// there are multiple candidates due to variance. See issue #445.
matchingInterfaces.sort(function (lhs, rhs) {
return JSIL.CompareValues(lhs.distance, rhs.distance);
});
generate_candidates:
for (var i = 0, l = matchingInterfaces.length; i < l; i++) {
var record = matchingInterfaces[i];
// FIXME: This is incredibly expensive.
var variantSignature = JSIL.$ResolveGenericMethodSignature(
record.interface, signature.openSignature, record.interface.__PublicInterface__
);
var candidate = variantSignature.GetNamedKey(qualifiedMethodName, true);
if (trace)
System.Console.WriteLine("Candidate (distance {0}): {1}", record.distance, candidate);
result.push(candidate);
}
return result;
};
JSIL.$GetStringEnumerator = function () {
return JSIL.GetEnumerator(this, $jsilcore.System.Char.__Type__, true);
};
$jsilcore.$GetArrayEnumeratorImplementations = {};
JSIL.$GetEnumeratorFallback = function (interfaceTypeObject, signature, thisReference) {
if (typeof (thisReference) === "string") {
return JSIL.$GetStringEnumerator;
} else if (JSIL.IsArray(thisReference)) {
var enumeratorTypeArgument = $jsilcore.System.Object.__Type__;
if (interfaceTypeObject.IsGenericType) {
enumeratorTypeArgument = interfaceTypeObject.__GenericArgumentValues__[0];
}
var key = enumeratorTypeArgument.__TypeId__;
var result = $jsilcore.$GetArrayEnumeratorImplementations[key];
if (!result) {
$jsilcore.$GetArrayEnumeratorImplementations[key] = result = function () {
return JSIL.GetEnumerator(this, enumeratorTypeArgument, true);
};
}
return result;
} else {
JSIL.RuntimeError("Object of type '" + JSIL.GetType(thisReference) + "' has no implementation of " + signature.toString("GetEnumerator"));
}
};
// FIXME: This can probably be replaced with compiler and/or runtime intelltypeigence
// to create interface overlays for strings, just like arrays.
JSIL.$PickFallbackMethodForInterfaceMethod = function (interfaceObject, methodName, signature) {
// HACK: Ensures that you can enumerate the chars of a JS string or array in cases where they lack an overlay.
if (
(
(interfaceObject.__FullName__ === "System.Collections.Generic.IEnumerable`1") ||
(interfaceObject.__FullName__ === "System.Collections.IEnumerable")
) && (methodName === "GetEnumerator")
) {
return JSIL.$GetEnumeratorFallback;
}
return null;
};
JSIL.$DoTypesMatch = function (expected, type) {
if (expected === null)
return (type === null);
if (expected === type)
return true;
if (expected.__FullName__ === "System.Array")
return type.__IsArray__;
if (expected instanceof JSIL.PositionalGenericParameter && type instanceof JSIL.PositionalGenericParameter && expected.index === type.index)
return true;
return false;
}
JSIL.$FilterMethodsByArgumentTypes = function (methods, argumentTypes, returnType) {
var trace = false;
var l = methods.length;
for (var i = 0; i < l; i++) {
var remove = false;
var method = methods[i];
var parameterInfos = $jsilcore.$MethodGetParameters(method);
if (parameterInfos.length !== argumentTypes.length) {
if (trace)
console.log("Dropping because wrong argcount", argumentTypes.length, parameterInfos.length);
remove = true;
} else {
for (var j = 0; j < argumentTypes.length; j++) {
var argumentType = argumentTypes[j];
var argumentTypeB = parameterInfos[j].get_ParameterType();
if (!JSIL.$DoTypesMatch(argumentType, argumentTypeB)) {
if (trace)
console.log("Dropping because arg mismatch", argumentType.__FullName__, argumentTypeB.__FullName__);
remove = true;
break;
}
}
}
if (typeof (returnType) !== "undefined") {
// FIXME: Do a more complete assignability check
if (!JSIL.$DoTypesMatch(returnType, method.get_ReturnType())) {
if (trace)
console.log("Dropping because wrong return type", returnType.__FullName__, method.get_ReturnType().__FullName__);
remove = true;
}
}
if (remove) {
methods[i] = methods[l - 1];
l -= 1;
i -= 1;
}
}
methods.length = l;
};
JSIL.$GetMethodImplementation = function (method, target) {
var isStatic = method._descriptor.Static;
var isInterface = method._typeObject.IsInterface;
var key = null;
if (isInterface)
key = method._descriptor.EscapedName;
else if (method._data.signature)
key = method._data.signature.GetNamedKey(method._descriptor.EscapedName, true);
else
key = method._data.mangledName || method._descriptor.EscapedName;
var genericArgumentValues = method._data.signature.genericArgumentValues;
var publicInterface = method._typeObject.__PublicInterface__;
var context = isStatic || isInterface
? publicInterface
: publicInterface.prototype;
var result = context[key] || null;
if (isInterface) {
if (!result.signature.IsClosed)
JSIL.RuntimeError("Generic method is not closed");
}
// 1. Generic
if (genericArgumentValues && genericArgumentValues.length) {
// 1.1 Generic static
if (isStatic) {
// Return an invoker that concats generic arguments and arglist and invokes
// static generic method implementation directly.
return function () {
var fullArgumentList = genericArgumentValues.concat(Array.prototype.slice.call(arguments));
return result.apply(
publicInterface, fullArgumentList
);
};
// 1.2 Generic instance (interface)
} else if (result instanceof JSIL.InterfaceMethod) {
// Return an invoker that specifies the generic arguments and passes in rest
return function () {
return result.Call.apply(result,
[this, genericArgumentValues].concat(Array.prototype.slice.call(arguments))
);
};
// 1.3 Generic instance (non-interface)
} else {
// Return an invoker that concats generic arguments and arglist and invokes
// generic method implementation directly.
return function () {
var fullArgumentList = genericArgumentValues.concat(Array.prototype.slice.call(arguments));
return result.apply(
this, fullArgumentList
);
};
}
// 2. Non-generic
// 2.1 Non-generic instance (interface)
} else if (result instanceof JSIL.InterfaceMethod) {
// Wrap the interface method invoker since it expects a generic arguments parameter.
return function (methodArgs) {
return result.Call(this, null, methodArgs);
};
}
if (!result) {
debugger;
}
// 2.2 Non-generic instance (non-interface)
// 2.3 Non-generic static
return result;
};
JSIL.$FindMethodBodyInTypeChain = function (typeObject, isStatic, key, recursive) {
var typeChain = [];
var currentType = typeObject;
while (currentType) {
if (currentType.__PublicInterface__)
typeChain.push(currentType.__PublicInterface__);
if (currentType.__OpenType__ && currentType.__OpenType__.__PublicInterface__)
typeChain.push(currentType.__OpenType__.__PublicInterface__);
if (recursive)
currentType = currentType.__BaseType__;
else
break;
}
for (var i = 0, l = typeChain.length; i < l; i++) {
currentType = typeChain[i];
var target = isStatic ? currentType : currentType.prototype;
var method = target[key];
if (typeof (method) === "function")
return method;
}
return null;
};
JSIL.$IgnoredPrototypeMembers = [
];
JSIL.$IgnoredPublicInterfaceMembers = [
"__Type__", "__TypeId__", "__ThisType__", "__TypeInitialized__", "__IsClosed__", "prototype",
"Of", "toString", "__FullName__", "__OfCache__", "Of$NoInitialize",
"GetType", "__ReflectionCache__", "__Members__", "__ThisTypeId__",
"__RanCctors__", "__RanFieldInitializers__", "__PreInitMembrane__",
"__FieldList__", "__Comparer__", "__Marshaller__", "__Unmarshaller__",
"__UnmarshalConstructor__", "__ElementProxyConstructor__", "__IsNativeType__"
];
JSIL.$CopyMembersIndirect = function (target, source, ignoredNames, recursive) {
if (!source)
JSIL.RuntimeError("No source provided for copy");
if (source.__ThisType__ && (source.__ThisType__.__FullName__.indexOf("ArrayEnumerator") >= 0)) {
// debugger;
}
// FIXME: for ( in ) is deoptimized in V8. Maybe use Object.keys(), or type metadata?
for (var k in source) {
if (ignoredNames.indexOf(k) !== -1)
continue;
if (!recursive && !source.hasOwnProperty(k))
continue;
if (target.hasOwnProperty(k))
continue;
JSIL.MakeIndirectProperty(target, k, source);
}
};
JSIL.$CopyInterfaceMethods = function (interfaceList, target) {
var imProto = JSIL.InterfaceMethod.prototype;
var makeGetter = function (src, key) {
return function () {
return src[key];
};
};
for (var i = 0, l = interfaceList.length; i < l; i++) {
var ifaceRef = interfaceList[i];
var iface = JSIL.ResolveTypeReference(ifaceRef)[0];
for (var k in iface) {
if (!Object.prototype.hasOwnProperty.call(iface, k))
continue;
if (Object.prototype.hasOwnProperty.call(target, k))
continue;
JSIL.SetLazyValueProperty(target, k, makeGetter(iface, k));
}
}
};
JSIL.SetEntryPoint = function (assembly, typeRef, methodName, methodSignature) {
if (JSIL.$EntryPoints[assembly.__AssemblyId__])
JSIL.RuntimeError("Assembly already has an entry point");
JSIL.$EntryPoints[assembly.__AssemblyId__] =
[assembly, typeRef, methodName, methodSignature];
};
JSIL.GetEntryPoint = function (assembly) {
var entryPoint = JSIL.$EntryPoints[assembly.__AssemblyId__];
if (!entryPoint)
return null;
var entryTypePublicInterface = JSIL.ResolveTypeReference(entryPoint[1])[0];
var methodName = entryPoint[2];
var methodSignature = entryPoint[3];
return {
thisReference: entryTypePublicInterface,
method: methodSignature.LookupMethod(entryTypePublicInterface, methodName)
};
};
JSIL.InvokeEntryPoint = function (assembly, args) {
var dict = JSIL.GetEntryPoint(assembly);
if (!dict)
JSIL.RuntimeError("Assembly has no entry point");
if (!args)
args = [];
return dict.method.apply(dict.thisReference, args);
};
JSIL.ThrowNullReferenceException = function () {
throw new System.NullReferenceException();
};
JSIL.RuntimeError = function (text) {
throw new Error(text);
};
JSIL.RuntimeErrorFormat = function (format, values) {
var text = JSIL.$FormatStringImpl(format, values);
throw new Error(text);
};
JSIL.WarningFormat = function (format, values) {
var text = JSIL.$FormatStringImpl(format, values);
JSIL.Host.warning(text);
};
JSIL.ValidateArgumentTypes = function (types) {
for (var i = 0, l = types.length; i < l; i++) {
var item = types[i];
if (
(typeof (item) === "string") ||
(typeof (item) === "number") ||
(typeof (item) === "undefined") ||
(item === null)
) {
JSIL.RuntimeError("Argument type list must only contain type objects: " + JSON.stringify(item));
}
}
};
JSIL.GetMethodInfo = function(typeObject, name, signature, isStatic, methodGenericParameters){
var methods = JSIL.GetMembersInternal(
typeObject.__Type__, $jsilcore.BindingFlags.$Flags("DeclaredOnly", "Public", "NonPublic", isStatic ? "Static" : "Instance"), "$AllMethods", name
);
for (var i = 0, l = methods.length; i < l; i++) {
var method = methods[i];
if (method._data.signature.Hash == signature.Hash){
if (JSIL.IsArray(methodGenericParameters)) {
var genericParameterTypes = [];
for (var i = 0, l = methodGenericParameters.length; i < l; i++) {
genericParameterTypes.push(methodGenericParameters[i].get().__Type__);
}
return method.MakeGenericMethod(genericParameterTypes);
}
return method;
}
}
return null;
};
JSIL.GetFieldInfo = function(typeObject, name, isStatic){
var fields = JSIL.GetMembersInternal(
typeObject.__Type__, $jsilcore.BindingFlags.$Flags("DeclaredOnly", "Public", "NonPublic", isStatic ? "Static" : "Instance"), "FieldInfo", name
);
if (fields.length == 1) {
return fields[0];
}
return null;
};
// index alignment valueFormat escape
JSIL.$FormatRegex = new RegExp("{([0-9]*)(?:,([-0-9]*))?(?::([^}]*))?}|{{|}}|{|}", "g");
JSIL.$FormatStringImpl = function (format, values) {
if ((arguments.length !== 2) || !JSIL.IsArray(values))
JSIL.RuntimeError("JSIL.$FormatStringImpl expects (formatString, [value0, value1, ...])");
var match = null;
var matcher = function (match, index, alignment, valueFormat, offset, str) {
if (match === "{{")
return "{";
else if (match === "}}")
return "}";
else if ((match === "{") || (match === "}"))
throw new System.FormatException("Input string was not in a correct format.");
index = parseInt(index);
var value = values[index];
if (alignment || valueFormat) {
return JSIL.NumberToFormattedString(value, alignment, valueFormat);
} else {
if (typeof (value) === "boolean") {
if (value)
return "True";
else
return "False";
} else if (value === null) {
return "";
} else {
return String(value);
}
}
};
return format.replace(JSIL.$FormatRegex, matcher);
};
JSIL.Array.IndexOf = function (array, count, value) {
for (var i = 0, l = count; i < l; i++) {
if (JSIL.ObjectEquals(array[i], value))
return i;
}
return -1;
}; | Get rid of custom .call/.apply on bound generic methods
| Libraries/JSIL.Core.js | Get rid of custom .call/.apply on bound generic methods | <ide><path>ibraries/JSIL.Core.js
<ide> innerDispatchCode.push(" }");
<ide>
<ide> body.push("");
<del> body.push("var outerThis = this;");
<add> body.push("var boundThis = this;");
<ide> body.push("var dispatcher = this[dispatcherKey];");
<ide>
<ide> body.push("");
<ide> body.push("var result = function BoundGenericMethod_Invoke (");
<ide> body.push(" " + normalArgumentList);
<ide> body.push(") {");
<del> body.push(" var thisReference = outerThis;");
<add> body.push(" var thisReference = this;");
<add> // HACK: Strict-mode functions get an undefined 'this' in cases where none is provided.
<add> // In non-strict mode, 'this' will be the global object, which would break this.
<add> // Thanks to strict mode, we don't need custom .call or .apply methods!
<add> body.push(" if (typeof (thisReference) === 'undefined')");
<add> body.push(" thisReference = boundThis;");
<ide> body.push(" var argc = arguments.length | 0;");
<ide> body.push(" ");
<ide> body.push.apply(body, innerDispatchCode);
<del> body.push("};");
<del>
<del> body.push("");
<del> body.push("result.call = function BoundGenericMethod_Call (");
<del> body.push(
<del> " thisReference" + (
<del> (maxArgumentCount !== 0)
<del> ? ", "
<del> : ""
<del> ) + normalArgumentList
<del> );
<del> body.push(") {");
<del> body.push(" var argc = ((arguments.length | 0) - 1) | 0;");
<del> body.push(" ");
<del> body.push.apply(body, innerDispatchCode);
<del> body.push("};");
<del>
<del> body.push("");
<del> body.push("result.apply = function BoundGenericMethod_Apply (");
<del> body.push(" thisReference, $arguments");
<del> body.push(") {");
<del> body.push(" var argc = $arguments.length | 0;");
<del> body.push(" ");
<del> body.push(" switch (argc) {");
<del>
<del> for (var k in argumentCounts) {
<del> var localArgCount = k | 0;
<del> body.push(" case " + localArgCount + ":");
<del> body.push(" return dispatcher.call(");
<del> body.push(" thisReference,");
<del> body.push(" " + binderArgumentList + (
<del> (localArgCount !== 0)
<del> ? ", "
<del> : ""
<del> )
<del> );
<del>
<del> for (var i = 0; i < localArgCount; i++) {
<del> body.push(
<del> " $arguments[" + i + "]" + (
<del> (i === localArgCount - 1)
<del> ? ""
<del> : ", "
<del> )
<del> );
<del> }
<del>
<del> body.push(" );");
<del> }
<del>
<del> body.push(" default:");
<del> body.push(" JSIL.RuntimeError('Unexpected argument count');");
<del> body.push(" }");
<ide> body.push("};");
<ide>
<ide> body.push(""); |
|
Java | apache-2.0 | 2e1962847a7baa6aa3c53394bf1b4331fe967d2e | 0 | ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop | package it.unibz.inf.ontop.answering.reformulation.impl;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import it.unibz.inf.ontop.answering.reformulation.ExecutableQuery;
import it.unibz.inf.ontop.answering.reformulation.QueryCache;
import it.unibz.inf.ontop.answering.reformulation.QueryReformulator;
import it.unibz.inf.ontop.answering.reformulation.generation.NativeQueryGenerator;
import it.unibz.inf.ontop.answering.reformulation.input.InputQuery;
import it.unibz.inf.ontop.answering.reformulation.input.InputQueryFactory;
import it.unibz.inf.ontop.answering.reformulation.input.translation.InputQueryTranslator;
import it.unibz.inf.ontop.answering.reformulation.rewriting.LinearInclusionDependencyTools;
import it.unibz.inf.ontop.answering.reformulation.rewriting.QueryRewriter;
import it.unibz.inf.ontop.answering.reformulation.rewriting.SameAsRewriter;
import it.unibz.inf.ontop.answering.reformulation.unfolding.QueryUnfolder;
import it.unibz.inf.ontop.datalog.*;
import it.unibz.inf.ontop.datalog.impl.CQCUtilities;
import it.unibz.inf.ontop.dbschema.DBMetadata;
import it.unibz.inf.ontop.exception.OntopInvalidInputQueryException;
import it.unibz.inf.ontop.exception.OntopReformulationException;
import it.unibz.inf.ontop.exception.OntopUnsupportedInputQueryException;
import it.unibz.inf.ontop.injection.OntopReformulationSettings;
import it.unibz.inf.ontop.injection.TranslationFactory;
import it.unibz.inf.ontop.iq.IntermediateQuery;
import it.unibz.inf.ontop.iq.exception.EmptyQueryException;
import it.unibz.inf.ontop.iq.optimizer.BindingLiftOptimizer;
import it.unibz.inf.ontop.iq.optimizer.JoinLikeOptimizer;
import it.unibz.inf.ontop.iq.optimizer.ProjectionShrinkingOptimizer;
import it.unibz.inf.ontop.iq.optimizer.impl.PushUpBooleanExpressionOptimizerImpl;
import it.unibz.inf.ontop.iq.tools.ExecutorRegistry;
import it.unibz.inf.ontop.model.term.functionsymbol.Predicate;
import it.unibz.inf.ontop.spec.OBDASpecification;
import it.unibz.inf.ontop.spec.mapping.Mapping;
import it.unibz.inf.ontop.spec.ontology.TBoxReasoner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import static it.unibz.inf.ontop.model.OntopModelSingletons.DATALOG_FACTORY;
import static it.unibz.inf.ontop.model.atom.PredicateConstants.ONTOP_QUERY;
/**
* TODO: rename it QueryTranslatorImpl ?
*/
public class QuestQueryProcessor implements QueryReformulator {
private final QueryRewriter rewriter;
private final LinearInclusionDependencies sigma;
private final NativeQueryGenerator datasourceQueryGenerator;
private final QueryCache queryCache;
private final QueryUnfolder queryUnfolder;
private final SameAsRewriter sameAsRewriter;
private final BindingLiftOptimizer bindingLiftOptimizer;
private static final Logger log = LoggerFactory.getLogger(QuestQueryProcessor.class);
private final ExecutorRegistry executorRegistry;
private final DatalogProgram2QueryConverter datalogConverter;
private final OntopReformulationSettings settings;
private final DBMetadata dbMetadata;
private final JoinLikeOptimizer joinLikeOptimizer;
private final InputQueryTranslator inputQueryTranslator;
private final InputQueryFactory inputQueryFactory;
@AssistedInject
private QuestQueryProcessor(@Assisted OBDASpecification obdaSpecification,
@Assisted ExecutorRegistry executorRegistry,
QueryCache queryCache,
BindingLiftOptimizer bindingLiftOptimizer, OntopReformulationSettings settings,
DatalogProgram2QueryConverter datalogConverter,
TranslationFactory translationFactory,
QueryRewriter queryRewriter,
JoinLikeOptimizer joinLikeOptimizer,
InputQueryFactory inputQueryFactory) {
this.bindingLiftOptimizer = bindingLiftOptimizer;
this.settings = settings;
this.joinLikeOptimizer = joinLikeOptimizer;
this.inputQueryFactory = inputQueryFactory;
TBoxReasoner saturatedTBox = obdaSpecification.getSaturatedTBox();
this.sigma = LinearInclusionDependencyTools.getABoxDependencies(saturatedTBox, true);
this.rewriter = queryRewriter;
this.rewriter.setTBox(saturatedTBox, obdaSpecification.getVocabulary(), sigma);
Mapping saturatedMapping = obdaSpecification.getSaturatedMapping();
if(log.isDebugEnabled()){
log.debug("Mapping: \n{}", Joiner.on("\n").join(saturatedMapping.getQueries()));
}
this.queryUnfolder = translationFactory.create(saturatedMapping);
this.dbMetadata = obdaSpecification.getDBMetadata();
this.datasourceQueryGenerator = translationFactory.create(dbMetadata);
this.inputQueryTranslator = translationFactory.createInputQueryTranslator(saturatedMapping.getMetadata()
.getUriTemplateMatcher());
this.sameAsRewriter = translationFactory.createSameAsRewriter(saturatedMapping);
this.queryCache = queryCache;
this.executorRegistry = executorRegistry;
this.datalogConverter = datalogConverter;
log.info("Ontop has completed the setup and it is ready for query answering!");
}
private DatalogProgram translateAndPreProcess(InputQuery inputQuery)
throws OntopUnsupportedInputQueryException, OntopInvalidInputQueryException {
InternalSparqlQuery translation = inputQuery.translate(inputQueryTranslator);
return preProcess(translation);
}
private DatalogProgram preProcess(InternalSparqlQuery translation) {
DatalogProgram program = translation.getProgram();
log.debug("Datalog program translated from the SPARQL query: \n{}", program);
if(settings.isSameAsInMappingsEnabled()){
program = sameAsRewriter.getSameAsRewriting(program);
log.debug("Datalog program after SameAs rewriting \n" + program);
}
log.debug("Replacing equivalences...");
DatalogProgram newprogramEq = DATALOG_FACTORY.getDatalogProgram(program.getQueryModifiers());
Predicate topLevelPredicate = null;
for (CQIE query : program.getRules()) {
// TODO: fix cloning
CQIE rule = query.clone();
// TODO: get rid of EQNormalizer
EQNormalizer.enforceEqualities(rule);
if (rule.getHead().getFunctionSymbol().getName().equals(ONTOP_QUERY))
topLevelPredicate = rule.getHead().getFunctionSymbol();
newprogramEq.appendRule(rule);
}
SPARQLQueryFlattener fl = new SPARQLQueryFlattener(newprogramEq);
List<CQIE> p = fl.flatten(newprogramEq.getRules(topLevelPredicate).get(0));
DatalogProgram newprogram = DATALOG_FACTORY.getDatalogProgram(program.getQueryModifiers(), p);
return newprogram;
}
public void clearNativeQueryCache() {
queryCache.clear();
}
@Override
public ExecutableQuery reformulateIntoNativeQuery(InputQuery inputQuery)
throws OntopReformulationException {
ExecutableQuery cachedQuery = queryCache.get(inputQuery);
if (cachedQuery != null)
return cachedQuery;
try {
InternalSparqlQuery translation = inputQuery.translate(inputQueryTranslator);
DatalogProgram newprogram = preProcess(translation);
for (CQIE q : newprogram.getRules())
DatalogNormalizer.unfoldJoinTrees(q);
log.debug("Normalized program: \n{}", newprogram);
if (newprogram.getRules().size() < 1)
throw new OntopInvalidInputQueryException("Error, the translation of the query generated 0 rules. " +
"This is not possible for any SELECT query (other queries are not supported by the translator).");
log.debug("Start the rewriting process...");
//final long startTime0 = System.currentTimeMillis();
for (CQIE cq : newprogram.getRules())
CQCUtilities.optimizeQueryWithSigmaRules(cq.getBody(), sigma);
DatalogProgram programAfterRewriting = rewriter.rewrite(newprogram);
//rewritingTime = System.currentTimeMillis() - startTime0;
//final long startTime = System.currentTimeMillis();
try {
IntermediateQuery intermediateQuery = datalogConverter.convertDatalogProgram(
dbMetadata, programAfterRewriting, ImmutableList.of(), executorRegistry);
log.debug("Directly translated (SPARQL) intermediate query: \n" + intermediateQuery.toString());
log.debug("Start the unfolding...");
intermediateQuery = queryUnfolder.optimize(intermediateQuery);
log.debug("Unfolded query: \n" + intermediateQuery.toString());
//lift bindings and union when it is possible
intermediateQuery = bindingLiftOptimizer.optimize(intermediateQuery);
log.debug("New query after substitution lift optimization: \n" + intermediateQuery.toString());
log.debug("New lifted query: \n" + intermediateQuery.toString());
intermediateQuery = new PushUpBooleanExpressionOptimizerImpl(false).optimize(intermediateQuery);
log.debug("After pushing up boolean expressions: \n" + intermediateQuery.toString());
intermediateQuery = new ProjectionShrinkingOptimizer().optimize(intermediateQuery);
log.debug("After projection shrinking: \n" + intermediateQuery.toString());
intermediateQuery = joinLikeOptimizer.optimize(intermediateQuery);
log.debug("New query after fixed point join optimization: \n" + intermediateQuery.toString());
// BasicLeftJoinOptimizer leftJoinOptimizer = new BasicLeftJoinOptimizer();
// intermediateQuery = leftJoinOptimizer.optimize(intermediateQuery);
// log.debug("New query after left join optimization: \n" + intermediateQuery.toString());
//
// BasicJoinOptimizer joinOptimizer = new BasicJoinOptimizer();
// intermediateQuery = joinOptimizer.optimize(intermediateQuery);
// log.debug("New query after join optimization: \n" + intermediateQuery.toString());
ExecutableQuery executableQuery = generateExecutableQuery(intermediateQuery,
ImmutableList.copyOf(translation.getSignature()));
queryCache.put(inputQuery, executableQuery);
return executableQuery;
}
/**
* No solution.
*/
catch (EmptyQueryException e) {
ExecutableQuery emptyQuery = datasourceQueryGenerator.generateEmptyQuery(
ImmutableList.copyOf(translation.getSignature()));
log.debug("Empty query --> no solution.");
queryCache.put(inputQuery, emptyQuery);
return emptyQuery;
}
//unfoldingTime = System.currentTimeMillis() - startTime;
}
catch (OntopReformulationException e) {
throw e;
}
/*
* Bug: should normally not be reached
* TODO: remove it
*/
catch (Exception e) {
log.warn("Unexpected exception: " + e.getMessage(), e);
throw new OntopReformulationException(e);
//throw new OntopReformulationException("Error rewriting and unfolding into SQL\n" + e.getMessage());
}
}
private ExecutableQuery generateExecutableQuery(IntermediateQuery intermediateQuery, ImmutableList<String> signature)
throws OntopReformulationException {
log.debug("Producing the native query string...");
ExecutableQuery executableQuery = datasourceQueryGenerator.generateSourceQuery(intermediateQuery, signature);
log.debug("Resulting native query: \n{}", executableQuery);
return executableQuery;
}
/**
* Returns the final rewriting of the given query
*/
@Override
public String getRewritingRendering(InputQuery query) throws OntopReformulationException {
DatalogProgram program = translateAndPreProcess(query);
DatalogProgram rewriting = rewriter.rewrite(program);
return DatalogProgramRenderer.encode(rewriting);
}
@Override
public InputQueryFactory getInputQueryFactory() {
return inputQueryFactory;
}
}
| engine/reformulation/core/src/main/java/it/unibz/inf/ontop/answering/reformulation/impl/QuestQueryProcessor.java | package it.unibz.inf.ontop.answering.reformulation.impl;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import it.unibz.inf.ontop.answering.reformulation.ExecutableQuery;
import it.unibz.inf.ontop.answering.reformulation.QueryCache;
import it.unibz.inf.ontop.answering.reformulation.QueryReformulator;
import it.unibz.inf.ontop.answering.reformulation.generation.NativeQueryGenerator;
import it.unibz.inf.ontop.answering.reformulation.input.InputQuery;
import it.unibz.inf.ontop.answering.reformulation.input.InputQueryFactory;
import it.unibz.inf.ontop.answering.reformulation.input.translation.InputQueryTranslator;
import it.unibz.inf.ontop.answering.reformulation.rewriting.LinearInclusionDependencyTools;
import it.unibz.inf.ontop.answering.reformulation.rewriting.QueryRewriter;
import it.unibz.inf.ontop.answering.reformulation.rewriting.SameAsRewriter;
import it.unibz.inf.ontop.answering.reformulation.unfolding.QueryUnfolder;
import it.unibz.inf.ontop.datalog.*;
import it.unibz.inf.ontop.datalog.impl.CQCUtilities;
import it.unibz.inf.ontop.dbschema.DBMetadata;
import it.unibz.inf.ontop.exception.OntopInvalidInputQueryException;
import it.unibz.inf.ontop.exception.OntopReformulationException;
import it.unibz.inf.ontop.exception.OntopUnsupportedInputQueryException;
import it.unibz.inf.ontop.injection.OntopReformulationSettings;
import it.unibz.inf.ontop.injection.TranslationFactory;
import it.unibz.inf.ontop.iq.IntermediateQuery;
import it.unibz.inf.ontop.iq.exception.EmptyQueryException;
import it.unibz.inf.ontop.iq.optimizer.BindingLiftOptimizer;
import it.unibz.inf.ontop.iq.optimizer.JoinLikeOptimizer;
import it.unibz.inf.ontop.iq.optimizer.ProjectionShrinkingOptimizer;
import it.unibz.inf.ontop.iq.optimizer.impl.PushUpBooleanExpressionOptimizerImpl;
import it.unibz.inf.ontop.iq.tools.ExecutorRegistry;
import it.unibz.inf.ontop.model.term.functionsymbol.Predicate;
import it.unibz.inf.ontop.spec.OBDASpecification;
import it.unibz.inf.ontop.spec.mapping.Mapping;
import it.unibz.inf.ontop.spec.ontology.TBoxReasoner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import static it.unibz.inf.ontop.model.OntopModelSingletons.DATALOG_FACTORY;
import static it.unibz.inf.ontop.model.atom.PredicateConstants.ONTOP_QUERY;
/**
* TODO: rename it QueryTranslatorImpl ?
*/
public class QuestQueryProcessor implements QueryReformulator {
private final QueryRewriter rewriter;
private final LinearInclusionDependencies sigma;
private final VocabularyValidator vocabularyValidator;
private final NativeQueryGenerator datasourceQueryGenerator;
private final QueryCache queryCache;
private final QueryUnfolder queryUnfolder;
private final SameAsRewriter sameAsRewriter;
private final BindingLiftOptimizer bindingLiftOptimizer;
private static final Logger log = LoggerFactory.getLogger(QuestQueryProcessor.class);
private final ExecutorRegistry executorRegistry;
private final DatalogProgram2QueryConverter datalogConverter;
private final OntopReformulationSettings settings;
private final DBMetadata dbMetadata;
private final JoinLikeOptimizer joinLikeOptimizer;
private final InputQueryTranslator inputQueryTranslator;
private final InputQueryFactory inputQueryFactory;
@AssistedInject
private QuestQueryProcessor(@Assisted OBDASpecification obdaSpecification,
@Assisted ExecutorRegistry executorRegistry,
QueryCache queryCache,
BindingLiftOptimizer bindingLiftOptimizer, OntopReformulationSettings settings,
DatalogProgram2QueryConverter datalogConverter,
TranslationFactory translationFactory,
QueryRewriter queryRewriter,
JoinLikeOptimizer joinLikeOptimizer,
InputQueryFactory inputQueryFactory) {
this.bindingLiftOptimizer = bindingLiftOptimizer;
this.settings = settings;
this.joinLikeOptimizer = joinLikeOptimizer;
this.inputQueryFactory = inputQueryFactory;
TBoxReasoner saturatedTBox = obdaSpecification.getSaturatedTBox();
this.sigma = LinearInclusionDependencyTools.getABoxDependencies(saturatedTBox, true);
this.rewriter = queryRewriter;
this.rewriter.setTBox(saturatedTBox, obdaSpecification.getVocabulary(), sigma);
Mapping saturatedMapping = obdaSpecification.getSaturatedMapping();
if(log.isDebugEnabled()){
log.debug("Mapping: \n{}", Joiner.on("\n").join(saturatedMapping.getQueries()));
}
this.queryUnfolder = translationFactory.create(saturatedMapping);
this.vocabularyValidator = new VocabularyValidator(obdaSpecification.getSaturatedTBox(),
obdaSpecification.getVocabulary());
this.dbMetadata = obdaSpecification.getDBMetadata();
this.datasourceQueryGenerator = translationFactory.create(dbMetadata);
this.inputQueryTranslator = translationFactory.createInputQueryTranslator(saturatedMapping.getMetadata()
.getUriTemplateMatcher());
this.sameAsRewriter = translationFactory.createSameAsRewriter(saturatedMapping);
this.queryCache = queryCache;
this.executorRegistry = executorRegistry;
this.datalogConverter = datalogConverter;
log.info("Ontop has completed the setup and it is ready for query answering!");
}
private DatalogProgram translateAndPreProcess(InputQuery inputQuery)
throws OntopUnsupportedInputQueryException, OntopInvalidInputQueryException {
InternalSparqlQuery translation = inputQuery.translate(inputQueryTranslator);
return preProcess(translation);
}
private DatalogProgram preProcess(InternalSparqlQuery translation) {
DatalogProgram program = translation.getProgram();
log.debug("Datalog program translated from the SPARQL query: \n{}", program);
if(settings.isSameAsInMappingsEnabled()){
program = sameAsRewriter.getSameAsRewriting(program);
log.debug("Datalog program after SameAs rewriting \n" + program);
}
log.debug("Replacing equivalences...");
DatalogProgram newprogramEq = DATALOG_FACTORY.getDatalogProgram(program.getQueryModifiers());
Predicate topLevelPredicate = null;
for (CQIE query : program.getRules()) {
// TODO: fix cloning
CQIE rule = query.clone();
// TODO: get rid of EQNormalizer
EQNormalizer.enforceEqualities(rule);
CQIE newquery = vocabularyValidator.replaceEquivalences(rule);
if (newquery.getHead().getFunctionSymbol().getName().equals(ONTOP_QUERY))
topLevelPredicate = newquery.getHead().getFunctionSymbol();
newprogramEq.appendRule(newquery);
}
SPARQLQueryFlattener fl = new SPARQLQueryFlattener(newprogramEq);
List<CQIE> p = fl.flatten(newprogramEq.getRules(topLevelPredicate).get(0));
DatalogProgram newprogram = DATALOG_FACTORY.getDatalogProgram(program.getQueryModifiers(), p);
return newprogram;
}
public void clearNativeQueryCache() {
queryCache.clear();
}
@Override
public ExecutableQuery reformulateIntoNativeQuery(InputQuery inputQuery)
throws OntopReformulationException {
ExecutableQuery cachedQuery = queryCache.get(inputQuery);
if (cachedQuery != null)
return cachedQuery;
try {
InternalSparqlQuery translation = inputQuery.translate(inputQueryTranslator);
DatalogProgram newprogram = preProcess(translation);
for (CQIE q : newprogram.getRules())
DatalogNormalizer.unfoldJoinTrees(q);
log.debug("Normalized program: \n{}", newprogram);
if (newprogram.getRules().size() < 1)
throw new OntopInvalidInputQueryException("Error, the translation of the query generated 0 rules. " +
"This is not possible for any SELECT query (other queries are not supported by the translator).");
log.debug("Start the rewriting process...");
//final long startTime0 = System.currentTimeMillis();
for (CQIE cq : newprogram.getRules())
CQCUtilities.optimizeQueryWithSigmaRules(cq.getBody(), sigma);
DatalogProgram programAfterRewriting = rewriter.rewrite(newprogram);
//rewritingTime = System.currentTimeMillis() - startTime0;
//final long startTime = System.currentTimeMillis();
try {
IntermediateQuery intermediateQuery = datalogConverter.convertDatalogProgram(
dbMetadata, programAfterRewriting, ImmutableList.of(), executorRegistry);
log.debug("Directly translated (SPARQL) intermediate query: \n" + intermediateQuery.toString());
log.debug("Start the unfolding...");
intermediateQuery = queryUnfolder.optimize(intermediateQuery);
log.debug("Unfolded query: \n" + intermediateQuery.toString());
//lift bindings and union when it is possible
intermediateQuery = bindingLiftOptimizer.optimize(intermediateQuery);
log.debug("New query after substitution lift optimization: \n" + intermediateQuery.toString());
log.debug("New lifted query: \n" + intermediateQuery.toString());
intermediateQuery = new PushUpBooleanExpressionOptimizerImpl(false).optimize(intermediateQuery);
log.debug("After pushing up boolean expressions: \n" + intermediateQuery.toString());
intermediateQuery = new ProjectionShrinkingOptimizer().optimize(intermediateQuery);
log.debug("After projection shrinking: \n" + intermediateQuery.toString());
intermediateQuery = joinLikeOptimizer.optimize(intermediateQuery);
log.debug("New query after fixed point join optimization: \n" + intermediateQuery.toString());
// BasicLeftJoinOptimizer leftJoinOptimizer = new BasicLeftJoinOptimizer();
// intermediateQuery = leftJoinOptimizer.optimize(intermediateQuery);
// log.debug("New query after left join optimization: \n" + intermediateQuery.toString());
//
// BasicJoinOptimizer joinOptimizer = new BasicJoinOptimizer();
// intermediateQuery = joinOptimizer.optimize(intermediateQuery);
// log.debug("New query after join optimization: \n" + intermediateQuery.toString());
ExecutableQuery executableQuery = generateExecutableQuery(intermediateQuery,
ImmutableList.copyOf(translation.getSignature()));
queryCache.put(inputQuery, executableQuery);
return executableQuery;
}
/**
* No solution.
*/
catch (EmptyQueryException e) {
ExecutableQuery emptyQuery = datasourceQueryGenerator.generateEmptyQuery(
ImmutableList.copyOf(translation.getSignature()));
log.debug("Empty query --> no solution.");
queryCache.put(inputQuery, emptyQuery);
return emptyQuery;
}
//unfoldingTime = System.currentTimeMillis() - startTime;
}
catch (OntopReformulationException e) {
throw e;
}
/*
* Bug: should normally not be reached
* TODO: remove it
*/
catch (Exception e) {
log.warn("Unexpected exception: " + e.getMessage(), e);
throw new OntopReformulationException(e);
//throw new OntopReformulationException("Error rewriting and unfolding into SQL\n" + e.getMessage());
}
}
private ExecutableQuery generateExecutableQuery(IntermediateQuery intermediateQuery, ImmutableList<String> signature)
throws OntopReformulationException {
log.debug("Producing the native query string...");
ExecutableQuery executableQuery = datasourceQueryGenerator.generateSourceQuery(intermediateQuery, signature);
log.debug("Resulting native query: \n{}", executableQuery);
return executableQuery;
}
/**
* Returns the final rewriting of the given query
*/
@Override
public String getRewritingRendering(InputQuery query) throws OntopReformulationException {
DatalogProgram program = translateAndPreProcess(query);
DatalogProgram rewriting = rewriter.rewrite(program);
return DatalogProgramRenderer.encode(rewriting);
}
@Override
public InputQueryFactory getInputQueryFactory() {
return inputQueryFactory;
}
}
| removed use of VocabularyValidator
| engine/reformulation/core/src/main/java/it/unibz/inf/ontop/answering/reformulation/impl/QuestQueryProcessor.java | removed use of VocabularyValidator | <ide><path>ngine/reformulation/core/src/main/java/it/unibz/inf/ontop/answering/reformulation/impl/QuestQueryProcessor.java
<ide>
<ide> private final QueryRewriter rewriter;
<ide> private final LinearInclusionDependencies sigma;
<del> private final VocabularyValidator vocabularyValidator;
<ide> private final NativeQueryGenerator datasourceQueryGenerator;
<ide> private final QueryCache queryCache;
<ide>
<ide>
<ide> this.queryUnfolder = translationFactory.create(saturatedMapping);
<ide>
<del> this.vocabularyValidator = new VocabularyValidator(obdaSpecification.getSaturatedTBox(),
<del> obdaSpecification.getVocabulary());
<ide> this.dbMetadata = obdaSpecification.getDBMetadata();
<ide> this.datasourceQueryGenerator = translationFactory.create(dbMetadata);
<ide> this.inputQueryTranslator = translationFactory.createInputQueryTranslator(saturatedMapping.getMetadata()
<ide> // TODO: get rid of EQNormalizer
<ide> EQNormalizer.enforceEqualities(rule);
<ide>
<del> CQIE newquery = vocabularyValidator.replaceEquivalences(rule);
<del> if (newquery.getHead().getFunctionSymbol().getName().equals(ONTOP_QUERY))
<del> topLevelPredicate = newquery.getHead().getFunctionSymbol();
<del> newprogramEq.appendRule(newquery);
<add> if (rule.getHead().getFunctionSymbol().getName().equals(ONTOP_QUERY))
<add> topLevelPredicate = rule.getHead().getFunctionSymbol();
<add> newprogramEq.appendRule(rule);
<ide> }
<ide>
<ide> SPARQLQueryFlattener fl = new SPARQLQueryFlattener(newprogramEq); |
|
Java | apache-2.0 | 982a701093fd01c44878daee78bd7c9b7d542e7e | 0 | jle/andy,jle/andy | package com.vandalsoftware.android.spdyexample;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.vandalsoftware.android.net.SSLSocketChannel;
import com.vandalsoftware.android.net.SocketReadHandler;
import com.vandalsoftware.android.spdy.DefaultSpdySynStreamFrame;
import com.vandalsoftware.android.spdy.FrameHandler;
import com.vandalsoftware.android.spdy.SpdyDataFrame;
import com.vandalsoftware.android.spdy.SpdyFrameCodec;
import com.vandalsoftware.android.spdy.SpdySessionHandler;
import com.vandalsoftware.android.spdy.SpdySynReplyFrame;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ByteChannel;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.Inflater;
public class SpdyActivity extends Activity {
private static final String TAG = "spdy";
private LogView mLogView;
private Socket mSock;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLogView = (LogView) findViewById(R.id.logview);
Button startBtn = (Button) findViewById(R.id.start);
startBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new ConnectTask().execute();
}
});
Button stopBtn = (Button) findViewById(R.id.stop);
stopBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
log("Closing.");
Socket s = mSock;
if (s != null) {
try {
s.close();
Log.d(TAG, "socket closed.");
} catch (IOException e) {
e.printStackTrace();
}
}
log("Finished.");
}
});
log("Ready.");
}
private void log(String message) {
Log.d(TAG, message);
mLogView.log(message);
}
class ConnectTask extends AsyncTask<Void, Void, Socket> implements SocketReadHandler, FrameHandler {
private SpdyFrameCodec mSpdyFrameCodec;
private SpdySessionHandler mSpdySessionHandler;
private IdentityHashMap<Integer, List<Map.Entry<String, String>>> mMap = new IdentityHashMap<Integer, List<Map.Entry<String, String>>>();
@Override
protected void onPreExecute() {
mSpdyFrameCodec = new SpdyFrameCodec(3);
mSpdySessionHandler = new SpdySessionHandler(3, false);
}
@Override
protected void onPostExecute(Socket s) {
mSock = s;
}
public void handleRead(ByteChannel channel, byte[] in, int index, int length) {
Log.d(TAG, "handleRead " + length);
ChannelBuffer channelBuffer = ChannelBuffers.wrappedBuffer(in, index, length);
try {
Log.d(TAG, "read index: " + channelBuffer.readerIndex());
mSpdyFrameCodec.handleUpstream(null, null, channelBuffer, this);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Log.d(TAG, "handleRead done");
}
@Override
protected Socket doInBackground(Void... voids) {
Socket s = null;
try {
SSLSocketChannel connector = SSLSocketChannel.open("TLS");
connector.setSocketReadHandler(this);
connector.connect(new InetSocketAddress("api.twitter.com", 443), 15000);
Log.d(TAG, "socket connected.");
SpdyFrameCodec codec = mSpdyFrameCodec;
final DefaultSpdySynStreamFrame synStreamFrame = new DefaultSpdySynStreamFrame(1, 0, (byte) 0);
synStreamFrame.addHeader(":method", "GET");
synStreamFrame.addHeader(":path", "/1.1/statuses/home_timeline.json");
synStreamFrame.addHeader(":version", "HTTP/1.1");
synStreamFrame.addHeader(":host", "api.twitter.com:443");
synStreamFrame.addHeader(":scheme", "https");
synStreamFrame.setLast(true);
mSpdySessionHandler.handleDownstream(null, null, synStreamFrame);
codec.handleDownstream(null, null, connector, synStreamFrame);
Log.d(TAG, "Wrote to socket.");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (false && s != null) {
try {
s.close();
Log.d(TAG, "socket closed.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
return s;
}
@Override
public void handleFrame(Object frame) {
try {
mSpdySessionHandler.messageReceived(null, null, frame);
if (frame instanceof SpdySynReplyFrame) {
// We've made a network request and now we are receiving the reply.
// Gather the stream Id and the headers.
SpdySynReplyFrame synReplyFrame = (SpdySynReplyFrame) frame;
final int streamId = synReplyFrame.getStreamId();
if (streamId > 0) {
mMap.put(streamId, synReplyFrame.getHeaders());
}
} else if (frame instanceof SpdyDataFrame) {
Log.d(TAG, "Got data frame");
SpdyDataFrame dataFrame = (SpdyDataFrame) frame;
final int streamId = dataFrame.getStreamId();
if (streamId == 0) {
return;
}
List<Map.Entry<String, String>> headers;
if (dataFrame.isLast()) {
headers = mMap.remove(streamId);
} else {
headers = mMap.get(streamId);
}
// Check the content-encoding header
String encoding = null;
for (Map.Entry<String, String> header : headers) {
if ("content-encoding".equals(header.getKey())) {
encoding = header.getValue();
break;
}
}
ChannelBuffer data = dataFrame.getData();
StringBuilder sb = new StringBuilder();
int len = data.readableBytes();
if ("deflate".equals(encoding)) {
Log.d(TAG, "deflating: " + len);
Inflater inflater = new Inflater(false);
byte[] compressed = new byte[4096];
byte[] decompressed = new byte[4096];
while (data.readable()) {
int length = Math.min(data.readableBytes(), compressed.length);
data.readBytes(compressed, 0, length);
if (inflater.needsInput()) {
inflater.setInput(compressed, 0, length);
}
int inflated = inflater.inflate(decompressed);
sb.append(new String(decompressed, 0, inflated));
}
inflater.end();
} else {
Log.d(TAG, "raw: " + len);
byte[] compressed = new byte[4096];
while (data.readable()) {
int length = Math.min(data.readableBytes(), compressed.length);
data.readBytes(compressed, 0, length);
sb.append(new String(compressed, 0, length));
}
}
Log.d(TAG, "done, len=" + len + ", res=" + sb.toString());
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
| example/src/com/vandalsoftware/android/spdyexample/SpdyActivity.java | package com.vandalsoftware.android.spdyexample;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.vandalsoftware.android.spdy.FrameHandler;
import com.vandalsoftware.android.net.SSLSocketChannel;
import com.vandalsoftware.android.net.SocketReadHandler;
import com.vandalsoftware.android.spdy.DefaultSpdySynStreamFrame;
import com.vandalsoftware.android.spdy.SpdyDataFrame;
import com.vandalsoftware.android.spdy.SpdyFrameCodec;
import com.vandalsoftware.android.spdy.SpdySessionHandler;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ByteChannel;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
public class SpdyActivity extends Activity {
private static final String TAG = "spdy";
private LogView mLogView;
private Socket mSock;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLogView = (LogView) findViewById(R.id.logview);
Button startBtn = (Button) findViewById(R.id.start);
startBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new ConnectTask().execute();
}
});
Button stopBtn = (Button) findViewById(R.id.stop);
stopBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
log("Closing.");
Socket s = mSock;
if (s != null) {
try {
s.close();
Log.d(TAG, "socket closed.");
} catch (IOException e) {
e.printStackTrace();
}
}
log("Finished.");
}
});
log("Ready.");
}
private void log(String message) {
Log.d(TAG, message);
mLogView.log(message);
}
class ConnectTask extends AsyncTask<Void, Void, Socket> implements SocketReadHandler, FrameHandler {
private SpdyFrameCodec mSpdyFrameCodec;
private SpdySessionHandler mSpdySessionHandler;
@Override
protected void onPreExecute() {
mSpdyFrameCodec = new SpdyFrameCodec(3);
mSpdySessionHandler = new SpdySessionHandler(3, false);
}
@Override
protected void onPostExecute(Socket s) {
mSock = s;
}
public void handleRead(ByteChannel channel, byte[] in, int index, int length) {
Log.d(TAG, "handleRead " + length);
ChannelBuffer channelBuffer = ChannelBuffers.wrappedBuffer(in, index, length);
try {
Log.d(TAG, "read index: " + channelBuffer.readerIndex());
mSpdyFrameCodec.handleUpstream(null, null, channelBuffer, this);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Log.d(TAG, "handleRead done");
}
@Override
protected Socket doInBackground(Void... voids) {
Socket s = null;
try {
SSLSocketChannel connector = SSLSocketChannel.open("TLS");
connector.setSocketReadHandler(this);
connector.connect(new InetSocketAddress("api.twitter.com", 443), 15000);
Log.d(TAG, "socket connected.");
SpdyFrameCodec codec = mSpdyFrameCodec;
final DefaultSpdySynStreamFrame synStreamFrame = new DefaultSpdySynStreamFrame(1, 0, (byte) 0);
synStreamFrame.addHeader(":method", "GET");
synStreamFrame.addHeader(":path", "/1.1/statuses/home_timeline.json");
synStreamFrame.addHeader(":version", "HTTP/1.1");
synStreamFrame.addHeader(":host", "api.twitter.com:443");
synStreamFrame.addHeader(":scheme", "https");
synStreamFrame.setLast(true);
mSpdySessionHandler.handleDownstream(null, null, synStreamFrame);
codec.handleDownstream(null, null, connector, synStreamFrame);
Log.d(TAG, "Wrote to socket.");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (false && s != null) {
try {
s.close();
Log.d(TAG, "socket closed.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
return s;
}
@Override
public void handleFrame(Object frame) {
try {
mSpdySessionHandler.messageReceived(null, null, frame);
if (frame instanceof SpdyDataFrame) {
Log.d(TAG, "Got data frame");
SpdyDataFrame dataFrame = (SpdyDataFrame) frame;
ChannelBuffer buffer = dataFrame.getData();
StringBuilder sb = new StringBuilder();
final int baselen = buffer.readableBytes();
int len = baselen;
int index = 0;
sb.setLength(0);
byte[] outBytes = new byte[len - index];
buffer.getBytes(buffer.readerIndex() + index, outBytes);
Log.d(TAG, "decoding: " + outBytes.length);
Inflater inflater = new Inflater(false);
byte[] compressed = new byte[4096];
byte[] decompressed = new byte[4096];
while (buffer.readable()) {
int length = Math.min(buffer.readableBytes(), compressed.length);
buffer.readBytes(compressed, 0, length);
if (inflater.needsInput()) {
inflater.setInput(compressed, 0, length);
}
int inflated = inflater.inflate(decompressed);
sb.append(new String(decompressed, 0, inflated));
}
inflater.end();
Log.d(TAG, "done, len=" + len + ", res=" + sb.toString());
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
| Add rudimentary selection of decoding data.
| example/src/com/vandalsoftware/android/spdyexample/SpdyActivity.java | Add rudimentary selection of decoding data. | <ide><path>xample/src/com/vandalsoftware/android/spdyexample/SpdyActivity.java
<ide> import android.view.View;
<ide> import android.widget.Button;
<ide>
<del>import com.vandalsoftware.android.spdy.FrameHandler;
<ide> import com.vandalsoftware.android.net.SSLSocketChannel;
<ide> import com.vandalsoftware.android.net.SocketReadHandler;
<ide> import com.vandalsoftware.android.spdy.DefaultSpdySynStreamFrame;
<add>import com.vandalsoftware.android.spdy.FrameHandler;
<ide> import com.vandalsoftware.android.spdy.SpdyDataFrame;
<ide> import com.vandalsoftware.android.spdy.SpdyFrameCodec;
<ide> import com.vandalsoftware.android.spdy.SpdySessionHandler;
<add>import com.vandalsoftware.android.spdy.SpdySynReplyFrame;
<ide> import org.jboss.netty.buffer.ChannelBuffer;
<ide> import org.jboss.netty.buffer.ChannelBuffers;
<ide>
<del>import java.io.ByteArrayInputStream;
<ide> import java.io.IOException;
<del>import java.io.InputStream;
<ide> import java.net.InetSocketAddress;
<ide> import java.net.Socket;
<ide> import java.nio.channels.ByteChannel;
<ide> import java.security.KeyManagementException;
<ide> import java.security.NoSuchAlgorithmException;
<add>import java.util.IdentityHashMap;
<add>import java.util.List;
<add>import java.util.Map;
<ide> import java.util.zip.Inflater;
<del>import java.util.zip.InflaterInputStream;
<ide>
<ide> public class SpdyActivity extends Activity {
<ide> private static final String TAG = "spdy";
<ide> class ConnectTask extends AsyncTask<Void, Void, Socket> implements SocketReadHandler, FrameHandler {
<ide> private SpdyFrameCodec mSpdyFrameCodec;
<ide> private SpdySessionHandler mSpdySessionHandler;
<add> private IdentityHashMap<Integer, List<Map.Entry<String, String>>> mMap = new IdentityHashMap<Integer, List<Map.Entry<String, String>>>();
<ide>
<ide> @Override
<ide> protected void onPreExecute() {
<ide> public void handleFrame(Object frame) {
<ide> try {
<ide> mSpdySessionHandler.messageReceived(null, null, frame);
<del> if (frame instanceof SpdyDataFrame) {
<add> if (frame instanceof SpdySynReplyFrame) {
<add> // We've made a network request and now we are receiving the reply.
<add> // Gather the stream Id and the headers.
<add> SpdySynReplyFrame synReplyFrame = (SpdySynReplyFrame) frame;
<add> final int streamId = synReplyFrame.getStreamId();
<add> if (streamId > 0) {
<add> mMap.put(streamId, synReplyFrame.getHeaders());
<add> }
<add> } else if (frame instanceof SpdyDataFrame) {
<ide> Log.d(TAG, "Got data frame");
<ide> SpdyDataFrame dataFrame = (SpdyDataFrame) frame;
<del> ChannelBuffer buffer = dataFrame.getData();
<add> final int streamId = dataFrame.getStreamId();
<add> if (streamId == 0) {
<add> return;
<add> }
<add> List<Map.Entry<String, String>> headers;
<add> if (dataFrame.isLast()) {
<add> headers = mMap.remove(streamId);
<add> } else {
<add> headers = mMap.get(streamId);
<add> }
<add> // Check the content-encoding header
<add> String encoding = null;
<add> for (Map.Entry<String, String> header : headers) {
<add> if ("content-encoding".equals(header.getKey())) {
<add> encoding = header.getValue();
<add> break;
<add> }
<add> }
<add> ChannelBuffer data = dataFrame.getData();
<ide> StringBuilder sb = new StringBuilder();
<del> final int baselen = buffer.readableBytes();
<del> int len = baselen;
<del> int index = 0;
<del> sb.setLength(0);
<del> byte[] outBytes = new byte[len - index];
<del> buffer.getBytes(buffer.readerIndex() + index, outBytes);
<del> Log.d(TAG, "decoding: " + outBytes.length);
<del> Inflater inflater = new Inflater(false);
<del> byte[] compressed = new byte[4096];
<del> byte[] decompressed = new byte[4096];
<del> while (buffer.readable()) {
<del> int length = Math.min(buffer.readableBytes(), compressed.length);
<del> buffer.readBytes(compressed, 0, length);
<del> if (inflater.needsInput()) {
<del> inflater.setInput(compressed, 0, length);
<add> int len = data.readableBytes();
<add> if ("deflate".equals(encoding)) {
<add> Log.d(TAG, "deflating: " + len);
<add> Inflater inflater = new Inflater(false);
<add> byte[] compressed = new byte[4096];
<add> byte[] decompressed = new byte[4096];
<add> while (data.readable()) {
<add> int length = Math.min(data.readableBytes(), compressed.length);
<add> data.readBytes(compressed, 0, length);
<add> if (inflater.needsInput()) {
<add> inflater.setInput(compressed, 0, length);
<add> }
<add> int inflated = inflater.inflate(decompressed);
<add> sb.append(new String(decompressed, 0, inflated));
<ide> }
<del> int inflated = inflater.inflate(decompressed);
<del> sb.append(new String(decompressed, 0, inflated));
<del> }
<del> inflater.end();
<add> inflater.end();
<add> } else {
<add> Log.d(TAG, "raw: " + len);
<add> byte[] compressed = new byte[4096];
<add> while (data.readable()) {
<add> int length = Math.min(data.readableBytes(), compressed.length);
<add> data.readBytes(compressed, 0, length);
<add> sb.append(new String(compressed, 0, length));
<add> }
<add> }
<ide> Log.d(TAG, "done, len=" + len + ", res=" + sb.toString());
<ide> }
<ide> } catch (IOException e) { |
|
Java | bsd-3-clause | 9023194f080be59761c84855bb163a62a1a8439c | 0 | softappeal/yass,softappeal/yass,softappeal/yass,softappeal/yass,softappeal/yass,softappeal/yass,softappeal/yass | package ch.softappeal.yass.autoconfig;
import ch.softappeal.yass.core.Interceptor;
import java.lang.reflect.Modifier;
import java.util.function.Predicate;
public final class ClassCollectorTest {
private static void print(final ClassCollector classCollector, final Predicate<? super Class<?>> filter) {
classCollector.classes.stream().filter(filter).forEach(c -> System.out.println(c.getName()));
}
public static void main(final String... args) throws Exception {
System.out.println("--- from file system ---");
final ClassCollector classCollector = new ClassCollector(Interceptor.class.getPackage().getName(), Interceptor.class.getClassLoader());
System.out.println("* interfaces");
print(classCollector, Class::isInterface);
System.out.println("* concreteClasses");
print(classCollector, c -> c.isEnum() || !Modifier.isAbstract(c.getModifiers()));
System.out.println("--- from jar ---");
print(new ClassCollector("org.junit", Interceptor.class.getClassLoader()), c -> true);
}
}
| java/test/ch/softappeal/yass/autoconfig/ClassCollectorTest.java | package ch.softappeal.yass.autoconfig;
import ch.softappeal.yass.core.Interceptor;
public final class ClassCollectorTest {
public static void main(final String... args) throws Exception {
new ClassCollector(Interceptor.class.getPackage().getName(), Interceptor.class.getClassLoader()).classes.forEach(c -> System.out.println(c.getName()));
System.out.println();
new ClassCollector("org.junit", Interceptor.class.getClassLoader()).classes.forEach(c -> System.out.println(c.getName()));
}
}
| ClassCollectorTest: shows how to filter classes
j
| java/test/ch/softappeal/yass/autoconfig/ClassCollectorTest.java | ClassCollectorTest: shows how to filter classes j | <ide><path>ava/test/ch/softappeal/yass/autoconfig/ClassCollectorTest.java
<ide>
<ide> import ch.softappeal.yass.core.Interceptor;
<ide>
<add>import java.lang.reflect.Modifier;
<add>import java.util.function.Predicate;
<add>
<ide> public final class ClassCollectorTest {
<ide>
<add> private static void print(final ClassCollector classCollector, final Predicate<? super Class<?>> filter) {
<add> classCollector.classes.stream().filter(filter).forEach(c -> System.out.println(c.getName()));
<add> }
<add>
<ide> public static void main(final String... args) throws Exception {
<del> new ClassCollector(Interceptor.class.getPackage().getName(), Interceptor.class.getClassLoader()).classes.forEach(c -> System.out.println(c.getName()));
<del> System.out.println();
<del> new ClassCollector("org.junit", Interceptor.class.getClassLoader()).classes.forEach(c -> System.out.println(c.getName()));
<add> System.out.println("--- from file system ---");
<add> final ClassCollector classCollector = new ClassCollector(Interceptor.class.getPackage().getName(), Interceptor.class.getClassLoader());
<add> System.out.println("* interfaces");
<add> print(classCollector, Class::isInterface);
<add> System.out.println("* concreteClasses");
<add> print(classCollector, c -> c.isEnum() || !Modifier.isAbstract(c.getModifiers()));
<add>
<add> System.out.println("--- from jar ---");
<add> print(new ClassCollector("org.junit", Interceptor.class.getClassLoader()), c -> true);
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | d1000865f90d6d31284f0d31abd57279fd850c78 | 0 | ppatierno/kaas,scholzj/barnabas,scholzj/barnabas,ppatierno/kaas | /*
* Copyright 2018, Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.operator.cluster.operator.resource;
import com.fasterxml.jackson.databind.JsonNode;
import io.fabric8.kubernetes.api.model.extensions.StatefulSet;
import io.fabric8.zjsonpatch.JsonDiff;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static io.fabric8.kubernetes.client.internal.PatchUtils.patchMapper;
import static java.util.Arrays.asList;
public class StatefulSetDiff {
private static final Logger log = LogManager.getLogger(StatefulSetDiff.class.getName());
private static final List<Pattern> IGNORABLE_PATHS;
static {
IGNORABLE_PATHS = asList(
"/spec/revisionHistoryLimit",
"/spec/template/spec/initContainers/[0-9]+/imagePullPolicy",
"/spec/template/spec/initContainers/[0-9]+/resources",
"/spec/template/spec/initContainers/[0-9]+/terminationMessagePath",
"/spec/template/spec/initContainers/[0-9]+/terminationMessagePolicy",
"/spec/template/spec/initContainers/[0-9]+/env/[0-9]+/valueFrom/fieldRef/apiVersion",
"/spec/template/spec/initContainers/[0-9]+/env/[0-9]+/value",
"/spec/template/spec/containers/0/imagePullPolicy",
"/spec/template/spec/containers/0/livenessProbe/failureThreshold",
"/spec/template/spec/containers/0/livenessProbe/periodSeconds",
"/spec/template/spec/containers/0/livenessProbe/successThreshold",
"/spec/template/spec/containers/0/readinessProbe/failureThreshold",
"/spec/template/spec/containers/0/readinessProbe/periodSeconds",
"/spec/template/spec/containers/0/readinessProbe/successThreshold",
"/spec/template/spec/containers/0/resources",
"/spec/template/spec/containers/0/terminationMessagePath",
"/spec/template/spec/containers/0/terminationMessagePolicy",
"/spec/template/spec/dnsPolicy",
"/spec/template/spec/restartPolicy",
"/spec/template/spec/schedulerName",
"/spec/template/spec/securityContext",
"/spec/template/spec/terminationGracePeriodSeconds",
"/spec/template/spec/volumes/[0-9]+/configMap/defaultMode",
"/spec/template/spec/volumes/[0-9]+/secret/defaultMode",
"/spec/volumeClaimTemplates/[0-9]+/status",
"/spec/template/spec/serviceAccount",
"/status").stream().map(Pattern::compile).collect(Collectors.toList());
}
private static boolean containsPathOrChild(Iterable<String> paths, String path) {
for (String pathValue : paths) {
if (equalsOrPrefix(path, pathValue)) {
return true;
}
}
return false;
}
private static boolean equalsOrPrefix(String path, String pathValue) {
return pathValue.equals(path)
|| pathValue.startsWith(path + "/");
}
private final boolean changesVolumeClaimTemplate;
private final boolean isEmpty;
private final boolean changesSpecTemplateSpec;
private final boolean changesLabels;
private final boolean changesSpecReplicas;
public StatefulSetDiff(StatefulSet current, StatefulSet updated) {
JsonNode diff = JsonDiff.asJson(patchMapper().valueToTree(current), patchMapper().valueToTree(updated));
Set<String> paths = new HashSet<>();
outer: for (JsonNode d : diff) {
String pathValue = d.get("path").asText();
for (Pattern pattern : IGNORABLE_PATHS) {
if (pattern.matcher(pathValue).matches()) {
log.debug("StatefulSet {}/{} ignoring diff {}", current.getMetadata().getNamespace(), current.getMetadata().getName(), d);
continue outer;
}
}
log.debug("StatefulSet {}/{} differs at path {}", current.getMetadata().getNamespace(), current.getMetadata().getName(), pathValue);
paths.add(pathValue);
}
isEmpty = paths.isEmpty();
changesVolumeClaimTemplate = containsPathOrChild(paths, "/spec/volumeClaimTemplates");
// Change changes to /spec/template/spec, except to imagePullPolicy, which gets changed
// by k8s
changesSpecTemplateSpec = containsPathOrChild(paths, "/spec/template/spec");
changesLabels = containsPathOrChild(paths, "/metadata/labels");
changesSpecReplicas = containsPathOrChild(paths, "/spec/replicas");
}
public boolean isEmpty() {
return isEmpty;
}
public boolean changesVolumeClaimTemplates() {
return changesVolumeClaimTemplate;
}
public boolean changesSpecTemplateSpec() {
return changesSpecTemplateSpec;
}
public boolean changesLabels() {
return changesLabels;
}
public boolean changesSpecReplicas() {
return changesSpecReplicas;
}
}
| cluster-operator/src/main/java/io/strimzi/operator/cluster/operator/resource/StatefulSetDiff.java | /*
* Copyright 2018, Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.operator.cluster.operator.resource;
import com.fasterxml.jackson.databind.JsonNode;
import io.fabric8.kubernetes.api.model.extensions.StatefulSet;
import io.fabric8.zjsonpatch.JsonDiff;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static io.fabric8.kubernetes.client.internal.PatchUtils.patchMapper;
import static java.util.Arrays.asList;
public class StatefulSetDiff {
private static final Logger log = LogManager.getLogger(StatefulSetDiff.class.getName());
private static final List<Pattern> IGNORABLE_PATHS;
static {
IGNORABLE_PATHS = asList(
"/spec/revisionHistoryLimit",
"/spec/template/spec/initContainers/[0-9]+/imagePullPolicy",
"/spec/template/spec/initContainers/[0-9]+/resources",
"/spec/template/spec/initContainers/[0-9]+/terminationMessagePath",
"/spec/template/spec/initContainers/[0-9]+/terminationMessagePolicy",
"/spec/template/spec/initContainers/[0-9]+/env/[0-9]+/valueFrom/fieldRef/apiVersion",
"/spec/template/spec/initContainers/[0-9]+/env/[0-9]+/value",
"/spec/template/spec/containers/0/imagePullPolicy",
"/spec/template/spec/containers/0/livenessProbe/failureThreshold",
"/spec/template/spec/containers/0/livenessProbe/periodSeconds",
"/spec/template/spec/containers/0/livenessProbe/successThreshold",
"/spec/template/spec/containers/0/readinessProbe/failureThreshold",
"/spec/template/spec/containers/0/readinessProbe/periodSeconds",
"/spec/template/spec/containers/0/readinessProbe/successThreshold",
"/spec/template/spec/containers/0/resources",
"/spec/template/spec/containers/0/terminationMessagePath",
"/spec/template/spec/containers/0/terminationMessagePolicy",
"/spec/template/spec/dnsPolicy",
"/spec/template/spec/restartPolicy",
"/spec/template/spec/schedulerName",
"/spec/template/spec/securityContext",
"/spec/template/spec/terminationGracePeriodSeconds",
"/spec/template/spec/volumes/[0-9]+/configMap/defaultMode",
"/spec/volumeClaimTemplates/[0-9]+/status",
"/spec/template/spec/serviceAccount",
"/status").stream().map(Pattern::compile).collect(Collectors.toList());
}
private static boolean containsPathOrChild(Iterable<String> paths, String path) {
for (String pathValue : paths) {
if (equalsOrPrefix(path, pathValue)) {
return true;
}
}
return false;
}
private static boolean equalsOrPrefix(String path, String pathValue) {
return pathValue.equals(path)
|| pathValue.startsWith(path + "/");
}
private final boolean changesVolumeClaimTemplate;
private final boolean isEmpty;
private final boolean changesSpecTemplateSpec;
private final boolean changesLabels;
private final boolean changesSpecReplicas;
public StatefulSetDiff(StatefulSet current, StatefulSet updated) {
JsonNode diff = JsonDiff.asJson(patchMapper().valueToTree(current), patchMapper().valueToTree(updated));
Set<String> paths = new HashSet<>();
outer: for (JsonNode d : diff) {
String pathValue = d.get("path").asText();
for (Pattern pattern : IGNORABLE_PATHS) {
if (pattern.matcher(pathValue).matches()) {
log.debug("StatefulSet {}/{} ignoring diff {}", current.getMetadata().getNamespace(), current.getMetadata().getName(), d);
continue outer;
}
}
log.debug("StatefulSet {}/{} differs at path {}", current.getMetadata().getNamespace(), current.getMetadata().getName(), pathValue);
paths.add(pathValue);
}
isEmpty = paths.isEmpty();
changesVolumeClaimTemplate = containsPathOrChild(paths, "/spec/volumeClaimTemplates");
// Change changes to /spec/template/spec, except to imagePullPolicy, which gets changed
// by k8s
changesSpecTemplateSpec = containsPathOrChild(paths, "/spec/template/spec");
changesLabels = containsPathOrChild(paths, "/metadata/labels");
changesSpecReplicas = containsPathOrChild(paths, "/spec/replicas");
}
public boolean isEmpty() {
return isEmpty;
}
public boolean changesVolumeClaimTemplates() {
return changesVolumeClaimTemplate;
}
public boolean changesSpecTemplateSpec() {
return changesSpecTemplateSpec;
}
public boolean changesLabels() {
return changesLabels;
}
public boolean changesSpecReplicas() {
return changesSpecReplicas;
}
}
| Ignored defaultMode on secret volumes for diff
| cluster-operator/src/main/java/io/strimzi/operator/cluster/operator/resource/StatefulSetDiff.java | Ignored defaultMode on secret volumes for diff | <ide><path>luster-operator/src/main/java/io/strimzi/operator/cluster/operator/resource/StatefulSetDiff.java
<ide> "/spec/template/spec/securityContext",
<ide> "/spec/template/spec/terminationGracePeriodSeconds",
<ide> "/spec/template/spec/volumes/[0-9]+/configMap/defaultMode",
<add> "/spec/template/spec/volumes/[0-9]+/secret/defaultMode",
<ide> "/spec/volumeClaimTemplates/[0-9]+/status",
<ide> "/spec/template/spec/serviceAccount",
<ide> "/status").stream().map(Pattern::compile).collect(Collectors.toList()); |
|
Java | apache-2.0 | 4008f426144f31b56af2cc94ed98fc5ac46322b6 | 0 | consulo/consulo,ernestp/consulo,ernestp/consulo,ernestp/consulo,ernestp/consulo,consulo/consulo,consulo/consulo,consulo/consulo,ernestp/consulo,consulo/consulo,ernestp/consulo,consulo/consulo | /*
* Copyright 2000-2009 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.codeInsight.highlighting;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.Consumer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* @author yole
*/
public abstract class HighlightUsagesHandlerBase<T extends PsiElement> {
protected final Editor myEditor;
protected final PsiFile myFile;
protected List<TextRange> myReadUsages = new ArrayList<TextRange>();
protected List<TextRange> myWriteUsages = new ArrayList<TextRange>();
protected String myStatusText;
protected String myHintText;
protected HighlightUsagesHandlerBase(final Editor editor, final PsiFile file) {
myEditor = editor;
myFile = file;
}
public void highlightUsages() {
List<T> targets = getTargets();
if (targets == null) {
return;
}
selectTargets(targets, new Consumer<List<T>>() {
@Override
public void consume(final List<T> targets) {
computeUsages(targets);
performHighlighting();
}
});
}
protected void performHighlighting() {
boolean clearHighlights = HighlightUsagesHandler.isClearHighlights(myEditor);
EditorColorsManager manager = EditorColorsManager.getInstance();
TextAttributes attributes = manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
TextAttributes writeAttributes = manager.getGlobalScheme().getAttributes(EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES);
HighlightUsagesHandler.highlightRanges(HighlightManager.getInstance(myEditor.getProject()),
myEditor, attributes, clearHighlights, myReadUsages);
HighlightUsagesHandler.highlightRanges(HighlightManager.getInstance(myEditor.getProject()),
myEditor, writeAttributes, clearHighlights, myWriteUsages);
if (!clearHighlights) {
WindowManager.getInstance().getStatusBar(myEditor.getProject()).setInfo(myStatusText);
HighlightHandlerBase.setupFindModel(myEditor.getProject()); // enable f3 navigation
}
if (myHintText != null) {
HintManager.getInstance().showInformationHint(myEditor, myHintText);
}
}
protected void buildStatusText(@Nullable String elementName, int refCount) {
if (refCount > 0) {
myStatusText = CodeInsightBundle.message(elementName != null ?
"status.bar.highlighted.usages.message" :
"status.bar.highlighted.usages.no.target.message", refCount, elementName,
HighlightUsagesHandler.getShortcutText());
}
else {
myStatusText = CodeInsightBundle.message(elementName != null ?
"status.bar.highlighted.usages.not.found.message" :
"status.bar.highlighted.usages.not.found.no.target.message", elementName);
}
}
public abstract List<T> getTargets();
protected abstract void selectTargets(List<T> targets, Consumer<List<T>> selectionConsumer);
public abstract void computeUsages(List<T> targets);
public void addOccurrence(@NotNull PsiElement element) {
TextRange range = element.getTextRange();
range = InjectedLanguageManager.getInstance(element.getProject()).injectedToHost(element, range);
myReadUsages.add(range);
}
public List<TextRange> getReadUsages() {
return myReadUsages;
}
public List<TextRange> getWriteUsages() {
return myWriteUsages;
}
}
| platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesHandlerBase.java | /*
* Copyright 2000-2009 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.codeInsight.highlighting;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.Consumer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* @author yole
*/
public abstract class HighlightUsagesHandlerBase<T extends PsiElement> {
protected final Editor myEditor;
protected final PsiFile myFile;
protected List<TextRange> myReadUsages = new ArrayList<TextRange>();
protected List<TextRange> myWriteUsages = new ArrayList<TextRange>();
protected String myStatusText;
protected String myHintText;
protected HighlightUsagesHandlerBase(final Editor editor, final PsiFile file) {
myEditor = editor;
myFile = file;
}
public void highlightUsages() {
List<T> targets = getTargets();
if (targets == null) {
return;
}
selectTargets(targets, new Consumer<List<T>>() {
@Override
public void consume(final List<T> targets) {
computeUsages(targets);
performHighlighting();
}
});
}
protected void performHighlighting() {
boolean clearHighlights = HighlightUsagesHandler.isClearHighlights(myEditor);
EditorColorsManager manager = EditorColorsManager.getInstance();
TextAttributes attributes = manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
TextAttributes writeAttributes = manager.getGlobalScheme().getAttributes(EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES);
HighlightUsagesHandler.highlightRanges(HighlightManager.getInstance(myEditor.getProject()),
myEditor, attributes, clearHighlights, myReadUsages);
HighlightUsagesHandler.highlightRanges(HighlightManager.getInstance(myEditor.getProject()),
myEditor, writeAttributes, clearHighlights, myWriteUsages);
if (!clearHighlights) {
WindowManager.getInstance().getStatusBar(myEditor.getProject()).setInfo(myStatusText);
HighlightHandlerBase.setupFindModel(myEditor.getProject()); // enable f3 navigation
}
if (myHintText != null) {
HintManager.getInstance().showInformationHint(myEditor, myHintText);
}
}
protected void buildStatusText(@Nullable String elementName, int refCount) {
if (refCount > 0) {
myStatusText = CodeInsightBundle.message(elementName != null ?
"status.bar.highlighted.usages.message" :
"status.bar.highlighted.usages.no.target.message", refCount, elementName,
HighlightUsagesHandler.getShortcutText());
}
else {
myStatusText = CodeInsightBundle.message(elementName != null ?
"status.bar.highlighted.usages.not.found.message" :
"status.bar.highlighted.usages.not.found.no.target.message", elementName);
}
}
public abstract List<T> getTargets();
protected abstract void selectTargets(List<T> targets, Consumer<List<T>> selectionConsumer);
public abstract void computeUsages(List<T> targets);
protected void addOccurrence(@NotNull PsiElement element) {
TextRange range = element.getTextRange();
range = InjectedLanguageManager.getInstance(element.getProject()).injectedToHost(element, range);
myReadUsages.add(range);
}
public List<TextRange> getReadUsages() {
return myReadUsages;
}
public List<TextRange> getWriteUsages() {
return myWriteUsages;
}
}
| fix while invoking
| platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesHandlerBase.java | fix while invoking | <ide><path>latform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesHandlerBase.java
<ide>
<ide> public abstract void computeUsages(List<T> targets);
<ide>
<del> protected void addOccurrence(@NotNull PsiElement element) {
<add> public void addOccurrence(@NotNull PsiElement element) {
<ide> TextRange range = element.getTextRange();
<ide> range = InjectedLanguageManager.getInstance(element.getProject()).injectedToHost(element, range);
<ide> myReadUsages.add(range); |
|
Java | mpl-2.0 | error: pathspec 'wizards/com/sun/star/wizards/report/IReportDocument.java' did not match any file(s) known to git
| 85dc3dcc4358bc5ffe870139736025a2325fe022 | 1 | JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core | /*
************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: IReportDocument.java,v $
*
* $Revision: 1.2 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
package com.sun.star.wizards.report;
import com.sun.star.beans.PropertyValue;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import java.util.ArrayList;
import java.util.Vector;
/**
* New Interface which gives us the possibility to switch on the fly between the old
* Wizard and the new Sun Report Builder Wizard, which use the same UI.
*
* @author ll93751
*/
public interface IReportDocument
{
// public ReportTextDocument getDoc();
// -------------------------------------------------------------------------
// initialisation
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// opening the dialog
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// Access Helper
// -------------------------------------------------------------------------
/**
* Gives access to the DB Values
* @return
*/
public com.sun.star.wizards.db.RecordParser getRecordParser();
/**
* Give access to the parent document
* It is a document in the old Wizard
* It is a Report Builder in the new Wizard
* @return
*/
public com.sun.star.awt.XWindowPeer getWizardParent();
/**
*
* @return the Frame of the document Window or Report Builder Window
*/
public com.sun.star.frame.XFrame getFrame();
public XComponent getComponent();
// -------------------------------------------------------------------------
// First step: After entering the table name, select fields
// -------------------------------------------------------------------------
/**
* Is called after first step, set Tablename and the fields, which should occur in the Report.
* @param _aType
* @param TableName
* @param FieldNames
*/
public void initializeFieldColumns(final int _aType, final String TableName, final String[] FieldNames);
/**
* Empties the report document
*/
public void clearDocument();
/**
* Empties the report document, if we called back, don't remove Grouping/Sorting
*/
public void removeTextTableAndTextSection();
// -------------------------------------------------------------------------
// Second step: Label field titles
// -------------------------------------------------------------------------
/**
* Set new names for the titles
* @param sFieldTitles
*/
public void setFieldTitles(final String[] sFieldTitles);
/**
* Change a the name of the 'title' of one field.
* It is possible to give all element names new names which are used as
* element title of a given element name.
* This is only used as a preview
* @param FieldName
* @param TitleName
*/
public void liveupdate_changeUserFieldContent(final String FieldName, final String TitleName);
// -------------------------------------------------------------------------
// Third step: Grouping
// -------------------------------------------------------------------------
/* Grouping Page */
// Document should not hold the grouping information!
/**
* Called by press ('greater then') add a group to the group list
* @param GroupNames
* @param CurGroupTitle
* @param GroupFieldVector
* @param ReportPath
* @param iSelCount
* @return
*/
public boolean liveupdate_addGroupNametoDocument(String[] GroupNames, String CurGroupTitle, Vector GroupFieldVector, ArrayList ReportPath, int iSelCount);
public void refreshGroupFields(String[] _sNewNames);
// public boolean isGroupField(String _FieldName);
/**
* Called by press ('less then') Removes an already set Groupname out of the list
* @param NewSelGroupNames
* @param CurGroupTitle
* @param GroupFieldVector
*/
public void liveupdate_removeGroupName(String[] NewSelGroupNames, String CurGroupTitle, java.util.Vector GroupFieldVector);
/**
* set the list how to group
* @param aGroupList
*/
public void setGrouping(String[] aGroupList);
// -------------------------------------------------------------------------
// Fourth step: Sorting
// -------------------------------------------------------------------------
/**
* Set the list how to sort
* @param aSort
*/
public void setSorting(String [][] aSort);
// -------------------------------------------------------------------------
// Fivth step: Templates / Layout
// -------------------------------------------------------------------------
/* Template Page */
public void setPageOrientation(int nOrientation) throws com.sun.star.lang.IllegalArgumentException;
public int getDefaultPageOrientation();
public ArrayList getReportPath();
public String getLayoutPath();
public String getContentPath();
/**
* Called if a new Layout is selected
* @param LayoutTemplatePath
*/
public void liveupdate_changeLayoutTemplate(String LayoutTemplatePath/*, String BitmapPath*/);
/**
* Called if a new Template is selected
* @param ContentTemplatePath
*/
public void liveupdate_changeContentTemplate(String ContentTemplatePath);
// public String[] getLayoutTemplates();
// public String[] getContentTemplates();
public void layout_selectFirstPage();
public void layout_setupRecordSection(String TemplateName);
// -------------------------------------------------------------------------
// finishing
// -------------------------------------------------------------------------
// preview (update titlenames)
// addTextListener
/**
* Set the Title into the document from the 'Create Report Page'
* BUG: The Title is empty after create Report.
* @param _sTitleName
*/
public void liveupdate_updateReportTitle(String _sTitleName);
/**
* Store the document by the given name
* @param Name
* @param OpenMode
*/
public void store(String Name, int OpenMode);
/**
* The current report is added to the DB View under the given name
* @param Name
* TODO: add Name to this functionality
*/
public void addReportToDBView(/* String Name */);
public void importReportData(ReportWizard aWizard);
/**
* Create the final Report document
* @param Name
* @param _bAsTemplate
* @param _bOpenInDesign
* @return
*/
public XComponent[] createFinalReportDocument(String Name, boolean _bAsTemplate, boolean _bOpenInDesign);
public void dispose();
// -------------------------------------------------------------------------
// Garbage dump
// -------------------------------------------------------------------------
/* DataImport */
// ???
// public void addTextSectionCopies();
// ???
public boolean reconnectToDatabase(XMultiServiceFactory xMSF, PropertyValue[] Properties);
// ???
public void insertDatabaseDatatoReportDocument(XMultiServiceFactory xMSF);
// ???
// public com.sun.star.lang.XMultiServiceFactory getDocumentServiceFactory();
/**
* set a internal variable to stop a maybe longer DB access.
*/
public void StopProcess(); // cancel
/**
* Returns a string list of layouts.
* @return
*/
public String[][] getDataLayout();
/**
* Returns a string list of header layouts
* @return
*/
public String[][] getHeaderLayout();
public void setCommandType(int CommandType);
public void setCommand(String Command);
}
| wizards/com/sun/star/wizards/report/IReportDocument.java | INTEGRATION: CWS rptwizard01 (1.1.2); FILE ADDED
2008/06/24 14:57:41 kz 1.1.2.11: fixed wrong license header
2008/06/03 09:45:25 lla 1.1.2.10: #i86092# problem with sorting fixed
2008/05/16 07:05:13 lla 1.1.2.9: #i86092# restructures to work with design templates
2008/04/04 12:40:59 lla 1.1.2.8: #i86092# handle store right
2008/03/31 12:31:01 lla 1.1.2.7: #i86092# doc cleanups
2008/03/18 12:13:31 lla 1.1.2.6: #i86092# enhance Tablename by CommandType
2008/03/14 13:48:14 lla 1.1.2.5: #i86092# PMD cleanups
2008/03/11 12:25:05 lla 1.1.2.4: #i86092# cleanups
2008/03/07 07:27:18 lla 1.1.2.3: #i86092# Change ReportBuilderWizard this way, it will exist and workable in the reportbuilder extension
2008/02/19 12:45:14 lla 1.1.2.2: #i86092 add getter for Layout access
2008/02/14 12:52:49 lla 1.1.2.1: #i86092# new Report Wizard
| wizards/com/sun/star/wizards/report/IReportDocument.java | INTEGRATION: CWS rptwizard01 (1.1.2); FILE ADDED 2008/06/24 14:57:41 kz 1.1.2.11: fixed wrong license header 2008/06/03 09:45:25 lla 1.1.2.10: #i86092# problem with sorting fixed 2008/05/16 07:05:13 lla 1.1.2.9: #i86092# restructures to work with design templates 2008/04/04 12:40:59 lla 1.1.2.8: #i86092# handle store right 2008/03/31 12:31:01 lla 1.1.2.7: #i86092# doc cleanups 2008/03/18 12:13:31 lla 1.1.2.6: #i86092# enhance Tablename by CommandType 2008/03/14 13:48:14 lla 1.1.2.5: #i86092# PMD cleanups 2008/03/11 12:25:05 lla 1.1.2.4: #i86092# cleanups 2008/03/07 07:27:18 lla 1.1.2.3: #i86092# Change ReportBuilderWizard this way, it will exist and workable in the reportbuilder extension 2008/02/19 12:45:14 lla 1.1.2.2: #i86092 add getter for Layout access 2008/02/14 12:52:49 lla 1.1.2.1: #i86092# new Report Wizard | <ide><path>izards/com/sun/star/wizards/report/IReportDocument.java
<add>/*
<add> ************************************************************************
<add> *
<add> * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
<add> *
<add> * Copyright 2008 by Sun Microsystems, Inc.
<add> *
<add> * OpenOffice.org - a multi-platform office productivity suite
<add> *
<add> * $RCSfile: IReportDocument.java,v $
<add> *
<add> * $Revision: 1.2 $
<add> *
<add> * This file is part of OpenOffice.org.
<add> *
<add> * OpenOffice.org is free software: you can redistribute it and/or modify
<add> * it under the terms of the GNU Lesser General Public License version 3
<add> * only, as published by the Free Software Foundation.
<add> *
<add> * OpenOffice.org is distributed in the hope that it will be useful,
<add> * but WITHOUT ANY WARRANTY; without even the implied warranty of
<add> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
<add> * GNU Lesser General Public License version 3 for more details
<add> * (a copy is included in the LICENSE file that accompanied this code).
<add> *
<add> * You should have received a copy of the GNU Lesser General Public License
<add> * version 3 along with OpenOffice.org. If not, see
<add> * <http://www.openoffice.org/license.html>
<add> * for a copy of the LGPLv3 License.
<add> *
<add> ************************************************************************/
<add>
<add>package com.sun.star.wizards.report;
<add>
<add>import com.sun.star.beans.PropertyValue;
<add>import com.sun.star.lang.XComponent;
<add>import com.sun.star.lang.XMultiServiceFactory;
<add>import java.util.ArrayList;
<add>import java.util.Vector;
<add>
<add>/**
<add> * New Interface which gives us the possibility to switch on the fly between the old
<add> * Wizard and the new Sun Report Builder Wizard, which use the same UI.
<add> *
<add> * @author ll93751
<add> */
<add>public interface IReportDocument
<add>{
<add> // public ReportTextDocument getDoc();
<add>
<add>
<add> // -------------------------------------------------------------------------
<add> // initialisation
<add> // -------------------------------------------------------------------------
<add>
<add> // -------------------------------------------------------------------------
<add> // opening the dialog
<add> // -------------------------------------------------------------------------
<add>
<add> // -------------------------------------------------------------------------
<add> // Access Helper
<add> // -------------------------------------------------------------------------
<add>
<add> /**
<add> * Gives access to the DB Values
<add> * @return
<add> */
<add> public com.sun.star.wizards.db.RecordParser getRecordParser();
<add> /**
<add> * Give access to the parent document
<add> * It is a document in the old Wizard
<add> * It is a Report Builder in the new Wizard
<add> * @return
<add> */
<add> public com.sun.star.awt.XWindowPeer getWizardParent();
<add> /**
<add> *
<add> * @return the Frame of the document Window or Report Builder Window
<add> */
<add> public com.sun.star.frame.XFrame getFrame();
<add> public XComponent getComponent();
<add>
<add> // -------------------------------------------------------------------------
<add> // First step: After entering the table name, select fields
<add> // -------------------------------------------------------------------------
<add>
<add> /**
<add> * Is called after first step, set Tablename and the fields, which should occur in the Report.
<add> * @param _aType
<add> * @param TableName
<add> * @param FieldNames
<add> */
<add> public void initializeFieldColumns(final int _aType, final String TableName, final String[] FieldNames);
<add>
<add> /**
<add> * Empties the report document
<add> */
<add> public void clearDocument();
<add>
<add> /**
<add> * Empties the report document, if we called back, don't remove Grouping/Sorting
<add> */
<add> public void removeTextTableAndTextSection();
<add>
<add> // -------------------------------------------------------------------------
<add> // Second step: Label field titles
<add> // -------------------------------------------------------------------------
<add> /**
<add> * Set new names for the titles
<add> * @param sFieldTitles
<add> */
<add> public void setFieldTitles(final String[] sFieldTitles);
<add>
<add> /**
<add> * Change a the name of the 'title' of one field.
<add> * It is possible to give all element names new names which are used as
<add> * element title of a given element name.
<add> * This is only used as a preview
<add> * @param FieldName
<add> * @param TitleName
<add> */
<add> public void liveupdate_changeUserFieldContent(final String FieldName, final String TitleName);
<add>
<add> // -------------------------------------------------------------------------
<add> // Third step: Grouping
<add> // -------------------------------------------------------------------------
<add>
<add> /* Grouping Page */
<add> // Document should not hold the grouping information!
<add>
<add> /**
<add> * Called by press ('greater then') add a group to the group list
<add> * @param GroupNames
<add> * @param CurGroupTitle
<add> * @param GroupFieldVector
<add> * @param ReportPath
<add> * @param iSelCount
<add> * @return
<add> */
<add> public boolean liveupdate_addGroupNametoDocument(String[] GroupNames, String CurGroupTitle, Vector GroupFieldVector, ArrayList ReportPath, int iSelCount);
<add>
<add> public void refreshGroupFields(String[] _sNewNames);
<add> // public boolean isGroupField(String _FieldName);
<add>
<add> /**
<add> * Called by press ('less then') Removes an already set Groupname out of the list
<add> * @param NewSelGroupNames
<add> * @param CurGroupTitle
<add> * @param GroupFieldVector
<add> */
<add> public void liveupdate_removeGroupName(String[] NewSelGroupNames, String CurGroupTitle, java.util.Vector GroupFieldVector);
<add>
<add> /**
<add> * set the list how to group
<add> * @param aGroupList
<add> */
<add> public void setGrouping(String[] aGroupList);
<add> // -------------------------------------------------------------------------
<add> // Fourth step: Sorting
<add> // -------------------------------------------------------------------------
<add> /**
<add> * Set the list how to sort
<add> * @param aSort
<add> */
<add> public void setSorting(String [][] aSort);
<add>
<add> // -------------------------------------------------------------------------
<add> // Fivth step: Templates / Layout
<add> // -------------------------------------------------------------------------
<add> /* Template Page */
<add> public void setPageOrientation(int nOrientation) throws com.sun.star.lang.IllegalArgumentException;
<add> public int getDefaultPageOrientation();
<add>
<add> public ArrayList getReportPath();
<add> public String getLayoutPath();
<add> public String getContentPath();
<add>
<add> /**
<add> * Called if a new Layout is selected
<add> * @param LayoutTemplatePath
<add> */
<add> public void liveupdate_changeLayoutTemplate(String LayoutTemplatePath/*, String BitmapPath*/);
<add> /**
<add> * Called if a new Template is selected
<add> * @param ContentTemplatePath
<add> */
<add> public void liveupdate_changeContentTemplate(String ContentTemplatePath);
<add>
<add> // public String[] getLayoutTemplates();
<add> // public String[] getContentTemplates();
<add> public void layout_selectFirstPage();
<add> public void layout_setupRecordSection(String TemplateName);
<add>
<add>
<add> // -------------------------------------------------------------------------
<add> // finishing
<add> // -------------------------------------------------------------------------
<add> // preview (update titlenames)
<add> // addTextListener
<add>
<add> /**
<add> * Set the Title into the document from the 'Create Report Page'
<add> * BUG: The Title is empty after create Report.
<add> * @param _sTitleName
<add> */
<add> public void liveupdate_updateReportTitle(String _sTitleName);
<add>
<add> /**
<add> * Store the document by the given name
<add> * @param Name
<add> * @param OpenMode
<add> */
<add> public void store(String Name, int OpenMode);
<add>
<add> /**
<add> * The current report is added to the DB View under the given name
<add> * @param Name
<add> * TODO: add Name to this functionality
<add> */
<add> public void addReportToDBView(/* String Name */);
<add>
<add> public void importReportData(ReportWizard aWizard);
<add>
<add> /**
<add> * Create the final Report document
<add> * @param Name
<add> * @param _bAsTemplate
<add> * @param _bOpenInDesign
<add> * @return
<add> */
<add> public XComponent[] createFinalReportDocument(String Name, boolean _bAsTemplate, boolean _bOpenInDesign);
<add> public void dispose();
<add>
<add>
<add>
<add> // -------------------------------------------------------------------------
<add> // Garbage dump
<add> // -------------------------------------------------------------------------
<add>
<add> /* DataImport */
<add> // ???
<add> // public void addTextSectionCopies();
<add> // ???
<add> public boolean reconnectToDatabase(XMultiServiceFactory xMSF, PropertyValue[] Properties);
<add> // ???
<add> public void insertDatabaseDatatoReportDocument(XMultiServiceFactory xMSF);
<add> // ???
<add> // public com.sun.star.lang.XMultiServiceFactory getDocumentServiceFactory();
<add>
<add> /**
<add> * set a internal variable to stop a maybe longer DB access.
<add> */
<add> public void StopProcess(); // cancel
<add>
<add> /**
<add> * Returns a string list of layouts.
<add> * @return
<add> */
<add> public String[][] getDataLayout();
<add>
<add> /**
<add> * Returns a string list of header layouts
<add> * @return
<add> */
<add> public String[][] getHeaderLayout();
<add>
<add> public void setCommandType(int CommandType);
<add> public void setCommand(String Command);
<add>} |
|
JavaScript | apache-2.0 | 753dfb8253a2a0d1a2c3c5dc861662eeab9ecd55 | 0 | osofem/BigArith.js,osofem/BigArith.js | /**
* bigarith.js - Written by Oso Oluwafemi Ebenezer
* The constructor for BigArith
* @param {string|number|null|BigArith} n Accepts no parameter, or number within the safe integer limit or string in "-123.456" form or
* "negative one hundred and twenty three point four five six" form or a constant "PI" form or a BigArith object
* Dependent on verify(), getter name()
*/
var BigArith=function(n){
//version
Object.defineProperty(this, 'version', {
enumerable: true,
writable: false,
value: "v0.0.8",
});
//Object name
Object.defineProperty(this, 'name', {
enumerable: true,
writable: false,
value: "BigArith"
});
//Word length support
Object.defineProperty(this, 'wordSupport', {
writable: false,
value: 1002 //up to (1x10^1,005) - 0.0{199}1
});
//Word decimal length support
Object.defineProperty(this, 'decimalSupport', {
writable: false,
value: 200 //200 decimal characters when using toWords()
});
//assign this.value
if(n == null) this.value = "0"
else if(typeof n == "object" && n.name == "BigArith") this.value = n.toString();
else if(typeof n == "undefined" /*null*/ || n == "") this.value = "0";
else if(n == "PI") this.value = "3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196";
else if(n == "E") this.value = "2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901";
/*else if(n == "LN2") this.value = "0.6931471805599453";
else if(n == "LN10") this.value = "2.302585092994046";
else if(n == "LOG2E") this.value = "1.4426950408889634";
else if(n == "LOG10E") this.value = "0.4342944819032518";*/
else if(n == "SQRT1_2") this.value = "0.70710678118654752440084436210484903928483593768847403658833986899536623923105351942519376716382078636750692311545614851246241802792536860632206074854996791570661133296375279637789997525057639103028574";
else if(n == "SQRT2") this.value = "1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147";
else this.value = this.verify(n);
};
/**
* Verify input evaluate to a valid number
* function verify
* @param {string|number|BigArth} n Number within the safe integer limit or string in "-123.456" or
* "negative one hundred and twenty three point four five six" form or a BigArith object
* @returns {string|NaN} - A string representation of @param in form "-123.456" or NaN if @param is not valid,
* or throws a RangeError if input is in number form but not within safe limits.
* Dependent on w_Dict()
*/
BigArith.prototype.verify = function(n){
//Can be an already verified BigArith object
if(typeof(n) == "object" && n.name == "BigArith") return n.toString();
//Can be a number in form of 1000 or 1e3
//Number must be within the safe integer range
if(typeof(n) == 'number' && n <= Number.MAX_SAFE_INTEGER && n >= Number.MIN_SAFE_INTEGER) return n.toString();
if(typeof(n) == 'number' && (n > Number.MAX_SAFE_INTEGER || n < Number.MIN_SAFE_INTEGER)) throw new RangeError("The number you entered in typeof 'number' form is not within the safe limit. Please enter the number as a string.");
//It can be string in form "-123.89"
if(typeof(n) == 'string' && /\d/.test(n)/*This just test if it contains any digit, real test in below*/){
n = n.replace(/^\s|\s$/g, "");
var sign = false;
if(n[0] == "-"){
sign = true;
n = n.slice(1, n.length);
}
else if(n[0] == "+"){
n = n.slice(1, n.length);
}
n = n.split(".");
if(n.length > 2) return NaN;
if(n[0] == "") n[0] = "0";
if(typeof(n[1]) == 'undefined') n[1] = "0";
if(/^\d+$/.test(n[0]) && /^\d+$/.test(n[1])/*Test that it contains only digits*/){
//Remove unnecessary zeroes
n[0] = n[0].replace(/^[0]+/g, "");
n[1] = n[1].replace(/[0]+$/g, "");
return ((sign)?"-":"") + ((n[0] == "")?"0":n[0]) + ((n[1] == "")?"":"."+n[1]);
}
else
return NaN;
}
//It can be string in form of "negative one thousand point one two"
if(typeof(n) == 'string'){
n = n.toLowerCase();
n = n.replace(/^\s|\s$/g, "").replace(/\s+/g, " ");
n = n.replace(/\s(and)\s/g, " ");
var fNum, dNum = fNum = "";
//Is Negative or Positive?
var sign = false;
n = n.split(" ");
if(n[0] == "negative"){
sign = true;
n.shift();
}
else if(n[0] == "positive"){
n.shift();
}
//The Mantissa part
if(n.indexOf("point") >= 0){
var decimal = n.splice(n.indexOf("point"), n.length - n.indexOf("point")); decimal.shift();
dNum = decimal.map(a=>{return typeof this.w_Dict(a) != "undefined"&&this.w_Dict(a).length<2&&this.w_Dict(a).length>0?this.w_Dict(a):NaN}).join("");
}
else dNum = "0";
//The Characteristic part
if(n.includes("zero") && n.lastIndexOf("zero") != 0) return NaN;
var subArray = [];
var subString = "";
var prevSuffix = "0".repeat(this.wordSupport);
var prevHSuffix = false; //To check have we gotten an hundred earlier?
var prevValue = false;
for(var i = 0; i < n.length; i++){
if(typeof(this.w_Dict(n[i])) == 'undefined')return NaN; //Spelling errors and what-nots
if(this.w_Dict(n[i]).length >= 3/*thousand and above*/){
if(prevSuffix.length < this.w_Dict(n[i]).length) return NaN; //"one million three billion" is wrong
if(!prevValue) return NaN; //"one million thousnad" is wrong
subString += this.w_Dict(n[i]);
subArray.push(subString);
subString = "";
prevSuffix = this.w_Dict(n[i]);
prevValue = false;
prevHSuffix = false;
}
else if(n[i] == "hundred"){
if(prevHSuffix) return NaN; // "one hundred two hundred" is wrong
if(typeof this.w_Dict(n[i-1]) == 'undefined') return NaN; //"hundred thousand" is wrong
if(this.w_Dict(n[i-1]).length > 1) return NaN;
subString += this.w_Dict(n[i]);
prevHSuffix = true;
}
else{
if(typeof this.w_Dict(n[i-1])!='undefined'&&(this.w_Dict(n[i]).length>this.w_Dict(n[i-1]).length||(this.w_Dict(n[i]).length==1&&this.w_Dict(n[i-1]).length==1))) return NaN; //one ninety is wrong, eight hundred and six three is wrong
subString = subString.substr(0, subString.length - this.w_Dict(n[i]).length) + this.w_Dict(n[i]);
prevValue = true;
}
}
subArray.push(subString);
for(var i = 0; i < subArray.length; i++){
fNum = fNum.substr(0, fNum.length - subArray[i].length) + subArray[i];
}
if(fNum == "") fNum = "0";
//output
if(/^\d+$/.test(fNum) && /^\d+$/.test(dNum)/*Test that it contains only digits*/){
//Remove unnecessary zeros
fNum = fNum.replace(/^[0]+/g, "");
dNum = dNum.replace(/[0]+$/g, "");
return (sign?"-":"") + ((fNum == "")?"0":fNum) + ((dNum == "")?"":"."+dNum);
}
else return NaN;
}
//That's all we support
return NaN;
};
/**
* Returns the this.value as a number
* @return {number} - this.value
*/
BigArith.prototype.valueOf=function(){
return this.value*1;
};
/**
* Returns the this.value as a string
* @return {string} - this.value
*/
BigArith.prototype.toString=function(){
return this.value;
};
/**
* Returns true if this.value is negative, false otherwise
* @return {boolean} - this.value is less than positive zero
*/
BigArith.prototype.isNegative=function(){
if(isNaN(this.value)) return NaN;
if(this.value[0] == "-") return true;
return false;
}
/**
* Returns true if this.value is positive, false otherwise
* @return {boolean} - this.value is greater than negative zero
*/
BigArith.prototype.isPositive=function(){
if(isNaN(this.value)) return NaN;
if(this.value[0] == "-") return false;
return true;
}
/**
* Returns true if this.value is integer, false otherwise
* @return {boolean} - this.value is integer?
*/
BigArith.prototype.isInteger=function(){
if(isNaN(this.value)) return NaN;
if(this.value.indexOf(".") == -1) return true;
return false;
}
/**
* Returns true if this.value is even, false otherwise
* @return {boolean} - this.value is even?
* Dependent on floor(), static divide(), isInteger(), static compare()
*/
BigArith.prototype.isEven=function(){
if(isNaN(this.value)) return NaN;
var d = new BigArith(this.value);
if(!d.isInteger()) return false;
d = BigArith.divide(this.value[this.value.length-1], 2);
if(BigArith.compare(d, d.floor()) == 0) return true;
return false;
}
/**
* Returns true if this.value is NOT even and is an integer, false otherwise
* @return {boolean} - this.value is NOT even and is an integer?
* Dependent on isEven(), isInteger()
*/
BigArith.prototype.isOdd=function(){
if(isNaN(this.value)) return NaN;
var d = new BigArith(this.value);
if(!d.isEven() && d.isInteger()) return true;
return false;
}
/**
* Returns square of this.value
* function square
* @return {BigArith} - product of this.value and this.value
* Dependent on static multiply()
*/
BigArith.prototype.square=function(){
return BigArith.multiply(this.value, this.value);
}
/** [NEEDS OPTIMIZATION - n tends to gets very large within few calculations and this slows down calculation speed. Takes 9105ms to calculate sqrt 2 to 200 decimal place]
* Returns square root of this.value
* function squareRoot
* @return {BigArith} - root of this.value
*/
BigArith.prototype.squareRoot=function(){
var n = this.value;
if(isNaN(n) || new BigArith(n).isNegative()) return NaN;
//Find the perfect square just less than or equal to n
var ps = BigArith.perfectSq(n);
var result = ps;
var quotient = ps;
n = BigArith.subtract(n, BigArith.multiply(ps, ps));
//If reminder (n) is 0, return result we have reached the end of calculation
if(BigArith.compare(n, 0) == 0) return new BigArith(result);
//If we got here that means we have reminders
n = BigArith.multiply(n, 100); //multiply reminder by 100
result += ".";
for(var count = 0; count <= new BigArith().decimalSupport+1; count++){
// take quotient double it and multiply by 10
var j = BigArith.multiply(quotient, 20);
//Find a number bewteen j+1 and j+9 such that (j+i)*i will just be less than or equal to n
var i = 1;
for(; i <= 9; i++){
var g = BigArith.multiply(BigArith.add(j,i), i); //(j+i)*i
if(BigArith.compare(g, n) >= 0 || BigArith.compare(n, 0) == 0) break;
}
//If (j+i)*i > n or i == 10, reduce i by 1
var ji = BigArith.multiply(BigArith.add(j,i), i); //(j+i)*i
if(i == 10 || BigArith.compare(BigArith.multiply(BigArith.add(j,i), i), n) == 1) i--;
n = BigArith.multiply(BigArith.subtract(n, BigArith.multiply(BigArith.add(j,i), i)),100);//(n-(j+i)*i)*100;
result += i;
quotient += i.toString();
//If reminder is 0, break we have reached the end of calculation
if(BigArith.compare(n, 0) == 0) break;
}
return new BigArith(new BigArith(result).toFixed(new BigArith().decimalSupport));
}
/** [NEEDS OPTIMIZATION - incase n is very large]
* Returns the square root of the perfect square just below or equals to n
* function perfectSq
* @param - {string|number|BigArth} n The number to find the perfect square before
* @return {string} - the perfect square just less than n or n if it is a perfect square
*/
BigArith.perfectSq=function(n){
var n = new BigArith(n).toString();
//start counting from 1 to we get to i*i<=n
//This is not the best idea if n is very large
var i = new BigArith(1);
while(true){
if(BigArith.compare(new BigArith(i).square(), n) >= 0) break;
i = BigArith.add(i, 1);
}
return (BigArith.compare(BigArith.multiply(i, i), n) == 0)?i.toString():i.subtract(1).toString();
}
/**
* Return the absolute value of this.value
* function abs
* @returns {BigArith} - Absolute value of this.value
* Dependent on static abs()
*/
BigArith.prototype.abs=function(){
return BigArith.abs(this.value);
}
/**
* Return the absolute value of n
* function abs
* @param {string|number|BigArth} n value to find absolute of.
* @returns {BigArith} - Absolute value of n
* Dependent on isNegative(), negate(), isNaN() (native)
*/
BigArith.abs=function(n){
var n=new BigArith(n);
if(isNaN(n)) return NaN;
return (n.isNegative())?n.negate():n;
}
/**
* Returns a number with it sign changed
* function negate
* @returns {BigArith} - this.value with the sign changed
* Dependent on static negate()
*/
BigArith.prototype.negate=function(){
return BigArith.negate(this.value);
}
/**
* Returns a number with it sign changed
* function negate
* @param {string|number|BigArth} n number to negate
* @returns {BigArith} - number with the sign changed
* Dependent toString()
*/
BigArith.negate=function(n){
var n = new BigArith(n);
if(isNaN(n)) return NaN;
return (n.toString()[0] == "-")?new BigArith(n.toString().substr(1)):new BigArith("-"+n);
}
/**
* Returns the characteristic part (part before the decimal point) of a number
* function truncate
* @returns {BigArith} - characteristic part of the number
* Dependent static truncate()
*/
BigArith.prototype.truncate=function(){
return BigArith.truncate(this.value);
}
/**
* Returns the characteristic part (part before the decimal point) of a number
* function truncate
* @param {string|number|BigArth} n number to truncate
* @returns {BigArith} - characteristic part of the number
* Dependent isNaN(), toString(), indexOf()
*/
BigArith.truncate=function(n){
var n = new BigArith(n);
if(isNaN(n)) return NaN;
if(n.toString().indexOf(".") == -1) return n;
return new BigArith(n.toString().split(".")[0]);
}
/**
* Comparing this.value to n
* function compare
* @param {string|number|BigArth} n the number this.value is to be compared to. Can be negative and fractional
* @returns {number} (-1 if this.value < n), (0 if this.value == n), (1 if this.value > n)
* Dependent on static compare()
*/
BigArith.prototype.compare=function(n){
return BigArith.compare(this.value, n);
}
/**
* Comparing a to b
* function compare
* @param {string|number|BigArth} a number to be compared. Can be negative and fractional
* @param {string|number|BigArth} b number to be compared. Can be negative and fractional
* @returns {number} - (-1 if a < b), (0 if a == b), (1 if a > b)
* Dependent on toString(), isNegative(), isPositive(), abs(), Math.max() (can't use BigArith.max, it's dependent on compare)
*/
BigArith.compare=function(a, b){
var a = new BigArith(a);
var b = new BigArith(b);
if(isNaN(a) || isNaN(b)) return NaN;
//Check for signs
var cSign = false, c = "";
var dSign = false, d = "";
if(a.isNegative()){
cSign = true;
c = a.abs().toString();
}else c=a.toString();
if(b.isNegative()){
dSign = true;
d = b.abs().toString();
}else d=b.toString();
c = c.split("."); d = d.split(".");
(typeof c[1] == 'undefined')?c[1]='0':0;
(typeof d[1] == 'undefined')?d[1]='0':0;
c[1]=c[1].replace(/[0]*$/g,""); if(c[1] == "") c[1] ="0";
d[1]=d[1].replace(/[0]*$/g,""); if(d[1] == "") d[1] ="0";
var max = Math.max(c[1].length, d[1].length);
c[1] += "0".repeat(max - c[1].length);
d[1] += "0".repeat(max - d[1].length);
if(cSign && dSign==false) return -1;
if(dSign && cSign==false) return 1;
if(c[0].length < d[0].length) return (cSign && dSign)?1:-1;
if(c[0].length > d[0].length) return (cSign && dSign)?-1:1;
//check characteristic
for(var i = 0; i < c[0].length/*Length is equal so pick one*/; i++){
if(c[0][i] > d[0][i]) return (cSign && dSign)?-1:1;
if(c[0][i] < d[0][i]) return (cSign && dSign)?1:-1;
}
//check mantissa
for(var i = 0; i < Math.max(c[1].length, d[1].length); i++){
if(c[1][i] > d[1][i]) return (cSign && dSign)?-1:1;
if(c[1][i] < d[1][i]) return (cSign && dSign)?1:-1;
}
return 0;
}
/**
* Comparing absolute value of this.value to absolute value of n
* function compareAbs
* @param {string|number|BigArth} n value to be comapared with this.value
* @returns {string} - (-1 if abs(a) < abs(b)) - (0 if abs(a) == abs(b)) - (1 if abs(a) > abs(b))
* Dependent on static compareAbs()
*/
BigArith.prototype.compareAbs=function(n){
return BigArith.compareAbs(this.value, n);
}
/**
* Comparing absolute value of a to absolute value of b
* function compareAbs
* @param {string|number|BigArth} a value to be compare
* @param {string|number|BigArth} b value to be compare
* @returns {string} - (-1 if abs(a) < abs(b)) - (0 if abs(a) == abs(b)) - (1 if abs(a) > abs(b))
* Dependent on static compare(), abs()
*/
BigArith.compareAbs=function(a, b){
return BigArith.compare(new BigArith(a).abs(), new BigArith(b).abs());
}
/**
* Returns the minimum between this.value and n
* function min
* @param {string|number|BigArth} - optional - zero or more parameters
* @returns {BigArith} - The smallest number between this.value and parameters
* Dependent on static min()
*/
BigArith.prototype.min=function(){
return BigArith.min(this.value, ...arguments);
}
/**
* Returns the minimum between a and b
* function min
* @param {string|number|BigArth|Array} - optional - zero or more parameters
* @returns {BigArith} - The smallest number between parameters
* Dependent on static compare(), valueOf()
*/
BigArith.min=function(){
var args = BigArith.extract(arguments);
var result = new BigArith(args[0]);
for(var i = 0; i < args.length; i++){
if(isNaN(new BigArith(args[i]).valueOf())) return NaN;
result = (BigArith.compare(result, args[i]) == -1)?result:new BigArith(args[i]);
}
return result;
}
/**
* Returns the maximum between this.value and n
* function max
* @param {string|number|BigArth} - optional - zero or more parameters
* @returns {BigArith} - The largest number between this.value and parameters
* Dependent on static max()
*/
BigArith.prototype.max=function(){
return BigArith.max(this.value, ...arguments);
}
/**
* Returns the maximum between a and b
* function max
* @param {string|number|BigArth|Array} - optional - zero or more parameters
* @returns {BigArith} - The largest number between parameters
* Dependent on static compare(), valueOf()
*/
BigArith.max=function(){
var args = BigArith.extract(arguments);
var result = new BigArith(args[0]);
for(var i = 0; i < args.length; i++){
if(isNaN(new BigArith(args[i]).valueOf())) return NaN;
result = (BigArith.compare(result, args[i]) == 1)?result:new BigArith(args[i]);
}
return result;
}
//TODO
BigArith.extract=function(a){
var args = [];
for(var k in a){
if(typeof a[k] == "number" || typeof a[k] == "string"){args.push(a[k]);}
else if(typeof a[k] == "object" && a[k].name == "BigArith"){args.push(a[k].toString());}
else if(typeof a[k] == "object"){args.push(...BigArith.extract(a[k]));}
}
return args;
}
/**
* Returns largest integer less than or equal to this.value
* function floor
* @returns {BigArith} - floored value of this.value
* Dependent on static floor()
*/
BigArith.prototype.floor=function(){
return BigArith.floor(this.value);
}
/**
* Returns largest integer less than or equal to n
* function floor
* @param {string|number|BigArth} n number to floor
* @returns {BigArith} - floored number
* Dependent of subtract(), isNegative(), isInteger(), truncate()
*/
BigArith.floor=function(n){
var n = new BigArith(n);
if(isNaN(n)) return NaN;
if(!n.isInteger()){
n = n.truncate();
if(n.isNegative()){
n = BigArith.subtract(n, "1");
}
}
return n;
}
/**
* Ceil this.value
* function ceil
* @returns {BigArith} - ceiled value of this.value
* Dependent on static ceil()
*/
BigArith.prototype.ceil=function(){
return BigArith.ceil(this.value);
}
/**
* Returns smallest integer greater than or equals to number
* function ceil
* @param {string|number|BigArth} n number to ceil
* @returns {BigArith} - ceiled number
* Dependent of static add(), isNegative(), isPositive(), isInteger(), truncate()
*/
BigArith.ceil=function(n){
var n = new BigArith(n);
if(isNaN(n)) return NaN;
if(!n.isInteger()){
if(n.isPositive())
n = BigArith.add(n.truncate(), "1");
else if(n.isNegative())
n = n.truncate();
}
return n;
}
/**
* Round this.value to the nearest integer
* function round
* @returns {BigArith} - this.value rounded to nearest whole number e.g "1"
* Dependent on static round()
*/
BigArith.prototype.round=function(){
return BigArith.round(this.value);
}
/**
* Round n to the nearest integer
* function round
* @param {string|number|BigArith} n number to round e.g "0.5"
* @returns {BigArith} - n rounded to nearest whole number e.g "1"
* Dependent on toString(), static compare(), isPositive(), add(), subtract()
*/
BigArith.round=function(n){
var n = new BigArith(n);
if(isNaN(n)) return NaN;
n = n.toString();
if(n.indexOf(".")>-1){
n = n.split(".");
if(BigArith.compare(n[1][0], "5") >= 0){
if(new BigArith(n[0]).isPositive())
n[0] = BigArith.add(n[0], "1").toString();
else
n[0] = BigArith.subtract(n[0], "1").toString();
}
n = n[0];
}
return new BigArith(n);
}
/**
* Format a number to a number of decimal places
* function toFixed
* @param {string|number|BigArith} d number of decimal place to return this.value in.
* @returns {string} - this.value to a number of decimal places
* Dependent on static toFixed()
*/
BigArith.prototype.toFixed=function(d=0){
return BigArith.toFixed(this.value, d);
}
/**
* Round n to the nearest integer
* function round
* @param {string|number|BigArith} n number to format
* @param {string|number|BigArith} d number of decimal place to return n in.
* @returns {string} - n rounded to nearest whole number e.g "1"
* Dependent on toString(), static compare(), isInteger(), add(), subtract()
*/
BigArith.toFixed=function(n, d=0){
var e = new BigArith(d).floor().toString();
if(isNaN(n) || isNaN(e)) return NaN;
//if(BigArith.compare(e, 0) == -1 || BigArith.compare(e, new BigArith.decimalSupport) == 1 || isNaN(e)) throw new Error("Argument must be between 0 and "+ new BigArith.decimalSupport +"! " + e + " supplied.");
var n = new BigArith(n);
var sign = n.isNegative();
if(!n.isInteger()){
n = n.toString().split(".");
if(BigArith.compare(e, "0") == 0){
if(BigArith.compare(n[1][0], "5") >= 0){
if(!sign){
n[0] = BigArith.add(n[0], "1").toString();
}
else{
n[0] = BigArith.subtract(n[0], "1").toString();
}
n[1] = "0";
}
else n[1] = "0";
}
else if(BigArith.compare(n[1].length.toString(), e) == -1){ n[1] += "0".repeat(e - Number(n[1].length));}
else if(BigArith.compare(n[1].length.toString(), e) == 1){
if(BigArith.compare(n[1][e], "5") >= 0){
var z0 = n[1].slice(0, e).length;
var z1 = BigArith.add(n[1].slice(0, e), "0").toString().length; //To check if it have leading zeros hence 0.00456 can become 0.456
n[1] = BigArith.add(n[1].slice(0, e), "1").toString();
var z2 = n[1].length;
if(z0 != z1){//Has leading zero
n[1] = "0".repeat(z0-z1) + n[1];
}
if(z2 > z1){
if(n[1][0] != "0"){
n[0] = BigArith.add(n[0], "1").toString();
n[1] = "0".repeat(e);
}
else{
n[1] = n[1].substr(1);
}
}
}
else n[1] = n[1].slice(0, e);
}
n = n[0]+((n[1]!="0")?("."+n[1]):"");
}
else n=n.toString()+((BigArith.compare(e, "0") == 1)?("."+"0".repeat(e)):"");
return n;
}
/**
* Random number between 0 and 1 (1 exclusive)
* function random
* @returns {BigArith} - any number between 0 and 1 (1 exclusive)
* Dependent on Math.random(), floor(), toString(), valueOf()
*/
BigArith.random=function(){
var len = new BigArith(Math.random()*new BigArith().decimalSupport).floor().valueOf();
var n = "0";
for(var i = 0; i < len; i++){
n += new BigArith(Math.random()*10).floor().toString();
}
return (n == "0")?new BigArith(n):(new BigArith("0."+n.slice(1)));
}
/**
* Random integer between min and max (min inclusive, max exclusive)
* function randomInt
* @param {number|string|BigArith} min minimum integer that can be returned (inclusive)
* @param {number|string|BigArith} max maximum integer that can be returned (exclusive)
* @returns {BigArith} - any integer between min and max
* Dependent on static random(), floor(), toString(), multiply(), subtract(), add(), ceil()
*/
BigArith.randomInt=function(min, max){
var min = new BigArith(min).floor();
var max = new BigArith (max).ceil();
if(isNaN(min) || isNaN(max)) return NaN;
return (BigArith.random().multiply(BigArith.subtract(max, min)).add(min)).floor(); // floor((ran()*(max-min))+min)
}
/**
* Word representation of this.value
* @return {string} - this.value in English short scale naming system words e.g "one billion" for "1000000000".
* Throw error if value of this.value is higher than 1x10^124 - (0.0{199}1)
* Dependent on w_Dict2()
*/
BigArith.prototype.toWords = function(){
var n = this.value, sign = false;
if(this.value[0] == "-"){
n = this.value.substr(1);
sign = true;
}
else n=this.value;
n = n.split(".");
if(typeof n[0] == 'undefined') n[0] = "0";
if(typeof n[1] == 'undefined') n[1] = "0";
n[0] = n[0].replace(/^[0]*/g,""); if(n[0] == '') n[0] = "0";
n[1] = n[1].replace(/[0]*$/g,"");
if(n[0].length > this.wordSupport+3) throw new RangeError("Value higher than the recently supported range");
if(n[1].length > this.decimalSupport) throw new RangeError("Length of mantissa value greater than supported length");
//Characteristic part
//Break into chunks of 3 digits e.g. ["1","000"] for "1000"
var chunk = [], c = n[0];
for(var i = c.length; i > -1; i-=3){
chunk.unshift(c.slice((i-3>0)?i-3:0, i));
}(chunk[0] == "")?chunk.shift():0;
var word = "";
for(var i = 0; i < chunk.length; i++){
var m = chunk[i];
if(m =="000") continue;
if(m.length == 3){
if(m[0] != "0"){
word += this.w_Dict2(m[0]) + " hundred ";
if(m[1] + m[2] != "00") word += "and "
}
if(m[1] == "1") word += " "+this.w_Dict2(m[1]+m[2]);
else if(m[1] > "1") word += " "+this.w_Dict2(m[1]+"0");
if(m[2] != "0" && m[1] != "1") word += " "+this.w_Dict2(m[2]);
}
if(m.length == 2){
if(m[0] == "1")
{
word += " "+this.w_Dict2(m[0]+m[1]);
}
else{
if(m[0] != "0")
word += " "+this.w_Dict2(m[0]+"0");
if(m[1] != "0")
word += " "+this.w_Dict2(m[1]);
}
}
if(m.length == 1){
if(m[0] != "0")
word += " "+this.w_Dict2(m[0]);
else
word = this.w_Dict2(m[0]);
}
word += " "+this.w_Dict2("0".repeat(3*(chunk.length-i-1))) + " ";
}
//Mantissa part
if(n[1] != "") word += " point";
for(var i = 0; i < n[1].length; i++){
word += " "+this.w_Dict2(n[1][i]);
}
return (sign?"negative ":"") + word.replace(/\s+/g," ").trim();
}
/**
* Add n to this.value
* function add
* @param {number|string|BigArith} The summand with this.value as the second summand
* @returns {BigArith} - sum of this.value and @param
* Dependent of the static add()
*/
BigArith.prototype.add = function(n){
return BigArith.add(this.value, n);
}
/**
* Add two numbers together
* function add
* @param {number|string|BigArith} A summand.
* @param {number|string|BigArith} A summand.
* @returns {BigArith} - sum of a and b
* Dependent on toString(), floor(), substract(), abs(), max(), valueOf()
*/
BigArith.add = function(a, b){
var a = new BigArith(a);
var b = new BigArith(b);
var signFlag = "";
if(isNaN(a) || isNaN(b))
return NaN;
if(a.isNegative() && b.isPositive())
return BigArith.subtract(b, a.abs());
if(a.isPositive() && b.isNegative())
return BigArith.subtract(a, b.abs());
if(a.isNegative() && b.isNegative()){
signFlag = "-";
a = a.abs();
b = b.abs();
}
a = a.toString().split(".");
b = b.toString().split(".");
(typeof(a[1]) == 'undefined')?a[1]="0":0;
(typeof(b[1]) == 'undefined')?b[1]="0":0;
var max = BigArith.max(a[1].length, b[1].length).valueOf();
a[1] += "0".repeat(max - a[1].length);
b[1] += "0".repeat(max - b[1].length);
a = a[0] + a[1];
b = b[0] + b[1];
var result = "";
var flag = 0;
for(var i = a.length-1, j = b.length-1; i >= 0 || j >= 0; i--, j--)
{
var z = a.charAt(i)*1 + b.charAt(j)*1 + flag;
if(z>9 && (i>0 || j>0))
{
flag = new BigArith(z/10).floor().valueOf();
result = (z-flag*10)+result;
}
else
{
result = z+result;
flag = 0;
}
}
result = result.slice(0, result.length - max) + "." + result.slice(result.length - max);
result = result.replace(/^0+/g,"")/*Remove front zeros*/.replace(/\.0+$/g,"")/*Remove zeros after decimal point zeros*/;
if(result[0] == ".") result = "0" + result;
return ((result == "")? new BigArith("0") : new BigArith(((signFlag=="")?"":"-")+result));
}
/**
* Subtract n from this.value
* function subtract
* @param {number|string|BigArith} The subtrahend with this.value as the minuend
* @returns {BigArith} - difference of this.value and @param
* Dependent on static subtract
*/
BigArith.prototype.subtract=function(n){
return BigArith.subtract(this.value, n);
}
/**
* Subtract b from a
* function subtract
* @param {number|string|BigArith} The Minuend
* @param {number|string|BigArith} The subtrahend
* @returns {BigArith} - difference of a and b
* Dependent on add(), abs(), toString(), compare(), max(), valueOf()
*/
BigArith.subtract=function(a, b){
var a = new BigArith(a);
var b = new BigArith(b);
if(isNaN(a) || isNaN(b))
return NaN;
if(a.isNegative() && b.isPositive())
return BigArith.add(a, "-"+b.toString());
if(a.isPositive() && b.isNegative())
return BigArith.add(a, b.abs());
if(a.isNegative() && b.isNegative()){
//swap the absolute parameters
var temp = a.abs();
a = b.abs();
b = temp;
}
a = a.toString().split(".");
b = b.toString().split(".");
(typeof(a[1]) == 'undefined')?a[1]="0":0;
(typeof(b[1]) == 'undefined')?b[1]="0":0;
var max = BigArith.max(a[1].length, b[1].length).valueOf();
a[1] += "0".repeat(max - a[1].length);
b[1] += "0".repeat(max - b[1].length);
var signFlag = "";
if(BigArith.compare(a[0]+"."+a[1], b[0]+"."+b[1]) >= 0){
a = a[0]+a[1];
b = b[0]+b[1];
}
else{
//swap the parameters
var temp = a[0]+a[1];
a = b[0]+b[1];
b = temp;
signFlag = "-";
}
a = a.split("");
b = b.split("");
var result = "";
for(var i = a.length-1, j = b.length-1; i >= 0 || j >= 0; i--, j--){
if(isNaN(parseInt(b[j]))) b[j] = "0";
if(parseInt(a[i]) >= parseInt(b[j])){
result = (parseInt(a[i]) - parseInt(b[j])).toString() + result;
}
else if(parseInt(a[i]) < parseInt(b[j])){
if(i == 0)
result = (parseInt(a[i]) - parseInt(b[j])).toString() + result;
else{
result = (parseInt(a[i])+10 - parseInt(b[j])).toString() + result;
a[i-1] = parseInt(a[i-1])-1;
}
}
}
result = result.slice(0, result.length - max) + "." + result.slice(result.length - max);
result = result.replace(/^0+/g,"")/*Remove front zeros*/.replace(/\.0+$/g,"")/*Remove zeros after decimal point zeros*/;
if(result[0] == ".") result = "0" + result;
return ((result == "")? new BigArith("0") : new BigArith((signFlag+result)));
}
/**
* Multiplies n and this.value
* function multiply
* @param {number|string|BigArith} - the multiplier with this.value as the multiplicand
* @returns {BigArith} - product of this.value and @param
* Dependent on static multiply
*/
BigArith.prototype.multiply=function(n){
return BigArith.multiply(this.value, n);
}
/**
* Multiplies a and b
* function multiply
* @param {number|string|BigArith} - the multiplicand
* @param {number|string|BigArith} - the multiplier
* @returns {BigArith} - product of a and b
* Dependent on toString(), abs(), max(), static add(), valueOf()
*/
BigArith.multiply=function(a, b){
var a = new BigArith(a);
var b = new BigArith(b);
var signFlag = "";
if(isNaN(a) || isNaN(b)) return NaN;
if((a.isNegative() || b.isNegative()) && !(a.isNegative() && b.isNegative())) signFlag = "-";
a = a.abs().toString().split(".");
b = b.abs().toString().split(".");
(typeof(a[1]) == 'undefined')?a[1]="0":0;
(typeof(b[1]) == 'undefined')?b[1]="0":0;
var max = BigArith.max(a[1].length, b[1].length).valueOf();
a[1] += "0".repeat(max - a[1].length);
b[1] += "0".repeat(max - b[1].length);
a = a[0] + a[1];
b = b[0] + b[1];
var results = [];
for(var i = a.length-1; i >= 0; i--){
var subSum = "";
var flag = 0;
if(i < a.lastIndexOf(a.charAt(i))){ /* Do not need to compute already computed values, just copy answer from previous computation*/
results.push(results[a.length-1-a.lastIndexOf(a.charAt(i))]);
continue;
}
else{
for(var j = b.length-1; j >= 0; j--){
var z = a.charAt(i)*b.charAt(j)+flag;
if(z>9 && j>0){
flag = new BigArith(z/10).floor().valueOf();
subSum = (z-flag*10)+subSum;
}
else{
subSum = z+subSum;
flag = 0;
}
}
}
results.push(subSum);
}
// Sum all the answers
var result = "0";
for(var i = 0; i < results.length; i++) result = BigArith.add(result, results[i]+"0".repeat(i));
//Put the decimal point in the apropriate place
result = result.toString(); //It's a BigArith
if(max*2 > result.length) result = "0".repeat(max*2 - result.length) + result; //Problem with slice if result is shorter than max*2
result = result.slice(0, result.length - max*2) + "." + result.slice(result.length - max*2);
return ((BigArith.compare(new BigArith(result),0) == 0)?new BigArith("0"):new BigArith(signFlag+result));
}
/**
* Return this.value%n (reminder of this.value/n)
* function modulus
* @param {string|number|BigArth} n The divisor with this.value as the dividend
* @returns {BigArith} reminder of this.value/n
* Dependent on static modulus
*/
BigArith.prototype.modulus=function(n){
return BigArith.modulus(this.value, n);
}
/**
* Return a%b (reminder of a/b)
* function modulus
* @param {string|number|BigArth} a the dividend
* @param {string|number|BigArth} b the divisor.
* @returns {BigArith} - reminder of a/b
* Dependent on static compare, isInteger, isNegative, divWithRem, abs, static multiply, static subtract, static divide, toString
*/
BigArith.modulus=function(a, b){
var a = new BigArith(a);
var b = new BigArith(b);
if(BigArith.compare(b, "0") == 0 || isNaN(a) || isNaN(b)) return NaN;
if(a.isInteger() && b.isInteger())
return new BigArith(((a.isNegative())?"-":"")+BigArith.divWithRem(a, b)[1]);
else
return new BigArith(((a.isNegative())?"-":"")+BigArith.subtract(a.abs(), BigArith.multiply(BigArith.divide(a.abs(), b.abs()).toString().split(".")[0], b.abs())));
}
/**
* Return this.valus/n (division of this.valus and n)
* function divide
* @param {string|number|BigArth} The divisor with this.value as the dividend.
* @returns {BigArith} - The quotient to "decimalSupport" decimal places when necessary.
*/
BigArith.prototype.divide=function(n){
return BigArith.divide(this.value, n);
}
/**
* Return a/b (division of a/b)
* function divide
* @param {string|number|BigArth} The dividend.
* @param {string|number|BigArth} The divisor.
* @returns {BigArith} - The quotient to "decimalSupport" decimal places when necessary.
*/
BigArith.divide=function(a, b){
return BigArith.div(a, b, new BigArith().decimalSupport);
}
/**Helper**/
BigArith.div=function(a, b, d){
var a = new BigArith(a).toString().split(".");
var b = new BigArith(b).toString().split(".");
//Note where the decimal points are and remove them
var numeratorIndex = 0;
var denominatorIndex = 0;
if(typeof a[1] != "undefined")
numeratorIndex = a[1].length;
if(typeof b[1] != "undefined")
denominatorIndex = b[1].length;
a = a[0] + ((typeof a[1] != "undefined")?a[1]:"");
b = b[0] + ((typeof b[1] != "undefined")?b[1]:"");
var result = BigArith.divWithRem(a, b);
var rem = result[1];
var remResult = "0.";
/* If the decimal place index of denominator - numerator is positive,
we are likely going to encroach into the 200 decimal result
when shifting the decimal pointto the left. The best is to start count from -(denominator-numerator)
instead of 0 in this case.
*/
var count = (denominatorIndex-numeratorIndex>0)?(-1*(denominatorIndex-numeratorIndex)):0, c = 0;
var flag = false;
while(BigArith.compare(rem, "0") == 1 && BigArith.compare(count, d+1) == -1){
rem += "0";
var j = BigArith.divWithRem(rem, b);
remResult += j[0];
rem = j[1];
/*Don't count yet if quotient is still all 0's
This takes care of (x/x.y) returning (x.x) instead of (x.y)
where x is any single digit, and y is any 200 digits*/
if(j[0] > 0) flag = true; if(!flag) c++;
if(c > 201) break; //if we have gotten 0.00{199 more 0's}, no need to continue
if(flag)count++;
}
remResult = remResult.replace(/\-/g,"");
if(remResult == "0.") remResult = "0.0";
result = result[0] + "." + remResult.split(".")[1];
var dPosition = (result.indexOf(".") == -1)?result.length : result.indexOf("."); // decimal position in answer
//Numerator decimal point means we shift the decimal point in answer forward
//Denominator decimal point means we shift the decimal point in answer backward
dPosition = dPosition+denominatorIndex-numeratorIndex;
result = result.split(".");
if(dPosition < 0){
result = "0." + "0".repeat(-1*dPosition) + result[0] + result[1];
}
else if(dPosition == 0){
result = "0." + result[0] + result[1];
}
else if(dPosition > 0){
if(dPosition <= result[0].length){
result = result[0].slice(0, dPosition) + "." + result[0].slice(dPosition) + result[1];
}
else{
dPosition -= result[0].length;
result = result[0] + result[1].slice(0, dPosition) +
((dPosition-result[1].length>0)?"0".repeat(dPosition-result[1].length):"") + "." +
result[1].substr(dPosition)+ "0";
}
}
return new BigArith(new BigArith(result.replace(/^0+/,"")).toFixed(d));
};
/**
* Return a/b (division of a/b)
* function divWithRem
* @param {string|number|BigArth} a The dividend. Must always be integers.
* @param {String|Number|BigArth} b The divisor. Must always be integers.
* @returns {Array of "strings of digits" (integer)} - [quotient, reminder]
*/
BigArith.divWithRem=function(a, b){
var a = new BigArith(a);
var b = new BigArith(b);
if(isNaN(a) || isNaN(b))
return NaN;
if(!a.isInteger() || !b.isInteger()) throw new TypeError("divWithRem accepts only integers. Non integers passed in");
if(BigArith.compare(b, 0) == 0) throw new RangeError("Division by zero");
var signFlag = false;
if((a.isNegative() || b.isNegative()) && !(a.isNegative() && b.isNegative())) signFlag = true; //Only one of the parameters is negative
a = a.abs().toString();
b = b.abs().toString();
var aLen = a.length;
var aSub = "";
var result = "0";
var hold = a;
for(var i = 0; i < aLen; i++){
aSub += a[i];
if(BigArith.compare(aSub, "0") == 0){result += "0";}
else if(BigArith.compare(b, aSub) == 1){result += "0"; continue;}
else{
var count = 0;
hold = aSub;
while(BigArith.compare(hold, b) != -1){
hold = BigArith.subtract(hold, b);
count++;
}
result += count;
}
aSub = hold.toString();
}
hold = new BigArith(aSub).toString();
result = result.replace(/^0*/g,"");
result = (result == "")? "0" : result;
return [((signFlag)?"-":"")+result, hold.toString()];
};
/* [UNSTABLE - Takes a lot of computation time]
* Returns the sine of an angle (in degree)
* function sin
* @param {string|number|BigArth} n The angle in degree
* @returns {BigArith} - sine of n
* x - x^3/3! + x^5/5! - x^7/7! + x^9/9! - ... (x in radian)
*/
BigArith.sin=function(n){
//Have to use PI to atleast 203 decimal places so new BigArith("PI") won't work here as it is to 200 decimal place
var x = BigArith.div(new BigArith("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975"), 180, new BigArith().decimalSupport+3).multiply(n);
var tolerance = new BigArith("0." + "0".repeat(new BigArith().decimalSupport+3) + "1");
var sin = new BigArith("0");
var i = 1;
var term = x.toString(), _x = x.toString();
var sign = true;
while(BigArith.compare(term, tolerance) == 1){
if(i > 1){
_x = BigArith.multiply(_x, x.square()).toString().split(".");
//only the first 203 decimal digit is needed as _x gets very large quickly
_x = _x[0] + "." +_x[1].substr(0, new BigArith().decimalSupport+3);
term = BigArith.div(_x, BigArith.factorial(i), new BigArith().decimalSupport+3).toString();
}
if(sign)
sin = BigArith.add(sin, term);
else
sin = BigArith.subtract(sin, term);
sign = !sign;
i += 2;
}
return new BigArith(sin.toFixed(new BigArith().decimalSupport));
}
/* [UNSTABLE - Takes a lot of computation time]
* Returns the cosine of an angle (when angle is in degrees)
* function cos
* @param {string|number|BigArth} n The angle in degrees
* @returns {BigArith} - cosine of n
* 1 - x^2/2! + x^4/4! - x^6/6! + x8/8! - ... (x in radian)
*/
BigArith.cos=function(n){
//Have to use PI to atleast 203 decimal places so new BigArith("PI") won't work here as it is to 200 decimal place
var x = BigArith.div(new BigArith("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975"), 180, new BigArith().decimalSupport+3).multiply(n);
var tolerance = new BigArith("0." + "0".repeat(new BigArith().decimalSupport+3) + "1");
var cos = new BigArith("0");
var i = 0;
var term = "1", _x = "1";
var sign = true;
while(term == "1" || BigArith.compare(term, tolerance) == 1){
if(i > 1){
_x = BigArith.multiply(_x, x.square());
if(BigArith.compare(_x, "0") == 0) break;
_x = _x.toString().split(".");
//the first 203 decimal digit is needed as _x gets very large quickly
_x = _x[0] + "." +_x[1].substr(0, new BigArith().decimalSupport+3);
term = BigArith.div(_x, BigArith.factorial(i), new BigArith().decimalSupport+3).toString();
}
if(sign)
cos = BigArith.add(cos, term);
else
cos = BigArith.subtract(cos, term);
sign = !sign;
i += 2;
}
return new BigArith(cos.toFixed(new BigArith().decimalSupport));
}
/* [UNSTABLE - Takes a lot of computation time]
* Returns the tangent of an angle (when angle is in degrees)
* function cos
* @param {string|number|BigArth} n The angle in degrees
* @returns {BigArith} - tangent of n
* tan = sin/cos
*/
BigArith.tan=function(n){
var sin = BigArith.sin(n);
var cos = BigArith.cos(n);
return BigArith.divide(sin, cos);
}
/**
* Word Dictionary
* function w_Dict
* @param {string} - Word value for numbers e.g "one"
* @returns {string} - String value of @param e.g "1"
*/
BigArith.prototype.w_Dict=function(w){
/*Word Dictionary*/
var w_Dict = [];
w_Dict["zero"] = "0"; w_Dict["one"] = "1"; w_Dict["two"] = "2"; w_Dict["three"] = "3"; w_Dict["four"] = "4"; w_Dict["five"] = "5"; w_Dict["six"] = "6"; w_Dict["seven"] = "7"; w_Dict["eight"] = "8"; w_Dict["nine"] = "9"; w_Dict["ten"] = "10";
w_Dict["eleven"] = "11"; w_Dict["twelve"] = "12"; w_Dict["thirteen"] = "13"; w_Dict["fourteen"] = "14"; w_Dict["fifteen"] = "15"; w_Dict["sixteen"] = "16"; w_Dict["seventeen"] = "17"; w_Dict["eighteen"] = "18"; w_Dict["nineteen"] = "19"; w_Dict["twenty"] = "20";
w_Dict["thirty"] = "30"; w_Dict["forty"] = "40"; w_Dict["fifty"] = "50"; w_Dict["sixty"] = "60"; w_Dict["seventy"] = "70"; w_Dict["eighty"] = "80"; w_Dict["ninety"] = "90"; w_Dict["hundred"] = "0".repeat(2);
w_Dict["thousand"] = "0".repeat(3); w_Dict["million"]="0".repeat(6);w_Dict["billion"]="0".repeat(9);w_Dict["trillion"]="0".repeat(12);w_Dict["quadrillion"]="0".repeat(15);w_Dict["quintillion"]="0".repeat(18);w_Dict["sextillion"]="0".repeat(21);w_Dict["septillion"]="0".repeat(24);w_Dict["octillion"]="0".repeat(27);w_Dict["nonillion"]="0".repeat(30);w_Dict["decillion"]="0".repeat(33);w_Dict["undecillion"]="0".repeat(36);w_Dict["duodecillion"]="0".repeat(39);w_Dict["tredecillion"]="0".repeat(42);w_Dict["quattuordecillion"]="0".repeat(45);w_Dict["quindecillion"]="0".repeat(48);w_Dict["sexdecillion"]="0".repeat(51);w_Dict["septendecillion"]="0".repeat(54);w_Dict["octodecillion"]="0".repeat(57);w_Dict["novemdecillion"]="0".repeat(60);w_Dict["vigintillion"]="0".repeat(63);w_Dict["unvigintillion"]="0".repeat(66);w_Dict["duovigintillion"]="0".repeat(69);w_Dict["trevigintillion"]="0".repeat(72);w_Dict["quattuorvigintillion"]="0".repeat(75);w_Dict["quinvigintillion"]="0".repeat(78);w_Dict["sexvigintillion"]="0".repeat(81);w_Dict["septenvigintillion"]="0".repeat(84);w_Dict["octavigintillion"]="0".repeat(87);w_Dict["novemvigintillion"]="0".repeat(90);w_Dict["trigintillion"]="0".repeat(93);w_Dict["untrigintillion"]="0".repeat(96);w_Dict["duotrigintillion"]="0".repeat(99);w_Dict["tretrigintillion"]="0".repeat(102);w_Dict["quattuortrigintillion"]="0".repeat(105);w_Dict["quintrigintillion"]="0".repeat(108);w_Dict["sextrigintillion"]="0".repeat(111);w_Dict["septentrigintillion"]="0".repeat(114);w_Dict["octotrigintillion"]="0".repeat(117);w_Dict["novemtrigintillion"]="0".repeat(120);w_Dict["quadragintillion"]="0".repeat(123);w_Dict["unquadragintillion"]="0".repeat(126);w_Dict["duoquadragintillion"]="0".repeat(129);w_Dict["trequadragintillion"]="0".repeat(132);w_Dict["quattuorquadragintillion"]="0".repeat(135);w_Dict["quinquadragintillion"]="0".repeat(138);w_Dict["sexquadragintillion"]="0".repeat(141);w_Dict["septenquadragintillion"]="0".repeat(144);w_Dict["octaquadragintillion"]="0".repeat(147);w_Dict["novemquadragintillion"]="0".repeat(150);w_Dict["quinquagintillion"]="0".repeat(153);w_Dict["unquinquagintillion"]="0".repeat(156);w_Dict["duoquinquagintillion"]="0".repeat(159);w_Dict["trequinquagintillion"]="0".repeat(162);w_Dict["quattuorquinquagintillion"]="0".repeat(165);w_Dict["quinquinquagintillion"]="0".repeat(168);w_Dict["sexquinquagintillion"]="0".repeat(171);w_Dict["septenquinquagintillion"]="0".repeat(174);w_Dict["octaquinquagintillion"]="0".repeat(177);w_Dict["novemquinquagintillion"]="0".repeat(180);w_Dict["sexagintillion"]="0".repeat(183);w_Dict["unsexagintillion"]="0".repeat(186);w_Dict["duosexagintillion"]="0".repeat(189);w_Dict["tresexagintillion"]="0".repeat(192);w_Dict["quattuorsexagintillion"]="0".repeat(195);w_Dict["quinsexagintillion"]="0".repeat(198);w_Dict["sexsexagintillion"]="0".repeat(201);w_Dict["septensexagintillion"]="0".repeat(204);w_Dict["octasexagintillion"]="0".repeat(207);w_Dict["novemsexagintillion"]="0".repeat(210);w_Dict["septuagintillion"]="0".repeat(213);w_Dict["unseptuagintillion"]="0".repeat(216);w_Dict["duoseptuagintillion"]="0".repeat(219);w_Dict["treseptuagintillion"]="0".repeat(222);w_Dict["quattuorseptuagintillion"]="0".repeat(225);w_Dict["quinseptuagintillion"]="0".repeat(228);w_Dict["sexseptuagintillion"]="0".repeat(231);w_Dict["septenseptuagintillion"]="0".repeat(234);w_Dict["octaseptuagintillion"]="0".repeat(237);w_Dict["novemseptuagintillion"]="0".repeat(240);w_Dict["octagintillion"]="0".repeat(243);w_Dict["unoctogintillion"]="0".repeat(246);w_Dict["duooctogintillion"]="0".repeat(249);w_Dict["treoctogintillion"]="0".repeat(252);w_Dict["quattuoroctogintillion"]="0".repeat(255);w_Dict["quinoctogintillion"]="0".repeat(258);w_Dict["sexoctogintillion"]="0".repeat(261);w_Dict["septenoctogintillion"]="0".repeat(264);w_Dict["octaoctogintillion"]="0".repeat(267);w_Dict["novemoctogintillion"]="0".repeat(270);w_Dict["nonagintillion"]="0".repeat(273);w_Dict["unnonagintillion"]="0".repeat(276);w_Dict["duononagintillion"]="0".repeat(279);w_Dict["trenonagintillion"]="0".repeat(282);w_Dict["quattuornonagintillion"]="0".repeat(285);w_Dict["quinnonagintillion"]="0".repeat(288);w_Dict["sexnonagintillion"]="0".repeat(291);w_Dict["septennonagintillion"]="0".repeat(294);w_Dict["octanonagintillion"]="0".repeat(297);w_Dict["novemnonagintillion"]="0".repeat(300);w_Dict["centillion"]="0".repeat(303);w_Dict["cenuntillion"]="0".repeat(306);w_Dict["cendotillion"]="0".repeat(309);w_Dict["centretillion"]="0".repeat(312);w_Dict["cenquattuortillion"]="0".repeat(315);w_Dict["cenquintillion"]="0".repeat(318);w_Dict["censextillion"]="0".repeat(321);w_Dict["censeptentillion"]="0".repeat(324);w_Dict["cenoctotillion"]="0".repeat(327);w_Dict["cennovemtillion"]="0".repeat(330);w_Dict["cendecillion"]="0".repeat(333);w_Dict["cenundecillion"]="0".repeat(336);w_Dict["cendodecillion"]="0".repeat(339);w_Dict["centredecillion"]="0".repeat(342);w_Dict["cenquattuordecillion"]="0".repeat(345);w_Dict["cenquindecillion"]="0".repeat(348);w_Dict["censexdecillion"]="0".repeat(351);w_Dict["censeptendecillion"]="0".repeat(354);w_Dict["cenoctodecillion"]="0".repeat(357);w_Dict["cennovemdecillion"]="0".repeat(360);w_Dict["cenvigintillion"]="0".repeat(363);w_Dict["cenunvigintillion"]="0".repeat(366);w_Dict["cendovigintillion"]="0".repeat(369);w_Dict["centrevigintillion"]="0".repeat(372);w_Dict["cenquattuorvigintillion"]="0".repeat(375);w_Dict["cenquinvigintillion"]="0".repeat(378);w_Dict["censexvigintillion"]="0".repeat(381);w_Dict["censeptenvigintillion"]="0".repeat(384);w_Dict["cenoctovigintillion"]="0".repeat(387);w_Dict["cennovemvigintillion"]="0".repeat(390);w_Dict["centrigintillion"]="0".repeat(393);w_Dict["cenuntrigintillion"]="0".repeat(396);w_Dict["cendotrigintillion"]="0".repeat(399);w_Dict["centretrigintillion"]="0".repeat(402);w_Dict["cenquattuortrigintillion"]="0".repeat(405);w_Dict["cenquintrigintillion"]="0".repeat(408);w_Dict["censextrigintillion"]="0".repeat(411);w_Dict["censeptentrigintillion"]="0".repeat(414);w_Dict["cenoctotrigintillion"]="0".repeat(417);w_Dict["cennovemtrigintillion"]="0".repeat(420);w_Dict["cenquadragintillion"]="0".repeat(423);w_Dict["cenunquadragintillion"]="0".repeat(426);w_Dict["cendoquadragintillion"]="0".repeat(429);w_Dict["centrequadragintillion"]="0".repeat(432);w_Dict["cenquattuorquadragintillion"]="0".repeat(435);w_Dict["cenquinquadragintillion"]="0".repeat(438);w_Dict["censexquadragintillion"]="0".repeat(441);w_Dict["censeptenquadragintillion"]="0".repeat(444);w_Dict["cenoctoquadragintillion"]="0".repeat(447);w_Dict["cennovemquadragintillion"]="0".repeat(450);w_Dict["cenquinquagintillion"]="0".repeat(453);w_Dict["cenunquinquagintillion"]="0".repeat(456);w_Dict["cendoquinquagintillion"]="0".repeat(459);w_Dict["centrequinquagintillion"]="0".repeat(462);w_Dict["cenquattuorquinquagintillion"]="0".repeat(465);w_Dict["cenquinquinquagintillion"]="0".repeat(468);w_Dict["censexquinquagintillion"]="0".repeat(471);w_Dict["censeptenquinquagintillion"]="0".repeat(474);w_Dict["cenoctoquinquagintillion"]="0".repeat(477);w_Dict["cennovemquinquagintillion"]="0".repeat(480);w_Dict["censexagintillion"]="0".repeat(483);w_Dict["cenunsexagintillion"]="0".repeat(486);w_Dict["cendosexagintillion"]="0".repeat(489);w_Dict["centresexagintillion"]="0".repeat(492);w_Dict["cenquattuorsexagintillion"]="0".repeat(495);w_Dict["cenquinsexagintillion"]="0".repeat(498);w_Dict["censexsexagintillion"]="0".repeat(501);w_Dict["censeptensexagintillion"]="0".repeat(504);w_Dict["cenoctosexagintillion"]="0".repeat(507);w_Dict["cennovemsexagintillion"]="0".repeat(510);w_Dict["censeptuagintillion"]="0".repeat(513);w_Dict["cenunseptuagintillion"]="0".repeat(516);w_Dict["cendoseptuagintillion"]="0".repeat(519);w_Dict["centreseptuagintillion"]="0".repeat(522);w_Dict["cenquattuorseptuagintillion"]="0".repeat(525);w_Dict["cenquinseptuagintillion"]="0".repeat(528);w_Dict["censexseptuagintillion"]="0".repeat(531);w_Dict["censeptenseptuagintillion"]="0".repeat(534);w_Dict["cenoctoseptuagintillion"]="0".repeat(537);w_Dict["cennovemseptuagintillion"]="0".repeat(540);w_Dict["cenoctogintillion"]="0".repeat(543);w_Dict["cenunoctogintillion"]="0".repeat(546);w_Dict["cendooctogintillion"]="0".repeat(549);w_Dict["centreoctogintillion"]="0".repeat(552);w_Dict["cenquattuoroctogintillion"]="0".repeat(555);w_Dict["cenquinoctogintillion"]="0".repeat(558);w_Dict["censexoctogintillion"]="0".repeat(561);w_Dict["censeptenoctogintillion"]="0".repeat(564);w_Dict["cenoctooctogintillion"]="0".repeat(567);w_Dict["cennovemoctogintillion"]="0".repeat(570);w_Dict["cennonagintillion"]="0".repeat(573);w_Dict["cenunnonagintillion"]="0".repeat(576);w_Dict["cendononagintillion"]="0".repeat(579);w_Dict["centrenonagintillion"]="0".repeat(582);w_Dict["cenquattuornonagintillion"]="0".repeat(585);w_Dict["cenquinnonagintillion"]="0".repeat(588);w_Dict["censexnonagintillion"]="0".repeat(591);w_Dict["censeptennonagintillion"]="0".repeat(594);w_Dict["cenoctononagintillion"]="0".repeat(597);w_Dict["cennovemnonagintillion"]="0".repeat(600);w_Dict["duocentillion"]="0".repeat(603);w_Dict["duocenuntillion"]="0".repeat(606);w_Dict["duocendotillion"]="0".repeat(609);w_Dict["duocentretillion"]="0".repeat(612);w_Dict["duocenquattuortillion"]="0".repeat(615);w_Dict["duocenquintillion"]="0".repeat(618);w_Dict["duocensextillion"]="0".repeat(621);w_Dict["duocenseptentillion"]="0".repeat(624);w_Dict["duocenoctotillion"]="0".repeat(627);w_Dict["duocennovemtillion"]="0".repeat(630);w_Dict["duocendecillion"]="0".repeat(633);w_Dict["duocenundecillion"]="0".repeat(636);w_Dict["duocendodecillion"]="0".repeat(639);w_Dict["duocentredecillion"]="0".repeat(642);w_Dict["duocenquattuordecillion"]="0".repeat(645);w_Dict["duocenquindecillion"]="0".repeat(648);w_Dict["duocensexdecillion"]="0".repeat(651);w_Dict["duocenseptendecillion"]="0".repeat(654);w_Dict["duocenoctodecillion"]="0".repeat(657);w_Dict["duocennovemdecillion"]="0".repeat(660);w_Dict["duocenvigintillion"]="0".repeat(663);w_Dict["duocenunvigintillion"]="0".repeat(666);w_Dict["duocendovigintillion"]="0".repeat(669);w_Dict["duocentrevigintillion"]="0".repeat(672);w_Dict["duocenquattuorvigintillion"]="0".repeat(675);w_Dict["duocenquinvigintillion"]="0".repeat(678);w_Dict["duocensexvigintillion"]="0".repeat(681);w_Dict["duocenseptenvigintillion"]="0".repeat(684);w_Dict["duocenoctovigintillion"]="0".repeat(687);w_Dict["duocennovemvigintillion"]="0".repeat(690);w_Dict["duocentrigintillion"]="0".repeat(693);w_Dict["duocenuntrigintillion"]="0".repeat(696);w_Dict["duocendotrigintillion"]="0".repeat(699);w_Dict["duocentretrigintillion"]="0".repeat(702);w_Dict["duocenquattuortrigintillion"]="0".repeat(705);w_Dict["duocenquintrigintillion"]="0".repeat(708);w_Dict["duocensextrigintillion"]="0".repeat(711);w_Dict["duocenseptentrigintillion"]="0".repeat(714);w_Dict["duocenoctotrigintillion"]="0".repeat(717);w_Dict["duocennovemtrigintillion"]="0".repeat(720);w_Dict["duocenquadragintillion"]="0".repeat(723);w_Dict["duocenunquadragintillion"]="0".repeat(726);w_Dict["duocendoquadragintillion"]="0".repeat(729);w_Dict["duocentrequadragintillion"]="0".repeat(732);w_Dict["duocenquattuorquadragintillion"]="0".repeat(735);w_Dict["duocenquinquadragintillion"]="0".repeat(738);w_Dict["duocensexquadragintillion"]="0".repeat(741);w_Dict["duocenseptenquadragintillion"]="0".repeat(744);w_Dict["duocenoctoquadragintillion"]="0".repeat(747);w_Dict["duocennovemquadragintillion"]="0".repeat(750);w_Dict["duocenquinquagintillion"]="0".repeat(753);w_Dict["duocenunquinquagintillion"]="0".repeat(756);w_Dict["duocendoquinquagintillion"]="0".repeat(759);w_Dict["duocentrequinquagintillion"]="0".repeat(762);w_Dict["duocenquattuorquinquagintillion"]="0".repeat(765);w_Dict["duocenquinquinquagintillion"]="0".repeat(768);w_Dict["duocensexquinquagintillion"]="0".repeat(771);w_Dict["duocenseptenquinquagintillion"]="0".repeat(774);w_Dict["duocenoctoquinquagintillion"]="0".repeat(777);w_Dict["duocennovemquinquagintillion"]="0".repeat(780);w_Dict["duocensexagintillion"]="0".repeat(783);w_Dict["duocenunsexagintillion"]="0".repeat(786);w_Dict["duocendosexagintillion"]="0".repeat(789);w_Dict["duocentresexagintillion"]="0".repeat(792);w_Dict["duocenquattuorsexagintillion"]="0".repeat(795);w_Dict["duocenquinsexagintillion"]="0".repeat(798);w_Dict["duocensexsexagintillion"]="0".repeat(801);w_Dict["duocenseptensexagintillion"]="0".repeat(804);w_Dict["duocenoctosexagintillion"]="0".repeat(807);w_Dict["duocennovemsexagintillion"]="0".repeat(810);w_Dict["duocenseptuagintillion"]="0".repeat(813);w_Dict["duocenunseptuagintillion"]="0".repeat(816);w_Dict["duocendoseptuagintillion"]="0".repeat(819);w_Dict["duocentreseptuagintillion"]="0".repeat(822);w_Dict["duocenquattuorseptuagintillion"]="0".repeat(825);w_Dict["duocenquinseptuagintillion"]="0".repeat(828);w_Dict["duocensexseptuagintillion"]="0".repeat(831);w_Dict["duocenseptenseptuagintillion"]="0".repeat(834);w_Dict["duocenoctoseptuagintillion"]="0".repeat(837);w_Dict["duocennovemseptuagintillion"]="0".repeat(840);w_Dict["duocenoctogintillion"]="0".repeat(843);w_Dict["duocenunoctogintillion"]="0".repeat(846);w_Dict["duocendooctogintillion"]="0".repeat(849);w_Dict["duocentreoctogintillion"]="0".repeat(852);w_Dict["duocenquattuoroctogintillion"]="0".repeat(855);w_Dict["duocenquinoctogintillion"]="0".repeat(858);w_Dict["duocensexoctogintillion"]="0".repeat(861);w_Dict["duocenseptenoctogintillion"]="0".repeat(864);w_Dict["duocenoctooctogintillion"]="0".repeat(867);w_Dict["duocennovemoctogintillion"]="0".repeat(870);w_Dict["duocennonagintillion"]="0".repeat(873);w_Dict["duocenunnonagintillion"]="0".repeat(876);w_Dict["duocendononagintillion"]="0".repeat(879);w_Dict["duocentrenonagintillion"]="0".repeat(882);w_Dict["duocenquattuornonagintillion"]="0".repeat(885);w_Dict["duocenquinnonagintillion"]="0".repeat(888);w_Dict["duocensexnonagintillion"]="0".repeat(891);w_Dict["duocenseptennonagintillion"]="0".repeat(894);w_Dict["duocenoctononagintillion"]="0".repeat(897);w_Dict["duocennovemnonagintillion"]="0".repeat(900);w_Dict["trecentillion"]="0".repeat(903);w_Dict["trecenuntillion"]="0".repeat(906);w_Dict["trecendotillion"]="0".repeat(909);w_Dict["trecentretillion"]="0".repeat(912);w_Dict["trecenquattuortillion"]="0".repeat(915);w_Dict["trecenquintillion"]="0".repeat(918);w_Dict["trecensextillion"]="0".repeat(921);w_Dict["trecenseptentillion"]="0".repeat(924);w_Dict["trecenoctotillion"]="0".repeat(927);w_Dict["trecennovemtillion"]="0".repeat(930);w_Dict["trecendecillion"]="0".repeat(933);w_Dict["trecenundecillion"]="0".repeat(936);w_Dict["trecendodecillion"]="0".repeat(939);w_Dict["trecentredecillion"]="0".repeat(942);w_Dict["trecenquattuordecillion"]="0".repeat(945);w_Dict["trecenquindecillion"]="0".repeat(948);w_Dict["trecensexdecillion"]="0".repeat(951);w_Dict["trecenseptendecillion"]="0".repeat(954);w_Dict["trecenoctodecillion"]="0".repeat(957);w_Dict["trecennovemdecillion"]="0".repeat(960);w_Dict["trecenvigintillion"]="0".repeat(963);w_Dict["trecenunvigintillion"]="0".repeat(966);w_Dict["trecendovigintillion"]="0".repeat(969);w_Dict["trecentrevigintillion"]="0".repeat(972);w_Dict["trecenquattuorvigintillion"]="0".repeat(975);w_Dict["trecenquinvigintillion"]="0".repeat(978);w_Dict["trecensexvigintillion"]="0".repeat(981);w_Dict["trecenseptenvigintillion"]="0".repeat(984);w_Dict["trecenoctovigintillion"]="0".repeat(987);w_Dict["trecennovemvigintillion"]="0".repeat(990);w_Dict["trecentrigintillion"]="0".repeat(993);w_Dict["trecenuntrigintillion"]="0".repeat(996);w_Dict["trecendotrigintillion"]="0".repeat(999);w_Dict["trecentretrigintillion"]="0".repeat(1002);
return w_Dict[w];
};
/**
* Word Dictionary 2
* function w_Dict2
* @param {string} - Number as strings of digits e.g "1"
* @returns {String} - @param value in English short scale naming system words e.g "one billion" for "1000000000"
*/
BigArith.prototype.w_Dict2=function(w){
/*Word Dictionary*/
var w_Dict = []; w_Dict[""] = "";
w_Dict["0"] = "zero"; w_Dict["1"] = "one"; w_Dict["2"] = "two"; w_Dict["3"] = "three"; w_Dict["4"] = "four"; w_Dict["5"] = "five"; w_Dict["6"] = "six"; w_Dict["7"] = "seven"; w_Dict["8"] = "eight"; w_Dict["9"] = "nine"; w_Dict["10"] = "ten";
w_Dict["11"] = "eleven"; w_Dict["12"] = "twelve"; w_Dict["13"] = "thirteen"; w_Dict["14"] = "fourteen"; w_Dict["15"] = "fifteen"; w_Dict["16"] = "sixteen"; w_Dict["17"] = "seventeen"; w_Dict["18"] = "eighteen"; w_Dict["19"] = "nineteen"; w_Dict["20"] = "twenty";
w_Dict["30"] = "thirty"; w_Dict["40"] = "forty"; w_Dict["50"] = "fifty"; w_Dict["60"] = "sixty"; w_Dict["70"] = "seventy"; w_Dict["80"] = "eighty"; w_Dict["90"] = "ninety"; w_Dict["0".repeat(2)] = "hundred";
w_Dict["0".repeat(3)] = "thousand"; w_Dict["0".repeat(6)]="million";w_Dict["0".repeat(9)]="billion";w_Dict["0".repeat(12)]="trillion";w_Dict["0".repeat(15)]="quadrillion";w_Dict["0".repeat(18)]="quintillion";w_Dict["0".repeat(21)]="sextillion";w_Dict["0".repeat(24)]="septillion";w_Dict["0".repeat(27)]="octillion";w_Dict["0".repeat(30)]="nonillion";w_Dict["0".repeat(33)]="decillion";w_Dict["0".repeat(36)]="undecillion";w_Dict["0".repeat(39)]="duodecillion";w_Dict["0".repeat(42)]="tredecillion";w_Dict["0".repeat(45)]="quattuordecillion";w_Dict["0".repeat(48)]="quindecillion";w_Dict["0".repeat(51)]="sexdecillion";w_Dict["0".repeat(54)]="septendecillion";w_Dict["0".repeat(57)]="octodecillion";w_Dict["0".repeat(60)]="novemdecillion";w_Dict["0".repeat(63)]="vigintillion";w_Dict["0".repeat(66)]="unvigintillion";w_Dict["0".repeat(69)]="duovigintillion";w_Dict["0".repeat(72)]="trevigintillion";w_Dict["0".repeat(75)]="quattuorvigintillion";w_Dict["0".repeat(78)]="quinvigintillion";w_Dict["0".repeat(81)]="sexvigintillion";w_Dict["0".repeat(84)]="septenvigintillion";w_Dict["0".repeat(87)]="octavigintillion";w_Dict["0".repeat(90)]="novemvigintillion";w_Dict["0".repeat(93)]="trigintillion";w_Dict["0".repeat(96)]="untrigintillion";w_Dict["0".repeat(99)]="duotrigintillion";w_Dict["0".repeat(102)]="tretrigintillion";w_Dict["0".repeat(105)]="quattuortrigintillion";w_Dict["0".repeat(108)]="quintrigintillion";w_Dict["0".repeat(111)]="sextrigintillion";w_Dict["0".repeat(114)]="septentrigintillion";w_Dict["0".repeat(117)]="octotrigintillion";w_Dict["0".repeat(120)]="novemtrigintillion";w_Dict["0".repeat(123)]="quadragintillion";w_Dict["0".repeat(126)]="unquadragintillion";w_Dict["0".repeat(129)]="duoquadragintillion";w_Dict["0".repeat(132)]="trequadragintillion";w_Dict["0".repeat(135)]="quattuorquadragintillion";w_Dict["0".repeat(138)]="quinquadragintillion";w_Dict["0".repeat(141)]="sexquadragintillion";w_Dict["0".repeat(144)]="septenquadragintillion";w_Dict["0".repeat(147)]="octaquadragintillion";w_Dict["0".repeat(150)]="novemquadragintillion";w_Dict["0".repeat(153)]="quinquagintillion";w_Dict["0".repeat(156)]="unquinquagintillion";w_Dict["0".repeat(159)]="duoquinquagintillion";w_Dict["0".repeat(162)]="trequinquagintillion";w_Dict["0".repeat(165)]="quattuorquinquagintillion";w_Dict["0".repeat(168)]="quinquinquagintillion";w_Dict["0".repeat(171)]="sexquinquagintillion";w_Dict["0".repeat(174)]="septenquinquagintillion";w_Dict["0".repeat(177)]="octaquinquagintillion";w_Dict["0".repeat(180)]="novemquinquagintillion";w_Dict["0".repeat(183)]="sexagintillion";w_Dict["0".repeat(186)]="unsexagintillion";w_Dict["0".repeat(189)]="duosexagintillion";w_Dict["0".repeat(192)]="tresexagintillion";w_Dict["0".repeat(195)]="quattuorsexagintillion";w_Dict["0".repeat(198)]="quinsexagintillion";w_Dict["0".repeat(201)]="sexsexagintillion";w_Dict["0".repeat(204)]="septensexagintillion";w_Dict["0".repeat(207)]="octasexagintillion";w_Dict["0".repeat(210)]="novemsexagintillion";w_Dict["0".repeat(213)]="septuagintillion";w_Dict["0".repeat(216)]="unseptuagintillion";w_Dict["0".repeat(219)]="duoseptuagintillion";w_Dict["0".repeat(222)]="treseptuagintillion";w_Dict["0".repeat(225)]="quattuorseptuagintillion";w_Dict["0".repeat(228)]="quinseptuagintillion";w_Dict["0".repeat(231)]="sexseptuagintillion";w_Dict["0".repeat(234)]="septenseptuagintillion";w_Dict["0".repeat(237)]="octaseptuagintillion";w_Dict["0".repeat(240)]="novemseptuagintillion";w_Dict["0".repeat(243)]="octagintillion";w_Dict["0".repeat(246)]="unoctogintillion";w_Dict["0".repeat(249)]="duooctogintillion";w_Dict["0".repeat(252)]="treoctogintillion";w_Dict["0".repeat(255)]="quattuoroctogintillion";w_Dict["0".repeat(258)]="quinoctogintillion";w_Dict["0".repeat(261)]="sexoctogintillion";w_Dict["0".repeat(264)]="septenoctogintillion";w_Dict["0".repeat(267)]="octaoctogintillion";w_Dict["0".repeat(270)]="novemoctogintillion";w_Dict["0".repeat(273)]="nonagintillion";w_Dict["0".repeat(276)]="unnonagintillion";w_Dict["0".repeat(279)]="duononagintillion";w_Dict["0".repeat(282)]="trenonagintillion";w_Dict["0".repeat(285)]="quattuornonagintillion";w_Dict["0".repeat(288)]="quinnonagintillion";w_Dict["0".repeat(291)]="sexnonagintillion";w_Dict["0".repeat(294)]="septennonagintillion";w_Dict["0".repeat(297)]="octanonagintillion";w_Dict["0".repeat(300)]="novemnonagintillion";w_Dict["0".repeat(303)]="centillion";w_Dict["0".repeat(306)]="cenuntillion";w_Dict["0".repeat(309)]="cendotillion";w_Dict["0".repeat(312)]="centretillion";w_Dict["0".repeat(315)]="cenquattuortillion";w_Dict["0".repeat(318)]="cenquintillion";w_Dict["0".repeat(321)]="censextillion";w_Dict["0".repeat(324)]="censeptentillion";w_Dict["0".repeat(327)]="cenoctotillion";w_Dict["0".repeat(330)]="cennovemtillion";w_Dict["0".repeat(333)]="cendecillion";w_Dict["0".repeat(336)]="cenundecillion";w_Dict["0".repeat(339)]="cendodecillion";w_Dict["0".repeat(342)]="centredecillion";w_Dict["0".repeat(345)]="cenquattuordecillion";w_Dict["0".repeat(348)]="cenquindecillion";w_Dict["0".repeat(351)]="censexdecillion";w_Dict["0".repeat(354)]="censeptendecillion";w_Dict["0".repeat(357)]="cenoctodecillion";w_Dict["0".repeat(360)]="cennovemdecillion";w_Dict["0".repeat(363)]="cenvigintillion";w_Dict["0".repeat(366)]="cenunvigintillion";w_Dict["0".repeat(369)]="cendovigintillion";w_Dict["0".repeat(372)]="centrevigintillion";w_Dict["0".repeat(375)]="cenquattuorvigintillion";w_Dict["0".repeat(378)]="cenquinvigintillion";w_Dict["0".repeat(381)]="censexvigintillion";w_Dict["0".repeat(384)]="censeptenvigintillion";w_Dict["0".repeat(387)]="cenoctovigintillion";w_Dict["0".repeat(390)]="cennovemvigintillion";w_Dict["0".repeat(393)]="centrigintillion";w_Dict["0".repeat(396)]="cenuntrigintillion";w_Dict["0".repeat(399)]="cendotrigintillion";w_Dict["0".repeat(402)]="centretrigintillion";w_Dict["0".repeat(405)]="cenquattuortrigintillion";w_Dict["0".repeat(408)]="cenquintrigintillion";w_Dict["0".repeat(411)]="censextrigintillion";w_Dict["0".repeat(414)]="censeptentrigintillion";w_Dict["0".repeat(417)]="cenoctotrigintillion";w_Dict["0".repeat(420)]="cennovemtrigintillion";w_Dict["0".repeat(423)]="cenquadragintillion";w_Dict["0".repeat(426)]="cenunquadragintillion";w_Dict["0".repeat(429)]="cendoquadragintillion";w_Dict["0".repeat(432)]="centrequadragintillion";w_Dict["0".repeat(435)]="cenquattuorquadragintillion";w_Dict["0".repeat(438)]="cenquinquadragintillion";w_Dict["0".repeat(441)]="censexquadragintillion";w_Dict["0".repeat(444)]="censeptenquadragintillion";w_Dict["0".repeat(447)]="cenoctoquadragintillion";w_Dict["0".repeat(450)]="cennovemquadragintillion";w_Dict["0".repeat(453)]="cenquinquagintillion";w_Dict["0".repeat(456)]="cenunquinquagintillion";w_Dict["0".repeat(459)]="cendoquinquagintillion";w_Dict["0".repeat(462)]="centrequinquagintillion";w_Dict["0".repeat(465)]="cenquattuorquinquagintillion";w_Dict["0".repeat(468)]="cenquinquinquagintillion";w_Dict["0".repeat(471)]="censexquinquagintillion";w_Dict["0".repeat(474)]="censeptenquinquagintillion";w_Dict["0".repeat(477)]="cenoctoquinquagintillion";w_Dict["0".repeat(480)]="cennovemquinquagintillion";w_Dict["0".repeat(483)]="censexagintillion";w_Dict["0".repeat(486)]="cenunsexagintillion";w_Dict["0".repeat(489)]="cendosexagintillion";w_Dict["0".repeat(492)]="centresexagintillion";w_Dict["0".repeat(495)]="cenquattuorsexagintillion";w_Dict["0".repeat(498)]="cenquinsexagintillion";w_Dict["0".repeat(501)]="censexsexagintillion";w_Dict["0".repeat(504)]="censeptensexagintillion";w_Dict["0".repeat(507)]="cenoctosexagintillion";w_Dict["0".repeat(510)]="cennovemsexagintillion";w_Dict["0".repeat(513)]="censeptuagintillion";w_Dict["0".repeat(516)]="cenunseptuagintillion";w_Dict["0".repeat(519)]="cendoseptuagintillion";w_Dict["0".repeat(522)]="centreseptuagintillion";w_Dict["0".repeat(525)]="cenquattuorseptuagintillion";w_Dict["0".repeat(528)]="cenquinseptuagintillion";w_Dict["0".repeat(531)]="censexseptuagintillion";w_Dict["0".repeat(534)]="censeptenseptuagintillion";w_Dict["0".repeat(537)]="cenoctoseptuagintillion";w_Dict["0".repeat(540)]="cennovemseptuagintillion";w_Dict["0".repeat(543)]="cenoctogintillion";w_Dict["0".repeat(546)]="cenunoctogintillion";w_Dict["0".repeat(549)]="cendooctogintillion";w_Dict["0".repeat(552)]="centreoctogintillion";w_Dict["0".repeat(555)]="cenquattuoroctogintillion";w_Dict["0".repeat(558)]="cenquinoctogintillion";w_Dict["0".repeat(561)]="censexoctogintillion";w_Dict["0".repeat(564)]="censeptenoctogintillion";w_Dict["0".repeat(567)]="cenoctooctogintillion";w_Dict["0".repeat(570)]="cennovemoctogintillion";w_Dict["0".repeat(573)]="cennonagintillion";w_Dict["0".repeat(576)]="cenunnonagintillion";w_Dict["0".repeat(579)]="cendononagintillion";w_Dict["0".repeat(582)]="centrenonagintillion";w_Dict["0".repeat(585)]="cenquattuornonagintillion";w_Dict["0".repeat(588)]="cenquinnonagintillion";w_Dict["0".repeat(591)]="censexnonagintillion";w_Dict["0".repeat(594)]="censeptennonagintillion";w_Dict["0".repeat(597)]="cenoctononagintillion";w_Dict["0".repeat(600)]="cennovemnonagintillion";w_Dict["0".repeat(603)]="duocentillion";w_Dict["0".repeat(606)]="duocenuntillion";w_Dict["0".repeat(609)]="duocendotillion";w_Dict["0".repeat(612)]="duocentretillion";w_Dict["0".repeat(615)]="duocenquattuortillion";w_Dict["0".repeat(618)]="duocenquintillion";w_Dict["0".repeat(621)]="duocensextillion";w_Dict["0".repeat(624)]="duocenseptentillion";w_Dict["0".repeat(627)]="duocenoctotillion";w_Dict["0".repeat(630)]="duocennovemtillion";w_Dict["0".repeat(633)]="duocendecillion";w_Dict["0".repeat(636)]="duocenundecillion";w_Dict["0".repeat(639)]="duocendodecillion";w_Dict["0".repeat(642)]="duocentredecillion";w_Dict["0".repeat(645)]="duocenquattuordecillion";w_Dict["0".repeat(648)]="duocenquindecillion";w_Dict["0".repeat(651)]="duocensexdecillion";w_Dict["0".repeat(654)]="duocenseptendecillion";w_Dict["0".repeat(657)]="duocenoctodecillion";w_Dict["0".repeat(660)]="duocennovemdecillion";w_Dict["0".repeat(663)]="duocenvigintillion";w_Dict["0".repeat(666)]="duocenunvigintillion";w_Dict["0".repeat(669)]="duocendovigintillion";w_Dict["0".repeat(672)]="duocentrevigintillion";w_Dict["0".repeat(675)]="duocenquattuorvigintillion";w_Dict["0".repeat(678)]="duocenquinvigintillion";w_Dict["0".repeat(681)]="duocensexvigintillion";w_Dict["0".repeat(684)]="duocenseptenvigintillion";w_Dict["0".repeat(687)]="duocenoctovigintillion";w_Dict["0".repeat(690)]="duocennovemvigintillion";w_Dict["0".repeat(693)]="duocentrigintillion";w_Dict["0".repeat(696)]="duocenuntrigintillion";w_Dict["0".repeat(699)]="duocendotrigintillion";w_Dict["0".repeat(702)]="duocentretrigintillion";w_Dict["0".repeat(705)]="duocenquattuortrigintillion";w_Dict["0".repeat(708)]="duocenquintrigintillion";w_Dict["0".repeat(711)]="duocensextrigintillion";w_Dict["0".repeat(714)]="duocenseptentrigintillion";w_Dict["0".repeat(717)]="duocenoctotrigintillion";w_Dict["0".repeat(720)]="duocennovemtrigintillion";w_Dict["0".repeat(723)]="duocenquadragintillion";w_Dict["0".repeat(726)]="duocenunquadragintillion";w_Dict["0".repeat(729)]="duocendoquadragintillion";w_Dict["0".repeat(732)]="duocentrequadragintillion";w_Dict["0".repeat(735)]="duocenquattuorquadragintillion";w_Dict["0".repeat(738)]="duocenquinquadragintillion";w_Dict["0".repeat(741)]="duocensexquadragintillion";w_Dict["0".repeat(744)]="duocenseptenquadragintillion";w_Dict["0".repeat(747)]="duocenoctoquadragintillion";w_Dict["0".repeat(750)]="duocennovemquadragintillion";w_Dict["0".repeat(753)]="duocenquinquagintillion";w_Dict["0".repeat(756)]="duocenunquinquagintillion";w_Dict["0".repeat(759)]="duocendoquinquagintillion";w_Dict["0".repeat(762)]="duocentrequinquagintillion";w_Dict["0".repeat(765)]="duocenquattuorquinquagintillion";w_Dict["0".repeat(768)]="duocenquinquinquagintillion";w_Dict["0".repeat(771)]="duocensexquinquagintillion";w_Dict["0".repeat(774)]="duocenseptenquinquagintillion";w_Dict["0".repeat(777)]="duocenoctoquinquagintillion";w_Dict["0".repeat(780)]="duocennovemquinquagintillion";w_Dict["0".repeat(783)]="duocensexagintillion";w_Dict["0".repeat(786)]="duocenunsexagintillion";w_Dict["0".repeat(789)]="duocendosexagintillion";w_Dict["0".repeat(792)]="duocentresexagintillion";w_Dict["0".repeat(795)]="duocenquattuorsexagintillion";w_Dict["0".repeat(798)]="duocenquinsexagintillion";w_Dict["0".repeat(801)]="duocensexsexagintillion";w_Dict["0".repeat(804)]="duocenseptensexagintillion";w_Dict["0".repeat(807)]="duocenoctosexagintillion";w_Dict["0".repeat(810)]="duocennovemsexagintillion";w_Dict["0".repeat(813)]="duocenseptuagintillion";w_Dict["0".repeat(816)]="duocenunseptuagintillion";w_Dict["0".repeat(819)]="duocendoseptuagintillion";w_Dict["0".repeat(822)]="duocentreseptuagintillion";w_Dict["0".repeat(825)]="duocenquattuorseptuagintillion";w_Dict["0".repeat(828)]="duocenquinseptuagintillion";w_Dict["0".repeat(831)]="duocensexseptuagintillion";w_Dict["0".repeat(834)]="duocenseptenseptuagintillion";w_Dict["0".repeat(837)]="duocenoctoseptuagintillion";w_Dict["0".repeat(840)]="duocennovemseptuagintillion";w_Dict["0".repeat(843)]="duocenoctogintillion";w_Dict["0".repeat(846)]="duocenunoctogintillion";w_Dict["0".repeat(849)]="duocendooctogintillion";w_Dict["0".repeat(852)]="duocentreoctogintillion";w_Dict["0".repeat(855)]="duocenquattuoroctogintillion";w_Dict["0".repeat(858)]="duocenquinoctogintillion";w_Dict["0".repeat(861)]="duocensexoctogintillion";w_Dict["0".repeat(864)]="duocenseptenoctogintillion";w_Dict["0".repeat(867)]="duocenoctooctogintillion";w_Dict["0".repeat(870)]="duocennovemoctogintillion";w_Dict["0".repeat(873)]="duocennonagintillion";w_Dict["0".repeat(876)]="duocenunnonagintillion";w_Dict["0".repeat(879)]="duocendononagintillion";w_Dict["0".repeat(882)]="duocentrenonagintillion";w_Dict["0".repeat(885)]="duocenquattuornonagintillion";w_Dict["0".repeat(888)]="duocenquinnonagintillion";w_Dict["0".repeat(891)]="duocensexnonagintillion";w_Dict["0".repeat(894)]="duocenseptennonagintillion";w_Dict["0".repeat(897)]="duocenoctononagintillion";w_Dict["0".repeat(900)]="duocennovemnonagintillion";w_Dict["0".repeat(903)]="trecentillion";w_Dict["0".repeat(906)]="trecenuntillion";w_Dict["0".repeat(909)]="trecendotillion";w_Dict["0".repeat(912)]="trecentretillion";w_Dict["0".repeat(915)]="trecenquattuortillion";w_Dict["0".repeat(918)]="trecenquintillion";w_Dict["0".repeat(921)]="trecensextillion";w_Dict["0".repeat(924)]="trecenseptentillion";w_Dict["0".repeat(927)]="trecenoctotillion";w_Dict["0".repeat(930)]="trecennovemtillion";w_Dict["0".repeat(933)]="trecendecillion";w_Dict["0".repeat(936)]="trecenundecillion";w_Dict["0".repeat(939)]="trecendodecillion";w_Dict["0".repeat(942)]="trecentredecillion";w_Dict["0".repeat(945)]="trecenquattuordecillion";w_Dict["0".repeat(948)]="trecenquindecillion";w_Dict["0".repeat(951)]="trecensexdecillion";w_Dict["0".repeat(954)]="trecenseptendecillion";w_Dict["0".repeat(957)]="trecenoctodecillion";w_Dict["0".repeat(960)]="trecennovemdecillion";w_Dict["0".repeat(963)]="trecenvigintillion";w_Dict["0".repeat(966)]="trecenunvigintillion";w_Dict["0".repeat(969)]="trecendovigintillion";w_Dict["0".repeat(972)]="trecentrevigintillion";w_Dict["0".repeat(975)]="trecenquattuorvigintillion";w_Dict["0".repeat(978)]="trecenquinvigintillion";w_Dict["0".repeat(981)]="trecensexvigintillion";w_Dict["0".repeat(984)]="trecenseptenvigintillion";w_Dict["0".repeat(987)]="trecenoctovigintillion";w_Dict["0".repeat(990)]="trecennovemvigintillion";w_Dict["0".repeat(993)]="trecentrigintillion";w_Dict["0".repeat(996)]="trecenuntrigintillion";w_Dict["0".repeat(999)]="trecendotrigintillion";w_Dict["0".repeat(1002)]="trecentretrigintillion";
return w_Dict[w];
}
/*
* Factorial 0 to 200
* Precompiled factorial reduces computation time in calculating sine and cosine
* But increases file size by 34kb
*/
BigArith.factorial = function(n){
var factorial = [
"1",
"1",
"2",
"6",
"24",
"120",
"720",
"5040",
"40320",
"362880",
"3628800",
"39916800",
"479001600",
"6227020800",
"87178291200",
"1307674368000",
"20922789888000",
"355687428096000",
"6402373705728000",
"121645100408832000",
"2432902008176640000",
"51090942171709440000",
"1124000727777607680000",
"25852016738884976640000",
"620448401733239439360000",
"15511210043330985984000000",
"403291461126605635584000000",
"10888869450418352160768000000",
"304888344611713860501504000000",
"8841761993739701954543616000000",
"265252859812191058636308480000000",
"8222838654177922817725562880000000",
"263130836933693530167218012160000000",
"8683317618811886495518194401280000000",
"295232799039604140847618609643520000000",
"10333147966386144929666651337523200000000",
"371993326789901217467999448150835200000000",
"13763753091226345046315979581580902400000000",
"523022617466601111760007224100074291200000000",
"20397882081197443358640281739902897356800000000",
"815915283247897734345611269596115894272000000000",
"33452526613163807108170062053440751665152000000000",
"1405006117752879898543142606244511569936384000000000",
"60415263063373835637355132068513997507264512000000000",
"2658271574788448768043625811014615890319638528000000000",
"119622220865480194561963161495657715064383733760000000000",
"5502622159812088949850305428800254892961651752960000000000",
"258623241511168180642964355153611979969197632389120000000000",
"12413915592536072670862289047373375038521486354677760000000000",
"608281864034267560872252163321295376887552831379210240000000000",
"30414093201713378043612608166064768844377641568960512000000000000",
"1551118753287382280224243016469303211063259720016986112000000000000",
"80658175170943878571660636856403766975289505440883277824000000000000",
"4274883284060025564298013753389399649690343788366813724672000000000000",
"230843697339241380472092742683027581083278564571807941132288000000000000",
"12696403353658275925965100847566516959580321051449436762275840000000000000",
"710998587804863451854045647463724949736497978881168458687447040000000000000",
"40526919504877216755680601905432322134980384796226602145184481280000000000000",
"2350561331282878571829474910515074683828862318181142924420699914240000000000000",
"138683118545689835737939019720389406345902876772687432540821294940160000000000000",
"8320987112741390144276341183223364380754172606361245952449277696409600000000000000",
"507580213877224798800856812176625227226004528988036003099405939480985600000000000000",
"31469973260387937525653122354950764088012280797258232192163168247821107200000000000000",
"1982608315404440064116146708361898137544773690227268628106279599612729753600000000000000",
"126886932185884164103433389335161480802865516174545192198801894375214704230400000000000000",
"8247650592082470666723170306785496252186258551345437492922123134388955774976000000000000000",
"544344939077443064003729240247842752644293064388798874532860126869671081148416000000000000000",
"36471110918188685288249859096605464427167635314049524593701628500267962436943872000000000000000",
"2480035542436830599600990418569171581047399201355367672371710738018221445712183296000000000000000",
"171122452428141311372468338881272839092270544893520369393648040923257279754140647424000000000000000",
"11978571669969891796072783721689098736458938142546425857555362864628009582789845319680000000000000000",
"850478588567862317521167644239926010288584608120796235886430763388588680378079017697280000000000000000",
"61234458376886086861524070385274672740778091784697328983823014963978384987221689274204160000000000000000",
"4470115461512684340891257138125051110076800700282905015819080092370422104067183317016903680000000000000000",
"330788544151938641225953028221253782145683251820934971170611926835411235700971565459250872320000000000000000",
"24809140811395398091946477116594033660926243886570122837795894512655842677572867409443815424000000000000000000",
"1885494701666050254987932260861146558230394535379329335672487982961844043495537923117729972224000000000000000000",
"145183092028285869634070784086308284983740379224208358846781574688061991349156420080065207861248000000000000000000",
"11324281178206297831457521158732046228731749579488251990048962825668835325234200766245086213177344000000000000000000",
"894618213078297528685144171539831652069808216779571907213868063227837990693501860533361810841010176000000000000000000",
"71569457046263802294811533723186532165584657342365752577109445058227039255480148842668944867280814080000000000000000000",
"5797126020747367985879734231578109105412357244731625958745865049716390179693892056256184534249745940480000000000000000000",
"475364333701284174842138206989404946643813294067993328617160934076743994734899148613007131808479167119360000000000000000000",
"39455239697206586511897471180120610571436503407643446275224357528369751562996629334879591940103770870906880000000000000000000",
"3314240134565353266999387579130131288000666286242049487118846032383059131291716864129885722968716753156177920000000000000000000",
"281710411438055027694947944226061159480056634330574206405101912752560026159795933451040286452340924018275123200000000000000000000",
"24227095383672732381765523203441259715284870552429381750838764496720162249742450276789464634901319465571660595200000000000000000000",
"2107757298379527717213600518699389595229783738061356212322972511214654115727593174080683423236414793504734471782400000000000000000000",
"185482642257398439114796845645546284380220968949399346684421580986889562184028199319100141244804501828416633516851200000000000000000000",
"16507955160908461081216919262453619309839666236496541854913520707833171034378509739399912570787600662729080382999756800000000000000000000",
"1485715964481761497309522733620825737885569961284688766942216863704985393094065876545992131370884059645617234469978112000000000000000000000",
"135200152767840296255166568759495142147586866476906677791741734597153670771559994765685283954750449427751168336768008192000000000000000000000",
"12438414054641307255475324325873553077577991715875414356840239582938137710983519518443046123837041347353107486982656753664000000000000000000000",
"1156772507081641574759205162306240436214753229576413535186142281213246807121467315215203289516844845303838996289387078090752000000000000000000000",
"108736615665674308027365285256786601004186803580182872307497374434045199869417927630229109214583415458560865651202385340530688000000000000000000000",
"10329978488239059262599702099394727095397746340117372869212250571234293987594703124871765375385424468563282236864226607350415360000000000000000000000",
"991677934870949689209571401541893801158183648651267795444376054838492222809091499987689476037000748982075094738965754305639874560000000000000000000000",
"96192759682482119853328425949563698712343813919172976158104477319333745612481875498805879175589072651261284189679678167647067832320000000000000000000000",
"9426890448883247745626185743057242473809693764078951663494238777294707070023223798882976159207729119823605850588608460429412647567360000000000000000000000",
"933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000",
"93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000",
"9425947759838359420851623124482936749562312794702543768327889353416977599316221476503087861591808346911623490003549599583369706302603264000000000000000000000000",
"961446671503512660926865558697259548455355905059659464369444714048531715130254590603314961882364451384985595980362059157503710042865532928000000000000000000000000",
"99029007164861804075467152545817733490901658221144924830052805546998766658416222832141441073883538492653516385977292093222882134415149891584000000000000000000000000",
"10299016745145627623848583864765044283053772454999072182325491776887871732475287174542709871683888003235965704141638377695179741979175588724736000000000000000000000000",
"1081396758240290900504101305800329649720646107774902579144176636573226531909905153326984536526808240339776398934872029657993872907813436816097280000000000000000000000000",
"114628056373470835453434738414834942870388487424139673389282723476762012382449946252660360871841673476016298287096435143747350528228224302506311680000000000000000000000000",
"12265202031961379393517517010387338887131568154382945052653251412013535324922144249034658613287059061933743916719318560380966506520420000368175349760000000000000000000000000",
"1324641819451828974499891837121832599810209360673358065686551152497461815091591578895743130235002378688844343005686404521144382704205360039762937774080000000000000000000000000",
"144385958320249358220488210246279753379312820313396029159834075622223337844983482099636001195615259277084033387619818092804737714758384244334160217374720000000000000000000000000",
"15882455415227429404253703127090772871724410234473563207581748318444567162948183030959960131517678520479243672638179990208521148623422266876757623911219200000000000000000000000000",
"1762952551090244663872161047107075788761409536026565516041574063347346955087248316436555574598462315773196047662837978913145847497199871623320096254145331200000000000000000000000000",
"197450685722107402353682037275992488341277868034975337796656295094902858969771811440894224355027779366597957338237853638272334919686385621811850780464277094400000000000000000000000000",
"22311927486598136465966070212187151182564399087952213171022161345724023063584214692821047352118139068425569179220877461124773845924561575264739138192463311667200000000000000000000000000",
"2543559733472187557120132004189335234812341496026552301496526393412538629248600474981599398141467853800514886431180030568224218435400019580180261753940817530060800000000000000000000000000",
"292509369349301569068815180481773552003419272043053514672100535242441942363589054622883930786268803187059211939585703515345785120071002251720730101703194015956992000000000000000000000000000",
"33931086844518982011982560935885732032396635556994207701963662088123265314176330336254535971207181169698868584991941607780111073928236261199604691797570505851011072000000000000000000000000000",
"3969937160808720895401959629498630647790406360168322301129748464310422041758630649341780708631240196854767624444057168110272995649603642560353748940315749184568295424000000000000000000000000000",
"468452584975429065657431236280838416439267950499862031533310318788629800927518416622330123618486343228862579684398745837012213486653229822121742374957258403779058860032000000000000000000000000000",
"55745857612076058813234317117419771556272886109483581752463927935846946310374691578057284710599874844234646982443450754604453404911734348832487342619913750049708004343808000000000000000000000000000",
"6689502913449127057588118054090372586752746333138029810295671352301633557244962989366874165271984981308157637893214090552534408589408121859898481114389650005964960521256960000000000000000000000000000",
"809429852527344373968162284544935082997082306309701607045776233628497660426640521713391773997910182738287074185078904956856663439318382745047716214841147650721760223072092160000000000000000000000000000",
"98750442008336013624115798714482080125644041369783596059584700502676714572050143649033796427745042294071023050579626404736512939596842694895821378210620013388054747214795243520000000000000000000000000000",
"12146304367025329675766243241881295855454217088483382315328918161829235892362167668831156960612640202170735835221294047782591091570411651472186029519906261646730733907419814952960000000000000000000000000000",
"1506141741511140879795014161993280686076322918971939407100785852066825250652908790935063463115967385069171243567440461925041295354731044782551067660468376444194611004520057054167040000000000000000000000000000",
"188267717688892609974376770249160085759540364871492425887598231508353156331613598866882932889495923133646405445930057740630161919341380597818883457558547055524326375565007131770880000000000000000000000000000000",
"23721732428800468856771473051394170805702085973808045661837377170052497697783313457227249544076486314839447086187187275319400401837013955325179315652376928996065123321190898603130880000000000000000000000000000000",
"3012660018457659544809977077527059692324164918673621799053346900596667207618480809067860692097713761984609779945772783965563851033300772326297773087851869982500270661791244122597621760000000000000000000000000000000",
"385620482362580421735677065923463640617493109590223590278828403276373402575165543560686168588507361534030051833058916347592172932262498857766114955245039357760034644709279247692495585280000000000000000000000000000000",
"49745042224772874403902341504126809639656611137138843145968864022652168932196355119328515747917449637889876686464600208839390308261862352651828829226610077151044469167497022952331930501120000000000000000000000000000000",
"6466855489220473672507304395536485253155359447828049608975952322944781961185526165512707047229268452925683969240398027149120740074042105844737747799459310029635780991774612983803150965145600000000000000000000000000000000",
"847158069087882051098456875815279568163352087665474498775849754305766436915303927682164623187034167333264599970492141556534816949699515865660644961729169613882287309922474300878212776434073600000000000000000000000000000000",
"111824865119600430744996307607616902997562475571842633838412167568361169672820118454045730260688510087990927196104962685462595837360336094267205134948250389032461924909766607715924086489297715200000000000000000000000000000000",
"14872707060906857289084508911813048098675809251055070300508818286592035566485075754388082124671571841702793317081960037166525246368924700537538282948117301741317436012998958826217903503076596121600000000000000000000000000000000",
"1992942746161518876737324194182948445222558439641379420268181650403332765909000151088003004705990626788174304488982644980314383013435909872030129915047718433336536425741860482713199069412263880294400000000000000000000000000000000",
"269047270731805048359538766214698040105045389351586221736204522804449923397715020396880405635308734616403531106012657072342441706813847832724067538531441988500432417475151165166281874370655623839744000000000000000000000000000000000",
"36590428819525486576897272205198933454286172951815726156123815101405189582089242773975735166401987907830880230417721361838572072126683305250473185240276110436058808776620558462614334914409164842205184000000000000000000000000000000000",
"5012888748274991661034926292112253883237205694398754483388962668892510972746226260034675717797072343372830591567227826571884373881355612819314826377917827129740056802397016509378163883274055583382110208000000000000000000000000000000000",
"691778647261948849222819828311491035886734385827028118707676848307166514238979223884785249055995983385450621636277440066920043595627074569065446040152660143904127838730788278294186615891819670506731208704000000000000000000000000000000000",
"96157231969410890041971956135297253988256079629956908500367081914696145479218112119985149618783441690577636407442564169301886059792163365100096999581219760002673769583579570682891939608962934200435638009856000000000000000000000000000000000",
"13462012475717524605876073858941615558355851148193967190051391468057460367090535696797920946629681836680869097041958983702264048370902871114013579941370766400374327741701139895604871545254810788060989321379840000000000000000000000000000000000",
"1898143759076170969428526414110767793728175011895349373797246196996101911759765533248506853474785138972002542682916216702019230820297304827075914771733278062452780211579860725280286887880928321116599494314557440000000000000000000000000000000000",
"269536413788816277658850750803729026709400851689139611079208959973446471469886705721287973193419489734024361060974102771686730776482217285444779897586125484868294790044340222989800738079091821598557128192667156480000000000000000000000000000000000",
"38543707171800727705215657364933250819444321791546964384326881276202845420193798918144180166658987031965483631719296696351202501036957071818603525354815944336166154976340651887541505545310130488593669331551403376640000000000000000000000000000000000",
"5550293832739304789551054660550388117999982337982762871343070903773209740507907044212761943998894132603029642967578724274573160149321818341878907651093495984407926316593053871805976798524658790357488383743402086236160000000000000000000000000000000000",
"804792605747199194484902925779806277109997439007500616344745281047115412373646521410850481879839649227439298230298915019813108221651663659572441609408556917739149315905992811411866635786075524601835815642793302504243200000000000000000000000000000000000",
"117499720439091082394795827163851716458059626095095089986332811032878850206552392125984170354456588787206137541623641592892713800361142894297576474973649309989915800122274950466132528824767026591868029083847822165619507200000000000000000000000000000000000",
"17272458904546389112034986593086202319334765035978978227990923221833190980363201642519673042105118551719302218618675314155228928653088005461743741821126448568517622617974417718521481737240752909004600275325629858346067558400000000000000000000000000000000000",
"2556323917872865588581178015776757943261545225324888777742656636831312265093753843092911610231557545654456728355563946494973881440657024808338073789526714388140608147460213822341179297111631430532680840748193219035217998643200000000000000000000000000000000000",
"380892263763056972698595524350736933545970238573408427883655838887865527498969322620843829924502074302514052524979028027751108334657896696442372994639480443832950613971571859528835715269633083149369445271480789636247481797836800000000000000000000000000000000000",
"57133839564458545904789328652610540031895535786011264182548375833179829124845398393126574488675311145377107878746854204162666250198684504466355949195922066574942592095735778929325357290444962472405416790722118445437122269675520000000000000000000000000000000000000",
"8627209774233240431623188626544191544816225903687700891564804750810154197851655157362112747789971982951943289690774984828562603780001360174419748328584232052816331406456102618328128950857189333333217935399039885261005462721003520000000000000000000000000000000000000",
"1311335885683452545606724671234717114812066337360530535517850322123143438073451583919041137664075741408695380032997797693941515774560206746511801745944803272028082373781327597985875600530292778666649126180654062559672830333592535040000000000000000000000000000000000000",
"200634390509568239477828874698911718566246149616161171934231099284840946025238092339613294062603588435530393145048663047173051913507711632216305667129554900620296603188543122491838966881134795135997316305640071571629943041039657861120000000000000000000000000000000000000",
"30897696138473508879585646703632404659201907040888820477871589289865505687886666220300447285640952619071680544337494109264649994680187591361311072737951454695525676891035640863743200899694758450943586711068571022031011228320107310612480000000000000000000000000000000000000",
"4789142901463393876335775239063022722176295591337767174070096339929153381622433264146569329274347655956110484372311586936020749175429076661003216274382475477806479918110524333880196139452687559896255940215628508414806740389616633144934400000000000000000000000000000000000000",
"747106292628289444708380937293831544659502112248691679154935029028947927533099589206864815366798234329153235562080607562019236871366935959116501738803666174537810867225241796085310597754619259343815926673638047312709851500780194770609766400000000000000000000000000000000000000",
"117295687942641442819215807155131552511541831623044593627324799557544824622696635505477776012587322789677057983246655387237020188804608945581290772992175589402436306154362961985393763847475223716979100487761173428095446685622490578985733324800000000000000000000000000000000000000",
"18532718694937347965436097530510785296823609396441045793117318330092082290386068409865488609988797000768975161352971551183449189831128213401843942132763743125584936372389347993692214687901085347282697877066265401639080576328353511479745865318400000000000000000000000000000000000000",
"2946702272495038326504339507351214862194953894034126281105653614484641084171384877168612688988218723122267050655122476638168421183149385930893186799109435156968004883209906330997062135376272570217948962453536198860613811636208208325279592585625600000000000000000000000000000000000000",
"471472363599206132240694321176194377951192623045460204976904578317542573467421580346978030238114995699562728104819596262106947389303901748942909887857509625114880781313585012959529941660203611234871833992565791817698209861793313332044734813700096000000000000000000000000000000000000000",
"75907050539472187290751785709367294850142012310319093001281637109124354328254874435863462868336514307629599224875954998199218529677928181579808491945059049643495805791487187086484320607292781408814365272803092482649411787748723446459202305005715456000000000000000000000000000000000000000",
"12296942187394494341101789284917501765723005994271693066207625211678145401177289658609880984670515317835995074429904709708273401807824365415928975695099566042246320538220924308010459938381430588227927174194100982189204709615293198326390773410925903872000000000000000000000000000000000000000",
"2004401576545302577599591653441552787812849977066285969791842909503537700391898214353410600501293996807267197132074467682448564494675371562796423038301229264886150247730010662205704969956173185881152129393638460096840367667292791327201696065980922331136000000000000000000000000000000000000000",
"328721858553429622726333031164414657201307396238870899045862237158580182864271307153959338482212215476391820329660212699921564577126760936298613378281401599441328640627721748601735615072812402484508949220556707455881820297436017777661078154820871262306304000000000000000000000000000000000000000",
"54239106661315887749844950142128418438215720379413698342567269131165730172604765680403290849565015553604650354393935095487058155225915554489271207416431263907819225703574088519286376487014046409943976621391856730220500349076942933314077895545443758280540160000000000000000000000000000000000000000",
"9003691705778437366474261723593317460743809582982673924866166675773511208652391102946946281027792581898371958829393225850851653767501982045219020431127589808697991466793298694201538496844331704050700119151048217216603057946772526930136930660543663874569666560000000000000000000000000000000000000000",
"1503616514864999040201201707840084015944216200358106545452649834854176371844949314192140028931641361177028117124508668717092226179172831001551576411998307498052564574954480881931656928973003394576466919898225052275172710677111011997332867420310791867053134315520000000000000000000000000000000000000000",
"252607574497319838753801886917134114678628321660161899636045172255501630469951484784279524860515748677740723676917456344471493998101035608260664837215715659672830848592352788164518364067464570288846442542901808782229015393754650015551921726612213033664926565007360000000000000000000000000000000000000000",
"42690680090047052749392518888995665380688186360567361038491634111179775549421800928543239701427161526538182301399050122215682485679075017796052357489455946484708413412107621199803603527401512378815048789750405684196703601544535852628274771797464002689372589486243840000000000000000000000000000000000000000",
"7257415615307998967396728211129263114716991681296451376543577798900561843401706157852350749242617459511490991237838520776666022565442753025328900773207510902400430280058295603966612599658257104398558294257568966313439612262571094946806711205568880457193340212661452800000000000000000000000000000000000000000",
"1241018070217667823424840524103103992616605577501693185388951803611996075221691752992751978120487585576464959501670387052809889858690710767331242032218484364310473577889968548278290754541561964852153468318044293239598173696899657235903947616152278558180061176365108428800000000000000000000000000000000000000000",
"213455108077438865629072570145733886730056159330291227886899710221263324938130981514753340236723864719151973034287306573083301055694802251980973629541579310661401455397074590303866009781148657954570396550703618437210885875866741044575478989978191912006970522334798649753600000000000000000000000000000000000000000",
"36927733697396923753829554635211962404299715564140382424433649868278555214296659802052327860953228596413291334931704037143411082635200789592708437910693220744422451783693904122568819692138717826140678603271725989637483256524946200711557865266227200777205900363920166407372800000000000000000000000000000000000000000",
"6425425663347064733166342506526881458348150508160426541851455077080468607287618805557105047805861775775912692278116502462953528378524937389131268196460620409529506610362739317326974626432136901748478076969280322196922086635340638923811068556323532935233826663322108954882867200000000000000000000000000000000000000000",
"1124449491085736328304109938642204255210926338928074644824004638489082006275333290972493383366025810760784721148670387931016867466241864043097971934380608571667663656813479380532220559625623957805983663469624056384461365161184611811666936997356618263665919666081369067104501760000000000000000000000000000000000000000000",
"197903110431089593781523349201027948917123035651341137489024816374078433104458659211158835472420542693898110922165988275858968674058568071585243060450987108613508803599172370973670818494109816573853124770653833923665200268368491678853380911534764814405201861230320955810392309760000000000000000000000000000000000000000000",
"35028850546302858099329632808581946958330777310287381335557392498211882659489182680375113878618436056819965633223379924827037455308366548670588021699824718224591058237053509662339734873457437533572003084405728604488740447501223027157048421341653372149720729437766809178439438827520000000000000000000000000000000000000000000",
"6235135397241908741680674639927586558582878361231153877729215864681715113389074517106770270394081618113953882713761626619212667044889245663364667862568799843977208366195524719896472807475423880975816549024219691598995799655217698833954618998814300242650289839922492033762220111298560000000000000000000000000000000000000000000",
"1116089236106301664760840760547037993986335226660376544113529639778027005296644338562111878400540609642397745005763331164839067401035174973742275547399815172071920297548998924861468632538100874694671162275335324796220248138283968091277876800787759743434401881346126074043437399922442240000000000000000000000000000000000000000000",
"200896062499134299656951336898466838917540340798867777940435335160044860953395980941180138112097309735631594101037399609671032132186331495273609598531966730972945653558819806475064353856858157445040809209560358463319644664891114256430017824141796753818192338642302693327818731986039603200000000000000000000000000000000000000000000",
"36362187312343308237908191978622497844074801684595067807218795663968119832564672550353604998289613062149318532287769329350456815925726000644523337334285978306103163294146384971986648048091326497552386466930424881860855684345291680413833226169665212441092813294256787492335190489473168179200000000000000000000000000000000000000000000",
"6617918090846482099299290940109294607621613906596302340913820810842197809526770404164356109688709577311175972876374017941783140498482132117303247394840048051710775719534642064901569944752621422554534336981337328498675734550843085835317647162879068664278892019554735323605004669084116608614400000000000000000000000000000000000000000000",
"1211079010624906224171770242040000913194755344907123328387229208384122199143398983962077168073033852647945203036376445283346314711222230177466494273255728793463071956674839497876987299889729720327479783667584731115257659422804284707863129430806869565563037239578516564219715854442393339376435200000000000000000000000000000000000000000000",
"222838537954982745247605724535360168027834983462910692423250174342678484642385413049022198925438228887221917358693265932135721906864890352653834946279054097997205240028170467609365663179710268540256280194835590525207409333795988386246815815268464000063598852082447047816427717217400374445264076800000000000000000000000000000000000000000000",
"41225129521671807870807059039041631085149471940638478098301282253395519658841301414069106801206072344136054711358254197445108552770004715240959465061625008129482969405211536507732647688246399679947411836044584247163370726752257851455660925824665840011765787635252703846039127685219069272373854208000000000000000000000000000000000000000000000",
"7667874091030956263970112981261743381837801780958756926284038499131566656544482063016853865024329456009306176312635280724790190815220877034818460501462251512083832309369345790438272470013830340470218601504292669972386955175919960370752932203387846242188436500157002915363277749450746884661536882688000000000000000000000000000000000000000000000",
"1433892455022788821362411127495946012403668933039287545215115199337602964773818145784151672759549608273740254970462797495535765682446304005511052113773441032759676641852067662811956951892586273667930878481302729284836360617897032589330798322033527247289237625529359545172932939147289667431707397062656000000000000000000000000000000000000000000000",
"269571781544284298416133291969237850331889759411386058500441657475469357377477811407420514478795326355463167934447005929160723948299905153036077797389406914158819208668188720608647906955806219449571005154484913105549235796164642126794190084542303122490376673599519594492511392559690457477160990647779328000000000000000000000000000000000000000000000",
"50949066711869732400649192182185953712727164528751965056583473262863708544343306356002477236492316681182538739610484120611376826228682073923818703706597906776016830438287668195034454414647375475968919974197648576948805565475117361964101925978495290150681191310309203359084653193781496463183427232430292992000000000000000000000000000000000000000000000",
"9680322675255249156123346514615331205418161260462873360750859919944104623425228207640470674933540169424682360525991982916161596983449594045525553704253602287443197783274656957056546338783001340434094795097553229620273057440272298773179365935914105128629426348958748638226084106818484328004851174161755668480000000000000000000000000000000000000000000000",
"1848941630973752588819559184291528260234868800748408811903414244709323983074218587659329898912306172360114330860464468736986865023838872462695380757512438036901650776605459478797800350707553256022912105863632666857472153971092009065677258893759594079568220432651120989901182064402330506648926574264895332679680000000000000000000000000000000000000000000000",
"354996793146960497053355363383973425965094809743694491885455534984190204750249968830591340591162785093141951525209177997501478084577063512837513105442388103085116949108248219929177667335850225156399124325817472036634653562449665740610033707601842063277098323069015230061026956365247457276593902258859903874498560000000000000000000000000000000000000000000000",
"68514381077363375931297585133106871211263298280533036933892918251948709516798243984304128734094417522976396644365371353517785270323373257977640029350380903895427571177891906446331289795819093455185030994882772103070488137552785487937736505567155518212479976352319939401778202578492759254382623135959961447778222080000000000000000000000000000000000000000000000",
"13291789929008494930671731515822733014985079866423409165175226140878049646258859332955000974414316999457420949006882042582450342442734412047662165693973895355712948808511029850588270220388904130305896013007257787995674698685240384659920882080028170533221115412350068243944971300227595295350228888376232520868975083520000000000000000000000000000000000000000000000",
"2591899036156656511480987645585432937922090573952564787209169097471219681020477569926225190010791814894197085056341998303577816776333210349294122310324909594364025017659650820864712692975836305409649722536415268659156566243621875008684572005605493253978117505408263307569269403544381082593294633233365341569450141286400000000000000000000000000000000000000000000000",
"508012211086704676250273578534744855832729752494702698292997143104359057480013603705540137242115195719262628671043031667501252088161309228461647972823682280495348903461291560889483687823263915860291345617137392657194686983749887501702176113098676677779711031060019608283576803094698692188285748113739606947612227692134400000000000000000000000000000000000000000000000",
"100078405584080821221303894971344736599047761241456431563720437191558734323562679929991407036696693556694737848195477238497746661367777918006944650646265409257583733981874437495228286501182991424477395086576066353467353335798727837835328694280439305522603073118823862831864630209655642361092292378406702568679608855350476800000000000000000000000000000000000000000000000",
"19815524305648002601818171204326257846611456725808373449616646563928629396065410626138298593265945324225558093942704493222553838950820027765375040827960551033001579328411138624055200727234232302046524227142061137986535960488148111891395081467526982493475408477527124840709196781511817187496273890924527108598562553359394406400000000000000000000000000000000000000000000000",
"3943289336823952517761816069660925311475679888435866316473712666221797249817016714601521420059923119520886060694598194151288213951213185525309633124764149655567314286353816586186984944719612228107258321201270166459320656137141474266387621212037869516201606287027897843301130159520851620311758504293980894611113948118519486873600000000000000000000000000000000000000000000000",
"788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000"];
return factorial[n];
};
if(typeof module != 'undefined') module.exports = BigArith; | bigarith.js | /**
* bigarith.js - Written by Oso Oluwafemi Ebenezer
* The constructor for BigArith
* @param {string|number|null|BigArith} n Accepts no parameter, or number within the safe integer limit or string in "-123.456" form or
* "negative one hundred and twenty three point four five six" form or a constant "PI" form or a BigArith object
* Dependent on verify(), getter name()
*/
var BigArith=function(n){
//version
Object.defineProperty(this, 'version', {
enumerable: true,
writable: false,
value: "v0.0.7",
});
//Object name
Object.defineProperty(this, 'name', {
enumerable: true,
writable: false,
value: "BigArith"
});
//Word length support
Object.defineProperty(this, 'wordSupport', {
writable: false,
value: 1002 //up to (1x10^1,005) - 0.0{199}1
});
//Word decimal length support
Object.defineProperty(this, 'decimalSupport', {
writable: false,
value: 200 //200 decimal characters when using toWords()
});
//assign this.value
if(n == null) this.value = "0"
else if(typeof n == "object" && n.name == "BigArith") this.value = n.toString();
else if(typeof n == "undefined" /*null*/ || n == "") this.value = "0";
else if(n == "PI") this.value = "3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196";
else if(n == "E") this.value = "2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901";
/*else if(n == "LN2") this.value = "0.6931471805599453";
else if(n == "LN10") this.value = "2.302585092994046";
else if(n == "LOG2E") this.value = "1.4426950408889634";
else if(n == "LOG10E") this.value = "0.4342944819032518";*/
else if(n == "SQRT1_2") this.value = "0.70710678118654752440084436210484903928483593768847403658833986899536623923105351942519376716382078636750692311545614851246241802792536860632206074854996791570661133296375279637789997525057639103028574";
else if(n == "SQRT2") this.value = "1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147";
else this.value = this.verify(n);
};
/**
* Verify input evaluate to a valid number
* function verify
* @param {string|number|BigArth} n Number within the safe integer limit or string in "-123.456" or
* "negative one hundred and twenty three point four five six" form or a BigArith object
* @returns {string|NaN} - A string representation of @param in form "-123.456" or NaN if @param is not valid,
* or throws a RangeError if input is in number form but not within safe limits.
* Dependent on w_Dict()
*/
BigArith.prototype.verify = function(n){
//Can be an already verified BigArith object
if(typeof(n) == "object" && n.name == "BigArith") return n.toString();
//Can be a number in form of 1000 or 1e3
//Number must be within the safe integer range
if(typeof(n) == 'number' && n <= Number.MAX_SAFE_INTEGER && n >= Number.MIN_SAFE_INTEGER) return n.toString();
if(typeof(n) == 'number' && (n > Number.MAX_SAFE_INTEGER || n < Number.MIN_SAFE_INTEGER)) throw new RangeError("The number you entered in typeof 'number' form is not within the safe limit. Please enter the number as a string.");
//It can be string in form "-123.89"
if(typeof(n) == 'string' && /\d/.test(n)/*This just test if it contains any digit, real test in below*/){
n = n.replace(/^\s|\s$/g, "");
var sign = false;
if(n[0] == "-"){
sign = true;
n = n.slice(1, n.length);
}
else if(n[0] == "+"){
n = n.slice(1, n.length);
}
n = n.split(".");
if(n.length > 2) return NaN;
if(n[0] == "") n[0] = "0";
if(typeof(n[1]) == 'undefined') n[1] = "0";
if(/^\d+$/.test(n[0]) && /^\d+$/.test(n[1])/*Test that it contains only digits*/){
//Remove unnecessary zeroes
n[0] = n[0].replace(/^[0]+/g, "");
n[1] = n[1].replace(/[0]+$/g, "");
return ((sign)?"-":"") + ((n[0] == "")?"0":n[0]) + ((n[1] == "")?"":"."+n[1]);
}
else
return NaN;
}
//It can be string in form of "negative one thousand point one two"
if(typeof(n) == 'string'){
n = n.toLowerCase();
n = n.replace(/^\s|\s$/g, "").replace(/\s+/g, " ");
n = n.replace(/\s(and)\s/g, " ");
var fNum, dNum = fNum = "";
//Is Negative or Positive?
var sign = false;
n = n.split(" ");
if(n[0] == "negative"){
sign = true;
n.shift();
}
else if(n[0] == "positive"){
n.shift();
}
//The Mantissa part
if(n.indexOf("point") >= 0){
var decimal = n.splice(n.indexOf("point"), n.length - n.indexOf("point")); decimal.shift();
dNum = decimal.map(a=>{return typeof this.w_Dict(a) != "undefined"&&this.w_Dict(a).length<2&&this.w_Dict(a).length>0?this.w_Dict(a):NaN}).join("");
}
else dNum = "0";
//The Characteristic part
if(n.includes("zero") && n.lastIndexOf("zero") != 0) return NaN;
var subArray = [];
var subString = "";
var prevSuffix = "0".repeat(this.wordSupport);
var prevHSuffix = false; //To check have we gotten an hundred earlier?
var prevValue = false;
for(var i = 0; i < n.length; i++){
if(typeof(this.w_Dict(n[i])) == 'undefined')return NaN; //Spelling errors and what-nots
if(this.w_Dict(n[i]).length >= 3/*thousand and above*/){
if(prevSuffix.length < this.w_Dict(n[i]).length) return NaN; //"one million three billion" is wrong
if(!prevValue) return NaN; //"one million thousnad" is wrong
subString += this.w_Dict(n[i]);
subArray.push(subString);
subString = "";
prevSuffix = this.w_Dict(n[i]);
prevValue = false;
prevHSuffix = false;
}
else if(n[i] == "hundred"){
if(prevHSuffix) return NaN; // "one hundred two hundred" is wrong
if(typeof this.w_Dict(n[i-1]) == 'undefined') return NaN; //"hundred thousand" is wrong
if(this.w_Dict(n[i-1]).length > 1) return NaN;
subString += this.w_Dict(n[i]);
prevHSuffix = true;
}
else{
if(typeof this.w_Dict(n[i-1])!='undefined'&&(this.w_Dict(n[i]).length>this.w_Dict(n[i-1]).length||(this.w_Dict(n[i]).length==1&&this.w_Dict(n[i-1]).length==1))) return NaN; //one ninety is wrong, eight hundred and six three is wrong
subString = subString.substr(0, subString.length - this.w_Dict(n[i]).length) + this.w_Dict(n[i]);
prevValue = true;
}
}
subArray.push(subString);
for(var i = 0; i < subArray.length; i++){
fNum = fNum.substr(0, fNum.length - subArray[i].length) + subArray[i];
}
if(fNum == "") fNum = "0";
//output
if(/^\d+$/.test(fNum) && /^\d+$/.test(dNum)/*Test that it contains only digits*/){
//Remove unnecessary zeros
fNum = fNum.replace(/^[0]+/g, "");
dNum = dNum.replace(/[0]+$/g, "");
return (sign?"-":"") + ((fNum == "")?"0":fNum) + ((dNum == "")?"":"."+dNum);
}
else return NaN;
}
//That's all we support
return NaN;
};
/**
* Returns the this.value as a number
* @return {number} - this.value
*/
BigArith.prototype.valueOf=function(){
return this.value*1;
};
/**
* Returns the this.value as a string
* @return {string} - this.value
*/
BigArith.prototype.toString=function(){
return this.value;
};
/**
* Returns true if this.value is negative, false otherwise
* @return {boolean} - this.value is less than positive zero
*/
BigArith.prototype.isNegative=function(){
if(isNaN(this.value)) return NaN;
if(this.value[0] == "-") return true;
return false;
}
/**
* Returns true if this.value is positive, false otherwise
* @return {boolean} - this.value is greater than negative zero
*/
BigArith.prototype.isPositive=function(){
if(isNaN(this.value)) return NaN;
if(this.value[0] == "-") return false;
return true;
}
/**
* Returns true if this.value is integer, false otherwise
* @return {boolean} - this.value is integer?
*/
BigArith.prototype.isInteger=function(){
if(isNaN(this.value)) return NaN;
if(this.value.indexOf(".") == -1) return true;
return false;
}
/**
* Returns true if this.value is even, false otherwise
* @return {boolean} - this.value is even?
* Dependent on floor(), static divide(), isInteger(), static compare()
*/
BigArith.prototype.isEven=function(){
if(isNaN(this.value)) return NaN;
var d = new BigArith(this.value);
if(!d.isInteger()) return false;
d = BigArith.divide(this.value[this.value.length-1], 2);
if(BigArith.compare(d, d.floor()) == 0) return true;
return false;
}
/**
* Returns true if this.value is NOT even and is an integer, false otherwise
* @return {boolean} - this.value is NOT even and is an integer?
* Dependent on isEven(), isInteger()
*/
BigArith.prototype.isOdd=function(){
if(isNaN(this.value)) return NaN;
var d = new BigArith(this.value);
if(!d.isEven() && d.isInteger()) return true;
return false;
}
/**
* Returns square of this.value
* function square
* @return {BigArith} - product of this.value and this.value
* Dependent on static multiply()
*/
BigArith.prototype.square=function(){
return BigArith.multiply(this.value, this.value);
}
/** [NEEDS OPTIMIZATION - n tends to gets very large within few calculations and this slows down calculation speed. Takes 9105ms to calculate sqrt 2 to 200 decimal place]
* Returns square root of this.value
* function squareRoot
* @return {BigArith} - root of this.value
*/
BigArith.prototype.squareRoot=function(){
var n = this.value;
if(isNaN(n) || new BigArith(n).isNegative()) return NaN;
//Find the perfect square just less than or equal to n
var ps = BigArith.perfectSq(n);
var result = ps;
var quotient = ps;
n = BigArith.subtract(n, BigArith.multiply(ps, ps));
//If reminder (n) is 0, return result we have reached the end of calculation
if(BigArith.compare(n, 0) == 0) return new BigArith(result);
//If we got here that means we have reminders
n = BigArith.multiply(n, 100); //multiply reminder by 100
result += ".";
for(var count = 0; count <= new BigArith().decimalSupport+1; count++){
// take quotient double it and multiply by 10
var j = BigArith.multiply(quotient, 20);
//Find a number bewteen j+1 and j+9 such that (j+i)*i will just be less than or equal to n
var i = 1;
for(; i <= 9; i++){
var g = BigArith.multiply(BigArith.add(j,i), i); //(j+i)*i
if(BigArith.compare(g, n) >= 0 || BigArith.compare(n, 0) == 0) break;
}
//If (j+i)*i > n or i == 10, reduce i by 1
var ji = BigArith.multiply(BigArith.add(j,i), i); //(j+i)*i
if(i == 10 || BigArith.compare(BigArith.multiply(BigArith.add(j,i), i), n) == 1) i--;
n = BigArith.multiply(BigArith.subtract(n, BigArith.multiply(BigArith.add(j,i), i)),100);//(n-(j+i)*i)*100;
result += i;
quotient += i.toString();
//If reminder is 0, break we have reached the end of calculation
if(BigArith.compare(n, 0) == 0) break;
}
return new BigArith(new BigArith(result).toFixed(new BigArith().decimalSupport));
}
/** [NEEDS OPTIMIZATION - incase n is very large]
* Returns the square root of the perfect square just below or equals to n
* function perfectSq
* @param - {string|number|BigArth} n The number to find the perfect square before
* @return {string} - the perfect square just less than n or n if it is a perfect square
*/
BigArith.perfectSq=function(n){
var n = new BigArith(n).toString();
//start counting from 1 to we get to i*i<=n
//This is not the best idea if n is very large
var i = new BigArith(1);
while(true){
if(BigArith.compare(new BigArith(i).square(), n) >= 0) break;
i = BigArith.add(i, 1);
}
return (BigArith.compare(BigArith.multiply(i, i), n) == 0)?i.toString():i.subtract(1).toString();
}
/**
* Return the absolute value of this.value
* function abs
* @returns {BigArith} - Absolute value of this.value
* Dependent on static abs()
*/
BigArith.prototype.abs=function(){
return BigArith.abs(this.value);
}
/**
* Return the absolute value of n
* function abs
* @param {string|number|BigArth} n value to find absolute of.
* @returns {BigArith} - Absolute value of n
* Dependent on isNegative(), negate(), isNaN() (native)
*/
BigArith.abs=function(n){
var n=new BigArith(n);
if(isNaN(n)) return NaN;
return (n.isNegative())?n.negate():n;
}
/**
* Returns a number with it sign changed
* function negate
* @returns {BigArith} - this.value with the sign changed
* Dependent on static negate()
*/
BigArith.prototype.negate=function(){
return BigArith.negate(this.value);
}
/**
* Returns a number with it sign changed
* function negate
* @param {string|number|BigArth} n number to negate
* @returns {BigArith} - number with the sign changed
* Dependent toString()
*/
BigArith.negate=function(n){
var n = new BigArith(n);
if(isNaN(n)) return NaN;
return (n.toString()[0] == "-")?new BigArith(n.toString().substr(1)):new BigArith("-"+n);
}
/**
* Returns the characteristic part (part before the decimal point) of a number
* function truncate
* @returns {BigArith} - characteristic part of the number
* Dependent static truncate()
*/
BigArith.prototype.truncate=function(){
return BigArith.truncate(this.value);
}
/**
* Returns the characteristic part (part before the decimal point) of a number
* function truncate
* @param {string|number|BigArth} n number to truncate
* @returns {BigArith} - characteristic part of the number
* Dependent isNaN(), toString(), indexOf()
*/
BigArith.truncate=function(n){
var n = new BigArith(n);
if(isNaN(n)) return NaN;
if(n.toString().indexOf(".") == -1) return n;
return new BigArith(n.toString().split(".")[0]);
}
/**
* Comparing this.value to n
* function compare
* @param {string|number|BigArth} n the number this.value is to be compared to. Can be negative and fractional
* @returns {number} (-1 if this.value < n), (0 if this.value == n), (1 if this.value > n)
* Dependent on static compare()
*/
BigArith.prototype.compare=function(n){
return BigArith.compare(this.value, n);
}
/**
* Comparing a to b
* function compare
* @param {string|number|BigArth} a number to be compared. Can be negative and fractional
* @param {string|number|BigArth} b number to be compared. Can be negative and fractional
* @returns {number} - (-1 if a < b), (0 if a == b), (1 if a > b)
* Dependent on toString(), isNegative(), isPositive(), abs(), Math.max() (can't use BigArith.max, it's dependent on compare)
*/
BigArith.compare=function(a, b){
var a = new BigArith(a);
var b = new BigArith(b);
if(isNaN(a) || isNaN(b)) return NaN;
//Check for signs
var cSign = false, c = "";
var dSign = false, d = "";
if(a.isNegative()){
cSign = true;
c = a.abs().toString();
}else c=a.toString();
if(b.isNegative()){
dSign = true;
d = b.abs().toString();
}else d=b.toString();
c = c.split("."); d = d.split(".");
(typeof c[1] == 'undefined')?c[1]='0':0;
(typeof d[1] == 'undefined')?d[1]='0':0;
c[1]=c[1].replace(/[0]*$/g,""); if(c[1] == "") c[1] ="0";
d[1]=d[1].replace(/[0]*$/g,""); if(d[1] == "") d[1] ="0";
var max = Math.max(c[1].length, d[1].length);
c[1] += "0".repeat(max - c[1].length);
d[1] += "0".repeat(max - d[1].length);
if(cSign && dSign==false) return -1;
if(dSign && cSign==false) return 1;
if(c[0].length < d[0].length) return (cSign && dSign)?1:-1;
if(c[0].length > d[0].length) return (cSign && dSign)?-1:1;
//check characteristic
for(var i = 0; i < c[0].length/*Length is equal so pick one*/; i++){
if(c[0][i] > d[0][i]) return (cSign && dSign)?-1:1;
if(c[0][i] < d[0][i]) return (cSign && dSign)?1:-1;
}
//check mantissa
for(var i = 0; i < Math.max(c[1].length, d[1].length); i++){
if(c[1][i] > d[1][i]) return (cSign && dSign)?-1:1;
if(c[1][i] < d[1][i]) return (cSign && dSign)?1:-1;
}
return 0;
}
/**
* Comparing absolute value of this.value to absolute value of n
* function compareAbs
* @param {string|number|BigArth} n value to be comapared with this.value
* @returns {string} - (-1 if abs(a) < abs(b)) - (0 if abs(a) == abs(b)) - (1 if abs(a) > abs(b))
* Dependent on static compareAbs()
*/
BigArith.prototype.compareAbs=function(n){
return BigArith.compareAbs(this.value, n);
}
/**
* Comparing absolute value of a to absolute value of b
* function compareAbs
* @param {string|number|BigArth} a value to be compare
* @param {string|number|BigArth} b value to be compare
* @returns {string} - (-1 if abs(a) < abs(b)) - (0 if abs(a) == abs(b)) - (1 if abs(a) > abs(b))
* Dependent on static compare(), abs()
*/
BigArith.compareAbs=function(a, b){
return BigArith.compare(new BigArith(a).abs(), new BigArith(b).abs());
}
/**
* Returns the minimum between this.value and n
* function min
* @param {string|number|BigArth} - optional - zero or more parameters
* @returns {BigArith} - The smallest number between this.value and parameters
* Dependent on static min()
*/
BigArith.prototype.min=function(){
return BigArith.min(this.value, ...arguments);
}
/**
* Returns the minimum between a and b
* function min
* @param {string|number|BigArth|Array} - optional - zero or more parameters
* @returns {BigArith} - The smallest number between parameters
* Dependent on static compare(), valueOf()
*/
BigArith.min=function(){
var args = BigArith.extract(arguments);
var result = new BigArith(args[0]);
for(var i = 0; i < args.length; i++){
if(isNaN(new BigArith(args[i]).valueOf())) return NaN;
result = (BigArith.compare(result, args[i]) == -1)?result:new BigArith(args[i]);
}
return result;
}
/**
* Returns the maximum between this.value and n
* function max
* @param {string|number|BigArth} - optional - zero or more parameters
* @returns {BigArith} - The largest number between this.value and parameters
* Dependent on static max()
*/
BigArith.prototype.max=function(){
return BigArith.max(this.value, ...arguments);
}
/**
* Returns the maximum between a and b
* function max
* @param {string|number|BigArth|Array} - optional - zero or more parameters
* @returns {BigArith} - The largest number between parameters
* Dependent on static compare(), valueOf()
*/
BigArith.max=function(){
var args = BigArith.extract(arguments);
var result = new BigArith(args[0]);
for(var i = 0; i < args.length; i++){
if(isNaN(new BigArith(args[i]).valueOf())) return NaN;
result = (BigArith.compare(result, args[i]) == 1)?result:new BigArith(args[i]);
}
return result;
}
//TODO
BigArith.extract=function(a){
var args = [];
for(var k in a){
if(typeof a[k] == "number" || typeof a[k] == "string"){args.push(a[k]);}
else if(typeof a[k] == "object" && a[k].name == "BigArith"){args.push(a[k].toString());}
else if(typeof a[k] == "object"){args.push(...BigArith.extract(a[k]));}
}
return args;
}
/**
* Returns largest integer less than or equal to this.value
* function floor
* @returns {BigArith} - floored value of this.value
* Dependent on static floor()
*/
BigArith.prototype.floor=function(){
return BigArith.floor(this.value);
}
/**
* Returns largest integer less than or equal to n
* function floor
* @param {string|number|BigArth} n number to floor
* @returns {BigArith} - floored number
* Dependent of subtract(), isNegative(), isInteger(), truncate()
*/
BigArith.floor=function(n){
var n = new BigArith(n);
if(isNaN(n)) return NaN;
if(!n.isInteger()){
n = n.truncate();
if(n.isNegative()){
n = BigArith.subtract(n, "1");
}
}
return n;
}
/**
* Ceil this.value
* function ceil
* @returns {BigArith} - ceiled value of this.value
* Dependent on static ceil()
*/
BigArith.prototype.ceil=function(){
return BigArith.ceil(this.value);
}
/**
* Returns smallest integer greater than or equals to number
* function ceil
* @param {string|number|BigArth} n number to ceil
* @returns {BigArith} - ceiled number
* Dependent of static add(), isNegative(), isPositive(), isInteger(), truncate()
*/
BigArith.ceil=function(n){
var n = new BigArith(n);
if(isNaN(n)) return NaN;
if(!n.isInteger()){
if(n.isPositive())
n = BigArith.add(n.truncate(), "1");
else if(n.isNegative())
n = n.truncate();
}
return n;
}
/**
* Round this.value to the nearest integer
* function round
* @returns {BigArith} - this.value rounded to nearest whole number e.g "1"
* Dependent on static round()
*/
BigArith.prototype.round=function(){
return BigArith.round(this.value);
}
/**
* Round n to the nearest integer
* function round
* @param {string|number|BigArith} n number to round e.g "0.5"
* @returns {BigArith} - n rounded to nearest whole number e.g "1"
* Dependent on toString(), static compare(), isPositive(), add(), subtract()
*/
BigArith.round=function(n){
var n = new BigArith(n);
if(isNaN(n)) return NaN;
n = n.toString();
if(n.indexOf(".")>-1){
n = n.split(".");
if(BigArith.compare(n[1][0], "5") >= 0){
if(new BigArith(n[0]).isPositive())
n[0] = BigArith.add(n[0], "1").toString();
else
n[0] = BigArith.subtract(n[0], "1").toString();
}
n = n[0];
}
return new BigArith(n);
}
/**
* Format a number to a number of decimal places
* function toFixed
* @param {string|number|BigArith} d number of decimal place to return this.value in.
* @returns {string} - this.value to a number of decimal places
* Dependent on static toFixed()
*/
BigArith.prototype.toFixed=function(d=0){
return BigArith.toFixed(this.value, d);
}
/**
* Round n to the nearest integer
* function round
* @param {string|number|BigArith} n number to format
* @param {string|number|BigArith} d number of decimal place to return n in.
* @returns {string} - n rounded to nearest whole number e.g "1"
* Dependent on toString(), static compare(), isInteger(), add(), subtract()
*/
BigArith.toFixed=function(n, d=0){
var e = new BigArith(d).floor().toString();
if(isNaN(n) || isNaN(e)) return NaN;
//if(BigArith.compare(e, 0) == -1 || BigArith.compare(e, new BigArith.decimalSupport) == 1 || isNaN(e)) throw new Error("Argument must be between 0 and "+ new BigArith.decimalSupport +"! " + e + " supplied.");
var n = new BigArith(n);
var sign = n.isNegative();
if(!n.isInteger()){
n = n.toString().split(".");
if(BigArith.compare(e, "0") == 0){
if(BigArith.compare(n[1][0], "5") >= 0){
if(!sign){
n[0] = BigArith.add(n[0], "1").toString();
}
else{
n[0] = BigArith.subtract(n[0], "1").toString();
}
n[1] = "0";
}
else n[1] = "0";
}
else if(BigArith.compare(n[1].length.toString(), e) == -1){ n[1] += "0".repeat(e - Number(n[1].length));}
else if(BigArith.compare(n[1].length.toString(), e) == 1){
if(BigArith.compare(n[1][e], "5") >= 0){
var z0 = n[1].slice(0, e).length;
var z1 = BigArith.add(n[1].slice(0, e), "0").toString().length; //To check if it have leading zeros hence 0.00456 can become 0.456
n[1] = BigArith.add(n[1].slice(0, e), "1").toString();
var z2 = n[1].length;
if(z0 != z1){//Has leading zero
n[1] = "0".repeat(z0-z1) + n[1];
}
if(z2 > z1){
if(n[1][0] != "0"){
n[0] = BigArith.add(n[0], "1").toString();
n[1] = "0".repeat(e);
}
else{
n[1] = n[1].substr(1);
}
}
}
else n[1] = n[1].slice(0, e);
}
n = n[0]+((n[1]!="0")?("."+n[1]):"");
}
else n=n.toString()+((BigArith.compare(e, "0") == 1)?("."+"0".repeat(e)):"");
return n;
}
/**
* Random number between 0 and 1 (1 exclusive)
* function random
* @returns {BigArith} - any number between 0 and 1 (1 exclusive)
* Dependent on Math.random(), floor(), toString(), valueOf()
*/
BigArith.random=function(){
var len = new BigArith(Math.random()*new BigArith().decimalSupport).floor().valueOf();
var n = "0";
for(var i = 0; i < len; i++){
n += new BigArith(Math.random()*10).floor().toString();
}
return (n == "0")?new BigArith(n):(new BigArith("0."+n.slice(1)));
}
/**
* Random integer between min and max (min inclusive, max exclusive)
* function randomInt
* @param {number|string|BigArith} min minimum integer that can be returned (inclusive)
* @param {number|string|BigArith} max maximum integer that can be returned (exclusive)
* @returns {BigArith} - any integer between min and max
* Dependent on static random(), floor(), toString(), multiply(), subtract(), add(), ceil()
*/
BigArith.randomInt=function(min, max){
var min = new BigArith(min).floor();
var max = new BigArith (max).ceil();
if(isNaN(min) || isNaN(max)) return NaN;
return (BigArith.random().multiply(BigArith.subtract(max, min)).add(min)).floor(); // floor((ran()*(max-min))+min)
}
/**
* Word representation of this.value
* @return {string} - this.value in English short scale naming system words e.g "one billion" for "1000000000".
* Throw error if value of this.value is higher than 1x10^124 - (0.0{199}1)
* Dependent on w_Dict2()
*/
BigArith.prototype.toWords = function(){
var n = this.value, sign = false;
if(this.value[0] == "-"){
n = this.value.substr(1);
sign = true;
}
else n=this.value;
n = n.split(".");
if(typeof n[0] == 'undefined') n[0] = "0";
if(typeof n[1] == 'undefined') n[1] = "0";
n[0] = n[0].replace(/^[0]*/g,""); if(n[0] == '') n[0] = "0";
n[1] = n[1].replace(/[0]*$/g,"");
if(n[0].length > this.wordSupport+3) throw new RangeError("Value higher than the recently supported range");
if(n[1].length > this.decimalSupport) throw new RangeError("Length of mantissa value greater than supported length");
//Characteristic part
//Break into chunks of 3 digits e.g. ["1","000"] for "1000"
var chunk = [], c = n[0];
for(var i = c.length; i > -1; i-=3){
chunk.unshift(c.slice((i-3>0)?i-3:0, i));
}(chunk[0] == "")?chunk.shift():0;
var word = "";
for(var i = 0; i < chunk.length; i++){
var m = chunk[i];
if(m =="000") continue;
if(m.length == 3){
if(m[0] != "0"){
word += this.w_Dict2(m[0]) + " hundred ";
if(m[1] + m[2] != "00") word += "and "
}
if(m[1] == "1") word += " "+this.w_Dict2(m[1]+m[2]);
else if(m[1] > "1") word += " "+this.w_Dict2(m[1]+"0");
if(m[2] != "0" && m[1] != "1") word += " "+this.w_Dict2(m[2]);
}
if(m.length == 2){
if(m[0] == "1")
{
word += " "+this.w_Dict2(m[0]+m[1]);
}
else{
if(m[0] != "0")
word += " "+this.w_Dict2(m[0]+"0");
if(m[1] != "0")
word += " "+this.w_Dict2(m[1]);
}
}
if(m.length == 1){
if(m[0] != "0")
word += " "+this.w_Dict2(m[0]);
else
word = this.w_Dict2(m[0]);
}
word += " "+this.w_Dict2("0".repeat(3*(chunk.length-i-1))) + " ";
}
//Mantissa part
if(n[1] != "") word += " point";
for(var i = 0; i < n[1].length; i++){
word += " "+this.w_Dict2(n[1][i]);
}
return (sign?"negative ":"") + word.replace(/\s+/g," ").trim();
}
/**
* Add n to this.value
* function add
* @param {number|string|BigArith} The summand with this.value as the second summand
* @returns {BigArith} - sum of this.value and @param
* Dependent of the static add()
*/
BigArith.prototype.add = function(n){
return BigArith.add(this.value, n);
}
/**
* Add two numbers together
* function add
* @param {number|string|BigArith} A summand.
* @param {number|string|BigArith} A summand.
* @returns {BigArith} - sum of a and b
* Dependent on toString(), floor(), substract(), abs(), max(), valueOf()
*/
BigArith.add = function(a, b){
var a = new BigArith(a);
var b = new BigArith(b);
var signFlag = "";
if(isNaN(a) || isNaN(b))
return NaN;
if(a.isNegative() && b.isPositive())
return BigArith.subtract(b, a.abs());
if(a.isPositive() && b.isNegative())
return BigArith.subtract(a, b.abs());
if(a.isNegative() && b.isNegative()){
signFlag = "-";
a = a.abs();
b = b.abs();
}
a = a.toString().split(".");
b = b.toString().split(".");
(typeof(a[1]) == 'undefined')?a[1]="0":0;
(typeof(b[1]) == 'undefined')?b[1]="0":0;
var max = BigArith.max(a[1].length, b[1].length).valueOf();
a[1] += "0".repeat(max - a[1].length);
b[1] += "0".repeat(max - b[1].length);
a = a[0] + a[1];
b = b[0] + b[1];
var result = "";
var flag = 0;
for(var i = a.length-1, j = b.length-1; i >= 0 || j >= 0; i--, j--)
{
var z = a.charAt(i)*1 + b.charAt(j)*1 + flag;
if(z>9 && (i>0 || j>0))
{
flag = new BigArith(z/10).floor().valueOf();
result = (z-flag*10)+result;
}
else
{
result = z+result;
flag = 0;
}
}
result = result.slice(0, result.length - max) + "." + result.slice(result.length - max);
result = result.replace(/^0+/g,"")/*Remove front zeros*/.replace(/\.0+$/g,"")/*Remove zeros after decimal point zeros*/;
if(result[0] == ".") result = "0" + result;
return ((result == "")? new BigArith("0") : new BigArith(((signFlag=="")?"":"-")+result));
}
/**
* Subtract n from this.value
* function subtract
* @param {number|string|BigArith} The subtrahend with this.value as the minuend
* @returns {BigArith} - difference of this.value and @param
* Dependent on static subtract
*/
BigArith.prototype.subtract=function(n){
return BigArith.subtract(this.value, n);
}
/**
* Subtract b from a
* function subtract
* @param {number|string|BigArith} The Minuend
* @param {number|string|BigArith} The subtrahend
* @returns {BigArith} - difference of a and b
* Dependent on add(), abs(), toString(), compare(), max(), valueOf()
*/
BigArith.subtract=function(a, b){
var a = new BigArith(a);
var b = new BigArith(b);
if(isNaN(a) || isNaN(b))
return NaN;
if(a.isNegative() && b.isPositive())
return BigArith.add(a, "-"+b.toString());
if(a.isPositive() && b.isNegative())
return BigArith.add(a, b.abs());
if(a.isNegative() && b.isNegative()){
//swap the absolute parameters
var temp = a.abs();
a = b.abs();
b = temp;
}
a = a.toString().split(".");
b = b.toString().split(".");
(typeof(a[1]) == 'undefined')?a[1]="0":0;
(typeof(b[1]) == 'undefined')?b[1]="0":0;
var max = BigArith.max(a[1].length, b[1].length).valueOf();
a[1] += "0".repeat(max - a[1].length);
b[1] += "0".repeat(max - b[1].length);
var signFlag = "";
if(BigArith.compare(a[0]+"."+a[1], b[0]+"."+b[1]) >= 0){
a = a[0]+a[1];
b = b[0]+b[1];
}
else{
//swap the parameters
var temp = a[0]+a[1];
a = b[0]+b[1];
b = temp;
signFlag = "-";
}
a = a.split("");
b = b.split("");
var result = "";
for(var i = a.length-1, j = b.length-1; i >= 0 || j >= 0; i--, j--){
if(isNaN(parseInt(b[j]))) b[j] = "0";
if(parseInt(a[i]) >= parseInt(b[j])){
result = (parseInt(a[i]) - parseInt(b[j])).toString() + result;
}
else if(parseInt(a[i]) < parseInt(b[j])){
if(i == 0)
result = (parseInt(a[i]) - parseInt(b[j])).toString() + result;
else{
result = (parseInt(a[i])+10 - parseInt(b[j])).toString() + result;
a[i-1] = parseInt(a[i-1])-1;
}
}
}
result = result.slice(0, result.length - max) + "." + result.slice(result.length - max);
result = result.replace(/^0+/g,"")/*Remove front zeros*/.replace(/\.0+$/g,"")/*Remove zeros after decimal point zeros*/;
if(result[0] == ".") result = "0" + result;
return ((result == "")? new BigArith("0") : new BigArith((signFlag+result)));
}
/**
* Multiplies n and this.value
* function multiply
* @param {number|string|BigArith} - the multiplier with this.value as the multiplicand
* @returns {BigArith} - product of this.value and @param
* Dependent on static multiply
*/
BigArith.prototype.multiply=function(n){
return BigArith.multiply(this.value, n);
}
/**
* Multiplies a and b
* function multiply
* @param {number|string|BigArith} - the multiplicand
* @param {number|string|BigArith} - the multiplier
* @returns {BigArith} - product of a and b
* Dependent on toString(), abs(), max(), static add(), valueOf()
*/
BigArith.multiply=function(a, b){
var a = new BigArith(a);
var b = new BigArith(b);
var signFlag = "";
if(isNaN(a) || isNaN(b)) return NaN;
if((a.isNegative() || b.isNegative()) && !(a.isNegative() && b.isNegative())) signFlag = "-";
a = a.abs().toString().split(".");
b = b.abs().toString().split(".");
(typeof(a[1]) == 'undefined')?a[1]="0":0;
(typeof(b[1]) == 'undefined')?b[1]="0":0;
var max = BigArith.max(a[1].length, b[1].length).valueOf();
a[1] += "0".repeat(max - a[1].length);
b[1] += "0".repeat(max - b[1].length);
a = a[0] + a[1];
b = b[0] + b[1];
var results = [];
for(var i = a.length-1; i >= 0; i--){
var subSum = "";
var flag = 0;
if(i < a.lastIndexOf(a.charAt(i))){ /* Do not need to compute already computed values, just copy answer from previous computation*/
results.push(results[a.length-1-a.lastIndexOf(a.charAt(i))]);
continue;
}
else{
for(var j = b.length-1; j >= 0; j--){
var z = a.charAt(i)*b.charAt(j)+flag;
if(z>9 && j>0){
flag = new BigArith(z/10).floor().valueOf();
subSum = (z-flag*10)+subSum;
}
else{
subSum = z+subSum;
flag = 0;
}
}
}
results.push(subSum);
}
// Sum all the answers
var result = "0";
for(var i = 0; i < results.length; i++) result = BigArith.add(result, results[i]+"0".repeat(i));
//Put the decimal point in the apropriate place
result = result.toString(); //It's a BigArith
if(max*2 > result.length) result = "0".repeat(max*2 - result.length) + result; //Problem with slice if result is shorter than max*2
result = result.slice(0, result.length - max*2) + "." + result.slice(result.length - max*2);
return ((BigArith.compare(new BigArith(result),0) == 0)?new BigArith("0"):new BigArith(signFlag+result));
}
/**
* Return this.value%n (reminder of this.value/n)
* function modulus
* @param {string|number|BigArth} n The divisor with this.value as the dividend
* @returns {BigArith} reminder of this.value/n
* Dependent on static modulus
*/
BigArith.prototype.modulus=function(n){
return BigArith.modulus(this.value, n);
}
/**
* Return a%b (reminder of a/b)
* function modulus
* @param {string|number|BigArth} a the dividend
* @param {string|number|BigArth} b the divisor.
* @returns {BigArith} - reminder of a/b
* Dependent on static compare, isInteger, isNegative, divWithRem, abs, static multiply, static subtract, static divide, toString
*/
BigArith.modulus=function(a, b){
var a = new BigArith(a);
var b = new BigArith(b);
if(BigArith.compare(b, "0") == 0 || isNaN(a) || isNaN(b)) return NaN;
if(a.isInteger() && b.isInteger())
return new BigArith(((a.isNegative())?"-":"")+BigArith.divWithRem(a, b)[1]);
else
return new BigArith(((a.isNegative())?"-":"")+BigArith.subtract(a.abs(), BigArith.multiply(BigArith.divide(a.abs(), b.abs()).toString().split(".")[0], b.abs())));
}
/**
* Return this.valus/n (division of this.valus and n)
* function divide
* @param {string|number|BigArth} The divisor with this.value as the dividend.
* @returns {BigArith} - The quotient to "decimalSupport" decimal places when necessary.
*/
BigArith.prototype.divide=function(n){
return BigArith.divide(this.value, n);
}
/**
* Return a/b (division of a/b)
* function divide
* @param {string|number|BigArth} The dividend.
* @param {string|number|BigArth} The divisor.
* @returns {BigArith} - The quotient to "decimalSupport" decimal places when necessary.
*/
BigArith.divide=function(a, b){
return BigArith.div(a, b, new BigArith().decimalSupport);
}
/**Helper**/
BigArith.div=function(a, b, d){
var a = new BigArith(a).toString().split(".");
var b = new BigArith(b).toString().split(".");
//Note where the decimal points are and remove them
var numeratorIndex = 0;
var denominatorIndex = 0;
if(typeof a[1] != "undefined")
numeratorIndex = a[1].length;
if(typeof b[1] != "undefined")
denominatorIndex = b[1].length;
a = a[0] + ((typeof a[1] != "undefined")?a[1]:"");
b = b[0] + ((typeof b[1] != "undefined")?b[1]:"");
var result = BigArith.divWithRem(a, b);
var rem = result[1];
var remResult = "0.";
/* If the decimal place index of denominator - numerator is positive,
we are likely going to encroach into the 200 decimal result
when shifting the decimal pointto the left. The best is to start count from -(denominator-numerator)
instead of 0 in this case.
*/
var count = (denominatorIndex-numeratorIndex>0)?(-1*(denominatorIndex-numeratorIndex)):0, c = 0;
var flag = false;
while(BigArith.compare(rem, "0") == 1 && BigArith.compare(count, d+1) == -1){
rem += "0";
var j = BigArith.divWithRem(rem, b);
remResult += j[0];
rem = j[1];
/*Don't count yet if quotient is still all 0's
This takes care of (x/x.y) returning (x.x) instead of (x.y)
where x is any single digit, and y is any 200 digits*/
if(j[0] > 0) flag = true; if(!flag) c++;
if(c > 201) break; //if we have gotten 0.00{199 more 0's}, no need to continue
if(flag)count++;
}
if(remResult == "0.") remResult = "0.0";
result = result[0] + "." + remResult.split(".")[1];
var dPosition = (result.indexOf(".") == -1)?result.length : result.indexOf("."); // decimal position in answer
//Numerator decimal point means we shift the decimal point in answer forward
//Denominator decimal point means we shift the decimal point in answer backward
dPosition = dPosition+denominatorIndex-numeratorIndex;
result = result.split(".");
if(dPosition < 0){
result = "0." + "0".repeat(-1*dPosition) + result[0] + result[1];
}
else if(dPosition == 0){
result = "0." + result[0] + result[1];
}
else if(dPosition > 0){
if(dPosition <= result[0].length){
result = result[0].slice(0, dPosition) + "." + result[0].slice(dPosition) + result[1];
}
else{
dPosition -= result[0].length;
result = result[0] + result[1].slice(0, dPosition) +
((dPosition-result[1].length>0)?"0".repeat(dPosition-result[1].length):"") + "." +
result[1].substr(dPosition)+ "0";
}
}
return new BigArith(new BigArith(result.replace(/^0+/,"")).toFixed(d));
};
/**
* Return a/b (division of a/b)
* function divWithRem
* @param {string|number|BigArth} a The dividend. Must always be integers.
* @param {String|Number|BigArth} b The divisor. Must always be integers.
* @returns {Array of "strings of digits" (integer)} - [quotient, reminder]
*/
BigArith.divWithRem=function(a, b){
var a = new BigArith(a);
var b = new BigArith(b);
if(isNaN(a) || isNaN(b))
return NaN;
if(!a.isInteger() || !b.isInteger()) throw new TypeError("divWithRem accepts only integers. Non integers passed in");
if(BigArith.compare(b, 0) == 0) throw new RangeError("Division by zero");
var signFlag = false;
if((a.isNegative() || b.isNegative()) && !(a.isNegative() && b.isNegative())) signFlag = true; //Only one of the parameters is negative
a = a.abs().toString();
b = b.abs().toString();
var aLen = a.length;
var aSub = "";
var result = "0";
var hold = a;
for(var i = 0; i < aLen; i++){
aSub += a[i];
if(BigArith.compare(aSub, "0") == 0){result += "0";}
else if(BigArith.compare(b, aSub) == 1){result += "0"; continue;}
else{
var count = 0;
hold = aSub;
while(BigArith.compare(hold, b) != -1){
hold = BigArith.subtract(hold, b);
count++;
}
result += count;
}
aSub = hold.toString();
}
hold = new BigArith(aSub).toString();
result = result.replace(/^0*/g,"");
result = (result == "")? "0" : result;
return [((signFlag)?"-":"")+result, hold.toString()];
};
/* [UNSTABLE - Takes a lot of computation time]
* Returns the sine of an angle (in degree)
* function sin
* @param {string|number|BigArth} n The angle in degree
* @returns {BigArith} - sine of n
* x - x^3/3! + x^5/5! - x^7/7! + x^9/9! - ... (x in radian)
*/
BigArith.sin=function(n){
//Have to use PI to atleast 203 decimal places so new BigArith("PI") won't work here as it is to 200 decimal place
var x = BigArith.div(new BigArith("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975"), 180, new BigArith().decimalSupport+3).multiply(n);
var tolerance = new BigArith("0." + "0".repeat(new BigArith().decimalSupport+3) + "1");
var sin = new BigArith("0");
var i = 1;
var term = x.toString(), _x = x.toString();
var sign = true;
while(BigArith.compare(term, tolerance) == 1){
if(i > 1){
_x = BigArith.multiply(_x, x.square()).toString().split(".");
//only the first 203 decimal digit is needed as _x gets very large quickly
_x = _x[0] + "." +_x[1].substr(0, new BigArith().decimalSupport+3);
term = BigArith.div(_x, BigArith.factorial(i), new BigArith().decimalSupport+3).toString();
}
if(sign)
sin = BigArith.add(sin, term);
else
sin = BigArith.subtract(sin, term);
sign = !sign;
i += 2;
}
return new BigArith(sin.toFixed(new BigArith().decimalSupport));
}
/* [UNSTABLE - Takes a lot of computation time]
* Returns the cosine of an angle (when angle is in degrees)
* function cos
* @param {string|number|BigArth} n The angle in degrees
* @returns {BigArith} - cosine of n
* 1 - x^2/2! + x^4/4! - x^6/6! + x8/8! - ... (x in radian)
*/
BigArith.cos=function(n){
//Have to use PI to atleast 203 decimal places so new BigArith("PI") won't work here as it is to 200 decimal place
var x = BigArith.div(new BigArith("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975"), 180, new BigArith().decimalSupport+3).multiply(n);
var tolerance = new BigArith("0." + "0".repeat(new BigArith().decimalSupport+3) + "1");
var cos = new BigArith("0");
var i = 0;
var term = "1", _x = "1";
var sign = true;
while(term == "1" || BigArith.compare(term, tolerance) == 1){
if(i > 1){
_x = BigArith.multiply(_x, x.square());
if(BigArith.compare(_x, "0") == 0) break;
_x = _x.toString().split(".");
//the first 203 decimal digit is needed as _x gets very large quickly
_x = _x[0] + "." +_x[1].substr(0, new BigArith().decimalSupport+3);
term = BigArith.div(_x, BigArith.factorial(i), new BigArith().decimalSupport+3).toString();
}
if(sign)
cos = BigArith.add(cos, term);
else
cos = BigArith.subtract(cos, term);
sign = !sign;
i += 2;
}
return new BigArith(cos.toFixed(new BigArith().decimalSupport));
}
/* [UNSTABLE - Takes a lot of computation time]
* Returns the tangent of an angle (when angle is in degrees)
* function cos
* @param {string|number|BigArth} n The angle in degrees
* @returns {BigArith} - tangent of n
* tan = sin/cos
*/
BigArith.tan=function(n){
var sin = BigArith.sin(n);
var cos = BigArith.cos(n);
return BigArith.divide(sin, cos);
}
/**
* Word Dictionary
* function w_Dict
* @param {string} - Word value for numbers e.g "one"
* @returns {string} - String value of @param e.g "1"
*/
BigArith.prototype.w_Dict=function(w){
/*Word Dictionary*/
var w_Dict = [];
w_Dict["zero"] = "0"; w_Dict["one"] = "1"; w_Dict["two"] = "2"; w_Dict["three"] = "3"; w_Dict["four"] = "4"; w_Dict["five"] = "5"; w_Dict["six"] = "6"; w_Dict["seven"] = "7"; w_Dict["eight"] = "8"; w_Dict["nine"] = "9"; w_Dict["ten"] = "10";
w_Dict["eleven"] = "11"; w_Dict["twelve"] = "12"; w_Dict["thirteen"] = "13"; w_Dict["fourteen"] = "14"; w_Dict["fifteen"] = "15"; w_Dict["sixteen"] = "16"; w_Dict["seventeen"] = "17"; w_Dict["eighteen"] = "18"; w_Dict["nineteen"] = "19"; w_Dict["twenty"] = "20";
w_Dict["thirty"] = "30"; w_Dict["forty"] = "40"; w_Dict["fifty"] = "50"; w_Dict["sixty"] = "60"; w_Dict["seventy"] = "70"; w_Dict["eighty"] = "80"; w_Dict["ninety"] = "90"; w_Dict["hundred"] = "0".repeat(2);
w_Dict["thousand"] = "0".repeat(3); w_Dict["million"]="0".repeat(6);w_Dict["billion"]="0".repeat(9);w_Dict["trillion"]="0".repeat(12);w_Dict["quadrillion"]="0".repeat(15);w_Dict["quintillion"]="0".repeat(18);w_Dict["sextillion"]="0".repeat(21);w_Dict["septillion"]="0".repeat(24);w_Dict["octillion"]="0".repeat(27);w_Dict["nonillion"]="0".repeat(30);w_Dict["decillion"]="0".repeat(33);w_Dict["undecillion"]="0".repeat(36);w_Dict["duodecillion"]="0".repeat(39);w_Dict["tredecillion"]="0".repeat(42);w_Dict["quattuordecillion"]="0".repeat(45);w_Dict["quindecillion"]="0".repeat(48);w_Dict["sexdecillion"]="0".repeat(51);w_Dict["septendecillion"]="0".repeat(54);w_Dict["octodecillion"]="0".repeat(57);w_Dict["novemdecillion"]="0".repeat(60);w_Dict["vigintillion"]="0".repeat(63);w_Dict["unvigintillion"]="0".repeat(66);w_Dict["duovigintillion"]="0".repeat(69);w_Dict["trevigintillion"]="0".repeat(72);w_Dict["quattuorvigintillion"]="0".repeat(75);w_Dict["quinvigintillion"]="0".repeat(78);w_Dict["sexvigintillion"]="0".repeat(81);w_Dict["septenvigintillion"]="0".repeat(84);w_Dict["octavigintillion"]="0".repeat(87);w_Dict["novemvigintillion"]="0".repeat(90);w_Dict["trigintillion"]="0".repeat(93);w_Dict["untrigintillion"]="0".repeat(96);w_Dict["duotrigintillion"]="0".repeat(99);w_Dict["tretrigintillion"]="0".repeat(102);w_Dict["quattuortrigintillion"]="0".repeat(105);w_Dict["quintrigintillion"]="0".repeat(108);w_Dict["sextrigintillion"]="0".repeat(111);w_Dict["septentrigintillion"]="0".repeat(114);w_Dict["octotrigintillion"]="0".repeat(117);w_Dict["novemtrigintillion"]="0".repeat(120);w_Dict["quadragintillion"]="0".repeat(123);w_Dict["unquadragintillion"]="0".repeat(126);w_Dict["duoquadragintillion"]="0".repeat(129);w_Dict["trequadragintillion"]="0".repeat(132);w_Dict["quattuorquadragintillion"]="0".repeat(135);w_Dict["quinquadragintillion"]="0".repeat(138);w_Dict["sexquadragintillion"]="0".repeat(141);w_Dict["septenquadragintillion"]="0".repeat(144);w_Dict["octaquadragintillion"]="0".repeat(147);w_Dict["novemquadragintillion"]="0".repeat(150);w_Dict["quinquagintillion"]="0".repeat(153);w_Dict["unquinquagintillion"]="0".repeat(156);w_Dict["duoquinquagintillion"]="0".repeat(159);w_Dict["trequinquagintillion"]="0".repeat(162);w_Dict["quattuorquinquagintillion"]="0".repeat(165);w_Dict["quinquinquagintillion"]="0".repeat(168);w_Dict["sexquinquagintillion"]="0".repeat(171);w_Dict["septenquinquagintillion"]="0".repeat(174);w_Dict["octaquinquagintillion"]="0".repeat(177);w_Dict["novemquinquagintillion"]="0".repeat(180);w_Dict["sexagintillion"]="0".repeat(183);w_Dict["unsexagintillion"]="0".repeat(186);w_Dict["duosexagintillion"]="0".repeat(189);w_Dict["tresexagintillion"]="0".repeat(192);w_Dict["quattuorsexagintillion"]="0".repeat(195);w_Dict["quinsexagintillion"]="0".repeat(198);w_Dict["sexsexagintillion"]="0".repeat(201);w_Dict["septensexagintillion"]="0".repeat(204);w_Dict["octasexagintillion"]="0".repeat(207);w_Dict["novemsexagintillion"]="0".repeat(210);w_Dict["septuagintillion"]="0".repeat(213);w_Dict["unseptuagintillion"]="0".repeat(216);w_Dict["duoseptuagintillion"]="0".repeat(219);w_Dict["treseptuagintillion"]="0".repeat(222);w_Dict["quattuorseptuagintillion"]="0".repeat(225);w_Dict["quinseptuagintillion"]="0".repeat(228);w_Dict["sexseptuagintillion"]="0".repeat(231);w_Dict["septenseptuagintillion"]="0".repeat(234);w_Dict["octaseptuagintillion"]="0".repeat(237);w_Dict["novemseptuagintillion"]="0".repeat(240);w_Dict["octagintillion"]="0".repeat(243);w_Dict["unoctogintillion"]="0".repeat(246);w_Dict["duooctogintillion"]="0".repeat(249);w_Dict["treoctogintillion"]="0".repeat(252);w_Dict["quattuoroctogintillion"]="0".repeat(255);w_Dict["quinoctogintillion"]="0".repeat(258);w_Dict["sexoctogintillion"]="0".repeat(261);w_Dict["septenoctogintillion"]="0".repeat(264);w_Dict["octaoctogintillion"]="0".repeat(267);w_Dict["novemoctogintillion"]="0".repeat(270);w_Dict["nonagintillion"]="0".repeat(273);w_Dict["unnonagintillion"]="0".repeat(276);w_Dict["duononagintillion"]="0".repeat(279);w_Dict["trenonagintillion"]="0".repeat(282);w_Dict["quattuornonagintillion"]="0".repeat(285);w_Dict["quinnonagintillion"]="0".repeat(288);w_Dict["sexnonagintillion"]="0".repeat(291);w_Dict["septennonagintillion"]="0".repeat(294);w_Dict["octanonagintillion"]="0".repeat(297);w_Dict["novemnonagintillion"]="0".repeat(300);w_Dict["centillion"]="0".repeat(303);w_Dict["cenuntillion"]="0".repeat(306);w_Dict["cendotillion"]="0".repeat(309);w_Dict["centretillion"]="0".repeat(312);w_Dict["cenquattuortillion"]="0".repeat(315);w_Dict["cenquintillion"]="0".repeat(318);w_Dict["censextillion"]="0".repeat(321);w_Dict["censeptentillion"]="0".repeat(324);w_Dict["cenoctotillion"]="0".repeat(327);w_Dict["cennovemtillion"]="0".repeat(330);w_Dict["cendecillion"]="0".repeat(333);w_Dict["cenundecillion"]="0".repeat(336);w_Dict["cendodecillion"]="0".repeat(339);w_Dict["centredecillion"]="0".repeat(342);w_Dict["cenquattuordecillion"]="0".repeat(345);w_Dict["cenquindecillion"]="0".repeat(348);w_Dict["censexdecillion"]="0".repeat(351);w_Dict["censeptendecillion"]="0".repeat(354);w_Dict["cenoctodecillion"]="0".repeat(357);w_Dict["cennovemdecillion"]="0".repeat(360);w_Dict["cenvigintillion"]="0".repeat(363);w_Dict["cenunvigintillion"]="0".repeat(366);w_Dict["cendovigintillion"]="0".repeat(369);w_Dict["centrevigintillion"]="0".repeat(372);w_Dict["cenquattuorvigintillion"]="0".repeat(375);w_Dict["cenquinvigintillion"]="0".repeat(378);w_Dict["censexvigintillion"]="0".repeat(381);w_Dict["censeptenvigintillion"]="0".repeat(384);w_Dict["cenoctovigintillion"]="0".repeat(387);w_Dict["cennovemvigintillion"]="0".repeat(390);w_Dict["centrigintillion"]="0".repeat(393);w_Dict["cenuntrigintillion"]="0".repeat(396);w_Dict["cendotrigintillion"]="0".repeat(399);w_Dict["centretrigintillion"]="0".repeat(402);w_Dict["cenquattuortrigintillion"]="0".repeat(405);w_Dict["cenquintrigintillion"]="0".repeat(408);w_Dict["censextrigintillion"]="0".repeat(411);w_Dict["censeptentrigintillion"]="0".repeat(414);w_Dict["cenoctotrigintillion"]="0".repeat(417);w_Dict["cennovemtrigintillion"]="0".repeat(420);w_Dict["cenquadragintillion"]="0".repeat(423);w_Dict["cenunquadragintillion"]="0".repeat(426);w_Dict["cendoquadragintillion"]="0".repeat(429);w_Dict["centrequadragintillion"]="0".repeat(432);w_Dict["cenquattuorquadragintillion"]="0".repeat(435);w_Dict["cenquinquadragintillion"]="0".repeat(438);w_Dict["censexquadragintillion"]="0".repeat(441);w_Dict["censeptenquadragintillion"]="0".repeat(444);w_Dict["cenoctoquadragintillion"]="0".repeat(447);w_Dict["cennovemquadragintillion"]="0".repeat(450);w_Dict["cenquinquagintillion"]="0".repeat(453);w_Dict["cenunquinquagintillion"]="0".repeat(456);w_Dict["cendoquinquagintillion"]="0".repeat(459);w_Dict["centrequinquagintillion"]="0".repeat(462);w_Dict["cenquattuorquinquagintillion"]="0".repeat(465);w_Dict["cenquinquinquagintillion"]="0".repeat(468);w_Dict["censexquinquagintillion"]="0".repeat(471);w_Dict["censeptenquinquagintillion"]="0".repeat(474);w_Dict["cenoctoquinquagintillion"]="0".repeat(477);w_Dict["cennovemquinquagintillion"]="0".repeat(480);w_Dict["censexagintillion"]="0".repeat(483);w_Dict["cenunsexagintillion"]="0".repeat(486);w_Dict["cendosexagintillion"]="0".repeat(489);w_Dict["centresexagintillion"]="0".repeat(492);w_Dict["cenquattuorsexagintillion"]="0".repeat(495);w_Dict["cenquinsexagintillion"]="0".repeat(498);w_Dict["censexsexagintillion"]="0".repeat(501);w_Dict["censeptensexagintillion"]="0".repeat(504);w_Dict["cenoctosexagintillion"]="0".repeat(507);w_Dict["cennovemsexagintillion"]="0".repeat(510);w_Dict["censeptuagintillion"]="0".repeat(513);w_Dict["cenunseptuagintillion"]="0".repeat(516);w_Dict["cendoseptuagintillion"]="0".repeat(519);w_Dict["centreseptuagintillion"]="0".repeat(522);w_Dict["cenquattuorseptuagintillion"]="0".repeat(525);w_Dict["cenquinseptuagintillion"]="0".repeat(528);w_Dict["censexseptuagintillion"]="0".repeat(531);w_Dict["censeptenseptuagintillion"]="0".repeat(534);w_Dict["cenoctoseptuagintillion"]="0".repeat(537);w_Dict["cennovemseptuagintillion"]="0".repeat(540);w_Dict["cenoctogintillion"]="0".repeat(543);w_Dict["cenunoctogintillion"]="0".repeat(546);w_Dict["cendooctogintillion"]="0".repeat(549);w_Dict["centreoctogintillion"]="0".repeat(552);w_Dict["cenquattuoroctogintillion"]="0".repeat(555);w_Dict["cenquinoctogintillion"]="0".repeat(558);w_Dict["censexoctogintillion"]="0".repeat(561);w_Dict["censeptenoctogintillion"]="0".repeat(564);w_Dict["cenoctooctogintillion"]="0".repeat(567);w_Dict["cennovemoctogintillion"]="0".repeat(570);w_Dict["cennonagintillion"]="0".repeat(573);w_Dict["cenunnonagintillion"]="0".repeat(576);w_Dict["cendononagintillion"]="0".repeat(579);w_Dict["centrenonagintillion"]="0".repeat(582);w_Dict["cenquattuornonagintillion"]="0".repeat(585);w_Dict["cenquinnonagintillion"]="0".repeat(588);w_Dict["censexnonagintillion"]="0".repeat(591);w_Dict["censeptennonagintillion"]="0".repeat(594);w_Dict["cenoctononagintillion"]="0".repeat(597);w_Dict["cennovemnonagintillion"]="0".repeat(600);w_Dict["duocentillion"]="0".repeat(603);w_Dict["duocenuntillion"]="0".repeat(606);w_Dict["duocendotillion"]="0".repeat(609);w_Dict["duocentretillion"]="0".repeat(612);w_Dict["duocenquattuortillion"]="0".repeat(615);w_Dict["duocenquintillion"]="0".repeat(618);w_Dict["duocensextillion"]="0".repeat(621);w_Dict["duocenseptentillion"]="0".repeat(624);w_Dict["duocenoctotillion"]="0".repeat(627);w_Dict["duocennovemtillion"]="0".repeat(630);w_Dict["duocendecillion"]="0".repeat(633);w_Dict["duocenundecillion"]="0".repeat(636);w_Dict["duocendodecillion"]="0".repeat(639);w_Dict["duocentredecillion"]="0".repeat(642);w_Dict["duocenquattuordecillion"]="0".repeat(645);w_Dict["duocenquindecillion"]="0".repeat(648);w_Dict["duocensexdecillion"]="0".repeat(651);w_Dict["duocenseptendecillion"]="0".repeat(654);w_Dict["duocenoctodecillion"]="0".repeat(657);w_Dict["duocennovemdecillion"]="0".repeat(660);w_Dict["duocenvigintillion"]="0".repeat(663);w_Dict["duocenunvigintillion"]="0".repeat(666);w_Dict["duocendovigintillion"]="0".repeat(669);w_Dict["duocentrevigintillion"]="0".repeat(672);w_Dict["duocenquattuorvigintillion"]="0".repeat(675);w_Dict["duocenquinvigintillion"]="0".repeat(678);w_Dict["duocensexvigintillion"]="0".repeat(681);w_Dict["duocenseptenvigintillion"]="0".repeat(684);w_Dict["duocenoctovigintillion"]="0".repeat(687);w_Dict["duocennovemvigintillion"]="0".repeat(690);w_Dict["duocentrigintillion"]="0".repeat(693);w_Dict["duocenuntrigintillion"]="0".repeat(696);w_Dict["duocendotrigintillion"]="0".repeat(699);w_Dict["duocentretrigintillion"]="0".repeat(702);w_Dict["duocenquattuortrigintillion"]="0".repeat(705);w_Dict["duocenquintrigintillion"]="0".repeat(708);w_Dict["duocensextrigintillion"]="0".repeat(711);w_Dict["duocenseptentrigintillion"]="0".repeat(714);w_Dict["duocenoctotrigintillion"]="0".repeat(717);w_Dict["duocennovemtrigintillion"]="0".repeat(720);w_Dict["duocenquadragintillion"]="0".repeat(723);w_Dict["duocenunquadragintillion"]="0".repeat(726);w_Dict["duocendoquadragintillion"]="0".repeat(729);w_Dict["duocentrequadragintillion"]="0".repeat(732);w_Dict["duocenquattuorquadragintillion"]="0".repeat(735);w_Dict["duocenquinquadragintillion"]="0".repeat(738);w_Dict["duocensexquadragintillion"]="0".repeat(741);w_Dict["duocenseptenquadragintillion"]="0".repeat(744);w_Dict["duocenoctoquadragintillion"]="0".repeat(747);w_Dict["duocennovemquadragintillion"]="0".repeat(750);w_Dict["duocenquinquagintillion"]="0".repeat(753);w_Dict["duocenunquinquagintillion"]="0".repeat(756);w_Dict["duocendoquinquagintillion"]="0".repeat(759);w_Dict["duocentrequinquagintillion"]="0".repeat(762);w_Dict["duocenquattuorquinquagintillion"]="0".repeat(765);w_Dict["duocenquinquinquagintillion"]="0".repeat(768);w_Dict["duocensexquinquagintillion"]="0".repeat(771);w_Dict["duocenseptenquinquagintillion"]="0".repeat(774);w_Dict["duocenoctoquinquagintillion"]="0".repeat(777);w_Dict["duocennovemquinquagintillion"]="0".repeat(780);w_Dict["duocensexagintillion"]="0".repeat(783);w_Dict["duocenunsexagintillion"]="0".repeat(786);w_Dict["duocendosexagintillion"]="0".repeat(789);w_Dict["duocentresexagintillion"]="0".repeat(792);w_Dict["duocenquattuorsexagintillion"]="0".repeat(795);w_Dict["duocenquinsexagintillion"]="0".repeat(798);w_Dict["duocensexsexagintillion"]="0".repeat(801);w_Dict["duocenseptensexagintillion"]="0".repeat(804);w_Dict["duocenoctosexagintillion"]="0".repeat(807);w_Dict["duocennovemsexagintillion"]="0".repeat(810);w_Dict["duocenseptuagintillion"]="0".repeat(813);w_Dict["duocenunseptuagintillion"]="0".repeat(816);w_Dict["duocendoseptuagintillion"]="0".repeat(819);w_Dict["duocentreseptuagintillion"]="0".repeat(822);w_Dict["duocenquattuorseptuagintillion"]="0".repeat(825);w_Dict["duocenquinseptuagintillion"]="0".repeat(828);w_Dict["duocensexseptuagintillion"]="0".repeat(831);w_Dict["duocenseptenseptuagintillion"]="0".repeat(834);w_Dict["duocenoctoseptuagintillion"]="0".repeat(837);w_Dict["duocennovemseptuagintillion"]="0".repeat(840);w_Dict["duocenoctogintillion"]="0".repeat(843);w_Dict["duocenunoctogintillion"]="0".repeat(846);w_Dict["duocendooctogintillion"]="0".repeat(849);w_Dict["duocentreoctogintillion"]="0".repeat(852);w_Dict["duocenquattuoroctogintillion"]="0".repeat(855);w_Dict["duocenquinoctogintillion"]="0".repeat(858);w_Dict["duocensexoctogintillion"]="0".repeat(861);w_Dict["duocenseptenoctogintillion"]="0".repeat(864);w_Dict["duocenoctooctogintillion"]="0".repeat(867);w_Dict["duocennovemoctogintillion"]="0".repeat(870);w_Dict["duocennonagintillion"]="0".repeat(873);w_Dict["duocenunnonagintillion"]="0".repeat(876);w_Dict["duocendononagintillion"]="0".repeat(879);w_Dict["duocentrenonagintillion"]="0".repeat(882);w_Dict["duocenquattuornonagintillion"]="0".repeat(885);w_Dict["duocenquinnonagintillion"]="0".repeat(888);w_Dict["duocensexnonagintillion"]="0".repeat(891);w_Dict["duocenseptennonagintillion"]="0".repeat(894);w_Dict["duocenoctononagintillion"]="0".repeat(897);w_Dict["duocennovemnonagintillion"]="0".repeat(900);w_Dict["trecentillion"]="0".repeat(903);w_Dict["trecenuntillion"]="0".repeat(906);w_Dict["trecendotillion"]="0".repeat(909);w_Dict["trecentretillion"]="0".repeat(912);w_Dict["trecenquattuortillion"]="0".repeat(915);w_Dict["trecenquintillion"]="0".repeat(918);w_Dict["trecensextillion"]="0".repeat(921);w_Dict["trecenseptentillion"]="0".repeat(924);w_Dict["trecenoctotillion"]="0".repeat(927);w_Dict["trecennovemtillion"]="0".repeat(930);w_Dict["trecendecillion"]="0".repeat(933);w_Dict["trecenundecillion"]="0".repeat(936);w_Dict["trecendodecillion"]="0".repeat(939);w_Dict["trecentredecillion"]="0".repeat(942);w_Dict["trecenquattuordecillion"]="0".repeat(945);w_Dict["trecenquindecillion"]="0".repeat(948);w_Dict["trecensexdecillion"]="0".repeat(951);w_Dict["trecenseptendecillion"]="0".repeat(954);w_Dict["trecenoctodecillion"]="0".repeat(957);w_Dict["trecennovemdecillion"]="0".repeat(960);w_Dict["trecenvigintillion"]="0".repeat(963);w_Dict["trecenunvigintillion"]="0".repeat(966);w_Dict["trecendovigintillion"]="0".repeat(969);w_Dict["trecentrevigintillion"]="0".repeat(972);w_Dict["trecenquattuorvigintillion"]="0".repeat(975);w_Dict["trecenquinvigintillion"]="0".repeat(978);w_Dict["trecensexvigintillion"]="0".repeat(981);w_Dict["trecenseptenvigintillion"]="0".repeat(984);w_Dict["trecenoctovigintillion"]="0".repeat(987);w_Dict["trecennovemvigintillion"]="0".repeat(990);w_Dict["trecentrigintillion"]="0".repeat(993);w_Dict["trecenuntrigintillion"]="0".repeat(996);w_Dict["trecendotrigintillion"]="0".repeat(999);w_Dict["trecentretrigintillion"]="0".repeat(1002);
return w_Dict[w];
};
/**
* Word Dictionary 2
* function w_Dict2
* @param {string} - Number as strings of digits e.g "1"
* @returns {String} - @param value in English short scale naming system words e.g "one billion" for "1000000000"
*/
BigArith.prototype.w_Dict2=function(w){
/*Word Dictionary*/
var w_Dict = []; w_Dict[""] = "";
w_Dict["0"] = "zero"; w_Dict["1"] = "one"; w_Dict["2"] = "two"; w_Dict["3"] = "three"; w_Dict["4"] = "four"; w_Dict["5"] = "five"; w_Dict["6"] = "six"; w_Dict["7"] = "seven"; w_Dict["8"] = "eight"; w_Dict["9"] = "nine"; w_Dict["10"] = "ten";
w_Dict["11"] = "eleven"; w_Dict["12"] = "twelve"; w_Dict["13"] = "thirteen"; w_Dict["14"] = "fourteen"; w_Dict["15"] = "fifteen"; w_Dict["16"] = "sixteen"; w_Dict["17"] = "seventeen"; w_Dict["18"] = "eighteen"; w_Dict["19"] = "nineteen"; w_Dict["20"] = "twenty";
w_Dict["30"] = "thirty"; w_Dict["40"] = "forty"; w_Dict["50"] = "fifty"; w_Dict["60"] = "sixty"; w_Dict["70"] = "seventy"; w_Dict["80"] = "eighty"; w_Dict["90"] = "ninety"; w_Dict["0".repeat(2)] = "hundred";
w_Dict["0".repeat(3)] = "thousand"; w_Dict["0".repeat(6)]="million";w_Dict["0".repeat(9)]="billion";w_Dict["0".repeat(12)]="trillion";w_Dict["0".repeat(15)]="quadrillion";w_Dict["0".repeat(18)]="quintillion";w_Dict["0".repeat(21)]="sextillion";w_Dict["0".repeat(24)]="septillion";w_Dict["0".repeat(27)]="octillion";w_Dict["0".repeat(30)]="nonillion";w_Dict["0".repeat(33)]="decillion";w_Dict["0".repeat(36)]="undecillion";w_Dict["0".repeat(39)]="duodecillion";w_Dict["0".repeat(42)]="tredecillion";w_Dict["0".repeat(45)]="quattuordecillion";w_Dict["0".repeat(48)]="quindecillion";w_Dict["0".repeat(51)]="sexdecillion";w_Dict["0".repeat(54)]="septendecillion";w_Dict["0".repeat(57)]="octodecillion";w_Dict["0".repeat(60)]="novemdecillion";w_Dict["0".repeat(63)]="vigintillion";w_Dict["0".repeat(66)]="unvigintillion";w_Dict["0".repeat(69)]="duovigintillion";w_Dict["0".repeat(72)]="trevigintillion";w_Dict["0".repeat(75)]="quattuorvigintillion";w_Dict["0".repeat(78)]="quinvigintillion";w_Dict["0".repeat(81)]="sexvigintillion";w_Dict["0".repeat(84)]="septenvigintillion";w_Dict["0".repeat(87)]="octavigintillion";w_Dict["0".repeat(90)]="novemvigintillion";w_Dict["0".repeat(93)]="trigintillion";w_Dict["0".repeat(96)]="untrigintillion";w_Dict["0".repeat(99)]="duotrigintillion";w_Dict["0".repeat(102)]="tretrigintillion";w_Dict["0".repeat(105)]="quattuortrigintillion";w_Dict["0".repeat(108)]="quintrigintillion";w_Dict["0".repeat(111)]="sextrigintillion";w_Dict["0".repeat(114)]="septentrigintillion";w_Dict["0".repeat(117)]="octotrigintillion";w_Dict["0".repeat(120)]="novemtrigintillion";w_Dict["0".repeat(123)]="quadragintillion";w_Dict["0".repeat(126)]="unquadragintillion";w_Dict["0".repeat(129)]="duoquadragintillion";w_Dict["0".repeat(132)]="trequadragintillion";w_Dict["0".repeat(135)]="quattuorquadragintillion";w_Dict["0".repeat(138)]="quinquadragintillion";w_Dict["0".repeat(141)]="sexquadragintillion";w_Dict["0".repeat(144)]="septenquadragintillion";w_Dict["0".repeat(147)]="octaquadragintillion";w_Dict["0".repeat(150)]="novemquadragintillion";w_Dict["0".repeat(153)]="quinquagintillion";w_Dict["0".repeat(156)]="unquinquagintillion";w_Dict["0".repeat(159)]="duoquinquagintillion";w_Dict["0".repeat(162)]="trequinquagintillion";w_Dict["0".repeat(165)]="quattuorquinquagintillion";w_Dict["0".repeat(168)]="quinquinquagintillion";w_Dict["0".repeat(171)]="sexquinquagintillion";w_Dict["0".repeat(174)]="septenquinquagintillion";w_Dict["0".repeat(177)]="octaquinquagintillion";w_Dict["0".repeat(180)]="novemquinquagintillion";w_Dict["0".repeat(183)]="sexagintillion";w_Dict["0".repeat(186)]="unsexagintillion";w_Dict["0".repeat(189)]="duosexagintillion";w_Dict["0".repeat(192)]="tresexagintillion";w_Dict["0".repeat(195)]="quattuorsexagintillion";w_Dict["0".repeat(198)]="quinsexagintillion";w_Dict["0".repeat(201)]="sexsexagintillion";w_Dict["0".repeat(204)]="septensexagintillion";w_Dict["0".repeat(207)]="octasexagintillion";w_Dict["0".repeat(210)]="novemsexagintillion";w_Dict["0".repeat(213)]="septuagintillion";w_Dict["0".repeat(216)]="unseptuagintillion";w_Dict["0".repeat(219)]="duoseptuagintillion";w_Dict["0".repeat(222)]="treseptuagintillion";w_Dict["0".repeat(225)]="quattuorseptuagintillion";w_Dict["0".repeat(228)]="quinseptuagintillion";w_Dict["0".repeat(231)]="sexseptuagintillion";w_Dict["0".repeat(234)]="septenseptuagintillion";w_Dict["0".repeat(237)]="octaseptuagintillion";w_Dict["0".repeat(240)]="novemseptuagintillion";w_Dict["0".repeat(243)]="octagintillion";w_Dict["0".repeat(246)]="unoctogintillion";w_Dict["0".repeat(249)]="duooctogintillion";w_Dict["0".repeat(252)]="treoctogintillion";w_Dict["0".repeat(255)]="quattuoroctogintillion";w_Dict["0".repeat(258)]="quinoctogintillion";w_Dict["0".repeat(261)]="sexoctogintillion";w_Dict["0".repeat(264)]="septenoctogintillion";w_Dict["0".repeat(267)]="octaoctogintillion";w_Dict["0".repeat(270)]="novemoctogintillion";w_Dict["0".repeat(273)]="nonagintillion";w_Dict["0".repeat(276)]="unnonagintillion";w_Dict["0".repeat(279)]="duononagintillion";w_Dict["0".repeat(282)]="trenonagintillion";w_Dict["0".repeat(285)]="quattuornonagintillion";w_Dict["0".repeat(288)]="quinnonagintillion";w_Dict["0".repeat(291)]="sexnonagintillion";w_Dict["0".repeat(294)]="septennonagintillion";w_Dict["0".repeat(297)]="octanonagintillion";w_Dict["0".repeat(300)]="novemnonagintillion";w_Dict["0".repeat(303)]="centillion";w_Dict["0".repeat(306)]="cenuntillion";w_Dict["0".repeat(309)]="cendotillion";w_Dict["0".repeat(312)]="centretillion";w_Dict["0".repeat(315)]="cenquattuortillion";w_Dict["0".repeat(318)]="cenquintillion";w_Dict["0".repeat(321)]="censextillion";w_Dict["0".repeat(324)]="censeptentillion";w_Dict["0".repeat(327)]="cenoctotillion";w_Dict["0".repeat(330)]="cennovemtillion";w_Dict["0".repeat(333)]="cendecillion";w_Dict["0".repeat(336)]="cenundecillion";w_Dict["0".repeat(339)]="cendodecillion";w_Dict["0".repeat(342)]="centredecillion";w_Dict["0".repeat(345)]="cenquattuordecillion";w_Dict["0".repeat(348)]="cenquindecillion";w_Dict["0".repeat(351)]="censexdecillion";w_Dict["0".repeat(354)]="censeptendecillion";w_Dict["0".repeat(357)]="cenoctodecillion";w_Dict["0".repeat(360)]="cennovemdecillion";w_Dict["0".repeat(363)]="cenvigintillion";w_Dict["0".repeat(366)]="cenunvigintillion";w_Dict["0".repeat(369)]="cendovigintillion";w_Dict["0".repeat(372)]="centrevigintillion";w_Dict["0".repeat(375)]="cenquattuorvigintillion";w_Dict["0".repeat(378)]="cenquinvigintillion";w_Dict["0".repeat(381)]="censexvigintillion";w_Dict["0".repeat(384)]="censeptenvigintillion";w_Dict["0".repeat(387)]="cenoctovigintillion";w_Dict["0".repeat(390)]="cennovemvigintillion";w_Dict["0".repeat(393)]="centrigintillion";w_Dict["0".repeat(396)]="cenuntrigintillion";w_Dict["0".repeat(399)]="cendotrigintillion";w_Dict["0".repeat(402)]="centretrigintillion";w_Dict["0".repeat(405)]="cenquattuortrigintillion";w_Dict["0".repeat(408)]="cenquintrigintillion";w_Dict["0".repeat(411)]="censextrigintillion";w_Dict["0".repeat(414)]="censeptentrigintillion";w_Dict["0".repeat(417)]="cenoctotrigintillion";w_Dict["0".repeat(420)]="cennovemtrigintillion";w_Dict["0".repeat(423)]="cenquadragintillion";w_Dict["0".repeat(426)]="cenunquadragintillion";w_Dict["0".repeat(429)]="cendoquadragintillion";w_Dict["0".repeat(432)]="centrequadragintillion";w_Dict["0".repeat(435)]="cenquattuorquadragintillion";w_Dict["0".repeat(438)]="cenquinquadragintillion";w_Dict["0".repeat(441)]="censexquadragintillion";w_Dict["0".repeat(444)]="censeptenquadragintillion";w_Dict["0".repeat(447)]="cenoctoquadragintillion";w_Dict["0".repeat(450)]="cennovemquadragintillion";w_Dict["0".repeat(453)]="cenquinquagintillion";w_Dict["0".repeat(456)]="cenunquinquagintillion";w_Dict["0".repeat(459)]="cendoquinquagintillion";w_Dict["0".repeat(462)]="centrequinquagintillion";w_Dict["0".repeat(465)]="cenquattuorquinquagintillion";w_Dict["0".repeat(468)]="cenquinquinquagintillion";w_Dict["0".repeat(471)]="censexquinquagintillion";w_Dict["0".repeat(474)]="censeptenquinquagintillion";w_Dict["0".repeat(477)]="cenoctoquinquagintillion";w_Dict["0".repeat(480)]="cennovemquinquagintillion";w_Dict["0".repeat(483)]="censexagintillion";w_Dict["0".repeat(486)]="cenunsexagintillion";w_Dict["0".repeat(489)]="cendosexagintillion";w_Dict["0".repeat(492)]="centresexagintillion";w_Dict["0".repeat(495)]="cenquattuorsexagintillion";w_Dict["0".repeat(498)]="cenquinsexagintillion";w_Dict["0".repeat(501)]="censexsexagintillion";w_Dict["0".repeat(504)]="censeptensexagintillion";w_Dict["0".repeat(507)]="cenoctosexagintillion";w_Dict["0".repeat(510)]="cennovemsexagintillion";w_Dict["0".repeat(513)]="censeptuagintillion";w_Dict["0".repeat(516)]="cenunseptuagintillion";w_Dict["0".repeat(519)]="cendoseptuagintillion";w_Dict["0".repeat(522)]="centreseptuagintillion";w_Dict["0".repeat(525)]="cenquattuorseptuagintillion";w_Dict["0".repeat(528)]="cenquinseptuagintillion";w_Dict["0".repeat(531)]="censexseptuagintillion";w_Dict["0".repeat(534)]="censeptenseptuagintillion";w_Dict["0".repeat(537)]="cenoctoseptuagintillion";w_Dict["0".repeat(540)]="cennovemseptuagintillion";w_Dict["0".repeat(543)]="cenoctogintillion";w_Dict["0".repeat(546)]="cenunoctogintillion";w_Dict["0".repeat(549)]="cendooctogintillion";w_Dict["0".repeat(552)]="centreoctogintillion";w_Dict["0".repeat(555)]="cenquattuoroctogintillion";w_Dict["0".repeat(558)]="cenquinoctogintillion";w_Dict["0".repeat(561)]="censexoctogintillion";w_Dict["0".repeat(564)]="censeptenoctogintillion";w_Dict["0".repeat(567)]="cenoctooctogintillion";w_Dict["0".repeat(570)]="cennovemoctogintillion";w_Dict["0".repeat(573)]="cennonagintillion";w_Dict["0".repeat(576)]="cenunnonagintillion";w_Dict["0".repeat(579)]="cendononagintillion";w_Dict["0".repeat(582)]="centrenonagintillion";w_Dict["0".repeat(585)]="cenquattuornonagintillion";w_Dict["0".repeat(588)]="cenquinnonagintillion";w_Dict["0".repeat(591)]="censexnonagintillion";w_Dict["0".repeat(594)]="censeptennonagintillion";w_Dict["0".repeat(597)]="cenoctononagintillion";w_Dict["0".repeat(600)]="cennovemnonagintillion";w_Dict["0".repeat(603)]="duocentillion";w_Dict["0".repeat(606)]="duocenuntillion";w_Dict["0".repeat(609)]="duocendotillion";w_Dict["0".repeat(612)]="duocentretillion";w_Dict["0".repeat(615)]="duocenquattuortillion";w_Dict["0".repeat(618)]="duocenquintillion";w_Dict["0".repeat(621)]="duocensextillion";w_Dict["0".repeat(624)]="duocenseptentillion";w_Dict["0".repeat(627)]="duocenoctotillion";w_Dict["0".repeat(630)]="duocennovemtillion";w_Dict["0".repeat(633)]="duocendecillion";w_Dict["0".repeat(636)]="duocenundecillion";w_Dict["0".repeat(639)]="duocendodecillion";w_Dict["0".repeat(642)]="duocentredecillion";w_Dict["0".repeat(645)]="duocenquattuordecillion";w_Dict["0".repeat(648)]="duocenquindecillion";w_Dict["0".repeat(651)]="duocensexdecillion";w_Dict["0".repeat(654)]="duocenseptendecillion";w_Dict["0".repeat(657)]="duocenoctodecillion";w_Dict["0".repeat(660)]="duocennovemdecillion";w_Dict["0".repeat(663)]="duocenvigintillion";w_Dict["0".repeat(666)]="duocenunvigintillion";w_Dict["0".repeat(669)]="duocendovigintillion";w_Dict["0".repeat(672)]="duocentrevigintillion";w_Dict["0".repeat(675)]="duocenquattuorvigintillion";w_Dict["0".repeat(678)]="duocenquinvigintillion";w_Dict["0".repeat(681)]="duocensexvigintillion";w_Dict["0".repeat(684)]="duocenseptenvigintillion";w_Dict["0".repeat(687)]="duocenoctovigintillion";w_Dict["0".repeat(690)]="duocennovemvigintillion";w_Dict["0".repeat(693)]="duocentrigintillion";w_Dict["0".repeat(696)]="duocenuntrigintillion";w_Dict["0".repeat(699)]="duocendotrigintillion";w_Dict["0".repeat(702)]="duocentretrigintillion";w_Dict["0".repeat(705)]="duocenquattuortrigintillion";w_Dict["0".repeat(708)]="duocenquintrigintillion";w_Dict["0".repeat(711)]="duocensextrigintillion";w_Dict["0".repeat(714)]="duocenseptentrigintillion";w_Dict["0".repeat(717)]="duocenoctotrigintillion";w_Dict["0".repeat(720)]="duocennovemtrigintillion";w_Dict["0".repeat(723)]="duocenquadragintillion";w_Dict["0".repeat(726)]="duocenunquadragintillion";w_Dict["0".repeat(729)]="duocendoquadragintillion";w_Dict["0".repeat(732)]="duocentrequadragintillion";w_Dict["0".repeat(735)]="duocenquattuorquadragintillion";w_Dict["0".repeat(738)]="duocenquinquadragintillion";w_Dict["0".repeat(741)]="duocensexquadragintillion";w_Dict["0".repeat(744)]="duocenseptenquadragintillion";w_Dict["0".repeat(747)]="duocenoctoquadragintillion";w_Dict["0".repeat(750)]="duocennovemquadragintillion";w_Dict["0".repeat(753)]="duocenquinquagintillion";w_Dict["0".repeat(756)]="duocenunquinquagintillion";w_Dict["0".repeat(759)]="duocendoquinquagintillion";w_Dict["0".repeat(762)]="duocentrequinquagintillion";w_Dict["0".repeat(765)]="duocenquattuorquinquagintillion";w_Dict["0".repeat(768)]="duocenquinquinquagintillion";w_Dict["0".repeat(771)]="duocensexquinquagintillion";w_Dict["0".repeat(774)]="duocenseptenquinquagintillion";w_Dict["0".repeat(777)]="duocenoctoquinquagintillion";w_Dict["0".repeat(780)]="duocennovemquinquagintillion";w_Dict["0".repeat(783)]="duocensexagintillion";w_Dict["0".repeat(786)]="duocenunsexagintillion";w_Dict["0".repeat(789)]="duocendosexagintillion";w_Dict["0".repeat(792)]="duocentresexagintillion";w_Dict["0".repeat(795)]="duocenquattuorsexagintillion";w_Dict["0".repeat(798)]="duocenquinsexagintillion";w_Dict["0".repeat(801)]="duocensexsexagintillion";w_Dict["0".repeat(804)]="duocenseptensexagintillion";w_Dict["0".repeat(807)]="duocenoctosexagintillion";w_Dict["0".repeat(810)]="duocennovemsexagintillion";w_Dict["0".repeat(813)]="duocenseptuagintillion";w_Dict["0".repeat(816)]="duocenunseptuagintillion";w_Dict["0".repeat(819)]="duocendoseptuagintillion";w_Dict["0".repeat(822)]="duocentreseptuagintillion";w_Dict["0".repeat(825)]="duocenquattuorseptuagintillion";w_Dict["0".repeat(828)]="duocenquinseptuagintillion";w_Dict["0".repeat(831)]="duocensexseptuagintillion";w_Dict["0".repeat(834)]="duocenseptenseptuagintillion";w_Dict["0".repeat(837)]="duocenoctoseptuagintillion";w_Dict["0".repeat(840)]="duocennovemseptuagintillion";w_Dict["0".repeat(843)]="duocenoctogintillion";w_Dict["0".repeat(846)]="duocenunoctogintillion";w_Dict["0".repeat(849)]="duocendooctogintillion";w_Dict["0".repeat(852)]="duocentreoctogintillion";w_Dict["0".repeat(855)]="duocenquattuoroctogintillion";w_Dict["0".repeat(858)]="duocenquinoctogintillion";w_Dict["0".repeat(861)]="duocensexoctogintillion";w_Dict["0".repeat(864)]="duocenseptenoctogintillion";w_Dict["0".repeat(867)]="duocenoctooctogintillion";w_Dict["0".repeat(870)]="duocennovemoctogintillion";w_Dict["0".repeat(873)]="duocennonagintillion";w_Dict["0".repeat(876)]="duocenunnonagintillion";w_Dict["0".repeat(879)]="duocendononagintillion";w_Dict["0".repeat(882)]="duocentrenonagintillion";w_Dict["0".repeat(885)]="duocenquattuornonagintillion";w_Dict["0".repeat(888)]="duocenquinnonagintillion";w_Dict["0".repeat(891)]="duocensexnonagintillion";w_Dict["0".repeat(894)]="duocenseptennonagintillion";w_Dict["0".repeat(897)]="duocenoctononagintillion";w_Dict["0".repeat(900)]="duocennovemnonagintillion";w_Dict["0".repeat(903)]="trecentillion";w_Dict["0".repeat(906)]="trecenuntillion";w_Dict["0".repeat(909)]="trecendotillion";w_Dict["0".repeat(912)]="trecentretillion";w_Dict["0".repeat(915)]="trecenquattuortillion";w_Dict["0".repeat(918)]="trecenquintillion";w_Dict["0".repeat(921)]="trecensextillion";w_Dict["0".repeat(924)]="trecenseptentillion";w_Dict["0".repeat(927)]="trecenoctotillion";w_Dict["0".repeat(930)]="trecennovemtillion";w_Dict["0".repeat(933)]="trecendecillion";w_Dict["0".repeat(936)]="trecenundecillion";w_Dict["0".repeat(939)]="trecendodecillion";w_Dict["0".repeat(942)]="trecentredecillion";w_Dict["0".repeat(945)]="trecenquattuordecillion";w_Dict["0".repeat(948)]="trecenquindecillion";w_Dict["0".repeat(951)]="trecensexdecillion";w_Dict["0".repeat(954)]="trecenseptendecillion";w_Dict["0".repeat(957)]="trecenoctodecillion";w_Dict["0".repeat(960)]="trecennovemdecillion";w_Dict["0".repeat(963)]="trecenvigintillion";w_Dict["0".repeat(966)]="trecenunvigintillion";w_Dict["0".repeat(969)]="trecendovigintillion";w_Dict["0".repeat(972)]="trecentrevigintillion";w_Dict["0".repeat(975)]="trecenquattuorvigintillion";w_Dict["0".repeat(978)]="trecenquinvigintillion";w_Dict["0".repeat(981)]="trecensexvigintillion";w_Dict["0".repeat(984)]="trecenseptenvigintillion";w_Dict["0".repeat(987)]="trecenoctovigintillion";w_Dict["0".repeat(990)]="trecennovemvigintillion";w_Dict["0".repeat(993)]="trecentrigintillion";w_Dict["0".repeat(996)]="trecenuntrigintillion";w_Dict["0".repeat(999)]="trecendotrigintillion";w_Dict["0".repeat(1002)]="trecentretrigintillion";
return w_Dict[w];
}
/*
* Factorial 0 to 200
* Precompiled factorial reduces computation time in calculating sine and cosine
* But increases file size by 34kb
*/
BigArith.factorial = function(n){
var factorial = [
"1",
"1",
"2",
"6",
"24",
"120",
"720",
"5040",
"40320",
"362880",
"3628800",
"39916800",
"479001600",
"6227020800",
"87178291200",
"1307674368000",
"20922789888000",
"355687428096000",
"6402373705728000",
"121645100408832000",
"2432902008176640000",
"51090942171709440000",
"1124000727777607680000",
"25852016738884976640000",
"620448401733239439360000",
"15511210043330985984000000",
"403291461126605635584000000",
"10888869450418352160768000000",
"304888344611713860501504000000",
"8841761993739701954543616000000",
"265252859812191058636308480000000",
"8222838654177922817725562880000000",
"263130836933693530167218012160000000",
"8683317618811886495518194401280000000",
"295232799039604140847618609643520000000",
"10333147966386144929666651337523200000000",
"371993326789901217467999448150835200000000",
"13763753091226345046315979581580902400000000",
"523022617466601111760007224100074291200000000",
"20397882081197443358640281739902897356800000000",
"815915283247897734345611269596115894272000000000",
"33452526613163807108170062053440751665152000000000",
"1405006117752879898543142606244511569936384000000000",
"60415263063373835637355132068513997507264512000000000",
"2658271574788448768043625811014615890319638528000000000",
"119622220865480194561963161495657715064383733760000000000",
"5502622159812088949850305428800254892961651752960000000000",
"258623241511168180642964355153611979969197632389120000000000",
"12413915592536072670862289047373375038521486354677760000000000",
"608281864034267560872252163321295376887552831379210240000000000",
"30414093201713378043612608166064768844377641568960512000000000000",
"1551118753287382280224243016469303211063259720016986112000000000000",
"80658175170943878571660636856403766975289505440883277824000000000000",
"4274883284060025564298013753389399649690343788366813724672000000000000",
"230843697339241380472092742683027581083278564571807941132288000000000000",
"12696403353658275925965100847566516959580321051449436762275840000000000000",
"710998587804863451854045647463724949736497978881168458687447040000000000000",
"40526919504877216755680601905432322134980384796226602145184481280000000000000",
"2350561331282878571829474910515074683828862318181142924420699914240000000000000",
"138683118545689835737939019720389406345902876772687432540821294940160000000000000",
"8320987112741390144276341183223364380754172606361245952449277696409600000000000000",
"507580213877224798800856812176625227226004528988036003099405939480985600000000000000",
"31469973260387937525653122354950764088012280797258232192163168247821107200000000000000",
"1982608315404440064116146708361898137544773690227268628106279599612729753600000000000000",
"126886932185884164103433389335161480802865516174545192198801894375214704230400000000000000",
"8247650592082470666723170306785496252186258551345437492922123134388955774976000000000000000",
"544344939077443064003729240247842752644293064388798874532860126869671081148416000000000000000",
"36471110918188685288249859096605464427167635314049524593701628500267962436943872000000000000000",
"2480035542436830599600990418569171581047399201355367672371710738018221445712183296000000000000000",
"171122452428141311372468338881272839092270544893520369393648040923257279754140647424000000000000000",
"11978571669969891796072783721689098736458938142546425857555362864628009582789845319680000000000000000",
"850478588567862317521167644239926010288584608120796235886430763388588680378079017697280000000000000000",
"61234458376886086861524070385274672740778091784697328983823014963978384987221689274204160000000000000000",
"4470115461512684340891257138125051110076800700282905015819080092370422104067183317016903680000000000000000",
"330788544151938641225953028221253782145683251820934971170611926835411235700971565459250872320000000000000000",
"24809140811395398091946477116594033660926243886570122837795894512655842677572867409443815424000000000000000000",
"1885494701666050254987932260861146558230394535379329335672487982961844043495537923117729972224000000000000000000",
"145183092028285869634070784086308284983740379224208358846781574688061991349156420080065207861248000000000000000000",
"11324281178206297831457521158732046228731749579488251990048962825668835325234200766245086213177344000000000000000000",
"894618213078297528685144171539831652069808216779571907213868063227837990693501860533361810841010176000000000000000000",
"71569457046263802294811533723186532165584657342365752577109445058227039255480148842668944867280814080000000000000000000",
"5797126020747367985879734231578109105412357244731625958745865049716390179693892056256184534249745940480000000000000000000",
"475364333701284174842138206989404946643813294067993328617160934076743994734899148613007131808479167119360000000000000000000",
"39455239697206586511897471180120610571436503407643446275224357528369751562996629334879591940103770870906880000000000000000000",
"3314240134565353266999387579130131288000666286242049487118846032383059131291716864129885722968716753156177920000000000000000000",
"281710411438055027694947944226061159480056634330574206405101912752560026159795933451040286452340924018275123200000000000000000000",
"24227095383672732381765523203441259715284870552429381750838764496720162249742450276789464634901319465571660595200000000000000000000",
"2107757298379527717213600518699389595229783738061356212322972511214654115727593174080683423236414793504734471782400000000000000000000",
"185482642257398439114796845645546284380220968949399346684421580986889562184028199319100141244804501828416633516851200000000000000000000",
"16507955160908461081216919262453619309839666236496541854913520707833171034378509739399912570787600662729080382999756800000000000000000000",
"1485715964481761497309522733620825737885569961284688766942216863704985393094065876545992131370884059645617234469978112000000000000000000000",
"135200152767840296255166568759495142147586866476906677791741734597153670771559994765685283954750449427751168336768008192000000000000000000000",
"12438414054641307255475324325873553077577991715875414356840239582938137710983519518443046123837041347353107486982656753664000000000000000000000",
"1156772507081641574759205162306240436214753229576413535186142281213246807121467315215203289516844845303838996289387078090752000000000000000000000",
"108736615665674308027365285256786601004186803580182872307497374434045199869417927630229109214583415458560865651202385340530688000000000000000000000",
"10329978488239059262599702099394727095397746340117372869212250571234293987594703124871765375385424468563282236864226607350415360000000000000000000000",
"991677934870949689209571401541893801158183648651267795444376054838492222809091499987689476037000748982075094738965754305639874560000000000000000000000",
"96192759682482119853328425949563698712343813919172976158104477319333745612481875498805879175589072651261284189679678167647067832320000000000000000000000",
"9426890448883247745626185743057242473809693764078951663494238777294707070023223798882976159207729119823605850588608460429412647567360000000000000000000000",
"933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000",
"93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000",
"9425947759838359420851623124482936749562312794702543768327889353416977599316221476503087861591808346911623490003549599583369706302603264000000000000000000000000",
"961446671503512660926865558697259548455355905059659464369444714048531715130254590603314961882364451384985595980362059157503710042865532928000000000000000000000000",
"99029007164861804075467152545817733490901658221144924830052805546998766658416222832141441073883538492653516385977292093222882134415149891584000000000000000000000000",
"10299016745145627623848583864765044283053772454999072182325491776887871732475287174542709871683888003235965704141638377695179741979175588724736000000000000000000000000",
"1081396758240290900504101305800329649720646107774902579144176636573226531909905153326984536526808240339776398934872029657993872907813436816097280000000000000000000000000",
"114628056373470835453434738414834942870388487424139673389282723476762012382449946252660360871841673476016298287096435143747350528228224302506311680000000000000000000000000",
"12265202031961379393517517010387338887131568154382945052653251412013535324922144249034658613287059061933743916719318560380966506520420000368175349760000000000000000000000000",
"1324641819451828974499891837121832599810209360673358065686551152497461815091591578895743130235002378688844343005686404521144382704205360039762937774080000000000000000000000000",
"144385958320249358220488210246279753379312820313396029159834075622223337844983482099636001195615259277084033387619818092804737714758384244334160217374720000000000000000000000000",
"15882455415227429404253703127090772871724410234473563207581748318444567162948183030959960131517678520479243672638179990208521148623422266876757623911219200000000000000000000000000",
"1762952551090244663872161047107075788761409536026565516041574063347346955087248316436555574598462315773196047662837978913145847497199871623320096254145331200000000000000000000000000",
"197450685722107402353682037275992488341277868034975337796656295094902858969771811440894224355027779366597957338237853638272334919686385621811850780464277094400000000000000000000000000",
"22311927486598136465966070212187151182564399087952213171022161345724023063584214692821047352118139068425569179220877461124773845924561575264739138192463311667200000000000000000000000000",
"2543559733472187557120132004189335234812341496026552301496526393412538629248600474981599398141467853800514886431180030568224218435400019580180261753940817530060800000000000000000000000000",
"292509369349301569068815180481773552003419272043053514672100535242441942363589054622883930786268803187059211939585703515345785120071002251720730101703194015956992000000000000000000000000000",
"33931086844518982011982560935885732032396635556994207701963662088123265314176330336254535971207181169698868584991941607780111073928236261199604691797570505851011072000000000000000000000000000",
"3969937160808720895401959629498630647790406360168322301129748464310422041758630649341780708631240196854767624444057168110272995649603642560353748940315749184568295424000000000000000000000000000",
"468452584975429065657431236280838416439267950499862031533310318788629800927518416622330123618486343228862579684398745837012213486653229822121742374957258403779058860032000000000000000000000000000",
"55745857612076058813234317117419771556272886109483581752463927935846946310374691578057284710599874844234646982443450754604453404911734348832487342619913750049708004343808000000000000000000000000000",
"6689502913449127057588118054090372586752746333138029810295671352301633557244962989366874165271984981308157637893214090552534408589408121859898481114389650005964960521256960000000000000000000000000000",
"809429852527344373968162284544935082997082306309701607045776233628497660426640521713391773997910182738287074185078904956856663439318382745047716214841147650721760223072092160000000000000000000000000000",
"98750442008336013624115798714482080125644041369783596059584700502676714572050143649033796427745042294071023050579626404736512939596842694895821378210620013388054747214795243520000000000000000000000000000",
"12146304367025329675766243241881295855454217088483382315328918161829235892362167668831156960612640202170735835221294047782591091570411651472186029519906261646730733907419814952960000000000000000000000000000",
"1506141741511140879795014161993280686076322918971939407100785852066825250652908790935063463115967385069171243567440461925041295354731044782551067660468376444194611004520057054167040000000000000000000000000000",
"188267717688892609974376770249160085759540364871492425887598231508353156331613598866882932889495923133646405445930057740630161919341380597818883457558547055524326375565007131770880000000000000000000000000000000",
"23721732428800468856771473051394170805702085973808045661837377170052497697783313457227249544076486314839447086187187275319400401837013955325179315652376928996065123321190898603130880000000000000000000000000000000",
"3012660018457659544809977077527059692324164918673621799053346900596667207618480809067860692097713761984609779945772783965563851033300772326297773087851869982500270661791244122597621760000000000000000000000000000000",
"385620482362580421735677065923463640617493109590223590278828403276373402575165543560686168588507361534030051833058916347592172932262498857766114955245039357760034644709279247692495585280000000000000000000000000000000",
"49745042224772874403902341504126809639656611137138843145968864022652168932196355119328515747917449637889876686464600208839390308261862352651828829226610077151044469167497022952331930501120000000000000000000000000000000",
"6466855489220473672507304395536485253155359447828049608975952322944781961185526165512707047229268452925683969240398027149120740074042105844737747799459310029635780991774612983803150965145600000000000000000000000000000000",
"847158069087882051098456875815279568163352087665474498775849754305766436915303927682164623187034167333264599970492141556534816949699515865660644961729169613882287309922474300878212776434073600000000000000000000000000000000",
"111824865119600430744996307607616902997562475571842633838412167568361169672820118454045730260688510087990927196104962685462595837360336094267205134948250389032461924909766607715924086489297715200000000000000000000000000000000",
"14872707060906857289084508911813048098675809251055070300508818286592035566485075754388082124671571841702793317081960037166525246368924700537538282948117301741317436012998958826217903503076596121600000000000000000000000000000000",
"1992942746161518876737324194182948445222558439641379420268181650403332765909000151088003004705990626788174304488982644980314383013435909872030129915047718433336536425741860482713199069412263880294400000000000000000000000000000000",
"269047270731805048359538766214698040105045389351586221736204522804449923397715020396880405635308734616403531106012657072342441706813847832724067538531441988500432417475151165166281874370655623839744000000000000000000000000000000000",
"36590428819525486576897272205198933454286172951815726156123815101405189582089242773975735166401987907830880230417721361838572072126683305250473185240276110436058808776620558462614334914409164842205184000000000000000000000000000000000",
"5012888748274991661034926292112253883237205694398754483388962668892510972746226260034675717797072343372830591567227826571884373881355612819314826377917827129740056802397016509378163883274055583382110208000000000000000000000000000000000",
"691778647261948849222819828311491035886734385827028118707676848307166514238979223884785249055995983385450621636277440066920043595627074569065446040152660143904127838730788278294186615891819670506731208704000000000000000000000000000000000",
"96157231969410890041971956135297253988256079629956908500367081914696145479218112119985149618783441690577636407442564169301886059792163365100096999581219760002673769583579570682891939608962934200435638009856000000000000000000000000000000000",
"13462012475717524605876073858941615558355851148193967190051391468057460367090535696797920946629681836680869097041958983702264048370902871114013579941370766400374327741701139895604871545254810788060989321379840000000000000000000000000000000000",
"1898143759076170969428526414110767793728175011895349373797246196996101911759765533248506853474785138972002542682916216702019230820297304827075914771733278062452780211579860725280286887880928321116599494314557440000000000000000000000000000000000",
"269536413788816277658850750803729026709400851689139611079208959973446471469886705721287973193419489734024361060974102771686730776482217285444779897586125484868294790044340222989800738079091821598557128192667156480000000000000000000000000000000000",
"38543707171800727705215657364933250819444321791546964384326881276202845420193798918144180166658987031965483631719296696351202501036957071818603525354815944336166154976340651887541505545310130488593669331551403376640000000000000000000000000000000000",
"5550293832739304789551054660550388117999982337982762871343070903773209740507907044212761943998894132603029642967578724274573160149321818341878907651093495984407926316593053871805976798524658790357488383743402086236160000000000000000000000000000000000",
"804792605747199194484902925779806277109997439007500616344745281047115412373646521410850481879839649227439298230298915019813108221651663659572441609408556917739149315905992811411866635786075524601835815642793302504243200000000000000000000000000000000000",
"117499720439091082394795827163851716458059626095095089986332811032878850206552392125984170354456588787206137541623641592892713800361142894297576474973649309989915800122274950466132528824767026591868029083847822165619507200000000000000000000000000000000000",
"17272458904546389112034986593086202319334765035978978227990923221833190980363201642519673042105118551719302218618675314155228928653088005461743741821126448568517622617974417718521481737240752909004600275325629858346067558400000000000000000000000000000000000",
"2556323917872865588581178015776757943261545225324888777742656636831312265093753843092911610231557545654456728355563946494973881440657024808338073789526714388140608147460213822341179297111631430532680840748193219035217998643200000000000000000000000000000000000",
"380892263763056972698595524350736933545970238573408427883655838887865527498969322620843829924502074302514052524979028027751108334657896696442372994639480443832950613971571859528835715269633083149369445271480789636247481797836800000000000000000000000000000000000",
"57133839564458545904789328652610540031895535786011264182548375833179829124845398393126574488675311145377107878746854204162666250198684504466355949195922066574942592095735778929325357290444962472405416790722118445437122269675520000000000000000000000000000000000000",
"8627209774233240431623188626544191544816225903687700891564804750810154197851655157362112747789971982951943289690774984828562603780001360174419748328584232052816331406456102618328128950857189333333217935399039885261005462721003520000000000000000000000000000000000000",
"1311335885683452545606724671234717114812066337360530535517850322123143438073451583919041137664075741408695380032997797693941515774560206746511801745944803272028082373781327597985875600530292778666649126180654062559672830333592535040000000000000000000000000000000000000",
"200634390509568239477828874698911718566246149616161171934231099284840946025238092339613294062603588435530393145048663047173051913507711632216305667129554900620296603188543122491838966881134795135997316305640071571629943041039657861120000000000000000000000000000000000000",
"30897696138473508879585646703632404659201907040888820477871589289865505687886666220300447285640952619071680544337494109264649994680187591361311072737951454695525676891035640863743200899694758450943586711068571022031011228320107310612480000000000000000000000000000000000000",
"4789142901463393876335775239063022722176295591337767174070096339929153381622433264146569329274347655956110484372311586936020749175429076661003216274382475477806479918110524333880196139452687559896255940215628508414806740389616633144934400000000000000000000000000000000000000",
"747106292628289444708380937293831544659502112248691679154935029028947927533099589206864815366798234329153235562080607562019236871366935959116501738803666174537810867225241796085310597754619259343815926673638047312709851500780194770609766400000000000000000000000000000000000000",
"117295687942641442819215807155131552511541831623044593627324799557544824622696635505477776012587322789677057983246655387237020188804608945581290772992175589402436306154362961985393763847475223716979100487761173428095446685622490578985733324800000000000000000000000000000000000000",
"18532718694937347965436097530510785296823609396441045793117318330092082290386068409865488609988797000768975161352971551183449189831128213401843942132763743125584936372389347993692214687901085347282697877066265401639080576328353511479745865318400000000000000000000000000000000000000",
"2946702272495038326504339507351214862194953894034126281105653614484641084171384877168612688988218723122267050655122476638168421183149385930893186799109435156968004883209906330997062135376272570217948962453536198860613811636208208325279592585625600000000000000000000000000000000000000",
"471472363599206132240694321176194377951192623045460204976904578317542573467421580346978030238114995699562728104819596262106947389303901748942909887857509625114880781313585012959529941660203611234871833992565791817698209861793313332044734813700096000000000000000000000000000000000000000",
"75907050539472187290751785709367294850142012310319093001281637109124354328254874435863462868336514307629599224875954998199218529677928181579808491945059049643495805791487187086484320607292781408814365272803092482649411787748723446459202305005715456000000000000000000000000000000000000000",
"12296942187394494341101789284917501765723005994271693066207625211678145401177289658609880984670515317835995074429904709708273401807824365415928975695099566042246320538220924308010459938381430588227927174194100982189204709615293198326390773410925903872000000000000000000000000000000000000000",
"2004401576545302577599591653441552787812849977066285969791842909503537700391898214353410600501293996807267197132074467682448564494675371562796423038301229264886150247730010662205704969956173185881152129393638460096840367667292791327201696065980922331136000000000000000000000000000000000000000",
"328721858553429622726333031164414657201307396238870899045862237158580182864271307153959338482212215476391820329660212699921564577126760936298613378281401599441328640627721748601735615072812402484508949220556707455881820297436017777661078154820871262306304000000000000000000000000000000000000000",
"54239106661315887749844950142128418438215720379413698342567269131165730172604765680403290849565015553604650354393935095487058155225915554489271207416431263907819225703574088519286376487014046409943976621391856730220500349076942933314077895545443758280540160000000000000000000000000000000000000000",
"9003691705778437366474261723593317460743809582982673924866166675773511208652391102946946281027792581898371958829393225850851653767501982045219020431127589808697991466793298694201538496844331704050700119151048217216603057946772526930136930660543663874569666560000000000000000000000000000000000000000",
"1503616514864999040201201707840084015944216200358106545452649834854176371844949314192140028931641361177028117124508668717092226179172831001551576411998307498052564574954480881931656928973003394576466919898225052275172710677111011997332867420310791867053134315520000000000000000000000000000000000000000",
"252607574497319838753801886917134114678628321660161899636045172255501630469951484784279524860515748677740723676917456344471493998101035608260664837215715659672830848592352788164518364067464570288846442542901808782229015393754650015551921726612213033664926565007360000000000000000000000000000000000000000",
"42690680090047052749392518888995665380688186360567361038491634111179775549421800928543239701427161526538182301399050122215682485679075017796052357489455946484708413412107621199803603527401512378815048789750405684196703601544535852628274771797464002689372589486243840000000000000000000000000000000000000000",
"7257415615307998967396728211129263114716991681296451376543577798900561843401706157852350749242617459511490991237838520776666022565442753025328900773207510902400430280058295603966612599658257104398558294257568966313439612262571094946806711205568880457193340212661452800000000000000000000000000000000000000000",
"1241018070217667823424840524103103992616605577501693185388951803611996075221691752992751978120487585576464959501670387052809889858690710767331242032218484364310473577889968548278290754541561964852153468318044293239598173696899657235903947616152278558180061176365108428800000000000000000000000000000000000000000",
"213455108077438865629072570145733886730056159330291227886899710221263324938130981514753340236723864719151973034287306573083301055694802251980973629541579310661401455397074590303866009781148657954570396550703618437210885875866741044575478989978191912006970522334798649753600000000000000000000000000000000000000000",
"36927733697396923753829554635211962404299715564140382424433649868278555214296659802052327860953228596413291334931704037143411082635200789592708437910693220744422451783693904122568819692138717826140678603271725989637483256524946200711557865266227200777205900363920166407372800000000000000000000000000000000000000000",
"6425425663347064733166342506526881458348150508160426541851455077080468607287618805557105047805861775775912692278116502462953528378524937389131268196460620409529506610362739317326974626432136901748478076969280322196922086635340638923811068556323532935233826663322108954882867200000000000000000000000000000000000000000",
"1124449491085736328304109938642204255210926338928074644824004638489082006275333290972493383366025810760784721148670387931016867466241864043097971934380608571667663656813479380532220559625623957805983663469624056384461365161184611811666936997356618263665919666081369067104501760000000000000000000000000000000000000000000",
"197903110431089593781523349201027948917123035651341137489024816374078433104458659211158835472420542693898110922165988275858968674058568071585243060450987108613508803599172370973670818494109816573853124770653833923665200268368491678853380911534764814405201861230320955810392309760000000000000000000000000000000000000000000",
"35028850546302858099329632808581946958330777310287381335557392498211882659489182680375113878618436056819965633223379924827037455308366548670588021699824718224591058237053509662339734873457437533572003084405728604488740447501223027157048421341653372149720729437766809178439438827520000000000000000000000000000000000000000000",
"6235135397241908741680674639927586558582878361231153877729215864681715113389074517106770270394081618113953882713761626619212667044889245663364667862568799843977208366195524719896472807475423880975816549024219691598995799655217698833954618998814300242650289839922492033762220111298560000000000000000000000000000000000000000000",
"1116089236106301664760840760547037993986335226660376544113529639778027005296644338562111878400540609642397745005763331164839067401035174973742275547399815172071920297548998924861468632538100874694671162275335324796220248138283968091277876800787759743434401881346126074043437399922442240000000000000000000000000000000000000000000",
"200896062499134299656951336898466838917540340798867777940435335160044860953395980941180138112097309735631594101037399609671032132186331495273609598531966730972945653558819806475064353856858157445040809209560358463319644664891114256430017824141796753818192338642302693327818731986039603200000000000000000000000000000000000000000000",
"36362187312343308237908191978622497844074801684595067807218795663968119832564672550353604998289613062149318532287769329350456815925726000644523337334285978306103163294146384971986648048091326497552386466930424881860855684345291680413833226169665212441092813294256787492335190489473168179200000000000000000000000000000000000000000000",
"6617918090846482099299290940109294607621613906596302340913820810842197809526770404164356109688709577311175972876374017941783140498482132117303247394840048051710775719534642064901569944752621422554534336981337328498675734550843085835317647162879068664278892019554735323605004669084116608614400000000000000000000000000000000000000000000",
"1211079010624906224171770242040000913194755344907123328387229208384122199143398983962077168073033852647945203036376445283346314711222230177466494273255728793463071956674839497876987299889729720327479783667584731115257659422804284707863129430806869565563037239578516564219715854442393339376435200000000000000000000000000000000000000000000",
"222838537954982745247605724535360168027834983462910692423250174342678484642385413049022198925438228887221917358693265932135721906864890352653834946279054097997205240028170467609365663179710268540256280194835590525207409333795988386246815815268464000063598852082447047816427717217400374445264076800000000000000000000000000000000000000000000",
"41225129521671807870807059039041631085149471940638478098301282253395519658841301414069106801206072344136054711358254197445108552770004715240959465061625008129482969405211536507732647688246399679947411836044584247163370726752257851455660925824665840011765787635252703846039127685219069272373854208000000000000000000000000000000000000000000000",
"7667874091030956263970112981261743381837801780958756926284038499131566656544482063016853865024329456009306176312635280724790190815220877034818460501462251512083832309369345790438272470013830340470218601504292669972386955175919960370752932203387846242188436500157002915363277749450746884661536882688000000000000000000000000000000000000000000000",
"1433892455022788821362411127495946012403668933039287545215115199337602964773818145784151672759549608273740254970462797495535765682446304005511052113773441032759676641852067662811956951892586273667930878481302729284836360617897032589330798322033527247289237625529359545172932939147289667431707397062656000000000000000000000000000000000000000000000",
"269571781544284298416133291969237850331889759411386058500441657475469357377477811407420514478795326355463167934447005929160723948299905153036077797389406914158819208668188720608647906955806219449571005154484913105549235796164642126794190084542303122490376673599519594492511392559690457477160990647779328000000000000000000000000000000000000000000000",
"50949066711869732400649192182185953712727164528751965056583473262863708544343306356002477236492316681182538739610484120611376826228682073923818703706597906776016830438287668195034454414647375475968919974197648576948805565475117361964101925978495290150681191310309203359084653193781496463183427232430292992000000000000000000000000000000000000000000000",
"9680322675255249156123346514615331205418161260462873360750859919944104623425228207640470674933540169424682360525991982916161596983449594045525553704253602287443197783274656957056546338783001340434094795097553229620273057440272298773179365935914105128629426348958748638226084106818484328004851174161755668480000000000000000000000000000000000000000000000",
"1848941630973752588819559184291528260234868800748408811903414244709323983074218587659329898912306172360114330860464468736986865023838872462695380757512438036901650776605459478797800350707553256022912105863632666857472153971092009065677258893759594079568220432651120989901182064402330506648926574264895332679680000000000000000000000000000000000000000000000",
"354996793146960497053355363383973425965094809743694491885455534984190204750249968830591340591162785093141951525209177997501478084577063512837513105442388103085116949108248219929177667335850225156399124325817472036634653562449665740610033707601842063277098323069015230061026956365247457276593902258859903874498560000000000000000000000000000000000000000000000",
"68514381077363375931297585133106871211263298280533036933892918251948709516798243984304128734094417522976396644365371353517785270323373257977640029350380903895427571177891906446331289795819093455185030994882772103070488137552785487937736505567155518212479976352319939401778202578492759254382623135959961447778222080000000000000000000000000000000000000000000000",
"13291789929008494930671731515822733014985079866423409165175226140878049646258859332955000974414316999457420949006882042582450342442734412047662165693973895355712948808511029850588270220388904130305896013007257787995674698685240384659920882080028170533221115412350068243944971300227595295350228888376232520868975083520000000000000000000000000000000000000000000000",
"2591899036156656511480987645585432937922090573952564787209169097471219681020477569926225190010791814894197085056341998303577816776333210349294122310324909594364025017659650820864712692975836305409649722536415268659156566243621875008684572005605493253978117505408263307569269403544381082593294633233365341569450141286400000000000000000000000000000000000000000000000",
"508012211086704676250273578534744855832729752494702698292997143104359057480013603705540137242115195719262628671043031667501252088161309228461647972823682280495348903461291560889483687823263915860291345617137392657194686983749887501702176113098676677779711031060019608283576803094698692188285748113739606947612227692134400000000000000000000000000000000000000000000000",
"100078405584080821221303894971344736599047761241456431563720437191558734323562679929991407036696693556694737848195477238497746661367777918006944650646265409257583733981874437495228286501182991424477395086576066353467353335798727837835328694280439305522603073118823862831864630209655642361092292378406702568679608855350476800000000000000000000000000000000000000000000000",
"19815524305648002601818171204326257846611456725808373449616646563928629396065410626138298593265945324225558093942704493222553838950820027765375040827960551033001579328411138624055200727234232302046524227142061137986535960488148111891395081467526982493475408477527124840709196781511817187496273890924527108598562553359394406400000000000000000000000000000000000000000000000",
"3943289336823952517761816069660925311475679888435866316473712666221797249817016714601521420059923119520886060694598194151288213951213185525309633124764149655567314286353816586186984944719612228107258321201270166459320656137141474266387621212037869516201606287027897843301130159520851620311758504293980894611113948118519486873600000000000000000000000000000000000000000000000",
"788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000"];
return factorial[n];
};
if(typeof module != 'undefined') module.exports = BigArith; | Fixed a bug in div
Where numerator and denominator are both negative, division returned NaN. Fixed. | bigarith.js | Fixed a bug in div | <ide><path>igarith.js
<ide> Object.defineProperty(this, 'version', {
<ide> enumerable: true,
<ide> writable: false,
<del> value: "v0.0.7",
<add> value: "v0.0.8",
<ide> });
<ide>
<ide> //Object name
<ide> if(c > 201) break; //if we have gotten 0.00{199 more 0's}, no need to continue
<ide> if(flag)count++;
<ide> }
<add> remResult = remResult.replace(/\-/g,"");
<ide> if(remResult == "0.") remResult = "0.0";
<ide> result = result[0] + "." + remResult.split(".")[1];
<ide> var dPosition = (result.indexOf(".") == -1)?result.length : result.indexOf("."); // decimal position in answer |
|
Java | agpl-3.0 | 4205123468695eab41fb8b1e88db824d353a485d | 0 | yinan-liu/scheduling,ShatalovYaroslav/scheduling,laurianed/scheduling,jrochas/scheduling,marcocast/scheduling,tobwiens/scheduling,lpellegr/scheduling,zeineb/scheduling,paraita/scheduling,marcocast/scheduling,ShatalovYaroslav/scheduling,jrochas/scheduling,yinan-liu/scheduling,mbenguig/scheduling,tobwiens/scheduling,lpellegr/scheduling,ow2-proactive/scheduling,lpellegr/scheduling,lpellegr/scheduling,fviale/scheduling,ow2-proactive/scheduling,paraita/scheduling,ShatalovYaroslav/scheduling,paraita/scheduling,sgRomaric/scheduling,jrochas/scheduling,tobwiens/scheduling,mbenguig/scheduling,jrochas/scheduling,marcocast/scheduling,ShatalovYaroslav/scheduling,mbenguig/scheduling,zeineb/scheduling,jrochas/scheduling,fviale/scheduling,laurianed/scheduling,marcocast/scheduling,ShatalovYaroslav/scheduling,yinan-liu/scheduling,sgRomaric/scheduling,ow2-proactive/scheduling,tobwiens/scheduling,lpellegr/scheduling,lpellegr/scheduling,paraita/scheduling,sgRomaric/scheduling,laurianed/scheduling,ow2-proactive/scheduling,lpellegr/scheduling,laurianed/scheduling,paraita/scheduling,sgRomaric/scheduling,mbenguig/scheduling,zeineb/scheduling,mbenguig/scheduling,fviale/scheduling,yinan-liu/scheduling,fviale/scheduling,yinan-liu/scheduling,jrochas/scheduling,yinan-liu/scheduling,ShatalovYaroslav/scheduling,marcocast/scheduling,ow2-proactive/scheduling,ow2-proactive/scheduling,sgRomaric/scheduling,marcocast/scheduling,sgRomaric/scheduling,tobwiens/scheduling,tobwiens/scheduling,mbenguig/scheduling,fviale/scheduling,yinan-liu/scheduling,ow2-proactive/scheduling,zeineb/scheduling,sgRomaric/scheduling,marcocast/scheduling,jrochas/scheduling,tobwiens/scheduling,laurianed/scheduling,laurianed/scheduling,zeineb/scheduling,ShatalovYaroslav/scheduling,mbenguig/scheduling,paraita/scheduling,zeineb/scheduling,fviale/scheduling,zeineb/scheduling,laurianed/scheduling,paraita/scheduling,fviale/scheduling | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2015 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero 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
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.scheduler.common;
import javax.xml.bind.annotation.XmlRootElement;
import org.objectweb.proactive.annotation.PublicAPI;
/**
* Status of the scheduler.
* The status and what you can do with the scheduler according to the current status
* are best described below.
*
* @author The ProActive Team
* @since ProActive Scheduling 0.9
*/
@PublicAPI
@XmlRootElement(name = "schedulerstatus")
public enum SchedulerStatus implements java.io.Serializable {
/**
* The scheduler is running. Jobs can be submitted.
* Get the jobs results is possible.
* It can be paused, stopped or shutdown.
*/
STARTED("Started"),
/**
* The scheduler is stopped. Jobs cannot be submitted anymore.
* It will terminate every submitted jobs.
* Get the jobs results is possible.
* It can be started or shutdown.
*/
STOPPED("Stopped"),
/**
* The scheduler is in freeze mode.
* It means that every running tasks will be terminated,
* but the pending jobs will wait for the scheduler to resume.
* It can be resumed, stopped, paused or shutdown.
*/
FROZEN("Frozen"),
/**
* The scheduler is paused.
* It means that every running jobs will be terminated.
* It can be resumed, stopped, frozen or shutdown.
*/
PAUSED("Paused"),
/**
* The scheduler is shutting down,
* It will terminate all running jobs (during this time, get jobs results is possible),
* then it will serialize every remaining jobs results that still are in the finished queue.
* Finally, it will shutdown the scheduler.
*/
SHUTTING_DOWN("Shutting down"),
/**
* The scheduler is unlinked with RM,
* This can be due to the crash of the resource manager.
* This status will block every called to the scheduler except the terminate one
* and the call to reconnect to a new Resource Manager.
*/
UNLINKED("Unlinked from RM"),
/**
* The scheduler has been killed, nothing can be done anymore.
* (Similar to Ctrl-C)
*/
KILLED("Killed"),
/**
* The scheduler has been killed due to a db disconnection, nothing can be done anymore.
*/
DB_DOWN("Killed (DB down)");
/** The textual definition of the status */
private String definition;
/**
* Default constructor.
* @param def the textual definition of the status.
*/
SchedulerStatus(String def) {
definition = def;
}
/**
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return definition;
}
/**
* Return true if the scheduler is killed
*
* @return true if the scheduler is killed
*/
public boolean isKilled() {
return this == KILLED || this == DB_DOWN;
}
/**
* Return true if the scheduler is currently shutting down
*
* @return true if the scheduler is currently shutting down
*/
public boolean isShuttingDown() {
return isKilled() || this == SHUTTING_DOWN;
}
/**
* Return true if the scheduler is NOT usable in its current state
*
* @return true if the scheduler is NOT usable in its current state
*/
public boolean isUnusable() {
return isKilled();
}
/**
* Return true if the scheduler is not currently UP
*
* @return true if the scheduler is not currently UP
*/
public boolean isDown() {
return this == UNLINKED || isShuttingDown();
}
/**
* Return true if the scheduler can be stopped in its current state.
*
* @return true if the scheduler can be stopped in its current state.
*/
public boolean isStoppable() {
return !isDown() && this != STOPPED;
}
/**
* Return true if the scheduler is startable
*
* @return true if the scheduler is startable
*/
public boolean isStartable() {
return !isDown() && this == STOPPED;
}
/**
* Return true if the scheduler is freezable in its current state
*
* @return true if the scheduler is freezable in its current state
*/
public boolean isFreezable() {
return !isDown() && (this == PAUSED || this == STARTED);
}
/**
* Return true if the scheduler is pausable in its current state
*
* @return true if the scheduler is pausable in its current state
*/
public boolean isPausable() {
return !isDown() && (this == FROZEN || this == STARTED);
}
/**
* Return true if the scheduler is resumable in its current state
*
* @return true if the scheduler is resumable in its current state
*/
public boolean isResumable() {
return !isDown() && (this == PAUSED || this == FROZEN);
}
/**
* Return true if a job can be submitted to scheduler
*
* @return true if a job can be submitted to scheduler
*/
public boolean isSubmittable() {
return !isShuttingDown() && this != STOPPED;
}
}
| scheduler/scheduler-api/src/main/java/org/ow2/proactive/scheduler/common/SchedulerStatus.java | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2015 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero 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
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.scheduler.common;
import javax.xml.bind.annotation.XmlRootElement;
import org.objectweb.proactive.annotation.PublicAPI;
/**
* Status of the scheduler.
* The status and what you can do with the scheduler according to the current status
* are best described below.
*
* @author The ProActive Team
* @since ProActive Scheduling 0.9
*/
@PublicAPI
@XmlRootElement(name = "schedulerstatus")
public enum SchedulerStatus implements java.io.Serializable {
/**
* The scheduler is running. Jobs can be submitted.
* Get the jobs results is possible.
* It can be paused, stopped or shutdown.
*/
STARTED("Started"),
/**
* The scheduler is stopped. Jobs cannot be submitted anymore.
* It will terminate every submitted jobs.
* Get the jobs results is possible.
* It can be started or shutdown.
*/
STOPPED("Stopped"),
/**
* The scheduler is in freeze mode.
* It means that every running tasks will be terminated,
* but the running jobs will wait for the scheduler to resume.
* It can be resumed, stopped, paused or shutdown.
*/
FROZEN("Frozen"),
/**
* The scheduler is paused.
* It means that every running jobs will be terminated.
* It can be resumed, stopped, frozen or shutdown.
*/
PAUSED("Paused"),
/**
* The scheduler is shutting down,
* It will terminate all running jobs (during this time, get jobs results is possible),
* then it will serialize every remaining jobs results that still are in the finished queue.
* Finally, it will shutdown the scheduler.
*/
SHUTTING_DOWN("Shutting down"),
/**
* The scheduler is unlinked with RM,
* This can be due to the crash of the resource manager.
* This status will block every called to the scheduler except the terminate one
* and the call to reconnect to a new Resource Manager.
*/
UNLINKED("Unlinked from RM"),
/**
* The scheduler has been killed, nothing can be done anymore.
* (Similar to Ctrl-C)
*/
KILLED("Killed"),
/**
* The scheduler has been killed due to a db disconnection, nothing can be done anymore.
*/
DB_DOWN("Killed (DB down)");
/** The textual definition of the status */
private String definition;
/**
* Default constructor.
* @param def the textual definition of the status.
*/
SchedulerStatus(String def) {
definition = def;
}
/**
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return definition;
}
/**
* Return true if the scheduler is killed
*
* @return true if the scheduler is killed
*/
public boolean isKilled() {
return this == KILLED || this == DB_DOWN;
}
/**
* Return true if the scheduler is currently shutting down
*
* @return true if the scheduler is currently shutting down
*/
public boolean isShuttingDown() {
return isKilled() || this == SHUTTING_DOWN;
}
/**
* Return true if the scheduler is NOT usable in its current state
*
* @return true if the scheduler is NOT usable in its current state
*/
public boolean isUnusable() {
return isKilled();
}
/**
* Return true if the scheduler is not currently UP
*
* @return true if the scheduler is not currently UP
*/
public boolean isDown() {
return this == UNLINKED || isShuttingDown();
}
/**
* Return true if the scheduler can be stopped in its current state.
*
* @return true if the scheduler can be stopped in its current state.
*/
public boolean isStoppable() {
return !isDown() && this != STOPPED;
}
/**
* Return true if the scheduler is startable
*
* @return true if the scheduler is startable
*/
public boolean isStartable() {
return !isDown() && this == STOPPED;
}
/**
* Return true if the scheduler is freezable in its current state
*
* @return true if the scheduler is freezable in its current state
*/
public boolean isFreezable() {
return !isDown() && (this == PAUSED || this == STARTED);
}
/**
* Return true if the scheduler is pausable in its current state
*
* @return true if the scheduler is pausable in its current state
*/
public boolean isPausable() {
return !isDown() && (this == FROZEN || this == STARTED);
}
/**
* Return true if the scheduler is resumable in its current state
*
* @return true if the scheduler is resumable in its current state
*/
public boolean isResumable() {
return !isDown() && (this == PAUSED || this == FROZEN);
}
/**
* Return true if a job can be submitted to scheduler
*
* @return true if a job can be submitted to scheduler
*/
public boolean isSubmittable() {
return !isShuttingDown() && this != STOPPED;
}
} | Fix wrong comment about Scheduler FROZEN state | scheduler/scheduler-api/src/main/java/org/ow2/proactive/scheduler/common/SchedulerStatus.java | Fix wrong comment about Scheduler FROZEN state | <ide><path>cheduler/scheduler-api/src/main/java/org/ow2/proactive/scheduler/common/SchedulerStatus.java
<ide> /**
<ide> * The scheduler is in freeze mode.
<ide> * It means that every running tasks will be terminated,
<del> * but the running jobs will wait for the scheduler to resume.
<add> * but the pending jobs will wait for the scheduler to resume.
<ide> * It can be resumed, stopped, paused or shutdown.
<ide> */
<ide> FROZEN("Frozen"), |
|
Java | apache-2.0 | error: pathspec 'src/main/java/uk/ac/edukapp/renderer/CustomJsonDateSerializer.java' did not match any file(s) known to git
| 4aabb8e587af9b947062e501a358771f00a486af | 1 | pradeeshmp/edukapp,pradeeshmp/edukapp,metaboy/edukapp,palaniyappanBala/edukapp,palaniyappanBala/edukapp,metaboy/edukapp,palaniyappanBala/edukapp,pradeeshmp/edukapp,metaboy/edukapp | package uk.ac.edukapp.renderer;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
public class CustomJsonDateSerializer extends JsonSerializer<Date> {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM d, yy, h:mm a");
@Override
public void serialize(Date date, JsonGenerator generator, SerializerProvider provider)
throws IOException, JsonProcessingException {
String formattedDate = dateFormat.format(date);
generator.writeString(formattedDate);
}
}
| src/main/java/uk/ac/edukapp/renderer/CustomJsonDateSerializer.java | JSON date serializer | src/main/java/uk/ac/edukapp/renderer/CustomJsonDateSerializer.java | JSON date serializer | <ide><path>rc/main/java/uk/ac/edukapp/renderer/CustomJsonDateSerializer.java
<add>package uk.ac.edukapp.renderer;
<add>
<add>import java.io.IOException;
<add>import java.text.SimpleDateFormat;
<add>import java.util.Date;
<add>
<add>import org.codehaus.jackson.JsonGenerator;
<add>import org.codehaus.jackson.JsonProcessingException;
<add>import org.codehaus.jackson.map.JsonSerializer;
<add>import org.codehaus.jackson.map.SerializerProvider;
<add>
<add>public class CustomJsonDateSerializer extends JsonSerializer<Date> {
<add>
<add> private static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM d, yy, h:mm a");
<add>
<add> @Override
<add> public void serialize(Date date, JsonGenerator generator, SerializerProvider provider)
<add> throws IOException, JsonProcessingException {
<add> String formattedDate = dateFormat.format(date);
<add> generator.writeString(formattedDate);
<add>
<add> }
<add>
<add>} |
|
Java | mit | 5f99294fdafe5d99b87a800b24aca86a26084895 | 0 | concord-consortium/energy3d | package org.concord.energy3d.scene;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.io.IOException;
import java.net.URL;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.concord.energy3d.gui.EnergyPanel;
import org.concord.energy3d.gui.EnergyPanel.UpdateRadiation;
import org.concord.energy3d.gui.MainFrame;
import org.concord.energy3d.gui.MainPanel;
import org.concord.energy3d.gui.PopupMenuFactory;
import org.concord.energy3d.logger.PlayControl;
import org.concord.energy3d.logger.TimeSeriesLogger;
import org.concord.energy3d.model.CustomRoof;
import org.concord.energy3d.model.Door;
import org.concord.energy3d.model.Floor;
import org.concord.energy3d.model.Foundation;
import org.concord.energy3d.model.GambrelRoof;
import org.concord.energy3d.model.HipRoof;
import org.concord.energy3d.model.HousePart;
import org.concord.energy3d.model.Human;
import org.concord.energy3d.model.PickedHousePart;
import org.concord.energy3d.model.PyramidRoof;
import org.concord.energy3d.model.Roof;
import org.concord.energy3d.model.Sensor;
import org.concord.energy3d.model.ShedRoof;
import org.concord.energy3d.model.SolarPanel;
import org.concord.energy3d.model.Tree;
import org.concord.energy3d.model.UserData;
import org.concord.energy3d.model.Wall;
import org.concord.energy3d.model.Window;
import org.concord.energy3d.scene.CameraControl.ButtonAction;
import org.concord.energy3d.shapes.Heliodon;
import org.concord.energy3d.undo.AddPartCommand;
import org.concord.energy3d.undo.EditFoundationCommand;
import org.concord.energy3d.undo.EditPartCommand;
import org.concord.energy3d.undo.MoveBuildingCommand;
import org.concord.energy3d.undo.RemovePartCommand;
import org.concord.energy3d.undo.UndoManager;
import org.concord.energy3d.util.Blinker;
import org.concord.energy3d.util.Config;
import org.concord.energy3d.util.Config.RenderMode;
import org.concord.energy3d.util.FontManager;
import org.concord.energy3d.util.SelectUtil;
import org.concord.energy3d.util.Util;
import com.ardor3d.bounding.BoundingBox;
import com.ardor3d.bounding.BoundingVolume;
import com.ardor3d.extension.model.collada.jdom.ColladaAnimUtils;
import com.ardor3d.extension.model.collada.jdom.ColladaImporter;
import com.ardor3d.extension.model.collada.jdom.ColladaMaterialUtils;
import com.ardor3d.extension.model.collada.jdom.data.ColladaStorage;
import com.ardor3d.extension.shadow.map.ParallelSplitShadowMapPass;
import com.ardor3d.framework.Canvas;
import com.ardor3d.framework.DisplaySettings;
import com.ardor3d.framework.FrameHandler;
import com.ardor3d.framework.Updater;
import com.ardor3d.framework.jogl.JoglSwingCanvas;
import com.ardor3d.image.Texture;
import com.ardor3d.image.TextureStoreFormat;
import com.ardor3d.image.util.awt.AWTImageLoader;
import com.ardor3d.input.ButtonState;
import com.ardor3d.input.FocusWrapper;
import com.ardor3d.input.Key;
import com.ardor3d.input.KeyboardState;
import com.ardor3d.input.KeyboardWrapper;
import com.ardor3d.input.MouseButton;
import com.ardor3d.input.MouseState;
import com.ardor3d.input.MouseWrapper;
import com.ardor3d.input.PhysicalLayer;
import com.ardor3d.input.logical.InputTrigger;
import com.ardor3d.input.logical.KeyHeldCondition;
import com.ardor3d.input.logical.KeyPressedCondition;
import com.ardor3d.input.logical.KeyReleasedCondition;
import com.ardor3d.input.logical.LogicalLayer;
import com.ardor3d.input.logical.MouseButtonClickedCondition;
import com.ardor3d.input.logical.MouseButtonPressedCondition;
import com.ardor3d.input.logical.MouseButtonReleasedCondition;
import com.ardor3d.input.logical.MouseMovedCondition;
import com.ardor3d.input.logical.TriggerAction;
import com.ardor3d.input.logical.TwoInputStates;
import com.ardor3d.intersection.PickResults;
import com.ardor3d.intersection.PickingUtil;
import com.ardor3d.intersection.PrimitivePickResults;
import com.ardor3d.light.DirectionalLight;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.math.MathUtils;
import com.ardor3d.math.Matrix3;
import com.ardor3d.math.Ray3;
import com.ardor3d.math.Vector2;
import com.ardor3d.math.Vector3;
import com.ardor3d.math.type.ReadOnlyVector2;
import com.ardor3d.math.type.ReadOnlyVector3;
import com.ardor3d.renderer.Camera;
import com.ardor3d.renderer.Camera.ProjectionMode;
import com.ardor3d.renderer.Renderer;
import com.ardor3d.renderer.pass.BasicPassManager;
import com.ardor3d.renderer.pass.RenderPass;
import com.ardor3d.renderer.queue.RenderBucketType;
import com.ardor3d.renderer.state.BlendState;
import com.ardor3d.renderer.state.LightState;
import com.ardor3d.renderer.state.MaterialState;
import com.ardor3d.renderer.state.MaterialState.ColorMaterial;
import com.ardor3d.renderer.state.TextureState;
import com.ardor3d.renderer.state.ZBufferState;
import com.ardor3d.scenegraph.Line;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.scenegraph.Node;
import com.ardor3d.scenegraph.Spatial;
import com.ardor3d.scenegraph.controller.SpatialController;
import com.ardor3d.scenegraph.extension.CameraNode;
import com.ardor3d.scenegraph.hint.CullHint;
import com.ardor3d.scenegraph.hint.LightCombineMode;
import com.ardor3d.scenegraph.shape.Dome;
import com.ardor3d.scenegraph.shape.Quad;
import com.ardor3d.scenegraph.shape.Sphere;
import com.ardor3d.ui.text.BMText;
import com.ardor3d.ui.text.BMText.Align;
import com.ardor3d.util.GameTaskQueue;
import com.ardor3d.util.GameTaskQueueManager;
import com.ardor3d.util.ReadOnlyTimer;
import com.ardor3d.util.TextureManager;
import com.ardor3d.util.Timer;
import com.ardor3d.util.geom.BufferUtils;
import com.ardor3d.util.resource.ResourceLocatorTool;
import com.ardor3d.util.resource.ResourceSource;
import com.ardor3d.util.resource.SimpleResourceLocator;
import com.ardor3d.util.resource.URLResourceSource;
public class SceneManager implements com.ardor3d.framework.Scene, Runnable, Updater {
public enum Operation {
SELECT, RESIZE, ROTATE, DRAW_WALL, DRAW_DOOR, DRAW_ROOF_PYRAMID, DRAW_ROOF_HIP, DRAW_ROOF_SHED, DRAW_ROOF_GAMBREL, DRAW_ROOF_CUSTOM, DRAW_ROOF_GABLE, DRAW_WINDOW, DRAW_FOUNDATION, DRAW_FLOOR, DRAW_SOLAR_PANEL, DRAW_SENSOR, DRAW_DOGWOOD, DRAW_ELM, DRAW_OAK, DRAW_LINDEN, DRAW_MAPLE, DRAW_COTTONWOOD, DRAW_PINE, DRAW_JANE, DRAW_JENI, DRAW_JILL, DRAW_JACK, DRAW_JOHN, DRAW_JOSE
}
public enum CameraMode {
ORBIT, FIRST_PERSON
}
public enum ViewMode {
NORMAL, TOP_VIEW, PRINT_PREVIEW, PRINT
}
private static final GameTaskQueueManager taskManager = GameTaskQueueManager.getManager("Task Manager");
private static final SceneManager instance = new SceneManager(MainPanel.getInstance().getCanvasPanel());
private static final double MOVE_SPEED = 5;
private final Canvas canvas;
private final FrameHandler frameHandler;
private final LogicalLayer logicalLayer;
private final Node root = new Node("Root");
private final Node backgroundRoot = new Node("Scenary Root");
private final BasicPassManager passManager = new BasicPassManager();
private final Mesh land = new Quad("Land", 2000, 2000);
private final Mesh solarLand = new Quad("Solar Land", 256, 256);
private final Mesh collisionLand = new Quad("Collision Land", 2000, 2000);
private final Mesh gridsMesh = new Line("Floor Grids");
private final LightState lightState = new LightState();
private final UndoManager undoManager = new UndoManager();
private HousePart selectedHousePart = null;
private HousePart hoveredHousePart = null;
private Operation operation = Operation.SELECT;
private CameraControl cameraControl;
private final ParallelSplitShadowMapPass shadowPass;
private ViewMode viewMode = ViewMode.NORMAL;
private CameraNode cameraNode;
private MouseState mouseState;
private AddPartCommand addHousePartCommand;
private EditPartCommand editHousePartCommand;
private UserData pick;
private TwoInputStates firstClickState;
private double refreshTime = -1;
private boolean mouseControlEnabled = true;
private boolean rotAnim = false;
private boolean heliodonControl;
private boolean sunAnim;
private boolean operationStick = false;
private boolean operationFlag = false;
private boolean refresh = true;
private int refreshCount = 0;
private boolean refreshOnlyMode = false;
private boolean zoomLock = false;
public static final double SKY_RADIUS = 1000;
public final static byte DEFAULT_THEME = 0;
public final static byte SKETCHUP_THEME = 1;
private final byte theme = DEFAULT_THEME;
private Sphere kinectPointer;
private MouseState lastSelectedEditPointMouseState;
private MouseState pasteMouseState;
private Node newImport;
private Vector3 houseMoveStartPoint;
private ArrayList<Vector3> houseMovePoints;
private boolean solarHeatMap = false;
private boolean heatFluxDaily = true;
private final Spatial axes;
private boolean showBuildingLabels = false;
private boolean showHeatFlux = false;
private final Mesh sky;
private TextureState daySkyState, nightSkyState;
private boolean cameraChanged;
private boolean fineGrid;
public static SceneManager getInstance() {
return instance;
}
public static GameTaskQueueManager getTaskManager() {
return taskManager;
}
private SceneManager(final Container panel) {
System.out.print("Constructing SceneManager...");
final DisplaySettings settings = new DisplaySettings(400, 300, 24, 0, 0, 24, 0, 4, false, false);
final RendererFactory rendererFactory;
if (Config.RENDER_MODE == RenderMode.NEWT)
rendererFactory = new JoglNewtFactory(settings, this);
else if (Config.RENDER_MODE == RenderMode.JOGL)
rendererFactory = new JoglFactory(settings, this);
else
rendererFactory = new LwjglFactory(settings, this);
final MouseWrapper mouseWrapper = rendererFactory.getMouseWrapper();
final KeyboardWrapper keyboardWrapper = rendererFactory.getKeyboardWrapper();
final FocusWrapper focusWrapper = rendererFactory.getFocusWrapper();
canvas = rendererFactory.getCanvas();
final Component canvasComponent = (Component) canvas;
canvasComponent.setMinimumSize(new Dimension(100, 100));
canvasComponent.setPreferredSize(new Dimension(100, 100));
frameHandler = new FrameHandler(new Timer());
frameHandler.addCanvas(canvas);
logicalLayer = new LogicalLayer();
final PhysicalLayer physicalLayer = new PhysicalLayer(keyboardWrapper, mouseWrapper, focusWrapper);
logicalLayer.registerInput(canvas, physicalLayer);
frameHandler.addUpdater(this);
frameHandler.addUpdater(PrintController.getInstance());
frameHandler.addUpdater(Blinker.getInstance());
panel.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
resizeCamera();
refresh(1);
if (Heliodon.getInstance() != null)
Heliodon.getInstance().updateBloom();
}
});
panel.add(canvasComponent, BorderLayout.CENTER);
System.out.println("done");
System.out.print("Initializing SceneManager...");
AWTImageLoader.registerLoader();
try {
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, new SimpleResourceLocator(getClass().getResource("images/")));
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, new SimpleResourceLocator(getClass().getResource("fonts/")));
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_MODEL, new SimpleResourceLocator(getClass().getResource("models/")));
} catch (final Exception ex) {
ex.printStackTrace();
}
// enable depth test
final ZBufferState zbuf = new ZBufferState();
zbuf.setEnabled(true);
zbuf.setFunction(ZBufferState.TestFunction.LessThanOrEqualTo);
root.setRenderState(zbuf);
final DirectionalLight light = new DirectionalLight();
light.setDirection(new Vector3(0, 0, -1));
light.setAmbient(new ColorRGBA(1, 1, 1, 1));
light.setEnabled(true);
lightState.setEnabled(false);
lightState.attach(light);
root.setRenderState(lightState);
backgroundRoot.getSceneHints().setAllPickingHints(false);
sky = createSky();
backgroundRoot.attachChild(sky);
backgroundRoot.attachChild(createLand());
solarLand.setVisible(false);
backgroundRoot.attachChild(solarLand);
collisionLand.setModelBound(new BoundingBox());
collisionLand.getSceneHints().setCullHint(CullHint.Always);
root.attachChild(collisionLand);
gridsMesh.getSceneHints().setCullHint(CullHint.Always);
drawGrids(5);
backgroundRoot.attachChild(gridsMesh);
axes = createAxes();
backgroundRoot.attachChild(axes);
backgroundRoot.attachChild(createKinectPointer());
root.attachChild(backgroundRoot);
root.attachChild(Scene.getRoot());
final RenderPass rootPass = new RenderPass();
rootPass.add(root);
passManager.add(rootPass);
shadowPass = new ParallelSplitShadowMapPass(light, 2048, 4);
// shadowPass = new ParallelSplitShadowMapPass(light, 3072, 3);
shadowPass.setEnabled(false);
shadowPass.setUseSceneTexturing(true);
shadowPass.setUseObjectCullFace(true);
shadowPass.add(land);
shadowPass.add(solarLand);
// shadowPass.add(Scene.getRoot());
shadowPass.add(Scene.getOriginalHouseRoot());
// shadowPass.add(Scene.getTreesRoot());
// shadowPass.addOccluder(Scene.getRoot());
shadowPass.addOccluder(Scene.getOriginalHouseRoot());
shadowPass.addOccluder(Scene.getNotReceivingShadowRoot());
final Date today = Calendar.getInstance().getTime();
new Heliodon(root, light, passManager, logicalLayer, today);
// taskManager.update(new Callable<Object>() {
// @Override
// public Object call() throws Exception {
// final Date today = Calendar.getInstance().getTime();
// new Heliodon(root, light, passManager, logicalLayer, today);
// return null;
// }
// });
initMouse();
root.updateGeometricState(0, true);
System.out.println("Finished initialization.");
}
@Override
public void run() {
frameHandler.init();
long frameStartTime;
final long msPerFrame = 1000 / 60;
while (true) {
frameStartTime = System.currentTimeMillis();
logicalLayer.checkTriggers(frameHandler.getTimer().getTimePerFrame());
final double now = frameHandler.getTimer().getTimeInSeconds();
final boolean isUpdateTime = refreshTime != -1 && now <= refreshTime;
final boolean isTaskAvailable = taskManager.getQueue(GameTaskQueue.UPDATE).size() > 0 || taskManager.getQueue(GameTaskQueue.RENDER).size() > 0;
final boolean isPrintPreviewAnim = !PrintController.getInstance().isFinished();
final boolean doRefresh = refresh || !refreshOnlyMode && (isTaskAvailable || isPrintPreviewAnim || Scene.isRedrawAll() || isUpdateTime || rotAnim || Blinker.getInstance().getTarget() != null || sunAnim || (cameraControl != null && cameraControl.isAnimating()));
if (doRefresh || refreshCount > 0) {
if (now > refreshTime)
refreshTime = -1;
refresh = false;
if (doRefresh)
refreshCount = 2;
else
refreshCount--;
try {
synchronized (this) {
frameHandler.updateFrame();
}
} catch (final Throwable e) {
e.printStackTrace();
Util.reportError(e);
return;
}
synchronized (this) {
notifyAll();
}
} else
frameHandler.getTimer().update();
final long sleepTime = msPerFrame - (System.currentTimeMillis() - frameStartTime);
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void update(final ReadOnlyTimer timer) {
final double tpf = timer.getTimePerFrame();
passManager.updatePasses(tpf);
taskManager.getQueue(GameTaskQueue.UPDATE).setExecuteMultiple(true);
taskManager.getQueue(GameTaskQueue.UPDATE).execute(canvas.getCanvasRenderer().getRenderer());
if (operationFlag)
executeOperation();
if (mouseState != null)
mouseMoved();
if (Scene.isRedrawAll())
Scene.getInstance().redrawAllNow();
if (rotAnim && viewMode == ViewMode.NORMAL && canvas.getCanvasRenderer() != null) {
final Matrix3 rotate = new Matrix3();
rotate.fromAngleNormalAxis(45 * tpf * MathUtils.DEG_TO_RAD, Vector3.UNIT_Z);
final Camera camera = getCamera();
camera.setLocation(rotate.applyPre(camera.getLocation(), null));
camera.lookAt(0, 0, 1, Vector3.UNIT_Z);
getCameraNode().updateFromCamera();
Scene.getInstance().updateEditShapes();
}
final Heliodon heliodon = Heliodon.getInstance();
if (heliodon != null) {
if (sunAnim) {
heliodon.setHourAngle(heliodon.getHourAngle() + tpf * 0.5, true, true, false);
SceneManager.getInstance().changeSkyTexture();
SceneManager.getInstance().setShading(heliodon.isNightTime());
}
heliodon.update();
}
if (cameraControl != null && cameraControl.isAnimating())
cameraControl.animate();
root.updateGeometricState(tpf);
}
@Override
public boolean renderUnto(final Renderer renderer) {
if (cameraNode == null) {
initCamera();
return false;
}
final float[] f = new float[2];
((JoglSwingCanvas) canvas).getRequestedSurfaceScale(f);
setWindowsVisible(false);
passManager.renderPasses(renderer);
try {
if (!Heliodon.getInstance().isNightTime()) {
shadowPass.renderPass(renderer);
}
} catch (final Throwable e) {
e.printStackTrace();
Util.reportError(e);
if (shadowPass.isEnabled()) {
shadowPass.setEnabled(false);
}
}
setWindowsVisible(true);
passManager.renderPasses(renderer);
// com.ardor3d.util.geom.Debugger.drawBounds(Scene.getRoot(), renderer, true);
taskManager.getQueue(GameTaskQueue.RENDER).execute(renderer);
return true;
}
private void setWindowsVisible(final boolean visible) {
land.setVisible(!visible);
for (final HousePart part : Scene.getInstance().getParts())
if (part instanceof Window)
part.getMesh().setVisible(visible);
else
part.getRoot().getSceneHints().setCullHint(visible ? CullHint.Always : CullHint.Inherit);
}
public void initCamera() {
System.out.println("initCamera()");
final Camera camera = getCamera();
cameraNode = new CameraNode("Camera Node", camera);
root.attachChild(cameraNode);
cameraNode.updateFromCamera();
Scene.getInstance().updateEditShapes();
setCameraControl(CameraMode.ORBIT);
resetCamera(ViewMode.NORMAL);
SceneManager.getInstance().getCameraControl().reset();
taskManager.update(new Callable<Object>() {
@Override
public Object call() throws Exception {
final Spatial compass = createCompass();
compass.setScale(0.1);
compass.setTranslation(-1, -0.7, 2);
cameraNode.attachChild(compass);
Scene.getInstance().updateEditShapes();
return null;
}
});
}
@Override
public PickResults doPick(final Ray3 pickRay) {
return null;
}
public FrameHandler getFrameHandler() {
return frameHandler;
}
public Canvas getCanvas() {
return canvas;
}
private Mesh createLand() {
switch (theme) {
case DEFAULT_THEME:
land.setDefaultColor(new ColorRGBA(0, 1, 0, 0.5f));
break;
case SKETCHUP_THEME:
land.setDefaultColor(new ColorRGBA(1, 1, 1, 0.9f));
break;
}
land.setRenderState(HousePart.offsetState);
final BlendState blendState = new BlendState();
blendState.setBlendEnabled(true);
land.setRenderState(blendState);
land.getSceneHints().setRenderBucketType(RenderBucketType.Transparent);
final MaterialState ms = new MaterialState();
ms.setColorMaterial(ColorMaterial.Diffuse);
land.setRenderState(ms);
land.updateModelBound();
return land;
}
public void drawGrids(final double gridSize) {
gridsMesh.setDefaultColor(ColorRGBA.BLUE);
gridsMesh.setModelBound(new BoundingBox());
Util.disablePickShadowLight(gridsMesh);
final ReadOnlyVector3 width = Vector3.UNIT_X.multiply(2000, null);
final ReadOnlyVector3 height = Vector3.UNIT_Y.multiply(2000, null);
final ArrayList<ReadOnlyVector3> points = new ArrayList<ReadOnlyVector3>();
final ReadOnlyVector3 pMiddle = Vector3.ZERO;
final int cols = (int) (width.length() / gridSize);
for (int col = 1; col < cols / 2 + 1; col++) {
for (int neg = -1; neg <= 1; neg += 2) {
final ReadOnlyVector3 lineP1 = width.normalize(null).multiplyLocal(neg * col * gridSize).addLocal(pMiddle).subtractLocal(height.multiply(0.5, null));
points.add(lineP1);
final ReadOnlyVector3 lineP2 = lineP1.add(height, null);
points.add(lineP2);
if (col == 0)
break;
}
}
final int rows = (int) (height.length() / gridSize);
for (int row = 1; row < rows / 2 + 1; row++) {
for (int neg = -1; neg <= 1; neg += 2) {
final ReadOnlyVector3 lineP1 = height.normalize(null).multiplyLocal(neg * row * gridSize).addLocal(pMiddle).subtractLocal(width.multiply(0.5, null));
points.add(lineP1);
final ReadOnlyVector3 lineP2 = lineP1.add(width, null);
points.add(lineP2);
if (row == 0)
break;
}
}
final FloatBuffer buf = BufferUtils.createVector3Buffer(points.size());
for (final ReadOnlyVector3 p : points)
buf.put(p.getXf()).put(p.getYf()).put(0.01f);
gridsMesh.getMeshData().setVertexBuffer(buf);
gridsMesh.getMeshData().updateVertexCount();
gridsMesh.updateModelBound();
}
public void setGridsVisible(final boolean visible) {
gridsMesh.getSceneHints().setCullHint(visible ? CullHint.Inherit : CullHint.Always);
}
private Mesh createSky() {
daySkyState = new TextureState();
daySkyState.setTexture(TextureManager.load("daysky.jpg", Texture.MinificationFilter.Trilinear, TextureStoreFormat.GuessNoCompressedFormat, true));
nightSkyState = new TextureState();
nightSkyState.setTexture(TextureManager.load("nightsky.jpg", Texture.MinificationFilter.Trilinear, TextureStoreFormat.GuessNoCompressedFormat, true));
final Dome sky = new Dome("Sky", 100, 100, SKY_RADIUS);
sky.setRotation(new Matrix3().fromAngles(Math.PI / 2, 0, 0));
sky.setRenderState(daySkyState);
sky.getSceneHints().setLightCombineMode(LightCombineMode.Off);
sky.getSceneHints().setAllPickingHints(false);
return sky;
}
public void changeSkyTexture() {
if (sky != null)
sky.setRenderState(Heliodon.getInstance().isNightTime() ? nightSkyState : daySkyState);
}
private Spatial createAxes() {
final int axisLen = 1000;
final Node axisRoot = new Node();
FloatBuffer buf;
Line line;
// X-Axis
buf = BufferUtils.createVector3Buffer(2);
buf.put(-axisLen).put(0).put(0);
buf.put(axisLen).put(0).put(0);
line = new Line("X-Axis", buf, null, null, null);
line.setDefaultColor(ColorRGBA.RED);
Util.disablePickShadowLight(line);
axisRoot.attachChild(line);
// Y-Axis
buf = BufferUtils.createVector3Buffer(2);
buf.put(0).put(-axisLen).put(0);
buf.put(0).put(axisLen).put(0);
line = new Line("Y-Axis", buf, null, null, null);
line.setDefaultColor(ColorRGBA.GREEN);
Util.disablePickShadowLight(line);
axisRoot.attachChild(line);
// Z-Axis
buf = BufferUtils.createVector3Buffer(2);
buf.put(0).put(0).put(-axisLen);
buf.put(0).put(0).put(axisLen);
line = new Line("Z-Axis", buf, null, null, null);
Util.disablePickShadowLight(line);
line.setDefaultColor(ColorRGBA.BLUE);
axisRoot.attachChild(line);
return axisRoot;
}
private Mesh createKinectPointer() {
kinectPointer = new Sphere("Kinect Pointer", 10, 10, 0.01);
return kinectPointer;
}
private void initMouse() {
logicalLayer.registerTrigger(new InputTrigger(new MouseButtonPressedCondition(MouseButton.LEFT), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
((Component) canvas).requestFocusInWindow();
if (Config.isMac()) { // control-click is mouse right-click on the Mac, skip
final KeyboardState ks = inputStates.getCurrent().getKeyboardState();
if (ks.isDown(Key.LCONTROL) || ks.isDown(Key.RCONTROL))
return;
}
if (firstClickState == null) {
firstClickState = inputStates;
mousePressed(inputStates.getCurrent().getMouseState());
} else {
firstClickState = null;
mouseReleased(inputStates.getCurrent().getMouseState());
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new MouseButtonReleasedCondition(MouseButton.LEFT), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (Config.isMac()) { // control-click is mouse right-click on the Mac, skip
final KeyboardState ks = inputStates.getCurrent().getKeyboardState();
if (ks.isDown(Key.LCONTROL) || ks.isDown(Key.RCONTROL))
return;
}
// if editing object using select or resize then only mouse drag is allowed
if (operation == Operation.SELECT || operation == Operation.RESIZE) {
firstClickState = null;
mouseReleased(inputStates.getCurrent().getMouseState());
} else if (firstClickState != null) {
final MouseState mouseState = inputStates.getCurrent().getMouseState();
final MouseState prevMouseState = firstClickState.getCurrent().getMouseState();
final ReadOnlyVector2 p1 = new Vector2(prevMouseState.getX(), prevMouseState.getY());
final ReadOnlyVector2 p2 = new Vector2(mouseState.getX(), mouseState.getY());
if (selectedHousePart instanceof Roof || selectedHousePart instanceof Floor || selectedHousePart instanceof SolarPanel || selectedHousePart instanceof Sensor || selectedHousePart instanceof Tree || selectedHousePart instanceof Human || p1.distance(p2) > 10) {
firstClickState = null;
mouseReleased(inputStates.getCurrent().getMouseState());
}
}
}
}));
((Component) canvas).addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
if (Util.isRightClick(e)) {
final JPanel cp = MainPanel.getInstance().getCanvasPanel();
mouseRightClicked(e.getX(), cp.getHeight() - e.getY());
}
}
@Override
public void mouseReleased(final MouseEvent e) {
if (Util.isRightClick(e)) {
if (cameraChanged) {
TimeSeriesLogger.getInstance().logCamera("Pan");
cameraChanged = false;
}
}
}
});
((Component) canvas).addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(final MouseEvent e) {
EnergyPanel.getInstance().update();
cameraChanged = true;
}
});
((Component) canvas).addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(final MouseWheelEvent e) {
TimeSeriesLogger.getInstance().logCamera("Zoom");
}
});
logicalLayer.registerTrigger(new InputTrigger(new MouseMovedCondition(), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
refresh = true;
mouseState = inputStates.getCurrent().getMouseState();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new MouseButtonClickedCondition(MouseButton.LEFT), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (Config.isMac()) { // control-click is mouse right-click on the Mac, skip
final KeyboardState ks = inputStates.getCurrent().getKeyboardState();
if (ks.isDown(Key.LCONTROL) || ks.isDown(Key.RCONTROL))
return;
}
if (!isTopView() && inputStates.getCurrent().getMouseState().getClickCount(MouseButton.LEFT) == 2) {
if (PrintController.getInstance().isPrintPreview()) {
final MouseState mouse = inputStates.getCurrent().getMouseState();
final Ray3 pickRay = Camera.getCurrentCamera().getPickRay(new Vector2(mouse.getX(), mouse.getY()), false, null);
final PickResults pickResults = new PrimitivePickResults();
PickingUtil.findPick(PrintController.getInstance().getPagesRoot(), pickRay, pickResults, false);
if (pickResults.getNumber() > 0)
cameraControl.zoomAtPoint(pickResults.getPickData(0).getIntersectionRecord().getIntersectionPoint(0));
} else {
final PickedHousePart pickedHousePart = SelectUtil.pickPart(inputStates.getCurrent().getMouseState().getX(), inputStates.getCurrent().getMouseState().getY());
if (pickedHousePart != null)
cameraControl.zoomAtPoint(pickedHousePart.getPoint());
}
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.LSHIFT), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
// SelectUtil.setPickLayer(0);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyReleasedCondition(Key.LSHIFT), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
// SelectUtil.setPickLayer(-1);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.DELETE), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
deleteCurrentHousePart();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.BACK), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
deleteCurrentHousePart();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.ESCAPE), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
hideAllEditPoints();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.ZERO), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
final KeyboardState ks = inputStates.getCurrent().getKeyboardState();
if (Config.isMac()) {
if (ks.isDown(Key.LMETA) || ks.isDown(Key.RMETA)) {
resetCamera();
}
} else {
if (ks.isDown(Key.LCONTROL) || ks.isDown(Key.RCONTROL)) {
resetCamera();
}
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.I), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
System.out.println("---- Parts: ------------------------");
System.out.println("size = " + Scene.getInstance().getParts().size());
for (final HousePart part : Scene.getInstance().getParts())
System.out.println(part);
System.out.println("---- Scene: ------------------------");
System.out.println("size = " + Scene.getOriginalHouseRoot().getNumberOfChildren());
for (final Spatial mesh : Scene.getOriginalHouseRoot().getChildren()) {
System.out.println(mesh);
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.R), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
Scene.getInstance().redrawAll(true);
}
}));
// Run/pause model replay
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.SPACE), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (PlayControl.active) {
PlayControl.replaying = !PlayControl.replaying;
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.LEFT), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (PlayControl.active) {
PlayControl.replaying = false;
PlayControl.backward = true;
}
if (SceneManager.getInstance().isTopView()) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(-1, 0, 0));
} else {
if (selectedHousePart instanceof Window) {
final Vector3 v = selectedHousePart.getNormal().clone();
v.crossLocal(Vector3.UNIT_Z);
moveWithKey(inputStates.getCurrent().getKeyboardState(), v);
Scene.getInstance().redrawAll();
}
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.UP), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (PlayControl.active) {
PlayControl.replaying = false;
PlayControl.backward = true;
}
if (SceneManager.getInstance().isTopView()) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(0, 1, 0));
} else {
if (selectedHousePart instanceof Window) {
final Vector3 n = selectedHousePart.getNormal().clone();
final Vector3 v = n.cross(Vector3.UNIT_Z, null);
moveWithKey(inputStates.getCurrent().getKeyboardState(), v.crossLocal(n));
Scene.getInstance().redrawAll();
}
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.RIGHT), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (PlayControl.active) {
PlayControl.replaying = false;
PlayControl.forward = true;
}
if (SceneManager.getInstance().isTopView()) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(1, 0, 0));
} else {
if (selectedHousePart instanceof Window) {
final Vector3 v = selectedHousePart.getNormal().clone();
v.crossLocal(Vector3.UNIT_Z).negateLocal();
moveWithKey(inputStates.getCurrent().getKeyboardState(), v);
Scene.getInstance().redrawAll();
}
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.DOWN), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (PlayControl.active) {
PlayControl.replaying = false;
PlayControl.forward = true;
}
if (SceneManager.getInstance().isTopView()) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(0, -1, 0));
} else {
if (selectedHousePart instanceof Window) {
final Vector3 n = selectedHousePart.getNormal().clone();
final Vector3 v = n.cross(Vector3.UNIT_Z, null).negateLocal();
moveWithKey(inputStates.getCurrent().getKeyboardState(), v.crossLocal(n));
Scene.getInstance().redrawAll();
}
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.ESCAPE), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
PlayControl.active = false;
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.W), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(-1, 0, 0));
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.E), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(1, 0, 0));
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.S), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(0, -1, 0));
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.N), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(0, 1, 0));
}
}));
}
private void moveWithKey(final KeyboardState ks, final Vector3 v) {
if (ks.isDown(Key.LCONTROL) || ks.isDown(Key.RCONTROL) || ks.isDown(Key.LMETA) || ks.isDown(Key.LMETA))
return; // Ctrl/Cmd+key is often used for other purposes such as Ctrl+S or Cmd+S
fineGrid = ks.isDown(Key.LSHIFT) || ks.isDown(Key.RSHIFT);
move(v);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
EnergyPanel.getInstance().updateProperties();
}
});
}
public void move(final Vector3 v) {
MoveBuildingCommand c = null;
if (selectedHousePart == null) {
c = new MoveBuildingCommand(null, v);
for (final HousePart p : Scene.getInstance().getParts()) {
if (p instanceof Foundation) {
((Foundation) p).move(v, p.getGridSize());
}
}
} else if (selectedHousePart instanceof Foundation) {
c = new MoveBuildingCommand((Foundation) selectedHousePart, v);
((Foundation) selectedHousePart).move(v, selectedHousePart.getGridSize());
} else if (selectedHousePart instanceof Window) {
((Window) selectedHousePart).move(v);
}
if (c != null)
undoManager.addEdit(c);
Scene.getInstance().redrawAll();
Scene.getInstance().setEdited(true);
}
public void setCameraControl(final CameraMode type) {
if (cameraControl != null)
cameraControl.removeTriggers(logicalLayer);
if (type == CameraMode.ORBIT)
cameraControl = new OrbitControl(Vector3.UNIT_Z);
else if (type == CameraMode.FIRST_PERSON)
cameraControl = new FirstPersonControl(Vector3.UNIT_Z);
cameraControl.setupMouseTriggers(logicalLayer, true);
cameraControl.setMoveSpeed(MOVE_SPEED);
cameraControl.setKeyRotateSpeed(1);
}
public CameraControl getCameraControl() {
return cameraControl;
}
public void hideAllEditPoints() {
for (final HousePart part : Scene.getInstance().getParts()) {
part.setEditPointsVisible(false);
part.setGridsVisible(false);
}
selectedHousePart = null;
refresh = true;
}
public void resetCamera() {
resetCamera(viewMode);
cameraControl.reset();
refresh = true;
}
public void resetCamera(final ViewMode viewMode) {
System.out.println("resetCamera()");
this.viewMode = viewMode;
final Camera camera = getCamera();
cameraControl.setMouseButtonActions(ButtonAction.MOVE, ButtonAction.MOVE);
cameraControl.setMoveSpeed(MOVE_SPEED);
ReadOnlyVector3 loc = new Vector3(0, -120, 50);
ReadOnlyVector3 up = new Vector3(0, 0, 1);
ReadOnlyVector3 lookAt = new Vector3(0, 0, 0);
setCompassVisible(viewMode == ViewMode.NORMAL);
if (viewMode == ViewMode.NORMAL) {
cameraControl.setMouseButtonActions(ButtonAction.ROTATE, ButtonAction.MOVE);
camera.setProjectionMode(ProjectionMode.Perspective);
resizeCamera();
} else if (viewMode == ViewMode.TOP_VIEW) {
camera.setProjectionMode(ProjectionMode.Parallel);
loc = new Vector3(0, 0, 500);
up = new Vector3(0, 1, 0);
lookAt = new Vector3(0, 0, 0);
final double boundLength = Util.findBoundLength(Scene.getRoot().getWorldBound());
cameraControl.setMoveSpeed(boundLength / 2);
resizeCamera(boundLength);
} else if (viewMode == ViewMode.PRINT) {
camera.setProjectionMode(ProjectionMode.Parallel);
/* location will be set in PrintController.print() */
loc = new Vector3(0, -10, 0);
up = new Vector3(0, 0, -1);
} else if (viewMode == ViewMode.PRINT_PREVIEW) {
cameraControl.setMouseButtonActions(ButtonAction.MOVE, ButtonAction.MOVE);
camera.setProjectionMode(ProjectionMode.Perspective);
loc = PrintController.getInstance().getZoomAllCameraLocation();
lookAt = loc.add(0, 1, 0, null);
resizeCamera(PrintController.getInstance().getPageWidth());
}
camera.setLocation(loc);
camera.lookAt(lookAt, up);
camera.update();
cameraNode.updateFromCamera();
Scene.getInstance().updateEditShapes();
}
public ViewMode getViewMode() {
return viewMode;
}
private void resizeCamera() {
final BoundingVolume bounds = Scene.getRoot().getWorldBound();
if (bounds == null)
resizeCamera(2);
else
resizeCamera(Util.findBoundLength(bounds));
}
public void resizeCamera(final double orthoWidth) {
final Camera camera = getCamera();
if (camera == null)
return;
final Dimension size = ((Component) canvas).getSize();
camera.resize(size.width, size.height);
final double ratio = (double) size.width / size.height;
final double near = 1;
final double far = 2000;
if (camera.getProjectionMode() == ProjectionMode.Parallel)
camera.setFrustum(near, far, -orthoWidth / 2, orthoWidth / 2, orthoWidth / ratio / 2, -orthoWidth / ratio / 2);
else
camera.setFrustumPerspective(45.0, ratio, near, far);
}
public void toggleSpinView() {
cameraControl.reset();
rotAnim = !rotAnim;
}
public boolean getSpinView() {
return rotAnim;
}
public void setSpinView(final boolean spinView) {
rotAnim = spinView;
}
public void setOperation(final Operation operation) {
operationStick = false;
if (this.operation != operation) {
this.operation = operation;
operationFlag = true;
// need to be here to ensure immediate removal of unfinished house part before computeEnergy thread is started
SceneManager.getTaskManager().update(new Callable<Object>() {
@Override
public Object call() throws Exception {
if (selectedHousePart != null) {
if (selectedHousePart.isDrawCompleted())
selectedHousePart.setEditPointsVisible(false);
else
Scene.getInstance().remove(selectedHousePart, false);
selectedHousePart = null;
}
return null;
}
});
}
}
public void setOperationStick(final boolean stick) {
operationStick = stick;
}
public void executeOperation() {
operationFlag = false;
for (final HousePart part : Scene.getInstance().getParts())
if (part instanceof Foundation)
((Foundation) part).setResizeHouseMode(operation == Operation.RESIZE);
if (viewMode != ViewMode.PRINT_PREVIEW)
Scene.getInstance().drawResizeBounds();
selectedHousePart = newHousePart();
if (selectedHousePart != null)
cameraControl.setLeftMouseButtonEnabled(false);
}
private HousePart newHousePart() {
final HousePart drawn;
setGridsVisible(false);
if (operation == Operation.DRAW_WALL) {
drawn = new Wall();
drawn.setColor(Scene.getInstance().getWallColor());
} else if (operation == Operation.DRAW_DOOR) {
drawn = new Door();
drawn.setColor(Scene.getInstance().getDoorColor());
} else if (operation == Operation.DRAW_WINDOW) {
drawn = new Window();
} else if (operation == Operation.DRAW_ROOF_PYRAMID) {
drawn = new PyramidRoof();
drawn.setColor(Scene.getInstance().getRoofColor());
} else if (operation == Operation.DRAW_ROOF_HIP) {
drawn = new HipRoof();
drawn.setColor(Scene.getInstance().getRoofColor());
} else if (operation == Operation.DRAW_ROOF_SHED) {
drawn = new ShedRoof();
drawn.setColor(Scene.getInstance().getRoofColor());
} else if (operation == Operation.DRAW_ROOF_GAMBREL) {
drawn = new GambrelRoof();
drawn.setColor(Scene.getInstance().getRoofColor());
} else if (operation == Operation.DRAW_ROOF_CUSTOM) {
drawn = new CustomRoof();
drawn.setColor(Scene.getInstance().getRoofColor());
} else if (operation == Operation.DRAW_FLOOR) {
drawn = new Floor();
drawn.setColor(Scene.getInstance().getFloorColor());
} else if (operation == Operation.DRAW_SOLAR_PANEL) {
drawn = new SolarPanel(false);
} else if (operation == Operation.DRAW_SENSOR) {
drawn = new Sensor();
} else if (operation == Operation.DRAW_FOUNDATION) {
drawn = new Foundation();
setGridsVisible(true);
drawn.setColor(Scene.getInstance().getFoundationColor());
} else if (operation == Operation.DRAW_DOGWOOD) {
drawn = new Tree(Tree.DOGWOOD);
setGridsVisible(true);
} else if (operation == Operation.DRAW_ELM) {
drawn = new Tree(Tree.ELM);
setGridsVisible(true);
} else if (operation == Operation.DRAW_OAK) {
drawn = new Tree(Tree.OAK);
setGridsVisible(true);
} else if (operation == Operation.DRAW_LINDEN) {
drawn = new Tree(Tree.LINDEN);
setGridsVisible(true);
} else if (operation == Operation.DRAW_COTTONWOOD) {
drawn = new Tree(Tree.COTTONWOOD);
setGridsVisible(true);
} else if (operation == Operation.DRAW_MAPLE) {
drawn = new Tree(Tree.MAPLE);
setGridsVisible(true);
} else if (operation == Operation.DRAW_PINE) {
drawn = new Tree(Tree.PINE);
setGridsVisible(true);
} else if (operation == Operation.DRAW_JANE) {
drawn = new Human(Human.JANE);
setGridsVisible(true);
} else if (operation == Operation.DRAW_JENI) {
drawn = new Human(Human.JENI);
setGridsVisible(true);
} else if (operation == Operation.DRAW_JILL) {
drawn = new Human(Human.JILL);
setGridsVisible(true);
} else if (operation == Operation.DRAW_JACK) {
drawn = new Human(Human.JACK);
setGridsVisible(true);
} else if (operation == Operation.DRAW_JOHN) {
drawn = new Human(Human.JOHN);
setGridsVisible(true);
} else if (operation == Operation.DRAW_JOSE) {
drawn = new Human(Human.JOSE);
setGridsVisible(true);
} else
return null;
Scene.getInstance().add(drawn, false);
addHousePartCommand = new AddPartCommand(drawn);
return drawn;
}
public Operation getOperation() {
return operation;
}
public void setShading(final boolean enable) {
taskManager.update(new Callable<Object>() {
@Override
public Object call() throws Exception {
lightState.setEnabled(enable);
root.updateWorldRenderStates(true);
return null;
}
});
}
public void setHeliodonVisible(final boolean selected) {
heliodonControl = selected;
Heliodon.getInstance().setVisible(selected);
enableDisableRotationControl();
EnergyPanel.getInstance().compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI);
}
public void setSunAnimation(final boolean selected) {
sunAnim = selected;
}
public boolean isSunAnimation() {
return sunAnim;
}
public void enableDisableRotationControl() {
if (!mouseControlEnabled)
return;
if ((operation == Operation.SELECT || operation == Operation.RESIZE) && (selectedHousePart == null || selectedHousePart.isDrawCompleted()))
cameraControl.setMouseEnabled(true);
else
cameraControl.setMouseEnabled(false);
if (heliodonControl)
cameraControl.setKeyRotateSpeed(0);
else
cameraControl.setKeyRotateSpeed(1);
}
public HousePart getSelectedPart() {
return selectedHousePart;
}
public void setSelectedPart(final HousePart p) {
if (p == null && selectedHousePart != null)
selectedHousePart.setEditPointsVisible(false);
selectedHousePart = p;
if (selectedHousePart != null)
selectedHousePart.setEditPointsVisible(true);
}
public boolean isTopView() {
return viewMode == ViewMode.TOP_VIEW;
}
public void updatePrintPreviewScene(final boolean printPreview) {
if (printPreview)
Scene.saveCameraLocation();
resetCamera(printPreview ? ViewMode.PRINT_PREVIEW : ViewMode.NORMAL);
if (!printPreview) {
Scene.loadCameraLocation();
if (cameraControl instanceof OrbitControl)
((OrbitControl) cameraControl).clearOrbitCenter();
}
backgroundRoot.getSceneHints().setCullHint(printPreview ? CullHint.Always : CullHint.Inherit);
}
public CameraNode getCameraNode() {
return cameraNode;
}
private Node createCompass() throws IOException {
System.out.print("Loading compass...");
final ResourceSource source = ResourceLocatorTool.locateResource(ResourceLocatorTool.TYPE_MODEL, "compass.dae");
final ColladaImporter colladaImporter = new ColladaImporter();
// Load the collada scene
Logger.getLogger(ColladaAnimUtils.class.getName()).setLevel(Level.SEVERE);
Logger.getLogger(ColladaMaterialUtils.class.getName()).setLevel(Level.SEVERE);
final ColladaStorage storage = colladaImporter.load(source);
final Node compass = storage.getScene();
BMText txt;
final double Z = 0.1;
txt = new BMText("N", "N", FontManager.getInstance().getAnnotationFont(), Align.South);
txt.setAutoRotate(false);
txt.setTranslation(2, 0.0, Z);
txt.setRotation(new Matrix3().fromAngles(0.0, MathUtils.HALF_PI, -MathUtils.HALF_PI));
compass.attachChild(txt);
txt = new BMText("S", "S", FontManager.getInstance().getAnnotationFont(), Align.South);
txt.setAutoRotate(false);
txt.setTranslation(-2, -0.0, Z);
txt.setRotation(new Matrix3().fromAngles(0.0, -MathUtils.HALF_PI, MathUtils.HALF_PI));
compass.attachChild(txt);
txt = new BMText("W", "W", FontManager.getInstance().getAnnotationFont(), Align.South);
txt.setAutoRotate(false);
txt.setTranslation(-0.0, 2, Z);
txt.setRotation(new Matrix3().fromAngles(-MathUtils.HALF_PI, 0.0, 0.0));
compass.attachChild(txt);
txt = new BMText("E", "E", FontManager.getInstance().getAnnotationFont(), Align.South);
txt.setAutoRotate(false);
txt.setTranslation(-0.0, -2, Z);
txt.setRotation(new Matrix3().fromAngles(MathUtils.HALF_PI, MathUtils.PI, 0.0));
compass.attachChild(txt);
final DirectionalLight light = new DirectionalLight();
light.setDirection(new Vector3(0, 0, -1));
light.setEnabled(true);
final LightState lightState = new LightState();
lightState.attach(light);
compass.setRenderState(lightState);
compass.getSceneHints().setLightCombineMode(LightCombineMode.Replace);
compass.updateWorldRenderStates(true);
final Node compassNode = new Node();
compassNode.setRotation(new Matrix3().fromAngles(-MathUtils.HALF_PI, 0.0, 0.0));
compassNode.attachChild(compass);
System.out.println("done");
compass.addController(new SpatialController<Spatial>() {
@Override
public void update(final double time, final Spatial caller) {
final Vector3 direction = getCamera().getDirection().normalize(null);
direction.setZ(0);
direction.normalizeLocal();
double angle = -direction.smallestAngleBetween(Vector3.UNIT_Y);
if (direction.dot(Vector3.UNIT_X) > 0)
angle = -angle;
angle -= MathUtils.HALF_PI;
compass.setRotation(new Matrix3().fromAngles(0.0, 0.0, angle - 0.3));
}
});
return compassNode;
}
public void setCompassVisible(final boolean visible) {
cameraNode.getSceneHints().setCullHint(visible ? CullHint.Inherit : CullHint.Always);
}
public void updateHeliodonAndAnnotationSize() {
if (heliodonControl)
taskManager.update(new Callable<Object>() {
@Override
public Object call() throws Exception {
Heliodon.getInstance().updateSize();
return null;
}
});
}
private void mouseMoved() {
if (!mouseControlEnabled)
return;
final int x = mouseState.getX();
final int y = mouseState.getY();
try {
if (editHousePartCommand != null && editHousePartCommand.isReallyEdited())
EnergyPanel.getInstance().cancel();
if (selectedHousePart != null && !selectedHousePart.isDrawCompleted()) {
selectedHousePart.setPreviewPoint(x, y);
} else if (houseMoveStartPoint != null && (operation == Operation.RESIZE || selectedHousePart instanceof Foundation) && selectedHousePart.isDrawCompleted()) {
final PickedHousePart pick = SelectUtil.pickPart(x, y, collisionLand);
if (pick != null) {
if (selectedHousePart instanceof Foundation) {
final Foundation foundation = (Foundation) selectedHousePart;
final Vector3 pickPoint = pick.getPoint().clone();
// if (!foundation.insideBuilding(pickPoint.getX(), pickPoint.getY(), true)) { // only move the building when clicking outside
final Vector3 d = pickPoint.multiply(1, 1, 0, null).subtractLocal(houseMoveStartPoint.multiply(1, 1, 0, null));
foundation.move(d, houseMovePoints);
}
}
} else if (houseMoveStartPoint != null && selectedHousePart != null && selectedHousePart.isDrawCompleted() && selectedHousePart instanceof Tree) {
final PickedHousePart pick = SelectUtil.pickPart(x, y, collisionLand);
if (pick != null) {
final Vector3 d = pick.getPoint().multiply(1, 1, 0, null).subtractLocal(houseMoveStartPoint.multiply(1, 1, 0, null));
((Tree) selectedHousePart).move(d, houseMovePoints);
}
} else if (houseMoveStartPoint != null && selectedHousePart != null && selectedHousePart.isDrawCompleted() && selectedHousePart instanceof Window) {
final PickedHousePart pick = SelectUtil.pickPart(x, y, selectedHousePart.getContainer());
if (pick != null) {
final Vector3 d = pick.getPoint().clone().subtractLocal(houseMoveStartPoint);
((Window) selectedHousePart).move(d, houseMovePoints);
}
} else if ((operation == Operation.SELECT || operation == Operation.RESIZE) && mouseState.getButtonState(MouseButton.LEFT) == ButtonState.UP && mouseState.getButtonState(MouseButton.MIDDLE) == ButtonState.UP && mouseState.getButtonState(MouseButton.RIGHT) == ButtonState.UP) {
final PickedHousePart selectHousePart = SelectUtil.selectHousePart(x, y, false);
pick = selectHousePart == null ? null : selectHousePart.getUserData();
final HousePart housePart = pick == null ? null : pick.getHousePart();
if (pick != null) {
hoveredHousePart = housePart;
if (hoveredHousePart.isFrozen())
hoveredHousePart = null;
if (pick.getIndex() != -1)
lastSelectedEditPointMouseState = mouseState;
} else
hoveredHousePart = null;
}
mouseState = null;
} catch (Throwable t) {
t.printStackTrace();
Util.reportError(t);
}
final Component canvasComponent = (Component) canvas;
if (!zoomLock && (operation == Operation.SELECT || operation == Operation.RESIZE) && hoveredHousePart != null && pick.getIndex() == -1 && (hoveredHousePart instanceof Foundation || hoveredHousePart instanceof SolarPanel || hoveredHousePart instanceof Sensor || hoveredHousePart instanceof Window || hoveredHousePart instanceof Tree || hoveredHousePart instanceof Human))
canvasComponent.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
else
canvasComponent.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
public void setMouseControlEnabled(final boolean enabled) {
mouseControlEnabled = enabled;
cameraControl.setMouseEnabled(enabled);
}
@Override
public void init() {
if (Config.RENDER_MODE != RenderMode.LWJGL)
initCamera();
}
public boolean isShadingEnabled() {
return lightState.isEnabled();
}
public void setShadow(final boolean shadow) {
taskManager.update(new Callable<Object>() {
@Override
public Object call() throws Exception {
shadowPass.setEnabled(shadow);
root.updateWorldRenderStates(true);
return null;
}
});
}
public boolean isShadowEnabled() {
return shadowPass.isEnabled();
}
public void setZoomLock(final boolean zoomLock) {
this.zoomLock = zoomLock;
cameraControl.setLeftButtonAction(zoomLock ? ButtonAction.ZOOM : viewMode == ViewMode.NORMAL ? ButtonAction.ROTATE : ButtonAction.MOVE);
}
public void zoom(final boolean in) {
cameraControl.zoom(canvas, 0.1, in ? -1 : 1);
}
public void refresh() {
refresh = true;
}
public synchronized void refreshNow() {
refresh = true;
try {
wait();
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
public void refresh(final double updateDurationInSeconds) {
refreshTime = frameHandler.getTimer().getTimeInSeconds() + updateDurationInSeconds;
}
public UndoManager getUndoManager() {
return undoManager;
}
public Timer getTimer() {
return frameHandler.getTimer();
}
public Mesh getLand() {
return land;
}
public Mesh getSolarLand() {
return solarLand;
}
public boolean isHeliodonVisible() {
return heliodonControl;
}
// the x and y coordinates come from MouseEvent, not MouseState.
private void mouseRightClicked(final int x, final int y) {
mouseState = new MouseState(x, y, 0, 0, 0, null, null);
pasteMouseState = mouseState;
refresh = true;
taskManager.update(new Callable<Object>() {
@Override
public Object call() {
try {
if (operation == Operation.SELECT) {
final HousePart previousSelectedHousePart = selectedHousePart;
if (mouseState == null) // for some reason, there is a small chance that mouseState is nullified here
mouseState = new MouseState(x, y, 0, 0, 0, null, null);
final PickedHousePart pickedHousePart = SelectUtil.selectHousePart(mouseState.getX(), mouseState.getY(), true);
final UserData pick = pickedHousePart == null ? null : pickedHousePart.getUserData();
selectedHousePart = pick == null ? null : pick.getHousePart();
System.out.println("Right-clicked on: (" + mouseState.getX() + ", " + mouseState.getY() + ") " + pick);
if (previousSelectedHousePart != null && previousSelectedHousePart != selectedHousePart) {
previousSelectedHousePart.setEditPointsVisible(false);
previousSelectedHousePart.setGridsVisible(false);
}
if (selectedHousePart != null) {
selectedHousePart.complete(); // to undo edit flag set by SelectUtil above
if (!PrintController.getInstance().isPrintPreview())
selectedHousePart.setEditPointsVisible(true);
EnergyPanel.getInstance().update();
}
EnergyPanel.getInstance().updateGraphs();
final JPanel cp = MainPanel.getInstance().getCanvasPanel();
PopupMenuFactory.getPopupMenu(onLand(pasteMouseState.getX(), pasteMouseState.getY())).show(cp, mouseState.getX(), cp.getHeight() - mouseState.getY());
}
} catch (Throwable t) {
t.printStackTrace();
Util.reportError(t);
}
return null;
}
});
}
private void mousePressed(final MouseState mouseState) {
refresh = true;
taskManager.update(new Callable<Object>() {
@Override
public Object call() {
if (zoomLock)
return null;
System.out.println("OPERATION: " + operation);
try {
if (operation == Operation.SELECT || operation == Operation.RESIZE || operation == Operation.ROTATE || operation == Operation.DRAW_ROOF_GABLE) {
if (selectedHousePart == null || selectedHousePart.isDrawCompleted()) {
final HousePart previousSelectedHousePart = selectedHousePart;
final PickedHousePart selectHousePart = SelectUtil.selectHousePart(mouseState.getX(), mouseState.getY(), true);
final UserData pick = selectHousePart == null ? null : selectHousePart.getUserData();
if (pick == null)
selectedHousePart = null;
else
selectedHousePart = pick.getHousePart();
if (selectedHousePart != null && selectedHousePart.isFrozen())
selectedHousePart = null;
System.out.println("Clicked on: " + pick);
if (pick != null && pick.isEditPoint()) {
cameraControl.setLeftMouseButtonEnabled(false);
}
if (operation == Operation.SELECT || operation == Operation.ROTATE) {
if (previousSelectedHousePart instanceof Foundation) {
((Foundation) previousSelectedHousePart).updateAzimuthArrowVisibility(false);
}
if (selectedHousePart instanceof Foundation) {
((Foundation) selectedHousePart).drawAzimuthArrow();
}
}
if (operation == Operation.RESIZE && selectedHousePart != null) {
if (!(selectedHousePart instanceof Foundation)) {
selectedHousePart.setEditPointsVisible(false);
selectedHousePart = selectedHousePart.getTopContainer();
}
}
if (selectedHousePart instanceof Window || selectedHousePart instanceof Tree || selectedHousePart instanceof Foundation) {
cameraControl.setLeftMouseButtonEnabled(false);
houseMoveStartPoint = selectHousePart.getPoint().clone();
collisionLand.setTranslation(0, 0, houseMoveStartPoint.getZ());
final ArrayList<Vector3> points = selectedHousePart.getPoints();
houseMovePoints = new ArrayList<Vector3>(points.size());
for (final Vector3 p : points)
houseMovePoints.add(p.clone());
}
if (previousSelectedHousePart != null && previousSelectedHousePart != selectedHousePart && operation != Operation.RESIZE) {
previousSelectedHousePart.setEditPointsVisible(false);
previousSelectedHousePart.setGridsVisible(false);
}
if (selectedHousePart != null && !PrintController.getInstance().isPrintPreview()) {
selectedHousePart.setEditPointsVisible(true);
if (pick.isEditPoint() && pick.getIndex() != -1 || operation == Operation.RESIZE || selectedHousePart instanceof Window || selectedHousePart instanceof Tree || selectedHousePart instanceof Foundation) {
selectedHousePart.setGridsVisible(true);
if (selectedHousePart instanceof Foundation)
editHousePartCommand = new EditFoundationCommand((Foundation) selectedHousePart, !pick.isEditPoint());
else
editHousePartCommand = new EditPartCommand(selectedHousePart);
}
}
SelectUtil.nextPickLayer();
if (operation == Operation.DRAW_ROOF_GABLE && selectedHousePart instanceof Roof) {
System.out.println(selectedHousePart);
System.out.println("deleting roof #" + pick.getIndex());
final int roofPartIndex = pick.getIndex();
final Roof roof = (Roof) selectedHousePart;
roof.setGable(roofPartIndex, true, undoManager);
}
}
} else {
selectedHousePart.addPoint(mouseState.getX(), mouseState.getY());
}
} catch (Throwable t) {
t.printStackTrace();
Util.reportError(t);
}
return null;
}
});
}
private void mouseReleased(final MouseState mouseState) {
refresh = true;
taskManager.update(new Callable<Object>() {
@Override
public Object call() {
try {
if (selectedHousePart != null)
selectedHousePart.setGridsVisible(false);
if (operation == Operation.SELECT || operation == Operation.RESIZE) {
if (selectedHousePart != null && (!selectedHousePart.isDrawCompleted() || houseMoveStartPoint != null)) {
if (selectedHousePart.isDrawable()) {
selectedHousePart.complete();
if (editHousePartCommand != null && editHousePartCommand.isReallyEdited())
EnergyPanel.getInstance().compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI);
} else {
if (editHousePartCommand != null)
editHousePartCommand.undo();
selectedHousePart.setHighlight(false);
// selectedHousePart = null;
}
if (editHousePartCommand != null) {
if (editHousePartCommand.isReallyEdited())
undoManager.addEdit(editHousePartCommand);
editHousePartCommand = null;
}
}
if (!zoomLock)
cameraControl.setLeftMouseButtonEnabled(true);
houseMoveStartPoint = null;
houseMovePoints = null;
if (cameraChanged) {
TimeSeriesLogger.getInstance().logCamera(zoomLock ? "Zoom" : "Rotate");
cameraChanged = false;
}
} else {
if (selectedHousePart != null && !selectedHousePart.isDrawCompleted()) {
selectedHousePart.addPoint(mouseState.getX(), mouseState.getY());
if (selectedHousePart.isDrawCompleted() && !selectedHousePart.isDrawable()) {
addHousePartCommand = null;
Scene.getInstance().remove(selectedHousePart, true);
selectedHousePart = null;
if (operationStick)
operationFlag = true;
}
}
if (selectedHousePart != null && selectedHousePart.isDrawCompleted()) {
if (selectedHousePart.isDrawable()) {
if (addHousePartCommand != null)
undoManager.addEdit(addHousePartCommand);
addHousePartCommand = null;
} else
Scene.getInstance().remove(selectedHousePart, true);
selectedHousePart.setEditPointsVisible(false);
selectedHousePart = null;
if (operationStick)
operationFlag = true;
EnergyPanel.getInstance().compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI);
}
if (!operationFlag) {
MainPanel.getInstance().defaultTool();
cameraControl.setLeftMouseButtonEnabled(true);
}
}
updateHeliodonAndAnnotationSize();
EnergyPanel.getInstance().update();
} catch (Throwable t) {
t.printStackTrace();
Util.reportError(t);
}
return null;
}
});
EnergyPanel.getInstance().updateGraphs();
}
public void grabOrRelease() {
if (selectedHousePart != null && !selectedHousePart.isDrawCompleted())
mouseReleased(lastSelectedEditPointMouseState);
else
mousePressed(lastSelectedEditPointMouseState);
}
public void deleteCurrentHousePart() {
if (selectedHousePart instanceof Foundation) {
if (((Foundation) selectedHousePart).getLockEdit())
return;
if (!selectedHousePart.getChildren().isEmpty())
if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Deleting the platform also deletes the building on it. Are you sure?", "Confirmation", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION)
return;
}
if (selectedHousePart != null)
taskManager.update(new Callable<Object>() {
@Override
public Object call() throws Exception {
final RemovePartCommand command = new RemovePartCommand(selectedHousePart);
if (selectedHousePart instanceof Wall) { // undo/redo a gable roof
final Roof roof = ((Wall) selectedHousePart).getRoof();
if (roof != null) {
final List<Map<Integer, List<Wall>>> gableInfo = new ArrayList<Map<Integer, List<Wall>>>();
if (roof.getGableEditPointToWallMap() != null)
gableInfo.add(roof.getGableEditPointToWallMap());
command.setGableInfo(gableInfo);
}
} else if (selectedHousePart instanceof Foundation) { // undo/redo all the gable roofs
final List<Roof> roofs = ((Foundation) selectedHousePart).getRoofs();
if (!roofs.isEmpty()) {
final List<Map<Integer, List<Wall>>> gableInfo = new ArrayList<Map<Integer, List<Wall>>>();
for (final Roof r : roofs) {
if (r.getGableEditPointToWallMap() != null)
gableInfo.add(r.getGableEditPointToWallMap());
}
command.setGableInfo(gableInfo);
}
}
undoManager.addEdit(command);
Scene.getInstance().remove(selectedHousePart, true);
selectedHousePart = null;
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
MainPanel.getInstance().getEnergyViewButton().setSelected(false);
}
});
return null;
}
});
}
public void newImport(final URL file) throws IOException {
final ResourceSource source = new URLResourceSource(file);
final ColladaImporter colladaImporter = new ColladaImporter();
Logger.getLogger(ColladaAnimUtils.class.getName()).setLevel(Level.SEVERE);
Logger.getLogger(ColladaMaterialUtils.class.getName()).setLevel(Level.SEVERE);
final ColladaStorage storage = colladaImporter.load(source);
newImport = storage.getScene();
// newImport.setTranslation(0, 0, 30);
// newImport.setScale(0.025);
Scene.getRoot().attachChild(newImport);
}
public Camera getCamera() {
return canvas.getCanvasRenderer().getCamera();
}
public boolean getSolarHeatMap() {
return solarHeatMap;
}
public void setSolarHeatMapWithoutUpdate(final boolean solarHeatMap) {
this.solarHeatMap = solarHeatMap;
}
public void setSolarHeatMap(final boolean solarHeatMap) {
setSolarHeatMapWithoutUpdate(solarHeatMap);
EnergyPanel.getInstance().clearAlreadyRendered();
EnergyPanel.getInstance().compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI);
}
public boolean isHeatFluxDaily() {
return heatFluxDaily;
}
public void setHeatFluxDaily(final boolean heatFluxDaily) {
this.heatFluxDaily = heatFluxDaily;
}
public void setAxesVisible(final boolean b) {
if (b)
backgroundRoot.attachChild(axes);
else
backgroundRoot.detachChild(axes);
}
public boolean areAxesVisible() {
return backgroundRoot.hasChild(axes);
}
public void setHeatFluxVectorsVisible(final boolean b) {
showHeatFlux = b;
for (final HousePart part : Scene.getInstance().getParts())
part.updateHeatFluxVisibility();
}
public boolean areHeatFluxVectorsVisible() {
return showHeatFlux;
}
public void setBuildingLabelsVisible(final boolean b) {
showBuildingLabels = b;
for (final HousePart part : Scene.getInstance().getParts()) {
if (part instanceof Foundation)
((Foundation) part).showBuildingLabel(b);
}
}
public boolean areBuildingLabelsVisible() {
return showBuildingLabels;
}
/** negative angle for clockwise rotation, positive angle for counter-clockwise rotation */
public void rotateBuilding(final double angle, final boolean redraw) {
System.out.println("rotateBuilding()");
if (selectedHousePart != null) {
if (selectedHousePart instanceof Foundation) {
((Foundation) selectedHousePart).rotate(angle, null);
} else {
selectedHousePart.getTopContainer().rotate(angle, null);
}
if (redraw)
Scene.getInstance().redrawAll();
}
}
/** negative angle for clockwise rotation, positive angle for counter-clockwise rotation */
public void rotateAllBuildings(final double angle) {
System.out.println("rotateBuildings()");
final Vector3 origin = new Vector3();
for (final HousePart p : Scene.getInstance().getParts()) {
if (p instanceof Foundation) {
((Foundation) p).rotate(angle, origin);
}
}
Scene.getInstance().redrawAll();
}
public boolean isRefreshOnlyMode() {
return refreshOnlyMode;
}
public void setRefreshOnlyMode(final boolean refreshOnlyMode) {
this.refreshOnlyMode = refreshOnlyMode;
}
private boolean onLand(final int x, final int y) {
return SelectUtil.pickPart(x, y, land) != null;
}
Vector3 getPickedLocationOnLand() {
if (pasteMouseState != null) {
final PickedHousePart pick = SelectUtil.pickPart(pasteMouseState.getX(), pasteMouseState.getY(), land);
if (pick != null)
return pick.getPoint().multiply(1, 1, 0, null);
pasteMouseState = null;
}
return null;
}
Vector3 getPickedLocationOnFoundation() {
if (pasteMouseState != null) {
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (selectedPart instanceof Foundation) {
final PickedHousePart pick = SelectUtil.pickPart(pasteMouseState.getX(), pasteMouseState.getY(), selectedPart);
if (pick != null)
return pick.getPoint().clone();
}
pasteMouseState = null;
}
return null;
}
Vector3 getPickedLocationOnWall() {
if (pasteMouseState != null) {
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (selectedPart instanceof Wall) {
final PickedHousePart pick = SelectUtil.pickPart(pasteMouseState.getX(), pasteMouseState.getY(), selectedPart);
if (pick != null)
return pick.getPoint().clone();
}
pasteMouseState = null;
}
return null;
}
Vector3 getPickedLocationOnRoof() {
if (pasteMouseState != null) {
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (selectedPart instanceof Roof) {
final PickedHousePart pick = SelectUtil.pickPart(pasteMouseState.getX(), pasteMouseState.getY(), selectedPart);
if (pick != null)
return pick.getPoint().clone();
}
pasteMouseState = null;
}
return null;
}
public void computeEnergyView(final boolean b) {
setHeatFluxDaily(true);
setSolarHeatMap(b);
setHeatFluxVectorsVisible(b);
((Component) canvas).requestFocusInWindow();
}
public Foundation autoSelectBuilding(final boolean ask) {
Foundation foundation = null;
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (selectedPart == null || selectedPart instanceof Tree || selectedPart instanceof Human) {
SceneManager.getInstance().setSelectedPart(null);
int count = 0;
HousePart hp = null;
for (final HousePart x : Scene.getInstance().getParts()) {
if (x instanceof Foundation) {
count++;
hp = x;
}
}
if (count == 1) {
SceneManager.getInstance().setSelectedPart(hp);
foundation = (Foundation) hp;
} else {
if (ask) {
if (count > 1) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "There are multiple buildings. You must select a building first.", "No Selection", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no building.", "No Building", JOptionPane.INFORMATION_MESSAGE);
}
}
}
} else {
final HousePart topContainer = selectedPart.getTopContainer();
if (selectedPart instanceof Foundation) {
foundation = (Foundation) selectedPart;
} else if (topContainer instanceof Foundation) {
selectedPart.setEditPointsVisible(false);
SceneManager.getInstance().setSelectedPart(topContainer);
foundation = (Foundation) topContainer;
} else {
if (ask)
JOptionPane.showMessageDialog(MainFrame.getInstance(), "You must select a building first.", "No Selection", JOptionPane.INFORMATION_MESSAGE);
}
}
return foundation;
}
public void setFineGrid(final boolean b) {
fineGrid = b;
}
public boolean isFineGrid() {
return fineGrid;
}
}
| src/main/java/org/concord/energy3d/scene/SceneManager.java | package org.concord.energy3d.scene;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.io.IOException;
import java.net.URL;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.concord.energy3d.gui.EnergyPanel;
import org.concord.energy3d.gui.EnergyPanel.UpdateRadiation;
import org.concord.energy3d.gui.MainFrame;
import org.concord.energy3d.gui.MainPanel;
import org.concord.energy3d.gui.PopupMenuFactory;
import org.concord.energy3d.logger.PlayControl;
import org.concord.energy3d.logger.TimeSeriesLogger;
import org.concord.energy3d.model.CustomRoof;
import org.concord.energy3d.model.Door;
import org.concord.energy3d.model.Floor;
import org.concord.energy3d.model.Foundation;
import org.concord.energy3d.model.GambrelRoof;
import org.concord.energy3d.model.HipRoof;
import org.concord.energy3d.model.HousePart;
import org.concord.energy3d.model.Human;
import org.concord.energy3d.model.PickedHousePart;
import org.concord.energy3d.model.PyramidRoof;
import org.concord.energy3d.model.Roof;
import org.concord.energy3d.model.Sensor;
import org.concord.energy3d.model.ShedRoof;
import org.concord.energy3d.model.SolarPanel;
import org.concord.energy3d.model.Tree;
import org.concord.energy3d.model.UserData;
import org.concord.energy3d.model.Wall;
import org.concord.energy3d.model.Window;
import org.concord.energy3d.scene.CameraControl.ButtonAction;
import org.concord.energy3d.shapes.Heliodon;
import org.concord.energy3d.undo.AddPartCommand;
import org.concord.energy3d.undo.EditFoundationCommand;
import org.concord.energy3d.undo.EditPartCommand;
import org.concord.energy3d.undo.MoveBuildingCommand;
import org.concord.energy3d.undo.RemovePartCommand;
import org.concord.energy3d.undo.UndoManager;
import org.concord.energy3d.util.Blinker;
import org.concord.energy3d.util.Config;
import org.concord.energy3d.util.Config.RenderMode;
import org.concord.energy3d.util.FontManager;
import org.concord.energy3d.util.SelectUtil;
import org.concord.energy3d.util.Util;
import com.ardor3d.bounding.BoundingBox;
import com.ardor3d.bounding.BoundingVolume;
import com.ardor3d.extension.model.collada.jdom.ColladaAnimUtils;
import com.ardor3d.extension.model.collada.jdom.ColladaImporter;
import com.ardor3d.extension.model.collada.jdom.ColladaMaterialUtils;
import com.ardor3d.extension.model.collada.jdom.data.ColladaStorage;
import com.ardor3d.extension.shadow.map.ParallelSplitShadowMapPass;
import com.ardor3d.framework.Canvas;
import com.ardor3d.framework.DisplaySettings;
import com.ardor3d.framework.FrameHandler;
import com.ardor3d.framework.Updater;
import com.ardor3d.framework.jogl.JoglSwingCanvas;
import com.ardor3d.image.Texture;
import com.ardor3d.image.TextureStoreFormat;
import com.ardor3d.image.util.awt.AWTImageLoader;
import com.ardor3d.input.ButtonState;
import com.ardor3d.input.FocusWrapper;
import com.ardor3d.input.Key;
import com.ardor3d.input.KeyboardState;
import com.ardor3d.input.KeyboardWrapper;
import com.ardor3d.input.MouseButton;
import com.ardor3d.input.MouseState;
import com.ardor3d.input.MouseWrapper;
import com.ardor3d.input.PhysicalLayer;
import com.ardor3d.input.logical.InputTrigger;
import com.ardor3d.input.logical.KeyHeldCondition;
import com.ardor3d.input.logical.KeyPressedCondition;
import com.ardor3d.input.logical.KeyReleasedCondition;
import com.ardor3d.input.logical.LogicalLayer;
import com.ardor3d.input.logical.MouseButtonClickedCondition;
import com.ardor3d.input.logical.MouseButtonPressedCondition;
import com.ardor3d.input.logical.MouseButtonReleasedCondition;
import com.ardor3d.input.logical.MouseMovedCondition;
import com.ardor3d.input.logical.TriggerAction;
import com.ardor3d.input.logical.TwoInputStates;
import com.ardor3d.intersection.PickResults;
import com.ardor3d.intersection.PickingUtil;
import com.ardor3d.intersection.PrimitivePickResults;
import com.ardor3d.light.DirectionalLight;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.math.MathUtils;
import com.ardor3d.math.Matrix3;
import com.ardor3d.math.Ray3;
import com.ardor3d.math.Vector2;
import com.ardor3d.math.Vector3;
import com.ardor3d.math.type.ReadOnlyVector2;
import com.ardor3d.math.type.ReadOnlyVector3;
import com.ardor3d.renderer.Camera;
import com.ardor3d.renderer.Camera.ProjectionMode;
import com.ardor3d.renderer.Renderer;
import com.ardor3d.renderer.pass.BasicPassManager;
import com.ardor3d.renderer.pass.RenderPass;
import com.ardor3d.renderer.queue.RenderBucketType;
import com.ardor3d.renderer.state.BlendState;
import com.ardor3d.renderer.state.LightState;
import com.ardor3d.renderer.state.MaterialState;
import com.ardor3d.renderer.state.MaterialState.ColorMaterial;
import com.ardor3d.renderer.state.TextureState;
import com.ardor3d.renderer.state.ZBufferState;
import com.ardor3d.scenegraph.Line;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.scenegraph.Node;
import com.ardor3d.scenegraph.Spatial;
import com.ardor3d.scenegraph.controller.SpatialController;
import com.ardor3d.scenegraph.extension.CameraNode;
import com.ardor3d.scenegraph.hint.CullHint;
import com.ardor3d.scenegraph.hint.LightCombineMode;
import com.ardor3d.scenegraph.shape.Dome;
import com.ardor3d.scenegraph.shape.Quad;
import com.ardor3d.scenegraph.shape.Sphere;
import com.ardor3d.ui.text.BMText;
import com.ardor3d.ui.text.BMText.Align;
import com.ardor3d.util.GameTaskQueue;
import com.ardor3d.util.GameTaskQueueManager;
import com.ardor3d.util.ReadOnlyTimer;
import com.ardor3d.util.TextureManager;
import com.ardor3d.util.Timer;
import com.ardor3d.util.geom.BufferUtils;
import com.ardor3d.util.resource.ResourceLocatorTool;
import com.ardor3d.util.resource.ResourceSource;
import com.ardor3d.util.resource.SimpleResourceLocator;
import com.ardor3d.util.resource.URLResourceSource;
public class SceneManager implements com.ardor3d.framework.Scene, Runnable, Updater {
public enum Operation {
SELECT, RESIZE, ROTATE, DRAW_WALL, DRAW_DOOR, DRAW_ROOF_PYRAMID, DRAW_ROOF_HIP, DRAW_ROOF_SHED, DRAW_ROOF_GAMBREL, DRAW_ROOF_CUSTOM, DRAW_ROOF_GABLE, DRAW_WINDOW, DRAW_FOUNDATION, DRAW_FLOOR, DRAW_SOLAR_PANEL, DRAW_SENSOR, DRAW_DOGWOOD, DRAW_ELM, DRAW_OAK, DRAW_LINDEN, DRAW_MAPLE, DRAW_COTTONWOOD, DRAW_PINE, DRAW_JANE, DRAW_JENI, DRAW_JILL, DRAW_JACK, DRAW_JOHN, DRAW_JOSE
}
public enum CameraMode {
ORBIT, FIRST_PERSON
}
public enum ViewMode {
NORMAL, TOP_VIEW, PRINT_PREVIEW, PRINT
}
private static final GameTaskQueueManager taskManager = GameTaskQueueManager.getManager("Task Manager");
private static final SceneManager instance = new SceneManager(MainPanel.getInstance().getCanvasPanel());
private static final double MOVE_SPEED = 5;
private final Canvas canvas;
private final FrameHandler frameHandler;
private final LogicalLayer logicalLayer;
private final Node root = new Node("Root");
private final Node backgroundRoot = new Node("Scenary Root");
private final BasicPassManager passManager = new BasicPassManager();
private final Mesh land = new Quad("Land", 2000, 2000);
private final Mesh solarLand = new Quad("Solar Land", 256, 256);
private final Mesh collisionLand = new Quad("Collision Land", 2000, 2000);
private final Mesh gridsMesh = new Line("Floor Grids");
private final LightState lightState = new LightState();
private final UndoManager undoManager = new UndoManager();
private HousePart selectedHousePart = null;
private HousePart hoveredHousePart = null;
private Operation operation = Operation.SELECT;
private CameraControl cameraControl;
private final ParallelSplitShadowMapPass shadowPass;
private ViewMode viewMode = ViewMode.NORMAL;
private CameraNode cameraNode;
private MouseState mouseState;
private AddPartCommand addHousePartCommand;
private EditPartCommand editHousePartCommand;
private UserData pick;
private TwoInputStates firstClickState;
private double refreshTime = -1;
private boolean mouseControlEnabled = true;
private boolean rotAnim = false;
private boolean heliodonControl;
private boolean sunAnim;
private boolean operationStick = false;
private boolean operationFlag = false;
private boolean refresh = true;
private int refreshCount = 0;
private boolean refreshOnlyMode = false;
private boolean zoomLock = false;
public static final double SKY_RADIUS = 1000;
public final static byte DEFAULT_THEME = 0;
public final static byte SKETCHUP_THEME = 1;
private final byte theme = DEFAULT_THEME;
private Sphere kinectPointer;
private MouseState lastSelectedEditPointMouseState;
private MouseState pasteMouseState;
private Node newImport;
private Vector3 houseMoveStartPoint;
private ArrayList<Vector3> houseMovePoints;
private boolean solarHeatMap = false;
private boolean heatFluxDaily = true;
private final Spatial axes;
private boolean showBuildingLabels = false;
private boolean showHeatFlux = false;
private final Mesh sky;
private TextureState daySkyState, nightSkyState;
private boolean cameraChanged;
private boolean fineGrid;
public static SceneManager getInstance() {
return instance;
}
public static GameTaskQueueManager getTaskManager() {
return taskManager;
}
private SceneManager(final Container panel) {
System.out.print("Constructing SceneManager...");
final DisplaySettings settings = new DisplaySettings(400, 300, 24, 0, 0, 24, 0, 4, false, false);
final RendererFactory rendererFactory;
if (Config.RENDER_MODE == RenderMode.NEWT)
rendererFactory = new JoglNewtFactory(settings, this);
else if (Config.RENDER_MODE == RenderMode.JOGL)
rendererFactory = new JoglFactory(settings, this);
else
rendererFactory = new LwjglFactory(settings, this);
final MouseWrapper mouseWrapper = rendererFactory.getMouseWrapper();
final KeyboardWrapper keyboardWrapper = rendererFactory.getKeyboardWrapper();
final FocusWrapper focusWrapper = rendererFactory.getFocusWrapper();
canvas = rendererFactory.getCanvas();
final Component canvasComponent = (Component) canvas;
canvasComponent.setMinimumSize(new Dimension(100, 100));
canvasComponent.setPreferredSize(new Dimension(100, 100));
frameHandler = new FrameHandler(new Timer());
frameHandler.addCanvas(canvas);
logicalLayer = new LogicalLayer();
final PhysicalLayer physicalLayer = new PhysicalLayer(keyboardWrapper, mouseWrapper, focusWrapper);
logicalLayer.registerInput(canvas, physicalLayer);
frameHandler.addUpdater(this);
frameHandler.addUpdater(PrintController.getInstance());
frameHandler.addUpdater(Blinker.getInstance());
panel.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
resizeCamera();
refresh(1);
if (Heliodon.getInstance() != null)
Heliodon.getInstance().updateBloom();
}
});
panel.add(canvasComponent, BorderLayout.CENTER);
System.out.println("done");
System.out.print("Initializing SceneManager...");
AWTImageLoader.registerLoader();
try {
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, new SimpleResourceLocator(getClass().getResource("images/")));
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, new SimpleResourceLocator(getClass().getResource("fonts/")));
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_MODEL, new SimpleResourceLocator(getClass().getResource("models/")));
} catch (final Exception ex) {
ex.printStackTrace();
}
// enable depth test
final ZBufferState zbuf = new ZBufferState();
zbuf.setEnabled(true);
zbuf.setFunction(ZBufferState.TestFunction.LessThanOrEqualTo);
root.setRenderState(zbuf);
final DirectionalLight light = new DirectionalLight();
light.setDirection(new Vector3(0, 0, -1));
light.setAmbient(new ColorRGBA(1, 1, 1, 1));
light.setEnabled(true);
lightState.setEnabled(false);
lightState.attach(light);
root.setRenderState(lightState);
backgroundRoot.getSceneHints().setAllPickingHints(false);
sky = createSky();
backgroundRoot.attachChild(sky);
backgroundRoot.attachChild(createLand());
solarLand.setVisible(false);
backgroundRoot.attachChild(solarLand);
collisionLand.setModelBound(new BoundingBox());
collisionLand.getSceneHints().setCullHint(CullHint.Always);
root.attachChild(collisionLand);
gridsMesh.getSceneHints().setCullHint(CullHint.Always);
drawGrids(5);
backgroundRoot.attachChild(gridsMesh);
axes = createAxes();
backgroundRoot.attachChild(axes);
backgroundRoot.attachChild(createKinectPointer());
root.attachChild(backgroundRoot);
root.attachChild(Scene.getRoot());
final RenderPass rootPass = new RenderPass();
rootPass.add(root);
passManager.add(rootPass);
shadowPass = new ParallelSplitShadowMapPass(light, 2048, 4);
// shadowPass = new ParallelSplitShadowMapPass(light, 3072, 3);
shadowPass.setEnabled(false);
shadowPass.setUseSceneTexturing(true);
shadowPass.setUseObjectCullFace(true);
shadowPass.add(land);
shadowPass.add(solarLand);
// shadowPass.add(Scene.getRoot());
shadowPass.add(Scene.getOriginalHouseRoot());
// shadowPass.add(Scene.getTreesRoot());
// shadowPass.addOccluder(Scene.getRoot());
shadowPass.addOccluder(Scene.getOriginalHouseRoot());
shadowPass.addOccluder(Scene.getNotReceivingShadowRoot());
final Date today = Calendar.getInstance().getTime();
new Heliodon(root, light, passManager, logicalLayer, today);
// taskManager.update(new Callable<Object>() {
// @Override
// public Object call() throws Exception {
// final Date today = Calendar.getInstance().getTime();
// new Heliodon(root, light, passManager, logicalLayer, today);
// return null;
// }
// });
initMouse();
root.updateGeometricState(0, true);
System.out.println("Finished initialization.");
}
@Override
public void run() {
frameHandler.init();
long frameStartTime;
final long msPerFrame = 1000 / 60;
while (true) {
frameStartTime = System.currentTimeMillis();
logicalLayer.checkTriggers(frameHandler.getTimer().getTimePerFrame());
final double now = frameHandler.getTimer().getTimeInSeconds();
final boolean isUpdateTime = refreshTime != -1 && now <= refreshTime;
final boolean isTaskAvailable = taskManager.getQueue(GameTaskQueue.UPDATE).size() > 0 || taskManager.getQueue(GameTaskQueue.RENDER).size() > 0;
final boolean isPrintPreviewAnim = !PrintController.getInstance().isFinished();
final boolean doRefresh = refresh || !refreshOnlyMode && (isTaskAvailable || isPrintPreviewAnim || Scene.isRedrawAll() || isUpdateTime || rotAnim || Blinker.getInstance().getTarget() != null || sunAnim || (cameraControl != null && cameraControl.isAnimating()));
if (doRefresh || refreshCount > 0) {
if (now > refreshTime)
refreshTime = -1;
refresh = false;
if (doRefresh)
refreshCount = 2;
else
refreshCount--;
try {
synchronized (this) {
frameHandler.updateFrame();
}
} catch (final Throwable e) {
e.printStackTrace();
Util.reportError(e);
return;
}
synchronized (this) {
notifyAll();
}
} else
frameHandler.getTimer().update();
final long sleepTime = msPerFrame - (System.currentTimeMillis() - frameStartTime);
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void update(final ReadOnlyTimer timer) {
final double tpf = timer.getTimePerFrame();
passManager.updatePasses(tpf);
taskManager.getQueue(GameTaskQueue.UPDATE).setExecuteMultiple(true);
taskManager.getQueue(GameTaskQueue.UPDATE).execute(canvas.getCanvasRenderer().getRenderer());
if (operationFlag)
executeOperation();
if (mouseState != null)
mouseMoved();
if (Scene.isRedrawAll())
Scene.getInstance().redrawAllNow();
if (rotAnim && viewMode == ViewMode.NORMAL && canvas.getCanvasRenderer() != null) {
final Matrix3 rotate = new Matrix3();
rotate.fromAngleNormalAxis(45 * tpf * MathUtils.DEG_TO_RAD, Vector3.UNIT_Z);
final Camera camera = getCamera();
camera.setLocation(rotate.applyPre(camera.getLocation(), null));
camera.lookAt(0, 0, 1, Vector3.UNIT_Z);
getCameraNode().updateFromCamera();
Scene.getInstance().updateEditShapes();
}
final Heliodon heliodon = Heliodon.getInstance();
if (heliodon != null) {
if (sunAnim) {
heliodon.setHourAngle(heliodon.getHourAngle() + tpf * 0.5, true, true, false);
SceneManager.getInstance().changeSkyTexture();
SceneManager.getInstance().setShading(heliodon.isNightTime());
}
heliodon.update();
}
if (cameraControl != null && cameraControl.isAnimating())
cameraControl.animate();
root.updateGeometricState(tpf);
}
@Override
public boolean renderUnto(final Renderer renderer) {
if (cameraNode == null) {
initCamera();
return false;
}
final float[] f = new float[2];
((JoglSwingCanvas) canvas).getRequestedSurfaceScale(f);
setWindowsVisible(false);
passManager.renderPasses(renderer);
try {
if (!Heliodon.getInstance().isNightTime()) {
shadowPass.renderPass(renderer);
}
} catch (final Throwable e) {
e.printStackTrace();
Util.reportError(e);
if (shadowPass.isEnabled()) {
shadowPass.setEnabled(false);
}
}
setWindowsVisible(true);
passManager.renderPasses(renderer);
// com.ardor3d.util.geom.Debugger.drawBounds(Scene.getRoot(), renderer, true);
taskManager.getQueue(GameTaskQueue.RENDER).execute(renderer);
return true;
}
private void setWindowsVisible(final boolean visible) {
land.setVisible(!visible);
for (final HousePart part : Scene.getInstance().getParts())
if (part instanceof Window)
part.getMesh().setVisible(visible);
else
part.getRoot().getSceneHints().setCullHint(visible ? CullHint.Always : CullHint.Inherit);
}
public void initCamera() {
System.out.println("initCamera()");
final Camera camera = getCamera();
cameraNode = new CameraNode("Camera Node", camera);
root.attachChild(cameraNode);
cameraNode.updateFromCamera();
Scene.getInstance().updateEditShapes();
setCameraControl(CameraMode.ORBIT);
resetCamera(ViewMode.NORMAL);
SceneManager.getInstance().getCameraControl().reset();
taskManager.update(new Callable<Object>() {
@Override
public Object call() throws Exception {
final Spatial compass = createCompass();
compass.setScale(0.1);
compass.setTranslation(-1, -0.7, 2);
cameraNode.attachChild(compass);
Scene.getInstance().updateEditShapes();
return null;
}
});
}
@Override
public PickResults doPick(final Ray3 pickRay) {
return null;
}
public FrameHandler getFrameHandler() {
return frameHandler;
}
public Canvas getCanvas() {
return canvas;
}
private Mesh createLand() {
switch (theme) {
case DEFAULT_THEME:
land.setDefaultColor(new ColorRGBA(0, 1, 0, 0.5f));
break;
case SKETCHUP_THEME:
land.setDefaultColor(new ColorRGBA(1, 1, 1, 0.9f));
break;
}
land.setRenderState(HousePart.offsetState);
final BlendState blendState = new BlendState();
blendState.setBlendEnabled(true);
land.setRenderState(blendState);
land.getSceneHints().setRenderBucketType(RenderBucketType.Transparent);
final MaterialState ms = new MaterialState();
ms.setColorMaterial(ColorMaterial.Diffuse);
land.setRenderState(ms);
land.updateModelBound();
return land;
}
public void drawGrids(final double gridSize) {
gridsMesh.setDefaultColor(ColorRGBA.BLUE);
gridsMesh.setModelBound(new BoundingBox());
Util.disablePickShadowLight(gridsMesh);
final ReadOnlyVector3 width = Vector3.UNIT_X.multiply(2000, null);
final ReadOnlyVector3 height = Vector3.UNIT_Y.multiply(2000, null);
final ArrayList<ReadOnlyVector3> points = new ArrayList<ReadOnlyVector3>();
final ReadOnlyVector3 pMiddle = Vector3.ZERO;
final int cols = (int) (width.length() / gridSize);
for (int col = 1; col < cols / 2 + 1; col++) {
for (int neg = -1; neg <= 1; neg += 2) {
final ReadOnlyVector3 lineP1 = width.normalize(null).multiplyLocal(neg * col * gridSize).addLocal(pMiddle).subtractLocal(height.multiply(0.5, null));
points.add(lineP1);
final ReadOnlyVector3 lineP2 = lineP1.add(height, null);
points.add(lineP2);
if (col == 0)
break;
}
}
final int rows = (int) (height.length() / gridSize);
for (int row = 1; row < rows / 2 + 1; row++) {
for (int neg = -1; neg <= 1; neg += 2) {
final ReadOnlyVector3 lineP1 = height.normalize(null).multiplyLocal(neg * row * gridSize).addLocal(pMiddle).subtractLocal(width.multiply(0.5, null));
points.add(lineP1);
final ReadOnlyVector3 lineP2 = lineP1.add(width, null);
points.add(lineP2);
if (row == 0)
break;
}
}
final FloatBuffer buf = BufferUtils.createVector3Buffer(points.size());
for (final ReadOnlyVector3 p : points)
buf.put(p.getXf()).put(p.getYf()).put(0.01f);
gridsMesh.getMeshData().setVertexBuffer(buf);
gridsMesh.getMeshData().updateVertexCount();
gridsMesh.updateModelBound();
}
public void setGridsVisible(final boolean visible) {
gridsMesh.getSceneHints().setCullHint(visible ? CullHint.Inherit : CullHint.Always);
}
private Mesh createSky() {
daySkyState = new TextureState();
daySkyState.setTexture(TextureManager.load("daysky.jpg", Texture.MinificationFilter.Trilinear, TextureStoreFormat.GuessNoCompressedFormat, true));
nightSkyState = new TextureState();
nightSkyState.setTexture(TextureManager.load("nightsky.jpg", Texture.MinificationFilter.Trilinear, TextureStoreFormat.GuessNoCompressedFormat, true));
final Dome sky = new Dome("Sky", 100, 100, SKY_RADIUS);
sky.setRotation(new Matrix3().fromAngles(Math.PI / 2, 0, 0));
sky.setRenderState(daySkyState);
sky.getSceneHints().setLightCombineMode(LightCombineMode.Off);
sky.getSceneHints().setAllPickingHints(false);
return sky;
}
public void changeSkyTexture() {
if (sky != null)
sky.setRenderState(Heliodon.getInstance().isNightTime() ? nightSkyState : daySkyState);
}
private Spatial createAxes() {
final int axisLen = 1000;
final Node axisRoot = new Node();
FloatBuffer buf;
Line line;
// X-Axis
buf = BufferUtils.createVector3Buffer(2);
buf.put(-axisLen).put(0).put(0);
buf.put(axisLen).put(0).put(0);
line = new Line("X-Axis", buf, null, null, null);
line.setDefaultColor(ColorRGBA.RED);
Util.disablePickShadowLight(line);
axisRoot.attachChild(line);
// Y-Axis
buf = BufferUtils.createVector3Buffer(2);
buf.put(0).put(-axisLen).put(0);
buf.put(0).put(axisLen).put(0);
line = new Line("Y-Axis", buf, null, null, null);
line.setDefaultColor(ColorRGBA.GREEN);
Util.disablePickShadowLight(line);
axisRoot.attachChild(line);
// Z-Axis
buf = BufferUtils.createVector3Buffer(2);
buf.put(0).put(0).put(-axisLen);
buf.put(0).put(0).put(axisLen);
line = new Line("Z-Axis", buf, null, null, null);
Util.disablePickShadowLight(line);
line.setDefaultColor(ColorRGBA.BLUE);
axisRoot.attachChild(line);
return axisRoot;
}
private Mesh createKinectPointer() {
kinectPointer = new Sphere("Kinect Pointer", 10, 10, 0.01);
return kinectPointer;
}
private void initMouse() {
logicalLayer.registerTrigger(new InputTrigger(new MouseButtonPressedCondition(MouseButton.LEFT), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
((Component) canvas).requestFocusInWindow();
if (Config.isMac()) { // control-click is mouse right-click on the Mac, skip
final KeyboardState ks = inputStates.getCurrent().getKeyboardState();
if (ks.isDown(Key.LCONTROL) || ks.isDown(Key.RCONTROL))
return;
}
if (firstClickState == null) {
firstClickState = inputStates;
mousePressed(inputStates.getCurrent().getMouseState());
} else {
firstClickState = null;
mouseReleased(inputStates.getCurrent().getMouseState());
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new MouseButtonReleasedCondition(MouseButton.LEFT), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (Config.isMac()) { // control-click is mouse right-click on the Mac, skip
final KeyboardState ks = inputStates.getCurrent().getKeyboardState();
if (ks.isDown(Key.LCONTROL) || ks.isDown(Key.RCONTROL))
return;
}
// if editing object using select or resize then only mouse drag is allowed
if (operation == Operation.SELECT || operation == Operation.RESIZE) {
firstClickState = null;
mouseReleased(inputStates.getCurrent().getMouseState());
} else if (firstClickState != null) {
final MouseState mouseState = inputStates.getCurrent().getMouseState();
final MouseState prevMouseState = firstClickState.getCurrent().getMouseState();
final ReadOnlyVector2 p1 = new Vector2(prevMouseState.getX(), prevMouseState.getY());
final ReadOnlyVector2 p2 = new Vector2(mouseState.getX(), mouseState.getY());
if (selectedHousePart instanceof Roof || selectedHousePart instanceof Floor || selectedHousePart instanceof SolarPanel || selectedHousePart instanceof Sensor || selectedHousePart instanceof Tree || selectedHousePart instanceof Human || p1.distance(p2) > 10) {
firstClickState = null;
mouseReleased(inputStates.getCurrent().getMouseState());
}
}
}
}));
((Component) canvas).addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
if (Util.isRightClick(e)) {
final JPanel cp = MainPanel.getInstance().getCanvasPanel();
mouseRightClicked(e.getX(), cp.getHeight() - e.getY());
}
}
@Override
public void mouseReleased(final MouseEvent e) {
if (Util.isRightClick(e)) {
if (cameraChanged) {
TimeSeriesLogger.getInstance().logCamera("Pan");
cameraChanged = false;
}
}
}
});
((Component) canvas).addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(final MouseEvent e) {
EnergyPanel.getInstance().update();
cameraChanged = true;
}
});
((Component) canvas).addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(final MouseWheelEvent e) {
TimeSeriesLogger.getInstance().logCamera("Zoom");
}
});
logicalLayer.registerTrigger(new InputTrigger(new MouseMovedCondition(), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
refresh = true;
mouseState = inputStates.getCurrent().getMouseState();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new MouseButtonClickedCondition(MouseButton.LEFT), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (Config.isMac()) { // control-click is mouse right-click on the Mac, skip
final KeyboardState ks = inputStates.getCurrent().getKeyboardState();
if (ks.isDown(Key.LCONTROL) || ks.isDown(Key.RCONTROL))
return;
}
if (!isTopView() && inputStates.getCurrent().getMouseState().getClickCount(MouseButton.LEFT) == 2) {
if (PrintController.getInstance().isPrintPreview()) {
final MouseState mouse = inputStates.getCurrent().getMouseState();
final Ray3 pickRay = Camera.getCurrentCamera().getPickRay(new Vector2(mouse.getX(), mouse.getY()), false, null);
final PickResults pickResults = new PrimitivePickResults();
PickingUtil.findPick(PrintController.getInstance().getPagesRoot(), pickRay, pickResults, false);
if (pickResults.getNumber() > 0)
cameraControl.zoomAtPoint(pickResults.getPickData(0).getIntersectionRecord().getIntersectionPoint(0));
} else {
final PickedHousePart pickedHousePart = SelectUtil.pickPart(inputStates.getCurrent().getMouseState().getX(), inputStates.getCurrent().getMouseState().getY());
if (pickedHousePart != null)
cameraControl.zoomAtPoint(pickedHousePart.getPoint());
}
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.LSHIFT), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
// SelectUtil.setPickLayer(0);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyReleasedCondition(Key.LSHIFT), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
// SelectUtil.setPickLayer(-1);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.DELETE), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
deleteCurrentHousePart();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.BACK), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
deleteCurrentHousePart();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.ESCAPE), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
hideAllEditPoints();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.ZERO), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
final KeyboardState ks = inputStates.getCurrent().getKeyboardState();
if (Config.isMac()) {
if (ks.isDown(Key.LMETA) || ks.isDown(Key.RMETA)) {
resetCamera();
}
} else {
if (ks.isDown(Key.LCONTROL) || ks.isDown(Key.RCONTROL)) {
resetCamera();
}
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.I), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
System.out.println("---- Parts: ------------------------");
System.out.println("size = " + Scene.getInstance().getParts().size());
for (final HousePart part : Scene.getInstance().getParts())
System.out.println(part);
System.out.println("---- Scene: ------------------------");
System.out.println("size = " + Scene.getOriginalHouseRoot().getNumberOfChildren());
for (final Spatial mesh : Scene.getOriginalHouseRoot().getChildren()) {
System.out.println(mesh);
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.R), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
Scene.getInstance().redrawAll(true);
}
}));
// Run/pause model replay
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.SPACE), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (PlayControl.active) {
PlayControl.replaying = !PlayControl.replaying;
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.LEFT), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (PlayControl.active) {
PlayControl.replaying = false;
PlayControl.backward = true;
}
if (SceneManager.getInstance().isTopView()) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(-1, 0, 0));
} else {
if (selectedHousePart instanceof Window) {
final Vector3 v = selectedHousePart.getNormal().clone();
v.crossLocal(Vector3.UNIT_Z);
moveWithKey(inputStates.getCurrent().getKeyboardState(), v);
Scene.getInstance().redrawAll();
}
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.UP), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (PlayControl.active) {
PlayControl.replaying = false;
PlayControl.backward = true;
}
if (SceneManager.getInstance().isTopView()) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(0, 1, 0));
} else {
if (selectedHousePart instanceof Window) {
final Vector3 n = selectedHousePart.getNormal().clone();
final Vector3 v = n.cross(Vector3.UNIT_Z, null);
moveWithKey(inputStates.getCurrent().getKeyboardState(), v.crossLocal(n));
Scene.getInstance().redrawAll();
}
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.RIGHT), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (PlayControl.active) {
PlayControl.replaying = false;
PlayControl.forward = true;
}
if (SceneManager.getInstance().isTopView()) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(1, 0, 0));
} else {
if (selectedHousePart instanceof Window) {
final Vector3 v = selectedHousePart.getNormal().clone();
v.crossLocal(Vector3.UNIT_Z).negateLocal();
moveWithKey(inputStates.getCurrent().getKeyboardState(), v);
Scene.getInstance().redrawAll();
}
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.DOWN), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (PlayControl.active) {
PlayControl.replaying = false;
PlayControl.forward = true;
}
if (SceneManager.getInstance().isTopView()) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(0, -1, 0));
} else {
if (selectedHousePart instanceof Window) {
final Vector3 n = selectedHousePart.getNormal().clone();
final Vector3 v = n.cross(Vector3.UNIT_Z, null).negateLocal();
moveWithKey(inputStates.getCurrent().getKeyboardState(), v.crossLocal(n));
Scene.getInstance().redrawAll();
}
}
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.ESCAPE), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
PlayControl.active = false;
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.W), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(-1, 0, 0));
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.E), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(1, 0, 0));
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.S), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(0, -1, 0));
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.N), new TriggerAction() {
@Override
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
moveWithKey(inputStates.getCurrent().getKeyboardState(), new Vector3(0, 1, 0));
}
}));
}
private void moveWithKey(final KeyboardState ks, final Vector3 v) {
if (ks.isDown(Key.LCONTROL) || ks.isDown(Key.RCONTROL) || ks.isDown(Key.LMETA) || ks.isDown(Key.LMETA))
return; // Ctrl/Cmd+key is often used for other purposes such as Ctrl+S or Cmd+S
fineGrid = ks.isDown(Key.LSHIFT) || ks.isDown(Key.RSHIFT);
move(v);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
EnergyPanel.getInstance().updateProperties();
}
});
}
public void move(final Vector3 v) {
MoveBuildingCommand c = null;
if (selectedHousePart == null) {
c = new MoveBuildingCommand(null, v);
for (final HousePart p : Scene.getInstance().getParts()) {
if (p instanceof Foundation) {
((Foundation) p).move(v, p.getGridSize());
}
}
} else if (selectedHousePart instanceof Foundation) {
c = new MoveBuildingCommand((Foundation) selectedHousePart, v);
((Foundation) selectedHousePart).move(v, selectedHousePart.getGridSize());
} else if (selectedHousePart instanceof Window) {
((Window) selectedHousePart).move(v);
}
if (c != null)
undoManager.addEdit(c);
Scene.getInstance().setEdited(true);
}
public void setCameraControl(final CameraMode type) {
if (cameraControl != null)
cameraControl.removeTriggers(logicalLayer);
if (type == CameraMode.ORBIT)
cameraControl = new OrbitControl(Vector3.UNIT_Z);
else if (type == CameraMode.FIRST_PERSON)
cameraControl = new FirstPersonControl(Vector3.UNIT_Z);
cameraControl.setupMouseTriggers(logicalLayer, true);
cameraControl.setMoveSpeed(MOVE_SPEED);
cameraControl.setKeyRotateSpeed(1);
}
public CameraControl getCameraControl() {
return cameraControl;
}
public void hideAllEditPoints() {
for (final HousePart part : Scene.getInstance().getParts()) {
part.setEditPointsVisible(false);
part.setGridsVisible(false);
}
selectedHousePart = null;
refresh = true;
}
public void resetCamera() {
resetCamera(viewMode);
cameraControl.reset();
refresh = true;
}
public void resetCamera(final ViewMode viewMode) {
System.out.println("resetCamera()");
this.viewMode = viewMode;
final Camera camera = getCamera();
cameraControl.setMouseButtonActions(ButtonAction.MOVE, ButtonAction.MOVE);
cameraControl.setMoveSpeed(MOVE_SPEED);
ReadOnlyVector3 loc = new Vector3(0, -120, 50);
ReadOnlyVector3 up = new Vector3(0, 0, 1);
ReadOnlyVector3 lookAt = new Vector3(0, 0, 0);
setCompassVisible(viewMode == ViewMode.NORMAL);
if (viewMode == ViewMode.NORMAL) {
cameraControl.setMouseButtonActions(ButtonAction.ROTATE, ButtonAction.MOVE);
camera.setProjectionMode(ProjectionMode.Perspective);
resizeCamera();
} else if (viewMode == ViewMode.TOP_VIEW) {
camera.setProjectionMode(ProjectionMode.Parallel);
loc = new Vector3(0, 0, 500);
up = new Vector3(0, 1, 0);
lookAt = new Vector3(0, 0, 0);
final double boundLength = Util.findBoundLength(Scene.getRoot().getWorldBound());
cameraControl.setMoveSpeed(boundLength / 2);
resizeCamera(boundLength);
} else if (viewMode == ViewMode.PRINT) {
camera.setProjectionMode(ProjectionMode.Parallel);
/* location will be set in PrintController.print() */
loc = new Vector3(0, -10, 0);
up = new Vector3(0, 0, -1);
} else if (viewMode == ViewMode.PRINT_PREVIEW) {
cameraControl.setMouseButtonActions(ButtonAction.MOVE, ButtonAction.MOVE);
camera.setProjectionMode(ProjectionMode.Perspective);
loc = PrintController.getInstance().getZoomAllCameraLocation();
lookAt = loc.add(0, 1, 0, null);
resizeCamera(PrintController.getInstance().getPageWidth());
}
camera.setLocation(loc);
camera.lookAt(lookAt, up);
camera.update();
cameraNode.updateFromCamera();
Scene.getInstance().updateEditShapes();
}
public ViewMode getViewMode() {
return viewMode;
}
private void resizeCamera() {
final BoundingVolume bounds = Scene.getRoot().getWorldBound();
if (bounds == null)
resizeCamera(2);
else
resizeCamera(Util.findBoundLength(bounds));
}
public void resizeCamera(final double orthoWidth) {
final Camera camera = getCamera();
if (camera == null)
return;
final Dimension size = ((Component) canvas).getSize();
camera.resize(size.width, size.height);
final double ratio = (double) size.width / size.height;
final double near = 1;
final double far = 2000;
if (camera.getProjectionMode() == ProjectionMode.Parallel)
camera.setFrustum(near, far, -orthoWidth / 2, orthoWidth / 2, orthoWidth / ratio / 2, -orthoWidth / ratio / 2);
else
camera.setFrustumPerspective(45.0, ratio, near, far);
}
public void toggleSpinView() {
cameraControl.reset();
rotAnim = !rotAnim;
}
public boolean getSpinView() {
return rotAnim;
}
public void setSpinView(final boolean spinView) {
rotAnim = spinView;
}
public void setOperation(final Operation operation) {
operationStick = false;
if (this.operation != operation) {
this.operation = operation;
operationFlag = true;
// need to be here to ensure immediate removal of unfinished house part before computeEnergy thread is started
SceneManager.getTaskManager().update(new Callable<Object>() {
@Override
public Object call() throws Exception {
if (selectedHousePart != null) {
if (selectedHousePart.isDrawCompleted())
selectedHousePart.setEditPointsVisible(false);
else
Scene.getInstance().remove(selectedHousePart, false);
selectedHousePart = null;
}
return null;
}
});
}
}
public void setOperationStick(final boolean stick) {
operationStick = stick;
}
public void executeOperation() {
operationFlag = false;
for (final HousePart part : Scene.getInstance().getParts())
if (part instanceof Foundation)
((Foundation) part).setResizeHouseMode(operation == Operation.RESIZE);
if (viewMode != ViewMode.PRINT_PREVIEW)
Scene.getInstance().drawResizeBounds();
selectedHousePart = newHousePart();
if (selectedHousePart != null)
cameraControl.setLeftMouseButtonEnabled(false);
}
private HousePart newHousePart() {
final HousePart drawn;
setGridsVisible(false);
if (operation == Operation.DRAW_WALL) {
drawn = new Wall();
drawn.setColor(Scene.getInstance().getWallColor());
} else if (operation == Operation.DRAW_DOOR) {
drawn = new Door();
drawn.setColor(Scene.getInstance().getDoorColor());
} else if (operation == Operation.DRAW_WINDOW) {
drawn = new Window();
} else if (operation == Operation.DRAW_ROOF_PYRAMID) {
drawn = new PyramidRoof();
drawn.setColor(Scene.getInstance().getRoofColor());
} else if (operation == Operation.DRAW_ROOF_HIP) {
drawn = new HipRoof();
drawn.setColor(Scene.getInstance().getRoofColor());
} else if (operation == Operation.DRAW_ROOF_SHED) {
drawn = new ShedRoof();
drawn.setColor(Scene.getInstance().getRoofColor());
} else if (operation == Operation.DRAW_ROOF_GAMBREL) {
drawn = new GambrelRoof();
drawn.setColor(Scene.getInstance().getRoofColor());
} else if (operation == Operation.DRAW_ROOF_CUSTOM) {
drawn = new CustomRoof();
drawn.setColor(Scene.getInstance().getRoofColor());
} else if (operation == Operation.DRAW_FLOOR) {
drawn = new Floor();
drawn.setColor(Scene.getInstance().getFloorColor());
} else if (operation == Operation.DRAW_SOLAR_PANEL) {
drawn = new SolarPanel(false);
} else if (operation == Operation.DRAW_SENSOR) {
drawn = new Sensor();
} else if (operation == Operation.DRAW_FOUNDATION) {
drawn = new Foundation();
setGridsVisible(true);
drawn.setColor(Scene.getInstance().getFoundationColor());
} else if (operation == Operation.DRAW_DOGWOOD) {
drawn = new Tree(Tree.DOGWOOD);
setGridsVisible(true);
} else if (operation == Operation.DRAW_ELM) {
drawn = new Tree(Tree.ELM);
setGridsVisible(true);
} else if (operation == Operation.DRAW_OAK) {
drawn = new Tree(Tree.OAK);
setGridsVisible(true);
} else if (operation == Operation.DRAW_LINDEN) {
drawn = new Tree(Tree.LINDEN);
setGridsVisible(true);
} else if (operation == Operation.DRAW_COTTONWOOD) {
drawn = new Tree(Tree.COTTONWOOD);
setGridsVisible(true);
} else if (operation == Operation.DRAW_MAPLE) {
drawn = new Tree(Tree.MAPLE);
setGridsVisible(true);
} else if (operation == Operation.DRAW_PINE) {
drawn = new Tree(Tree.PINE);
setGridsVisible(true);
} else if (operation == Operation.DRAW_JANE) {
drawn = new Human(Human.JANE);
setGridsVisible(true);
} else if (operation == Operation.DRAW_JENI) {
drawn = new Human(Human.JENI);
setGridsVisible(true);
} else if (operation == Operation.DRAW_JILL) {
drawn = new Human(Human.JILL);
setGridsVisible(true);
} else if (operation == Operation.DRAW_JACK) {
drawn = new Human(Human.JACK);
setGridsVisible(true);
} else if (operation == Operation.DRAW_JOHN) {
drawn = new Human(Human.JOHN);
setGridsVisible(true);
} else if (operation == Operation.DRAW_JOSE) {
drawn = new Human(Human.JOSE);
setGridsVisible(true);
} else
return null;
Scene.getInstance().add(drawn, false);
addHousePartCommand = new AddPartCommand(drawn);
return drawn;
}
public Operation getOperation() {
return operation;
}
public void setShading(final boolean enable) {
taskManager.update(new Callable<Object>() {
@Override
public Object call() throws Exception {
lightState.setEnabled(enable);
root.updateWorldRenderStates(true);
return null;
}
});
}
public void setHeliodonVisible(final boolean selected) {
heliodonControl = selected;
Heliodon.getInstance().setVisible(selected);
enableDisableRotationControl();
EnergyPanel.getInstance().compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI);
}
public void setSunAnimation(final boolean selected) {
sunAnim = selected;
}
public boolean isSunAnimation() {
return sunAnim;
}
public void enableDisableRotationControl() {
if (!mouseControlEnabled)
return;
if ((operation == Operation.SELECT || operation == Operation.RESIZE) && (selectedHousePart == null || selectedHousePart.isDrawCompleted()))
cameraControl.setMouseEnabled(true);
else
cameraControl.setMouseEnabled(false);
if (heliodonControl)
cameraControl.setKeyRotateSpeed(0);
else
cameraControl.setKeyRotateSpeed(1);
}
public HousePart getSelectedPart() {
return selectedHousePart;
}
public void setSelectedPart(final HousePart p) {
if (p == null && selectedHousePart != null)
selectedHousePart.setEditPointsVisible(false);
selectedHousePart = p;
if (selectedHousePart != null)
selectedHousePart.setEditPointsVisible(true);
}
public boolean isTopView() {
return viewMode == ViewMode.TOP_VIEW;
}
public void updatePrintPreviewScene(final boolean printPreview) {
if (printPreview)
Scene.saveCameraLocation();
resetCamera(printPreview ? ViewMode.PRINT_PREVIEW : ViewMode.NORMAL);
if (!printPreview) {
Scene.loadCameraLocation();
if (cameraControl instanceof OrbitControl)
((OrbitControl) cameraControl).clearOrbitCenter();
}
backgroundRoot.getSceneHints().setCullHint(printPreview ? CullHint.Always : CullHint.Inherit);
}
public CameraNode getCameraNode() {
return cameraNode;
}
private Node createCompass() throws IOException {
System.out.print("Loading compass...");
final ResourceSource source = ResourceLocatorTool.locateResource(ResourceLocatorTool.TYPE_MODEL, "compass.dae");
final ColladaImporter colladaImporter = new ColladaImporter();
// Load the collada scene
Logger.getLogger(ColladaAnimUtils.class.getName()).setLevel(Level.SEVERE);
Logger.getLogger(ColladaMaterialUtils.class.getName()).setLevel(Level.SEVERE);
final ColladaStorage storage = colladaImporter.load(source);
final Node compass = storage.getScene();
BMText txt;
final double Z = 0.1;
txt = new BMText("N", "N", FontManager.getInstance().getAnnotationFont(), Align.South);
txt.setAutoRotate(false);
txt.setTranslation(2, 0.0, Z);
txt.setRotation(new Matrix3().fromAngles(0.0, MathUtils.HALF_PI, -MathUtils.HALF_PI));
compass.attachChild(txt);
txt = new BMText("S", "S", FontManager.getInstance().getAnnotationFont(), Align.South);
txt.setAutoRotate(false);
txt.setTranslation(-2, -0.0, Z);
txt.setRotation(new Matrix3().fromAngles(0.0, -MathUtils.HALF_PI, MathUtils.HALF_PI));
compass.attachChild(txt);
txt = new BMText("W", "W", FontManager.getInstance().getAnnotationFont(), Align.South);
txt.setAutoRotate(false);
txt.setTranslation(-0.0, 2, Z);
txt.setRotation(new Matrix3().fromAngles(-MathUtils.HALF_PI, 0.0, 0.0));
compass.attachChild(txt);
txt = new BMText("E", "E", FontManager.getInstance().getAnnotationFont(), Align.South);
txt.setAutoRotate(false);
txt.setTranslation(-0.0, -2, Z);
txt.setRotation(new Matrix3().fromAngles(MathUtils.HALF_PI, MathUtils.PI, 0.0));
compass.attachChild(txt);
final DirectionalLight light = new DirectionalLight();
light.setDirection(new Vector3(0, 0, -1));
light.setEnabled(true);
final LightState lightState = new LightState();
lightState.attach(light);
compass.setRenderState(lightState);
compass.getSceneHints().setLightCombineMode(LightCombineMode.Replace);
compass.updateWorldRenderStates(true);
final Node compassNode = new Node();
compassNode.setRotation(new Matrix3().fromAngles(-MathUtils.HALF_PI, 0.0, 0.0));
compassNode.attachChild(compass);
System.out.println("done");
compass.addController(new SpatialController<Spatial>() {
@Override
public void update(final double time, final Spatial caller) {
final Vector3 direction = getCamera().getDirection().normalize(null);
direction.setZ(0);
direction.normalizeLocal();
double angle = -direction.smallestAngleBetween(Vector3.UNIT_Y);
if (direction.dot(Vector3.UNIT_X) > 0)
angle = -angle;
angle -= MathUtils.HALF_PI;
compass.setRotation(new Matrix3().fromAngles(0.0, 0.0, angle - 0.3));
}
});
return compassNode;
}
public void setCompassVisible(final boolean visible) {
cameraNode.getSceneHints().setCullHint(visible ? CullHint.Inherit : CullHint.Always);
}
public void updateHeliodonAndAnnotationSize() {
if (heliodonControl)
taskManager.update(new Callable<Object>() {
@Override
public Object call() throws Exception {
Heliodon.getInstance().updateSize();
return null;
}
});
}
private void mouseMoved() {
if (!mouseControlEnabled)
return;
final int x = mouseState.getX();
final int y = mouseState.getY();
try {
if (editHousePartCommand != null && editHousePartCommand.isReallyEdited())
EnergyPanel.getInstance().cancel();
if (selectedHousePart != null && !selectedHousePart.isDrawCompleted()) {
selectedHousePart.setPreviewPoint(x, y);
} else if (houseMoveStartPoint != null && (operation == Operation.RESIZE || selectedHousePart instanceof Foundation) && selectedHousePart.isDrawCompleted()) {
final PickedHousePart pick = SelectUtil.pickPart(x, y, collisionLand);
if (pick != null) {
if (selectedHousePart instanceof Foundation) {
final Foundation foundation = (Foundation) selectedHousePart;
final Vector3 pickPoint = pick.getPoint().clone();
// if (!foundation.insideBuilding(pickPoint.getX(), pickPoint.getY(), true)) { // only move the building when clicking outside
final Vector3 d = pickPoint.multiply(1, 1, 0, null).subtractLocal(houseMoveStartPoint.multiply(1, 1, 0, null));
foundation.move(d, houseMovePoints);
}
}
} else if (houseMoveStartPoint != null && selectedHousePart != null && selectedHousePart.isDrawCompleted() && selectedHousePart instanceof Tree) {
final PickedHousePart pick = SelectUtil.pickPart(x, y, collisionLand);
if (pick != null) {
final Vector3 d = pick.getPoint().multiply(1, 1, 0, null).subtractLocal(houseMoveStartPoint.multiply(1, 1, 0, null));
((Tree) selectedHousePart).move(d, houseMovePoints);
}
} else if (houseMoveStartPoint != null && selectedHousePart != null && selectedHousePart.isDrawCompleted() && selectedHousePart instanceof Window) {
final PickedHousePart pick = SelectUtil.pickPart(x, y, selectedHousePart.getContainer());
if (pick != null) {
final Vector3 d = pick.getPoint().clone().subtractLocal(houseMoveStartPoint);
((Window) selectedHousePart).move(d, houseMovePoints);
}
} else if ((operation == Operation.SELECT || operation == Operation.RESIZE) && mouseState.getButtonState(MouseButton.LEFT) == ButtonState.UP && mouseState.getButtonState(MouseButton.MIDDLE) == ButtonState.UP && mouseState.getButtonState(MouseButton.RIGHT) == ButtonState.UP) {
final PickedHousePart selectHousePart = SelectUtil.selectHousePart(x, y, false);
pick = selectHousePart == null ? null : selectHousePart.getUserData();
final HousePart housePart = pick == null ? null : pick.getHousePart();
if (pick != null) {
hoveredHousePart = housePart;
if (hoveredHousePart.isFrozen())
hoveredHousePart = null;
if (pick.getIndex() != -1)
lastSelectedEditPointMouseState = mouseState;
} else
hoveredHousePart = null;
}
mouseState = null;
} catch (Throwable t) {
t.printStackTrace();
Util.reportError(t);
}
final Component canvasComponent = (Component) canvas;
if (!zoomLock && (operation == Operation.SELECT || operation == Operation.RESIZE) && hoveredHousePart != null && pick.getIndex() == -1 && (hoveredHousePart instanceof Foundation || hoveredHousePart instanceof SolarPanel || hoveredHousePart instanceof Sensor || hoveredHousePart instanceof Window || hoveredHousePart instanceof Tree || hoveredHousePart instanceof Human))
canvasComponent.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
else
canvasComponent.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
public void setMouseControlEnabled(final boolean enabled) {
mouseControlEnabled = enabled;
cameraControl.setMouseEnabled(enabled);
}
@Override
public void init() {
if (Config.RENDER_MODE != RenderMode.LWJGL)
initCamera();
}
public boolean isShadingEnabled() {
return lightState.isEnabled();
}
public void setShadow(final boolean shadow) {
taskManager.update(new Callable<Object>() {
@Override
public Object call() throws Exception {
shadowPass.setEnabled(shadow);
root.updateWorldRenderStates(true);
return null;
}
});
}
public boolean isShadowEnabled() {
return shadowPass.isEnabled();
}
public void setZoomLock(final boolean zoomLock) {
this.zoomLock = zoomLock;
cameraControl.setLeftButtonAction(zoomLock ? ButtonAction.ZOOM : viewMode == ViewMode.NORMAL ? ButtonAction.ROTATE : ButtonAction.MOVE);
}
public void zoom(final boolean in) {
cameraControl.zoom(canvas, 0.1, in ? -1 : 1);
}
public void refresh() {
refresh = true;
}
public synchronized void refreshNow() {
refresh = true;
try {
wait();
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
public void refresh(final double updateDurationInSeconds) {
refreshTime = frameHandler.getTimer().getTimeInSeconds() + updateDurationInSeconds;
}
public UndoManager getUndoManager() {
return undoManager;
}
public Timer getTimer() {
return frameHandler.getTimer();
}
public Mesh getLand() {
return land;
}
public Mesh getSolarLand() {
return solarLand;
}
public boolean isHeliodonVisible() {
return heliodonControl;
}
// the x and y coordinates come from MouseEvent, not MouseState.
private void mouseRightClicked(final int x, final int y) {
mouseState = new MouseState(x, y, 0, 0, 0, null, null);
pasteMouseState = mouseState;
refresh = true;
taskManager.update(new Callable<Object>() {
@Override
public Object call() {
try {
if (operation == Operation.SELECT) {
final HousePart previousSelectedHousePart = selectedHousePart;
if (mouseState == null) // for some reason, there is a small chance that mouseState is nullified here
mouseState = new MouseState(x, y, 0, 0, 0, null, null);
final PickedHousePart pickedHousePart = SelectUtil.selectHousePart(mouseState.getX(), mouseState.getY(), true);
final UserData pick = pickedHousePart == null ? null : pickedHousePart.getUserData();
selectedHousePart = pick == null ? null : pick.getHousePart();
System.out.println("Right-clicked on: (" + mouseState.getX() + ", " + mouseState.getY() + ") " + pick);
if (previousSelectedHousePart != null && previousSelectedHousePart != selectedHousePart) {
previousSelectedHousePart.setEditPointsVisible(false);
previousSelectedHousePart.setGridsVisible(false);
}
if (selectedHousePart != null) {
selectedHousePart.complete(); // to undo edit flag set by SelectUtil above
if (!PrintController.getInstance().isPrintPreview())
selectedHousePart.setEditPointsVisible(true);
EnergyPanel.getInstance().update();
}
EnergyPanel.getInstance().updateGraphs();
final JPanel cp = MainPanel.getInstance().getCanvasPanel();
PopupMenuFactory.getPopupMenu(onLand(pasteMouseState.getX(), pasteMouseState.getY())).show(cp, mouseState.getX(), cp.getHeight() - mouseState.getY());
}
} catch (Throwable t) {
t.printStackTrace();
Util.reportError(t);
}
return null;
}
});
}
private void mousePressed(final MouseState mouseState) {
refresh = true;
taskManager.update(new Callable<Object>() {
@Override
public Object call() {
if (zoomLock)
return null;
System.out.println("OPERATION: " + operation);
try {
if (operation == Operation.SELECT || operation == Operation.RESIZE || operation == Operation.ROTATE || operation == Operation.DRAW_ROOF_GABLE) {
if (selectedHousePart == null || selectedHousePart.isDrawCompleted()) {
final HousePart previousSelectedHousePart = selectedHousePart;
final PickedHousePart selectHousePart = SelectUtil.selectHousePart(mouseState.getX(), mouseState.getY(), true);
final UserData pick = selectHousePart == null ? null : selectHousePart.getUserData();
if (pick == null)
selectedHousePart = null;
else
selectedHousePart = pick.getHousePart();
if (selectedHousePart != null && selectedHousePart.isFrozen())
selectedHousePart = null;
System.out.println("Clicked on: " + pick);
if (pick != null && pick.isEditPoint()) {
cameraControl.setLeftMouseButtonEnabled(false);
}
if (operation == Operation.SELECT || operation == Operation.ROTATE) {
if (previousSelectedHousePart instanceof Foundation) {
((Foundation) previousSelectedHousePart).updateAzimuthArrowVisibility(false);
}
if (selectedHousePart instanceof Foundation) {
((Foundation) selectedHousePart).drawAzimuthArrow();
}
}
if (operation == Operation.RESIZE && selectedHousePart != null) {
if (!(selectedHousePart instanceof Foundation)) {
selectedHousePart.setEditPointsVisible(false);
selectedHousePart = selectedHousePart.getTopContainer();
}
}
if (selectedHousePart instanceof Window || selectedHousePart instanceof Tree || selectedHousePart instanceof Foundation) {
cameraControl.setLeftMouseButtonEnabled(false);
houseMoveStartPoint = selectHousePart.getPoint().clone();
collisionLand.setTranslation(0, 0, houseMoveStartPoint.getZ());
final ArrayList<Vector3> points = selectedHousePart.getPoints();
houseMovePoints = new ArrayList<Vector3>(points.size());
for (final Vector3 p : points)
houseMovePoints.add(p.clone());
}
if (previousSelectedHousePart != null && previousSelectedHousePart != selectedHousePart && operation != Operation.RESIZE) {
previousSelectedHousePart.setEditPointsVisible(false);
previousSelectedHousePart.setGridsVisible(false);
}
if (selectedHousePart != null && !PrintController.getInstance().isPrintPreview()) {
selectedHousePart.setEditPointsVisible(true);
if (pick.isEditPoint() && pick.getIndex() != -1 || operation == Operation.RESIZE || selectedHousePart instanceof Window || selectedHousePart instanceof Tree || selectedHousePart instanceof Foundation) {
selectedHousePart.setGridsVisible(true);
if (selectedHousePart instanceof Foundation)
editHousePartCommand = new EditFoundationCommand((Foundation) selectedHousePart, !pick.isEditPoint());
else
editHousePartCommand = new EditPartCommand(selectedHousePart);
}
}
SelectUtil.nextPickLayer();
if (operation == Operation.DRAW_ROOF_GABLE && selectedHousePart instanceof Roof) {
System.out.println(selectedHousePart);
System.out.println("deleting roof #" + pick.getIndex());
final int roofPartIndex = pick.getIndex();
final Roof roof = (Roof) selectedHousePart;
roof.setGable(roofPartIndex, true, undoManager);
}
}
} else {
selectedHousePart.addPoint(mouseState.getX(), mouseState.getY());
}
} catch (Throwable t) {
t.printStackTrace();
Util.reportError(t);
}
return null;
}
});
}
private void mouseReleased(final MouseState mouseState) {
refresh = true;
taskManager.update(new Callable<Object>() {
@Override
public Object call() {
try {
if (selectedHousePart != null)
selectedHousePart.setGridsVisible(false);
if (operation == Operation.SELECT || operation == Operation.RESIZE) {
if (selectedHousePart != null && (!selectedHousePart.isDrawCompleted() || houseMoveStartPoint != null)) {
if (selectedHousePart.isDrawable()) {
selectedHousePart.complete();
if (editHousePartCommand != null && editHousePartCommand.isReallyEdited())
EnergyPanel.getInstance().compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI);
} else {
if (editHousePartCommand != null)
editHousePartCommand.undo();
selectedHousePart.setHighlight(false);
// selectedHousePart = null;
}
if (editHousePartCommand != null) {
if (editHousePartCommand.isReallyEdited())
undoManager.addEdit(editHousePartCommand);
editHousePartCommand = null;
}
}
if (!zoomLock)
cameraControl.setLeftMouseButtonEnabled(true);
houseMoveStartPoint = null;
houseMovePoints = null;
if (cameraChanged) {
TimeSeriesLogger.getInstance().logCamera(zoomLock ? "Zoom" : "Rotate");
cameraChanged = false;
}
} else {
if (selectedHousePart != null && !selectedHousePart.isDrawCompleted()) {
selectedHousePart.addPoint(mouseState.getX(), mouseState.getY());
if (selectedHousePart.isDrawCompleted() && !selectedHousePart.isDrawable()) {
addHousePartCommand = null;
Scene.getInstance().remove(selectedHousePart, true);
selectedHousePart = null;
if (operationStick)
operationFlag = true;
}
}
if (selectedHousePart != null && selectedHousePart.isDrawCompleted()) {
if (selectedHousePart.isDrawable()) {
if (addHousePartCommand != null)
undoManager.addEdit(addHousePartCommand);
addHousePartCommand = null;
} else
Scene.getInstance().remove(selectedHousePart, true);
selectedHousePart.setEditPointsVisible(false);
selectedHousePart = null;
if (operationStick)
operationFlag = true;
EnergyPanel.getInstance().compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI);
}
if (!operationFlag) {
MainPanel.getInstance().defaultTool();
cameraControl.setLeftMouseButtonEnabled(true);
}
}
updateHeliodonAndAnnotationSize();
EnergyPanel.getInstance().update();
} catch (Throwable t) {
t.printStackTrace();
Util.reportError(t);
}
return null;
}
});
EnergyPanel.getInstance().updateGraphs();
}
public void grabOrRelease() {
if (selectedHousePart != null && !selectedHousePart.isDrawCompleted())
mouseReleased(lastSelectedEditPointMouseState);
else
mousePressed(lastSelectedEditPointMouseState);
}
public void deleteCurrentHousePart() {
if (selectedHousePart instanceof Foundation) {
if (((Foundation) selectedHousePart).getLockEdit())
return;
if (!selectedHousePart.getChildren().isEmpty())
if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Deleting the platform also deletes the building on it. Are you sure?", "Confirmation", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION)
return;
}
if (selectedHousePart != null)
taskManager.update(new Callable<Object>() {
@Override
public Object call() throws Exception {
final RemovePartCommand command = new RemovePartCommand(selectedHousePart);
if (selectedHousePart instanceof Wall) { // undo/redo a gable roof
final Roof roof = ((Wall) selectedHousePart).getRoof();
if (roof != null) {
final List<Map<Integer, List<Wall>>> gableInfo = new ArrayList<Map<Integer, List<Wall>>>();
if (roof.getGableEditPointToWallMap() != null)
gableInfo.add(roof.getGableEditPointToWallMap());
command.setGableInfo(gableInfo);
}
} else if (selectedHousePart instanceof Foundation) { // undo/redo all the gable roofs
final List<Roof> roofs = ((Foundation) selectedHousePart).getRoofs();
if (!roofs.isEmpty()) {
final List<Map<Integer, List<Wall>>> gableInfo = new ArrayList<Map<Integer, List<Wall>>>();
for (final Roof r : roofs) {
if (r.getGableEditPointToWallMap() != null)
gableInfo.add(r.getGableEditPointToWallMap());
}
command.setGableInfo(gableInfo);
}
}
undoManager.addEdit(command);
Scene.getInstance().remove(selectedHousePart, true);
selectedHousePart = null;
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
MainPanel.getInstance().getEnergyViewButton().setSelected(false);
}
});
return null;
}
});
}
public void newImport(final URL file) throws IOException {
final ResourceSource source = new URLResourceSource(file);
final ColladaImporter colladaImporter = new ColladaImporter();
Logger.getLogger(ColladaAnimUtils.class.getName()).setLevel(Level.SEVERE);
Logger.getLogger(ColladaMaterialUtils.class.getName()).setLevel(Level.SEVERE);
final ColladaStorage storage = colladaImporter.load(source);
newImport = storage.getScene();
// newImport.setTranslation(0, 0, 30);
// newImport.setScale(0.025);
Scene.getRoot().attachChild(newImport);
}
public Camera getCamera() {
return canvas.getCanvasRenderer().getCamera();
}
public boolean getSolarHeatMap() {
return solarHeatMap;
}
public void setSolarHeatMapWithoutUpdate(final boolean solarHeatMap) {
this.solarHeatMap = solarHeatMap;
}
public void setSolarHeatMap(final boolean solarHeatMap) {
setSolarHeatMapWithoutUpdate(solarHeatMap);
EnergyPanel.getInstance().clearAlreadyRendered();
EnergyPanel.getInstance().compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI);
}
public boolean isHeatFluxDaily() {
return heatFluxDaily;
}
public void setHeatFluxDaily(final boolean heatFluxDaily) {
this.heatFluxDaily = heatFluxDaily;
}
public void setAxesVisible(final boolean b) {
if (b)
backgroundRoot.attachChild(axes);
else
backgroundRoot.detachChild(axes);
}
public boolean areAxesVisible() {
return backgroundRoot.hasChild(axes);
}
public void setHeatFluxVectorsVisible(final boolean b) {
showHeatFlux = b;
for (final HousePart part : Scene.getInstance().getParts())
part.updateHeatFluxVisibility();
}
public boolean areHeatFluxVectorsVisible() {
return showHeatFlux;
}
public void setBuildingLabelsVisible(final boolean b) {
showBuildingLabels = b;
for (final HousePart part : Scene.getInstance().getParts()) {
if (part instanceof Foundation)
((Foundation) part).showBuildingLabel(b);
}
}
public boolean areBuildingLabelsVisible() {
return showBuildingLabels;
}
/** negative angle for clockwise rotation, positive angle for counter-clockwise rotation */
public void rotateBuilding(final double angle, final boolean redraw) {
System.out.println("rotateBuilding()");
if (selectedHousePart != null) {
if (selectedHousePart instanceof Foundation) {
((Foundation) selectedHousePart).rotate(angle, null);
} else {
selectedHousePart.getTopContainer().rotate(angle, null);
}
if (redraw)
Scene.getInstance().redrawAll();
}
}
/** negative angle for clockwise rotation, positive angle for counter-clockwise rotation */
public void rotateAllBuildings(final double angle) {
System.out.println("rotateBuildings()");
final Vector3 origin = new Vector3();
for (final HousePart p : Scene.getInstance().getParts()) {
if (p instanceof Foundation) {
((Foundation) p).rotate(angle, origin);
}
}
Scene.getInstance().redrawAll();
}
public boolean isRefreshOnlyMode() {
return refreshOnlyMode;
}
public void setRefreshOnlyMode(final boolean refreshOnlyMode) {
this.refreshOnlyMode = refreshOnlyMode;
}
private boolean onLand(final int x, final int y) {
return SelectUtil.pickPart(x, y, land) != null;
}
Vector3 getPickedLocationOnLand() {
if (pasteMouseState != null) {
final PickedHousePart pick = SelectUtil.pickPart(pasteMouseState.getX(), pasteMouseState.getY(), land);
if (pick != null)
return pick.getPoint().multiply(1, 1, 0, null);
pasteMouseState = null;
}
return null;
}
Vector3 getPickedLocationOnFoundation() {
if (pasteMouseState != null) {
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (selectedPart instanceof Foundation) {
final PickedHousePart pick = SelectUtil.pickPart(pasteMouseState.getX(), pasteMouseState.getY(), selectedPart);
if (pick != null)
return pick.getPoint().clone();
}
pasteMouseState = null;
}
return null;
}
Vector3 getPickedLocationOnWall() {
if (pasteMouseState != null) {
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (selectedPart instanceof Wall) {
final PickedHousePart pick = SelectUtil.pickPart(pasteMouseState.getX(), pasteMouseState.getY(), selectedPart);
if (pick != null)
return pick.getPoint().clone();
}
pasteMouseState = null;
}
return null;
}
Vector3 getPickedLocationOnRoof() {
if (pasteMouseState != null) {
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (selectedPart instanceof Roof) {
final PickedHousePart pick = SelectUtil.pickPart(pasteMouseState.getX(), pasteMouseState.getY(), selectedPart);
if (pick != null)
return pick.getPoint().clone();
}
pasteMouseState = null;
}
return null;
}
public void computeEnergyView(final boolean b) {
setHeatFluxDaily(true);
setSolarHeatMap(b);
setHeatFluxVectorsVisible(b);
((Component) canvas).requestFocusInWindow();
}
public Foundation autoSelectBuilding(final boolean ask) {
Foundation foundation = null;
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (selectedPart == null || selectedPart instanceof Tree || selectedPart instanceof Human) {
SceneManager.getInstance().setSelectedPart(null);
int count = 0;
HousePart hp = null;
for (final HousePart x : Scene.getInstance().getParts()) {
if (x instanceof Foundation) {
count++;
hp = x;
}
}
if (count == 1) {
SceneManager.getInstance().setSelectedPart(hp);
foundation = (Foundation) hp;
} else {
if (ask) {
if (count > 1) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "There are multiple buildings. You must select a building first.", "No Selection", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no building.", "No Building", JOptionPane.INFORMATION_MESSAGE);
}
}
}
} else {
final HousePart topContainer = selectedPart.getTopContainer();
if (selectedPart instanceof Foundation) {
foundation = (Foundation) selectedPart;
} else if (topContainer instanceof Foundation) {
selectedPart.setEditPointsVisible(false);
SceneManager.getInstance().setSelectedPart(topContainer);
foundation = (Foundation) topContainer;
} else {
if (ask)
JOptionPane.showMessageDialog(MainFrame.getInstance(), "You must select a building first.", "No Selection", JOptionPane.INFORMATION_MESSAGE);
}
}
return foundation;
}
public void setFineGrid(final boolean b) {
fineGrid = b;
}
public boolean isFineGrid() {
return fineGrid;
}
}
| Fixed a bug related to moving parts with keys | src/main/java/org/concord/energy3d/scene/SceneManager.java | Fixed a bug related to moving parts with keys | <ide><path>rc/main/java/org/concord/energy3d/scene/SceneManager.java
<ide> }
<ide> if (c != null)
<ide> undoManager.addEdit(c);
<add> Scene.getInstance().redrawAll();
<ide> Scene.getInstance().setEdited(true);
<ide> }
<ide> |
|
Java | mit | 21fcd1fec70db30aedf454a3abceeb60cdf38284 | 0 | AddstarMC/Minigames | package com.pauldavdesign.mineauz.minigames;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.FireworkEffect.Type;
import org.bukkit.configuration.Configuration;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.potion.PotionEffect;
import com.pauldavdesign.mineauz.minigames.events.EndMinigameEvent;
import com.pauldavdesign.mineauz.minigames.events.EndTeamMinigameEvent;
import com.pauldavdesign.mineauz.minigames.events.JoinMinigameEvent;
import com.pauldavdesign.mineauz.minigames.events.QuitMinigameEvent;
import com.pauldavdesign.mineauz.minigames.events.RevertCheckpointEvent;
import com.pauldavdesign.mineauz.minigames.events.SpectateMinigameEvent;
import com.pauldavdesign.mineauz.minigames.scoring.ScoreTypes;
public class PlayerData {
private Map<String, MinigamePlayer> minigamePlayers = new HashMap<String, MinigamePlayer>();
private Map<String, OfflineMinigamePlayer> offlineMinigamePlayers = new HashMap<String, OfflineMinigamePlayer>();
private Map<String, StoredPlayerCheckpoints> storedPlayerCheckpoints = new HashMap<String, StoredPlayerCheckpoints>();
private boolean partyMode = false;
private List<String> deniedCommands = new ArrayList<String>();
private static Minigames plugin = Minigames.plugin;
private MinigameData mdata = plugin.mdata;
MinigameSave invsave = new MinigameSave("playerinv");
public PlayerData(){}
public void joinMinigame(MinigamePlayer player, Minigame minigame) {
String gametype = minigame.getType();
JoinMinigameEvent event = new JoinMinigameEvent(player, minigame);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
if(mdata.getMinigameTypes().contains(gametype)){
player.setAllowTeleport(true);
player.getPlayer().setFallDistance(0);
if(mdata.minigameType(gametype).joinMinigame(player, minigame)){
plugin.getLogger().info(player.getName() + " started " + minigame.getName());
mdata.sendMinigameMessage(minigame, player.getName() + " has joined " + minigame.getName(), null, player);
player.getPlayer().setGameMode(minigame.getDefaultGamemode());
player.setAllowGamemodeChange(false);
player.getPlayer().setAllowFlight(false);
player.setAllowTeleport(false);
if(hasStoredPlayerCheckpoint(player)){
if(getPlayersStoredCheckpoints(player).hasCheckpoint(minigame.getName())){
player.setCheckpoint(getPlayersStoredCheckpoints(player).getCheckpoint(minigame.getName()));
if(getPlayersStoredCheckpoints(player).hasFlags(minigame.getName())){
player.setFlags(getPlayersStoredCheckpoints(player).getFlags(minigame.getName()));
}
getPlayersStoredCheckpoints(player).removeCheckpoint(minigame.getName());
getPlayersStoredCheckpoints(player).removeFlags(minigame.getName());
if(getPlayersStoredCheckpoints(player).hasNoCheckpoints() && !getPlayersStoredCheckpoints(player).hasGlobalCheckpoint()){
storedPlayerCheckpoints.remove(player.getName());
}
revertToCheckpoint(player);
}
}
for(MinigamePlayer pl : minigame.getSpectators()){
player.getPlayer().hidePlayer(pl.getPlayer());
}
for(PotionEffect potion : player.getPlayer().getActivePotionEffects()){
player.getPlayer().removePotionEffect(potion.getType());
}
}
}
else{
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "That gametype doesn't exist!");
}
}
}
public void spectateMinigame(MinigamePlayer player, Minigame minigame) {
SpectateMinigameEvent event = new SpectateMinigameEvent(player, minigame);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
player.storePlayerData();
player.setMinigame(minigame);
player.getPlayer().setGameMode(GameMode.ADVENTURE);
minigame.addSpectator(player);
minigameTeleport(player, minigame.getStartLocations().get(0));
if(minigame.canSpectateFly()){
player.getPlayer().setAllowFlight(true);
}
for(MinigamePlayer pl : minigame.getPlayers()){
pl.getPlayer().hidePlayer(player.getPlayer());
}
player.getPlayer().setScoreboard(minigame.getScoreboardManager());
for(PotionEffect potion : player.getPlayer().getActivePotionEffects()){
player.getPlayer().removePotionEffect(potion.getType());
}
player.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "You have started spectating " + minigame + ".\n" +
"Type \"/minigame quit\" to leave spectator mode.");
mdata.sendMinigameMessage(minigame, player.getName() + " is now spectating " + minigame, null, player);
}
}
public void joinWithBet(MinigamePlayer player, Minigame minigame, Double money){
JoinMinigameEvent event = new JoinMinigameEvent(player, minigame, true);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
if(minigame != null && minigame.isEnabled() && (minigame.getMpTimer() == null || minigame.getMpTimer().getPlayerWaitTimeLeft() != 0)){
if(minigame.getMpBets() == null && (player.getPlayer().getItemInHand().getType() != Material.AIR || money != 0)){
minigame.setMpBets(new MultiplayerBets());
}
MultiplayerBets pbet = minigame.getMpBets();
ItemStack item = player.getPlayer().getItemInHand().clone();
if(pbet != null &&
((money != 0 && pbet.canBet(player, money) && plugin.getEconomy().getBalance(player.getName()) >= money) ||
(pbet.canBet(player, item) && item.getType() != Material.AIR && pbet.betValue(item.getType()) > 0))){
if(minigame.getPlayers().isEmpty() || minigame.getPlayers().size() != minigame.getMaxPlayers()){
player.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "You've placed your bet! Good Luck!");
if(money == 0){
pbet.addBet(player, item);
}
else{
pbet.addBet(player, money);
plugin.getEconomy().withdrawPlayer(player.getName(), money);
}
player.getPlayer().getInventory().removeItem(new ItemStack(item.getType(), 1));
joinMinigame(player, minigame);
}
else{
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "Sorry, this minigame is full.");
}
}
else if(item.getType() == Material.AIR && money == 0){
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You can not bet nothing!");
}
else if(money != 0 && !pbet.canBet(player, money)){
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You haven't placed the correct bet amount for this round!");
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You must bet $" + minigame.getMpBets().getHighestMoneyBet() + ".");
}
else if(money != 0 && plugin.getEconomy().getBalance(player.getName()) < money){
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You haven't got enough money!");
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You must have $" + minigame.getMpBets().getHighestMoneyBet() + ".");
}
else{
player.sendMessage(ChatColor.RED + "You haven't bet the correct item for this round!");
player.sendMessage(ChatColor.RED + "You must bet a " + minigame.getMpBets().highestBetName() + ".");
}
}
else if(minigame != null && minigame.getMpTimer() != null && minigame.getMpTimer().getPlayerWaitTimeLeft() == 0){
player.sendMessage(ChatColor.RED + "The game has already started. Please try again later.");
}
}
}
public void startMPMinigame(Minigame minigame){
List<MinigamePlayer> players = new ArrayList<MinigamePlayer>();
players.addAll(minigame.getPlayers());
Collections.shuffle(players);
if(minigame.getType().equals("teamdm") && ScoreTypes.getScoreType(minigame.getScoreType()) != null){
ScoreTypes.getScoreType(minigame.getScoreType()).balanceTeam(players, minigame);
}
Location start = null;
int pos = 0;
int bluepos = 0;
int redpos = 0;
for(MinigamePlayer ply : players){
if(!minigame.getType().equals("teamdm")){
if(pos < minigame.getStartLocations().size()){
start = minigame.getStartLocations().get(pos);
minigameTeleport(ply, start);
ply.setCheckpoint(start);
if(minigame.getMaxScore() != 0 && minigame.getType().equals("dm") && !minigame.getScoreType().equals("none")){
ply.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "Score to win: " + minigame.getMaxScorePerPlayer(minigame.getPlayers().size()));
}
}
else{
pos = 0;
if(!minigame.getStartLocations().isEmpty()){
start = minigame.getStartLocations().get(0);
minigameTeleport(ply, start);
ply.setCheckpoint(start);
if(minigame.getMaxScore() != 0 && minigame.getType().equals("dm") && !minigame.getScoreType().equals("none")){
ply.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "Score to win: " + minigame.getMaxScorePerPlayer(minigame.getPlayers().size()));
}
}
else {
ply.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "Starting positions are incorrectly configured!");
quitMinigame(ply, false);
}
}
}
else{
int team = -1;
if(minigame.getBlueTeam().contains(ply.getPlayer())){
team = 1;
}
else if(minigame.getRedTeam().contains(ply.getPlayer())){
team = 0;
}
if(!minigame.getStartLocationsRed().isEmpty() && !minigame.getStartLocationsBlue().isEmpty()){
if(team == 0 && redpos < minigame.getStartLocationsRed().size()){
start = minigame.getStartLocationsRed().get(redpos);
redpos++;
}
else if(team == 1 && bluepos < minigame.getStartLocationsBlue().size()){
start = minigame.getStartLocationsBlue().get(bluepos);
bluepos++;
}
else if(team == 0 && !minigame.getStartLocationsRed().isEmpty()){
redpos = 0;
start = minigame.getStartLocationsRed().get(redpos);
redpos++;
}
else if(team == 1 && !minigame.getStartLocationsBlue().isEmpty()){
bluepos = 0;
start = minigame.getStartLocationsBlue().get(bluepos);
bluepos++;
}
else if(minigame.getStartLocationsBlue().isEmpty() || minigame.getStartLocationsRed().isEmpty()){
ply.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "Starting positions are incorrectly configured!");
quitMinigame(ply, false);
}
}
else{
if(pos <= minigame.getStartLocations().size()){
start = minigame.getStartLocations().get(pos);
minigameTeleport(ply, start);
ply.setCheckpoint(start);
}
else{
pos = 1;
if(!minigame.getStartLocations().isEmpty()){
start = minigame.getStartLocations().get(0);
minigameTeleport(ply, start);
ply.setCheckpoint(start);
}
else {
ply.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "Starting positions are incorrectly configured!");
quitMinigame(ply, false);
}
}
}
if(start != null){
minigameTeleport(ply, start);
ply.setCheckpoint(start);
if(minigame.getMaxScore() != 0 && !minigame.getScoreType().equals("none")){
ply.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "Score to win: " + minigame.getMaxScorePerPlayer(minigame.getPlayers().size()));
}
}
if(minigame.getLives() > 0){
ply.sendMessage(ChatColor.AQUA + "[Minigame] " + ChatColor.WHITE + "Lives left: " + minigame.getLives());
}
}
pos++;
if(!minigame.getPlayersLoadout(ply).getItems().isEmpty()){
minigame.getPlayersLoadout(ply).equiptLoadout(ply);
}
ply.getPlayer().setScoreboard(minigame.getScoreboardManager());
minigame.setScore(ply, 1);
minigame.setScore(ply, 0);
}
if(minigame.hasPlayers()){
if(minigame.getSpleefFloor1() != null && minigame.getSpleefFloor2() != null){
minigame.addFloorDegenerator();
minigame.getFloorDegenerator().startDegeneration();
}
if(minigame.hasRestoreBlocks()){
for(RestoreBlock block : minigame.getRestoreBlocks().values()){
minigame.getBlockRecorder().addBlock(block.getLocation().getBlock(), null);
}
}
if(minigame.getTimer() > 0){
minigame.setMinigameTimer(new MinigameTimer(minigame, minigame.getTimer()));
mdata.sendMinigameMessage(minigame, MinigameUtils.convertTime(minigame.getTimer()) + " left.", null, null);
}
}
}
public void revertToCheckpoint(MinigamePlayer player) {
RevertCheckpointEvent event = new RevertCheckpointEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
minigameTeleport(player, player.getCheckpoint());
player.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "You have been reverted to the checkpoint.");
}
}
public void quitMinigame(MinigamePlayer player, boolean forced){
Minigame mgm = player.getMinigame();
QuitMinigameEvent event = new QuitMinigameEvent(player, mgm, forced);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
if(!mgm.isSpectator(player)){
player.setAllowTeleport(true);
if(player.getPlayer().getVehicle() != null){
Vehicle vehicle = (Vehicle) player.getPlayer().getVehicle();
vehicle.eject();
}
player.getPlayer().closeInventory();
if(!forced){
mdata.sendMinigameMessage(mgm, player.getName() + " has left " + mgm, "error", player);
}
else{
mdata.sendMinigameMessage(mgm, player.getName() + " was removed from " + mgm, "error", player);
}
mgm.removePlayersLoadout(player);
final MinigamePlayer ply = player;
if(!player.getPlayer().isDead()){
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if(ply.getPlayer().isOnline() && !ply.getPlayer().isDead()){
ply.restorePlayerData();
}
}
});
}
player.removeMinigame();
mgm.removePlayer(player);
mdata.minigameType(mgm.getType()).quitMinigame(player, mgm, forced);
for(PotionEffect potion : player.getPlayer().getActivePotionEffects()){
player.getPlayer().removePotionEffect(potion.getType());
}
player.getPlayer().setFallDistance(0);
final MinigamePlayer fplayer = player;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
fplayer.getPlayer().setFireTicks(0);
fplayer.getPlayer().setNoDamageTicks(60);
}
});
player.clearFlags();
player.resetDeaths();
player.resetKills();
player.resetScore();
player.removeCheckpoint();
plugin.getLogger().info(player.getName() + " quit " + mgm);
if(mgm.getPlayers().size() == 0){
if(mgm.getMinigameTimer() != null){
mgm.getMinigameTimer().stopTimer();
mgm.setMinigameTimer(null);
}
if(mgm.getFloorDegenerator() != null){
mgm.getFloorDegenerator().stopDegenerator();
}
if(mgm.getBlockRecorder().hasData()){
mgm.getBlockRecorder().restoreBlocks();
mgm.getBlockRecorder().restoreEntities();
}
if(mgm.getMpBets() != null){
mgm.setMpBets(null);
}
}
mgm.getScoreboardManager().resetScores(player.getPlayer());
for(MinigamePlayer pl : mgm.getSpectators()){
player.getPlayer().showPlayer(pl.getPlayer());
}
ply.setAllowTeleport(true);
ply.setAllowGamemodeChange(true);
}
else{
if(player.getPlayer().getVehicle() != null){
Vehicle vehicle = (Vehicle) player.getPlayer().getVehicle();
vehicle.eject();
}
player.getPlayer().setFallDistance(0);
player.getPlayer().closeInventory();
final Player fplayer = player.getPlayer();
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
fplayer.setFireTicks(0);
fplayer.setNoDamageTicks(60);
}
});
final MinigamePlayer ply = player;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if(ply.getPlayer().isOnline()){
ply.restorePlayerData();
}
}
});
minigameTeleport(player, mgm.getQuitPosition());
player.removeMinigame();
mgm.removeSpectator(player);
for(PotionEffect potion : player.getPlayer().getActivePotionEffects()){
player.getPlayer().removePotionEffect(potion.getType());
}
for(MinigamePlayer pl : mgm.getPlayers()){
pl.getPlayer().showPlayer(player.getPlayer());
}
ply.getPlayer().setFlying(false);
ply.setAllowTeleport(true);
ply.setAllowGamemodeChange(true);
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You quit spectator mode in " + mgm);
mdata.sendMinigameMessage(mgm, player.getName() + " is no longer spectating " + mgm, "error", player);
}
}
}
public void endMinigame(final MinigamePlayer player){
Minigame mgm = player.getMinigame();
EndMinigameEvent event = new EndMinigameEvent(player, mgm);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
if(player.getPlayer().getVehicle() != null){
Vehicle vehicle = (Vehicle) player.getPlayer().getVehicle();
vehicle.eject();
}
player.getPlayer().closeInventory();
if(player.getPlayer().isOnline() && !player.getPlayer().isDead()){
player.restorePlayerData();
}
player.removeMinigame();
mgm.removePlayer(player);
mgm.removePlayersLoadout(player);
player.getPlayer().setFallDistance(0);
mdata.minigameType(mgm.getType()).endMinigame(player, mgm);
for(PotionEffect potion : player.getPlayer().getActivePotionEffects()){
player.getPlayer().removePotionEffect(potion.getType());
}
player.getPlayer().setFireTicks(0);
player.getPlayer().setNoDamageTicks(60);
player.clearFlags();
if(plugin.getSQL() == null || plugin.getSQL().getSql() == null){
player.resetDeaths();
player.resetKills();
player.resetScore();
}
if(mgm.getMinigameTimer() != null){
mgm.getMinigameTimer().stopTimer();
mgm.setMinigameTimer(null);
}
if(mgm.getFloorDegenerator() != null && mgm.getPlayers().size() == 0){
mgm.getFloorDegenerator().stopDegenerator();
}
if(mgm.getMpBets() != null && mgm.getPlayers().size() == 0){
mgm.setMpBets(null);
}
if(mgm.getBlockRecorder().hasData()){
if(!mgm.getType().equalsIgnoreCase("sp") || mgm.getPlayers().isEmpty()){
mgm.getBlockRecorder().restoreBlocks();
mgm.getBlockRecorder().restoreEntities();
}
else if(mgm.getPlayers().isEmpty()){
mgm.getBlockRecorder().restoreBlocks(player);
mgm.getBlockRecorder().restoreEntities(player);
}
}
for(MinigamePlayer pl : mgm.getSpectators()){
player.getPlayer().showPlayer(pl.getPlayer());
}
player.setAllowTeleport(true);
player.setAllowGamemodeChange(true);
plugin.getLogger().info(player.getName() + " completed " + mgm);
mgm.getScoreboardManager().resetScores(player.getPlayer());
}
}
public void endTeamMinigame(int teamnum, Minigame mgm){
List<MinigamePlayer> losers = new ArrayList<MinigamePlayer>();
List<MinigamePlayer> winners = new ArrayList<MinigamePlayer>();
if(teamnum == 1){
//Blue team
for(OfflinePlayer ply : mgm.getRedTeam()){
losers.add(getMinigamePlayer(ply.getName()));
}
for(OfflinePlayer ply : mgm.getBlueTeam()){
winners.add(getMinigamePlayer(ply.getName()));
}
}
else{
//Red team
for(OfflinePlayer ply : mgm.getRedTeam()){
winners.add(getMinigamePlayer(ply.getName()));
}
for(OfflinePlayer ply : mgm.getBlueTeam()){
losers.add(getMinigamePlayer(ply.getName()));
}
}
EndTeamMinigameEvent event = new EndTeamMinigameEvent(losers, winners, mgm, teamnum);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
if(event.getWinningTeamInt() == 1){
if(plugin.getConfig().getBoolean("multiplayer.broadcastwin")){
String score = "";
if(mgm.getRedTeamScore() != 0 && mgm.getBlueTeamScore() != 0){
score = ", " + ChatColor.BLUE + mgm.getBlueTeamScore() + ChatColor.WHITE + " to " + ChatColor.RED + mgm.getRedTeamScore();
}
plugin.getServer().broadcastMessage(ChatColor.GREEN + "[Minigames] " + ChatColor.BLUE + "Blue Team" + ChatColor.WHITE + " won " + mgm.getName() + score);
}
}
else{
if(plugin.getConfig().getBoolean("multiplayer.broadcastwin")){
String score = "";
if(mgm.getRedTeamScore() != 0 && mgm.getBlueTeamScore() != 0){
score = ", " + ChatColor.RED + mgm.getRedTeamScore() + ChatColor.WHITE + " to " + ChatColor.BLUE + mgm.getBlueTeamScore();
}
plugin.getServer().broadcastMessage(ChatColor.GREEN + "[Minigames] " + ChatColor.RED + "Red Team" + ChatColor.WHITE + " won " + mgm.getName() + score);
}
}
mgm.setRedTeamScore(0);
mgm.setBlueTeamScore(0);
mgm.getMpTimer().setStartWaitTime(0);
List<MinigamePlayer> winplayers = new ArrayList<MinigamePlayer>();
winplayers.addAll(event.getWinnningPlayers());
if(plugin.getSQL() != null){
new SQLCompletionSaver(mgm.getName(), winplayers, mdata.minigameType(mgm.getType()));
}
if(mgm.getMpBets() != null){
if(mgm.getMpBets().hasMoneyBets()){
List<MinigamePlayer> plys = new ArrayList<MinigamePlayer>();
plys.addAll(event.getWinnningPlayers());
if(!plys.isEmpty()){
double bets = mgm.getMpBets().claimMoneyBets() / (double) plys.size();
BigDecimal roundBets = new BigDecimal(bets);
roundBets = roundBets.setScale(2, BigDecimal.ROUND_HALF_UP);
bets = roundBets.doubleValue();
for(MinigamePlayer ply : plys){
plugin.getEconomy().depositPlayer(ply.getName(), bets);
ply.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "You won $" + bets);
}
}
}
mgm.setMpBets(null);
}
if(!event.getLosingPlayers().isEmpty()){
List<MinigamePlayer> loseplayers = new ArrayList<MinigamePlayer>();
loseplayers.addAll(event.getLosingPlayers());
for(int i = 0; i < loseplayers.size(); i++){
if(loseplayers.get(i) instanceof MinigamePlayer){
final MinigamePlayer p = loseplayers.get(i);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
p.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You have been beaten! Bad luck!");
quitMinigame(p, true);
}
});
}
else{
loseplayers.remove(i);
}
}
mgm.setMpTimer(null);
for(MinigamePlayer pl : loseplayers){
mgm.getPlayers().remove(pl);
}
}
for(int i = 0; i < winplayers.size(); i++){
if(winplayers.get(i) instanceof MinigamePlayer){
final MinigamePlayer p = winplayers.get(i);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
endMinigame(p);
}
});
}
else{
winplayers.remove(i);
}
}
mgm.setMpTimer(null);
}
}
@Deprecated
public boolean playerInMinigame(Player player){
return minigamePlayers.get(player.getName()).isInMinigame();
}
@Deprecated
public List<Player> playersInMinigame(){
List<Player> players = new ArrayList<Player>();
for(Player player : plugin.getServer().getOnlinePlayers()){
if(playerInMinigame(player)){
players.add(player);
}
}
return players;
}
public void addMinigamePlayer(Player player){
minigamePlayers.put(player.getName(), new MinigamePlayer(player));
}
public void removeMinigamePlayer(Player player){
if(minigamePlayers.containsKey(player.getName())){
minigamePlayers.remove(player.getName());
}
}
public MinigamePlayer getMinigamePlayer(Player player){
return minigamePlayers.get(player.getName());
}
public MinigamePlayer getMinigamePlayer(String player){
return minigamePlayers.get(player);
}
public Collection<MinigamePlayer> getAllMinigamePlayers(){
return minigamePlayers.values();
}
public boolean hasMinigamePlayer(String name){
return minigamePlayers.containsKey(name);
}
public void addOfflineMinigamePlayer(MinigamePlayer player){
Location loc = null;
if(player.getQuitPos() != null){
loc = player.getQuitPos();
}
else{
loc = player.getMinigame().getQuitPosition();
}
offlineMinigamePlayers.put(player.getName(), new OfflineMinigamePlayer(player.getName(), player.getStoredItems(), player.getStoredArmour(), player.getFood(), player.getHealth(), player.getSaturation(), player.getLastGamemode(), loc));
}
public void addOfflineMinigamePlayer(OfflineMinigamePlayer player){
offlineMinigamePlayers.put(player.getPlayer(), player);
}
public OfflineMinigamePlayer getOfflineMinigamePlayer(String name){
return offlineMinigamePlayers.get(name);
}
public boolean hasOfflineMinigamePlayer(String name){
return offlineMinigamePlayers.containsKey(name);
}
public void removeOfflineMinigamePlayer(String name){
offlineMinigamePlayers.remove(name);
}
// public void storePlayerInventory(String player, ItemStack[] items, ItemStack[] armour, Integer health, Integer food, Float saturation){
// OfflineMinigamePlayer oply = new OfflineMinigamePlayer(player, items, armour, food, health, saturation, GameMode.SURVIVAL, resPos.get(player));
// offlineMinigamePlayers.put(player, oply);
// }
public List<String> checkRequiredFlags(MinigamePlayer player, String minigame){
List<String> checkpoints = new ArrayList<String>();
checkpoints.addAll(mdata.getMinigame(minigame).getFlags());
List<String> pchecks = player.getFlags();
if(!pchecks.isEmpty()){
checkpoints.removeAll(pchecks);
}
return checkpoints;
}
public Configuration getInventorySaveConfig(){
return invsave.getConfig();
}
public void saveInventoryConfig(){
invsave.saveConfig();
}
public boolean onPartyMode(){
return partyMode;
}
public void setPartyMode(boolean mode){
partyMode = mode;
}
public void partyMode(MinigamePlayer player){
if(onPartyMode()){
Location loc = player.getPlayer().getLocation();
Firework firework = (Firework) player.getPlayer().getWorld().spawnEntity(loc, EntityType.FIREWORK);
FireworkMeta fwm = firework.getFireworkMeta();
Random chance = new Random();
Type type = Type.BALL_LARGE;
if(chance.nextInt(100) < 50){
type = Type.BALL;
}
Color col = Color.fromRGB(chance.nextInt(255), chance.nextInt(255), chance.nextInt(255));
FireworkEffect effect = FireworkEffect.builder().with(type).withColor(col).flicker(chance.nextBoolean()).trail(chance.nextBoolean()).build();
fwm.addEffect(effect);
fwm.setPower(1);
firework.setFireworkMeta(fwm);
}
}
public void partyMode(MinigamePlayer player, int amount, long delay){
final int fcount = amount;
final MinigamePlayer fplayer = player;
final long fdelay = delay;
partyMode(fplayer);
if(amount == 1) return;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if(fplayer != null){
partyMode(fplayer, fcount - 1, fdelay);
}
}
}, delay);
}
public List<String> getDeniedCommands() {
return deniedCommands;
}
public void setDeniedCommands(List<String> deniedCommands) {
this.deniedCommands = deniedCommands;
}
public void addDeniedCommand(String command){
deniedCommands.add(command);
}
public void removeDeniedCommand(String command){
deniedCommands.remove(command);
}
public void saveDeniedCommands(){
plugin.getConfig().set("disabledCommands", deniedCommands);
plugin.saveConfig();
}
public void loadDeniedCommands(){
setDeniedCommands(plugin.getConfig().getStringList("disabledCommands"));
}
public boolean hasStoredPlayerCheckpoint(MinigamePlayer player){
if(storedPlayerCheckpoints.containsKey(player.getName())){
return true;
}
return false;
}
public StoredPlayerCheckpoints getPlayersStoredCheckpoints(MinigamePlayer player){
return storedPlayerCheckpoints.get(player.getName());
}
public void addStoredPlayerCheckpoint(MinigamePlayer player, String minigame, Location checkpoint){
StoredPlayerCheckpoints spc = new StoredPlayerCheckpoints(player.getName(), minigame, checkpoint);
storedPlayerCheckpoints.put(player.getName(), spc);
}
public void addStoredPlayerCheckpoints(String name, StoredPlayerCheckpoints spc){
storedPlayerCheckpoints.put(name, spc);
}
public void minigameTeleport(MinigamePlayer player, Location location){
if(player.isInMinigame()){
player.setAllowTeleport(true);
player.getPlayer().teleport(location);
player.setAllowTeleport(false);
}
else{
player.getPlayer().teleport(location);
}
}
}
| src/com/pauldavdesign/mineauz/minigames/PlayerData.java | package com.pauldavdesign.mineauz.minigames;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.FireworkEffect.Type;
import org.bukkit.configuration.Configuration;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.potion.PotionEffect;
import com.pauldavdesign.mineauz.minigames.events.EndMinigameEvent;
import com.pauldavdesign.mineauz.minigames.events.EndTeamMinigameEvent;
import com.pauldavdesign.mineauz.minigames.events.JoinMinigameEvent;
import com.pauldavdesign.mineauz.minigames.events.QuitMinigameEvent;
import com.pauldavdesign.mineauz.minigames.events.RevertCheckpointEvent;
import com.pauldavdesign.mineauz.minigames.events.SpectateMinigameEvent;
import com.pauldavdesign.mineauz.minigames.scoring.ScoreTypes;
public class PlayerData {
private Map<String, MinigamePlayer> minigamePlayers = new HashMap<String, MinigamePlayer>();
private Map<String, OfflineMinigamePlayer> offlineMinigamePlayers = new HashMap<String, OfflineMinigamePlayer>();
private Map<String, StoredPlayerCheckpoints> storedPlayerCheckpoints = new HashMap<String, StoredPlayerCheckpoints>();
private boolean partyMode = false;
private List<String> deniedCommands = new ArrayList<String>();
private static Minigames plugin = Minigames.plugin;
private MinigameData mdata = plugin.mdata;
MinigameSave invsave = new MinigameSave("playerinv");
public PlayerData(){}
public void joinMinigame(MinigamePlayer player, Minigame minigame) {
String gametype = minigame.getType();
JoinMinigameEvent event = new JoinMinigameEvent(player, minigame);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
if(mdata.getMinigameTypes().contains(gametype)){
player.setAllowTeleport(true);
player.getPlayer().setFallDistance(0);
if(mdata.minigameType(gametype).joinMinigame(player, minigame)){
plugin.getLogger().info(player.getName() + " started " + minigame.getName());
mdata.sendMinigameMessage(minigame, player.getName() + " has joined " + minigame.getName(), null, player);
player.getPlayer().setGameMode(minigame.getDefaultGamemode());
player.setAllowGamemodeChange(false);
player.getPlayer().setAllowFlight(false);
player.setAllowTeleport(false);
if(hasStoredPlayerCheckpoint(player)){
if(getPlayersStoredCheckpoints(player).hasCheckpoint(minigame.getName())){
player.setCheckpoint(getPlayersStoredCheckpoints(player).getCheckpoint(minigame.getName()));
if(getPlayersStoredCheckpoints(player).hasFlags(minigame.getName())){
player.setFlags(getPlayersStoredCheckpoints(player).getFlags(minigame.getName()));
}
getPlayersStoredCheckpoints(player).removeCheckpoint(minigame.getName());
getPlayersStoredCheckpoints(player).removeFlags(minigame.getName());
if(getPlayersStoredCheckpoints(player).hasNoCheckpoints() && !getPlayersStoredCheckpoints(player).hasGlobalCheckpoint()){
storedPlayerCheckpoints.remove(player.getName());
}
revertToCheckpoint(player);
}
}
for(MinigamePlayer pl : minigame.getSpectators()){
player.getPlayer().hidePlayer(pl.getPlayer());
}
for(PotionEffect potion : player.getPlayer().getActivePotionEffects()){
player.getPlayer().removePotionEffect(potion.getType());
}
}
}
else{
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "That gametype doesn't exist!");
}
}
}
public void spectateMinigame(MinigamePlayer player, Minigame minigame) {
SpectateMinigameEvent event = new SpectateMinigameEvent(player, minigame);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
player.storePlayerData();
player.setMinigame(minigame);
player.getPlayer().setGameMode(GameMode.ADVENTURE);
minigame.addSpectator(player);
minigameTeleport(player, minigame.getStartLocations().get(0));
if(minigame.canSpectateFly()){
player.getPlayer().setAllowFlight(true);
}
for(MinigamePlayer pl : minigame.getPlayers()){
pl.getPlayer().hidePlayer(player.getPlayer());
}
player.getPlayer().setScoreboard(minigame.getScoreboardManager());
for(PotionEffect potion : player.getPlayer().getActivePotionEffects()){
player.getPlayer().removePotionEffect(potion.getType());
}
player.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "You have started spectating " + minigame + ".\n" +
"Type \"/minigame quit\" to leave spectator mode.");
mdata.sendMinigameMessage(minigame, player.getName() + " is now spectating " + minigame, null, player);
}
}
public void joinWithBet(MinigamePlayer player, Minigame minigame, Double money){
JoinMinigameEvent event = new JoinMinigameEvent(player, minigame, true);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
if(minigame != null && minigame.isEnabled() && (minigame.getMpTimer() == null || minigame.getMpTimer().getPlayerWaitTimeLeft() != 0)){
if(minigame.getMpBets() == null && (player.getPlayer().getItemInHand().getType() != Material.AIR || money != 0)){
minigame.setMpBets(new MultiplayerBets());
}
MultiplayerBets pbet = minigame.getMpBets();
ItemStack item = player.getPlayer().getItemInHand().clone();
if(pbet != null &&
((money != 0 && pbet.canBet(player, money) && plugin.getEconomy().getBalance(player.getName()) >= money) ||
(pbet.canBet(player, item) && item.getType() != Material.AIR && pbet.betValue(item.getType()) > 0))){
if(minigame.getPlayers().isEmpty() || minigame.getPlayers().size() != minigame.getMaxPlayers()){
player.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "You've placed your bet! Good Luck!");
if(money == 0){
pbet.addBet(player, item);
}
else{
pbet.addBet(player, money);
plugin.getEconomy().withdrawPlayer(player.getName(), money);
}
player.getPlayer().getInventory().removeItem(new ItemStack(item.getType(), 1));
joinMinigame(player, minigame);
}
else{
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "Sorry, this minigame is full.");
}
}
else if(item.getType() == Material.AIR && money == 0){
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You can not bet nothing!");
}
else if(money != 0 && !pbet.canBet(player, money)){
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You haven't placed the correct bet amount for this round!");
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You must bet $" + minigame.getMpBets().getHighestMoneyBet() + ".");
}
else if(money != 0 && plugin.getEconomy().getBalance(player.getName()) < money){
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You haven't got enough money!");
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You must have $" + minigame.getMpBets().getHighestMoneyBet() + ".");
}
else{
player.sendMessage(ChatColor.RED + "You haven't bet the correct item for this round!");
player.sendMessage(ChatColor.RED + "You must bet a " + minigame.getMpBets().highestBetName() + ".");
}
}
else if(minigame != null && minigame.getMpTimer() != null && minigame.getMpTimer().getPlayerWaitTimeLeft() == 0){
player.sendMessage(ChatColor.RED + "The game has already started. Please try again later.");
}
}
}
public void startMPMinigame(Minigame minigame){
List<MinigamePlayer> players = new ArrayList<MinigamePlayer>();
players.addAll(minigame.getPlayers());
Collections.shuffle(players);
if(minigame.getType().equals("teamdm") && ScoreTypes.getScoreType(minigame.getScoreType()) != null){
ScoreTypes.getScoreType(minigame.getScoreType()).balanceTeam(players, minigame);
}
Location start = null;
int pos = 0;
int bluepos = 0;
int redpos = 0;
for(MinigamePlayer ply : players){
if(!minigame.getType().equals("teamdm")){
if(pos < minigame.getStartLocations().size()){
start = minigame.getStartLocations().get(pos);
minigameTeleport(ply, start);
ply.setCheckpoint(start);
if(minigame.getMaxScore() != 0 && minigame.getType().equals("dm") && !minigame.getScoreType().equals("none")){
ply.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "Score to win: " + minigame.getMaxScorePerPlayer(minigame.getPlayers().size()));
}
}
else{
pos = 0;
if(!minigame.getStartLocations().isEmpty()){
start = minigame.getStartLocations().get(0);
minigameTeleport(ply, start);
ply.setCheckpoint(start);
if(minigame.getMaxScore() != 0 && minigame.getType().equals("dm") && !minigame.getScoreType().equals("none")){
ply.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "Score to win: " + minigame.getMaxScorePerPlayer(minigame.getPlayers().size()));
}
}
else {
ply.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "Starting positions are incorrectly configured!");
quitMinigame(ply, false);
}
}
}
else{
int team = -1;
if(minigame.getBlueTeam().contains(ply.getPlayer())){
team = 1;
}
else if(minigame.getRedTeam().contains(ply.getPlayer())){
team = 0;
}
if(!minigame.getStartLocationsRed().isEmpty() && !minigame.getStartLocationsBlue().isEmpty()){
if(team == 0 && redpos < minigame.getStartLocationsRed().size()){
start = minigame.getStartLocationsRed().get(redpos);
redpos++;
}
else if(team == 1 && bluepos < minigame.getStartLocationsBlue().size()){
start = minigame.getStartLocationsBlue().get(bluepos);
bluepos++;
}
else if(team == 0 && !minigame.getStartLocationsRed().isEmpty()){
redpos = 0;
start = minigame.getStartLocationsRed().get(redpos);
redpos++;
}
else if(team == 1 && !minigame.getStartLocationsBlue().isEmpty()){
bluepos = 0;
start = minigame.getStartLocationsBlue().get(bluepos);
bluepos++;
}
else if(minigame.getStartLocationsBlue().isEmpty() || minigame.getStartLocationsRed().isEmpty()){
ply.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "Starting positions are incorrectly configured!");
quitMinigame(ply, false);
}
}
else{
if(pos <= minigame.getStartLocations().size()){
start = minigame.getStartLocations().get(pos);
minigameTeleport(ply, start);
ply.setCheckpoint(start);
}
else{
pos = 1;
if(!minigame.getStartLocations().isEmpty()){
start = minigame.getStartLocations().get(0);
minigameTeleport(ply, start);
ply.setCheckpoint(start);
}
else {
ply.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "Starting positions are incorrectly configured!");
quitMinigame(ply, false);
}
}
}
if(start != null){
minigameTeleport(ply, start);
ply.setCheckpoint(start);
if(minigame.getMaxScore() != 0 && !minigame.getScoreType().equals("none")){
ply.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "Score to win: " + minigame.getMaxScorePerPlayer(minigame.getPlayers().size()));
}
}
if(minigame.getLives() > 0){
ply.sendMessage(ChatColor.AQUA + "[Minigame] " + ChatColor.WHITE + "Lives left: " + minigame.getLives());
}
}
pos++;
if(!minigame.getPlayersLoadout(ply).getItems().isEmpty()){
minigame.getPlayersLoadout(ply).equiptLoadout(ply);
}
ply.getPlayer().setScoreboard(minigame.getScoreboardManager());
minigame.setScore(ply, 1);
minigame.setScore(ply, 0);
}
if(minigame.hasPlayers()){
if(minigame.getSpleefFloor1() != null && minigame.getSpleefFloor2() != null){
minigame.addFloorDegenerator();
minigame.getFloorDegenerator().startDegeneration();
}
if(minigame.hasRestoreBlocks()){
for(RestoreBlock block : minigame.getRestoreBlocks().values()){
minigame.getBlockRecorder().addBlock(block.getLocation().getBlock(), null);
}
}
if(minigame.getTimer() > 0){
minigame.setMinigameTimer(new MinigameTimer(minigame, minigame.getTimer()));
mdata.sendMinigameMessage(minigame, MinigameUtils.convertTime(minigame.getTimer()) + " left.", null, null);
}
}
}
public void revertToCheckpoint(MinigamePlayer player) {
RevertCheckpointEvent event = new RevertCheckpointEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
minigameTeleport(player, player.getCheckpoint());
player.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "You have been reverted to the checkpoint.");
}
}
public void quitMinigame(MinigamePlayer player, boolean forced){
Minigame mgm = player.getMinigame();
QuitMinigameEvent event = new QuitMinigameEvent(player, mgm, forced);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
if(!mgm.isSpectator(player)){
player.setAllowTeleport(true);
if(player.getPlayer().getVehicle() != null){
Vehicle vehicle = (Vehicle) player.getPlayer().getVehicle();
vehicle.eject();
}
player.getPlayer().closeInventory();
if(!forced){
mdata.sendMinigameMessage(mgm, player.getName() + " has left " + mgm, "error", player);
}
else{
mdata.sendMinigameMessage(mgm, player.getName() + " was removed from " + mgm, "error", player);
}
mgm.removePlayersLoadout(player);
final MinigamePlayer ply = player;
if(!player.getPlayer().isDead()){
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if(ply.getPlayer().isOnline() && !ply.getPlayer().isDead()){
ply.restorePlayerData();
}
}
});
}
player.removeMinigame();
mgm.removePlayer(player);
mdata.minigameType(mgm.getType()).quitMinigame(player, mgm, forced);
for(PotionEffect potion : player.getPlayer().getActivePotionEffects()){
player.getPlayer().removePotionEffect(potion.getType());
}
player.getPlayer().setFallDistance(0);
final MinigamePlayer fplayer = player;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
fplayer.getPlayer().setFireTicks(0);
fplayer.getPlayer().setNoDamageTicks(60);
}
});
player.clearFlags();
player.resetDeaths();
player.resetKills();
player.resetScore();
player.removeCheckpoint();
plugin.getLogger().info(player.getName() + " quit " + mgm);
if(mgm.getPlayers().size() == 0){
if(mgm.getMinigameTimer() != null){
mgm.getMinigameTimer().stopTimer();
mgm.setMinigameTimer(null);
}
if(mgm.getFloorDegenerator() != null){
mgm.getFloorDegenerator().stopDegenerator();
}
if(mgm.getBlockRecorder().hasData()){
mgm.getBlockRecorder().restoreBlocks();
mgm.getBlockRecorder().restoreEntities();
}
if(mgm.getMpBets() != null){
mgm.setMpBets(null);
}
}
mgm.getScoreboardManager().resetScores(player.getPlayer());
for(MinigamePlayer pl : mgm.getSpectators()){
player.getPlayer().showPlayer(pl.getPlayer());
}
ply.setAllowTeleport(true);
ply.setAllowGamemodeChange(true);
}
else{
if(player.getPlayer().getVehicle() != null){
Vehicle vehicle = (Vehicle) player.getPlayer().getVehicle();
vehicle.eject();
}
player.getPlayer().setFallDistance(0);
player.getPlayer().closeInventory();
final Player fplayer = player.getPlayer();
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
fplayer.setFireTicks(0);
fplayer.setNoDamageTicks(60);
}
});
final MinigamePlayer ply = player;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if(ply.getPlayer().isOnline()){
ply.restorePlayerData();
}
}
});
minigameTeleport(player, mgm.getQuitPosition());
player.removeMinigame();
mgm.removeSpectator(player);
for(PotionEffect potion : player.getPlayer().getActivePotionEffects()){
player.getPlayer().removePotionEffect(potion.getType());
}
for(MinigamePlayer pl : mgm.getPlayers()){
pl.getPlayer().showPlayer(player.getPlayer());
}
ply.getPlayer().setFlying(false);
ply.setAllowTeleport(true);
ply.setAllowGamemodeChange(true);
player.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You quit spectator mode in " + mgm);
mdata.sendMinigameMessage(mgm, player.getName() + " is no longer spectating " + mgm, "error", player);
}
}
}
public void endMinigame(final MinigamePlayer player){
Minigame mgm = player.getMinigame();
EndMinigameEvent event = new EndMinigameEvent(player, mgm);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
if(player.getPlayer().getVehicle() != null){
Vehicle vehicle = (Vehicle) player.getPlayer().getVehicle();
vehicle.eject();
}
player.getPlayer().closeInventory();
if(player.getPlayer().isOnline() && !player.getPlayer().isDead()){
player.restorePlayerData();
}
player.removeMinigame();
mgm.removePlayer(player);
mgm.removePlayersLoadout(player);
player.getPlayer().setFallDistance(0);
mdata.minigameType(mgm.getType()).endMinigame(player, mgm);
for(PotionEffect potion : player.getPlayer().getActivePotionEffects()){
player.getPlayer().removePotionEffect(potion.getType());
}
player.getPlayer().setFireTicks(0);
player.getPlayer().setNoDamageTicks(60);
player.clearFlags();
if(plugin.getSQL() == null || plugin.getSQL().getSql() == null){
player.resetDeaths();
player.resetKills();
player.resetScore();
}
if(mgm.getMinigameTimer() != null){
mgm.getMinigameTimer().stopTimer();
mgm.setMinigameTimer(null);
}
if(mgm.getFloorDegenerator() != null && mgm.getPlayers().size() == 0){
mgm.getFloorDegenerator().stopDegenerator();
}
if(mgm.getMpBets() != null && mgm.getPlayers().size() == 0){
mgm.setMpBets(null);
}
if(mgm.getBlockRecorder().hasData()){
if(!mgm.getType().equalsIgnoreCase("sp") || mgm.getPlayers().isEmpty()){
mgm.getBlockRecorder().restoreBlocks();
mgm.getBlockRecorder().restoreEntities();
}
else if(mgm.getPlayers().isEmpty()){
mgm.getBlockRecorder().restoreBlocks(player);
mgm.getBlockRecorder().restoreEntities(player);
}
}
for(MinigamePlayer pl : mgm.getSpectators()){
player.getPlayer().showPlayer(pl.getPlayer());
}
player.setAllowTeleport(true);
player.setAllowGamemodeChange(true);
plugin.getLogger().info(player.getName() + " completed " + mgm);
mgm.getScoreboardManager().resetScores(player.getPlayer());
}
}
public void endTeamMinigame(int teamnum, Minigame mgm){
List<MinigamePlayer> losers = new ArrayList<MinigamePlayer>();
List<MinigamePlayer> winners = new ArrayList<MinigamePlayer>();
if(teamnum == 1){
//Blue team
for(OfflinePlayer ply : mgm.getRedTeam()){
losers.add(getMinigamePlayer(ply.getName()));
}
for(OfflinePlayer ply : mgm.getBlueTeam()){
winners.add(getMinigamePlayer(ply.getName()));
}
}
else{
//Red team
for(OfflinePlayer ply : mgm.getRedTeam()){
winners.add(getMinigamePlayer(ply.getName()));
}
for(OfflinePlayer ply : mgm.getBlueTeam()){
losers.add(getMinigamePlayer(ply.getName()));
}
}
EndTeamMinigameEvent event = new EndTeamMinigameEvent(losers, winners, mgm, teamnum);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
if(event.getWinningTeamInt() == 1){
if(plugin.getConfig().getBoolean("multiplayer.broadcastwin")){
String score = "";
if(mgm.getRedTeamScore() != 0 && mgm.getBlueTeamScore() != 0){
score = ", " + ChatColor.BLUE + mgm.getBlueTeamScore() + ChatColor.WHITE + " to " + ChatColor.RED + mgm.getRedTeamScore();
}
plugin.getServer().broadcastMessage(ChatColor.GREEN + "[Minigames] " + ChatColor.BLUE + "Blue Team" + ChatColor.WHITE + " won " + mgm.getName() + score);
}
}
else{
if(plugin.getConfig().getBoolean("multiplayer.broadcastwin")){
String score = "";
if(mgm.getRedTeamScore() != 0 && mgm.getBlueTeamScore() != 0){
score = ", " + ChatColor.RED + mgm.getRedTeamScore() + ChatColor.WHITE + " to " + ChatColor.BLUE + mgm.getBlueTeamScore();
}
plugin.getServer().broadcastMessage(ChatColor.GREEN + "[Minigames] " + ChatColor.RED + "Red Team" + ChatColor.WHITE + " won " + mgm.getName() + score);
}
}
mgm.setRedTeamScore(0);
mgm.setBlueTeamScore(0);
mgm.getMpTimer().setStartWaitTime(0);
List<MinigamePlayer> winplayers = new ArrayList<MinigamePlayer>();
winplayers.addAll(event.getWinnningPlayers());
if(plugin.getSQL() != null){
new SQLCompletionSaver(mgm.getName(), winplayers, mdata.minigameType(mgm.getType()));
}
if(mgm.getMpBets() != null){
if(mgm.getMpBets().hasMoneyBets()){
List<MinigamePlayer> plys = new ArrayList<MinigamePlayer>();
plys.addAll(event.getWinnningPlayers());
if(!plys.isEmpty()){
double bets = mgm.getMpBets().claimMoneyBets() / (double) plys.size();
BigDecimal roundBets = new BigDecimal(bets);
roundBets = roundBets.setScale(2, BigDecimal.ROUND_HALF_UP);
bets = roundBets.doubleValue();
for(MinigamePlayer ply : plys){
plugin.getEconomy().depositPlayer(ply.getName(), bets);
ply.sendMessage(ChatColor.AQUA + "[Minigames] " + ChatColor.WHITE + "You won $" + bets);
}
}
}
mgm.setMpBets(null);
}
if(!event.getLosingPlayers().isEmpty()){
List<MinigamePlayer> loseplayers = new ArrayList<MinigamePlayer>();
loseplayers.addAll(event.getLosingPlayers());
for(int i = 0; i < loseplayers.size(); i++){
if(loseplayers.get(i) instanceof MinigamePlayer){
final MinigamePlayer p = loseplayers.get(i);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
p.sendMessage(ChatColor.RED + "[Minigames] " + ChatColor.WHITE + "You have been beaten! Bad luck!");
quitMinigame(p, true);
}
});
}
else{
loseplayers.remove(i);
}
}
mgm.setMpTimer(null);
for(MinigamePlayer pl : loseplayers){
mgm.getPlayers().remove(pl);
}
}
for(int i = 0; i < winplayers.size(); i++){
if(winplayers.get(i) instanceof MinigamePlayer){
final MinigamePlayer p = winplayers.get(i);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
endMinigame(p);
}
});
}
else{
winplayers.remove(i);
}
}
mgm.setMpTimer(null);
}
}
@Deprecated
public boolean playerInMinigame(Player player){
return minigamePlayers.get(player.getName()).isInMinigame();
}
@Deprecated
public List<Player> playersInMinigame(){
List<Player> players = new ArrayList<Player>();
for(Player player : plugin.getServer().getOnlinePlayers()){
if(playerInMinigame(player)){
players.add(player);
}
}
return players;
}
public void addMinigamePlayer(Player player){
minigamePlayers.put(player.getName(), new MinigamePlayer(player));
}
public void removeMinigamePlayer(Player player){
if(minigamePlayers.containsKey(player.getName())){
minigamePlayers.remove(player.getName());
}
}
public MinigamePlayer getMinigamePlayer(Player player){
return minigamePlayers.get(player.getName());
}
public MinigamePlayer getMinigamePlayer(String player){
return minigamePlayers.get(player);
}
public Collection<MinigamePlayer> getAllMinigamePlayers(){
return minigamePlayers.values();
}
public boolean hasMinigamePlayer(String name){
return minigamePlayers.containsKey(name);
}
public void addOfflineMinigamePlayer(MinigamePlayer player){
offlineMinigamePlayers.put(player.getName(), new OfflineMinigamePlayer(player.getName(), player.getStoredItems(), player.getStoredArmour(), player.getFood(), player.getHealth(), player.getSaturation(), player.getLastGamemode(), player.getQuitPos()));
}
public void addOfflineMinigamePlayer(OfflineMinigamePlayer player){
offlineMinigamePlayers.put(player.getPlayer(), player);
}
public OfflineMinigamePlayer getOfflineMinigamePlayer(String name){
return offlineMinigamePlayers.get(name);
}
public boolean hasOfflineMinigamePlayer(String name){
return offlineMinigamePlayers.containsKey(name);
}
public void removeOfflineMinigamePlayer(String name){
offlineMinigamePlayers.remove(name);
}
// public void storePlayerInventory(String player, ItemStack[] items, ItemStack[] armour, Integer health, Integer food, Float saturation){
// OfflineMinigamePlayer oply = new OfflineMinigamePlayer(player, items, armour, food, health, saturation, GameMode.SURVIVAL, resPos.get(player));
// offlineMinigamePlayers.put(player, oply);
// }
public List<String> checkRequiredFlags(MinigamePlayer player, String minigame){
List<String> checkpoints = new ArrayList<String>();
checkpoints.addAll(mdata.getMinigame(minigame).getFlags());
List<String> pchecks = player.getFlags();
if(!pchecks.isEmpty()){
checkpoints.removeAll(pchecks);
}
return checkpoints;
}
public Configuration getInventorySaveConfig(){
return invsave.getConfig();
}
public void saveInventoryConfig(){
invsave.saveConfig();
}
public boolean onPartyMode(){
return partyMode;
}
public void setPartyMode(boolean mode){
partyMode = mode;
}
public void partyMode(MinigamePlayer player){
if(onPartyMode()){
Location loc = player.getPlayer().getLocation();
Firework firework = (Firework) player.getPlayer().getWorld().spawnEntity(loc, EntityType.FIREWORK);
FireworkMeta fwm = firework.getFireworkMeta();
Random chance = new Random();
Type type = Type.BALL_LARGE;
if(chance.nextInt(100) < 50){
type = Type.BALL;
}
Color col = Color.fromRGB(chance.nextInt(255), chance.nextInt(255), chance.nextInt(255));
FireworkEffect effect = FireworkEffect.builder().with(type).withColor(col).flicker(chance.nextBoolean()).trail(chance.nextBoolean()).build();
fwm.addEffect(effect);
fwm.setPower(1);
firework.setFireworkMeta(fwm);
}
}
public void partyMode(MinigamePlayer player, int amount, long delay){
final int fcount = amount;
final MinigamePlayer fplayer = player;
final long fdelay = delay;
partyMode(fplayer);
if(amount == 1) return;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if(fplayer != null){
partyMode(fplayer, fcount - 1, fdelay);
}
}
}, delay);
}
public List<String> getDeniedCommands() {
return deniedCommands;
}
public void setDeniedCommands(List<String> deniedCommands) {
this.deniedCommands = deniedCommands;
}
public void addDeniedCommand(String command){
deniedCommands.add(command);
}
public void removeDeniedCommand(String command){
deniedCommands.remove(command);
}
public void saveDeniedCommands(){
plugin.getConfig().set("disabledCommands", deniedCommands);
plugin.saveConfig();
}
public void loadDeniedCommands(){
setDeniedCommands(plugin.getConfig().getStringList("disabledCommands"));
}
public boolean hasStoredPlayerCheckpoint(MinigamePlayer player){
if(storedPlayerCheckpoints.containsKey(player.getName())){
return true;
}
return false;
}
public StoredPlayerCheckpoints getPlayersStoredCheckpoints(MinigamePlayer player){
return storedPlayerCheckpoints.get(player.getName());
}
public void addStoredPlayerCheckpoint(MinigamePlayer player, String minigame, Location checkpoint){
StoredPlayerCheckpoints spc = new StoredPlayerCheckpoints(player.getName(), minigame, checkpoint);
storedPlayerCheckpoints.put(player.getName(), spc);
}
public void addStoredPlayerCheckpoints(String name, StoredPlayerCheckpoints spc){
storedPlayerCheckpoints.put(name, spc);
}
public void minigameTeleport(MinigamePlayer player, Location location){
if(player.isInMinigame()){
player.setAllowTeleport(true);
player.getPlayer().teleport(location);
player.setAllowTeleport(false);
}
else{
player.getPlayer().teleport(location);
}
}
}
| Fixed players quitting game while in a Minigame throwing a NPE
| src/com/pauldavdesign/mineauz/minigames/PlayerData.java | Fixed players quitting game while in a Minigame throwing a NPE | <ide><path>rc/com/pauldavdesign/mineauz/minigames/PlayerData.java
<ide> }
<ide>
<ide> public void addOfflineMinigamePlayer(MinigamePlayer player){
<del> offlineMinigamePlayers.put(player.getName(), new OfflineMinigamePlayer(player.getName(), player.getStoredItems(), player.getStoredArmour(), player.getFood(), player.getHealth(), player.getSaturation(), player.getLastGamemode(), player.getQuitPos()));
<add> Location loc = null;
<add> if(player.getQuitPos() != null){
<add> loc = player.getQuitPos();
<add> }
<add> else{
<add> loc = player.getMinigame().getQuitPosition();
<add> }
<add> offlineMinigamePlayers.put(player.getName(), new OfflineMinigamePlayer(player.getName(), player.getStoredItems(), player.getStoredArmour(), player.getFood(), player.getHealth(), player.getSaturation(), player.getLastGamemode(), loc));
<ide> }
<ide>
<ide> public void addOfflineMinigamePlayer(OfflineMinigamePlayer player){ |
|
Java | apache-2.0 | 368a6cbe6b80e8d576bb203c104a9c33efad0a82 | 0 | burris/dwr,burris/dwr | /*
* Copyright 2005 Joe Walker
*
* 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.directwebremoting;
import java.util.ArrayList;
import java.util.List;
/**
* A ScriptBuffer is like a StringBuffer except that it is used to create
* Javascript commands. There are 2 version of the <code>append()</code> method:
* <p>The first is {@link #appendScript(String)} which assumes that the
* parameter is to be inserted literally into the output.
* <p>The second is {@link #appendData(String)} (and variants for Object and
* primitive types) which assumes that the parameter is a variable which should
* be properly converted, escaped and quoted.
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class ScriptBuffer
{
/**
* Create an empty ScriptBuffer.
*/
public ScriptBuffer()
{
}
/**
* Create a ScriptBuffer with some initial content.
* {@link #appendScript(String)} is called with the passed string
* @param str The initial string to place in the buffer
*/
public ScriptBuffer(String str)
{
appendScript(str);
}
/**
* @param str The String to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(java.lang.String)
*/
public ScriptBuffer appendScript(String str)
{
parts.add(new StringWrapper(str));
return this;
}
/**
* @param b The boolean to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(boolean)
*/
public ScriptBuffer appendData(boolean b)
{
Boolean data = b ? Boolean.TRUE : Boolean.FALSE;
parts.add(data);
return this;
}
/**
* @param c The char to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(char)
*/
public ScriptBuffer appendData(char c)
{
parts.add(new Character(c));
return this;
}
/**
* @param d The double to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(double)
*/
public ScriptBuffer appendData(double d)
{
parts.add(new Double(d));
return this;
}
/**
* @param f The float to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(float)
*/
public ScriptBuffer appendData(float f)
{
parts.add(new Float(f));
return this;
}
/**
* @param i The int to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(int)
*/
public ScriptBuffer appendData(int i)
{
parts.add(new Integer(i));
return this;
}
/**
* @param l The long to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(long)
*/
public ScriptBuffer appendData(long l)
{
parts.add(new Long(l));
return this;
}
/**
* @param obj The Object to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(java.lang.Object)
*/
public ScriptBuffer appendData(Object obj)
{
parts.add(obj);
return this;
}
/**
* @param str The String to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(java.lang.String)
*/
public ScriptBuffer appendData(String str)
{
parts.add(str);
return this;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString()
{
return parts.toString();
}
/**
* For DWR use only - This method is not part of the public API.
* Do not use it without understanding the implications for future proofing.
* @return The list of parts of the final output script
*/
public List getParts()
{
return parts;
}
/**
* A wrapper around a string to distinguish a string entered into this
* buffer as code and a string entered as data
*/
public class StringWrapper
{
StringWrapper(String data)
{
this.data = data;
}
String data;
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString()
{
return data;
}
}
/**
* This is where we store all the script components waiting to be serialized
*/
private List parts = new ArrayList();
}
| java/org/directwebremoting/ScriptBuffer.java | /*
* Copyright 2005 Joe Walker
*
* 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.directwebremoting;
import java.util.ArrayList;
import java.util.List;
/**
* A ScriptBuffer is like a StringBuffer except that it is used to create
* Javascript commands. There are 2 version of the <code>append()</code> method:
* <p>The first is {@link #appendScript(String)} which assumes that the
* parameter is to be inserted literally into the output.
* <p>The second is {@link #appendData(String)} (and variants for Object and
* primitive types) which assumes that the parameter is a variable which should
* be properly converted, escaped and quoted.
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class ScriptBuffer
{
/**
* Create an empty ScriptBuffer.
*/
public ScriptBuffer()
{
}
/**
* Create a ScriptBuffer with some initial content.
* {@link #appendScript(String)} is called with the passed string
* @param str The initial string to place in the buffer
*/
public ScriptBuffer(String str)
{
appendScript(str);
}
/**
* @param str The String to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(java.lang.String)
*/
public ScriptBuffer appendScript(String str)
{
parts.add(new StringWrapper(str));
return this;
}
/**
* @param b The boolean to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(boolean)
*/
public ScriptBuffer appendData(boolean b)
{
Boolean data = new Boolean(b);
parts.add(data);
return this;
}
/**
* @param c The char to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(char)
*/
public ScriptBuffer appendData(char c)
{
parts.add(new Character(c));
return this;
}
/**
* @param d The double to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(double)
*/
public ScriptBuffer appendData(double d)
{
parts.add(new Double(d));
return this;
}
/**
* @param f The float to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(float)
*/
public ScriptBuffer appendData(float f)
{
parts.add(new Float(f));
return this;
}
/**
* @param i The int to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(int)
*/
public ScriptBuffer appendData(int i)
{
parts.add(new Integer(i));
return this;
}
/**
* @param l The long to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(long)
*/
public ScriptBuffer appendData(long l)
{
parts.add(new Long(l));
return this;
}
/**
* @param obj The Object to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(java.lang.Object)
*/
public ScriptBuffer appendData(Object obj)
{
parts.add(obj);
return this;
}
/**
* @param str The String to add to the script
* @return this. To allow sv.append(x).append(y).append(z);
* @see java.lang.StringBuffer#append(java.lang.String)
*/
public ScriptBuffer appendData(String str)
{
parts.add(str);
return this;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString()
{
return parts.toString();
}
/**
* For DWR use only - This method is not part of the public API.
* Do not use it without understanding the implications for future proofing.
* @return The list of parts of the final output script
*/
public List getParts()
{
return parts;
}
/**
* A wrapper around a string to distinguish a string entered into this
* buffer as code and a string entered as data
*/
public class StringWrapper
{
StringWrapper(String data)
{
this.data = data;
}
String data;
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString()
{
return data;
}
}
/**
* This is where we store all the script components waiting to be serialized
*/
private List parts = new ArrayList();
}
| Boolean ctor optimization to keep findbugs happy
git-svn-id: ba1d8d5a2a2c535e023d6080c1e5c29aa0f5364e@1143 3a8262b2-faa5-11dc-8610-ff947880b6b2
| java/org/directwebremoting/ScriptBuffer.java | Boolean ctor optimization to keep findbugs happy | <ide><path>ava/org/directwebremoting/ScriptBuffer.java
<ide> */
<ide> public ScriptBuffer appendData(boolean b)
<ide> {
<del> Boolean data = new Boolean(b);
<add> Boolean data = b ? Boolean.TRUE : Boolean.FALSE;
<ide> parts.add(data);
<ide> return this;
<ide> } |
|
Java | apache-2.0 | 2fb01b67ad833f398f35919bdee45115e177ca4d | 0 | resmo/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,resmo/cloudstack,jcshen007/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,wido/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,resmo/cloudstack,wido/cloudstack | // 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 com.cloud.storage;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import javax.inject.Inject;
import com.cloud.utils.EncryptionUtil;
import com.cloud.utils.db.TransactionCallbackWithException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.cloudstack.api.command.user.volume.GetUploadParamsForVolumeCmd;
import org.apache.cloudstack.api.response.GetUploadParamsResponse;
import org.apache.cloudstack.engine.subsystem.api.storage.DataObject;
import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint;
import org.apache.cloudstack.storage.command.TemplateOrVolumePostUploadCommand;
import org.apache.cloudstack.utils.imagestore.ImageStoreUtil;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.MigrateVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.ResizeVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.UploadVolumeCmd;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService;
import org.apache.cloudstack.engine.subsystem.api.storage.ChapInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.HostScope;
import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.Scope;
import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult;
import org.apache.cloudstack.framework.async.AsyncCallFuture;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.framework.jobs.AsyncJob;
import org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext;
import org.apache.cloudstack.framework.jobs.AsyncJobManager;
import org.apache.cloudstack.framework.jobs.Outcome;
import org.apache.cloudstack.framework.jobs.dao.VmWorkJobDao;
import org.apache.cloudstack.framework.jobs.impl.AsyncJobVO;
import org.apache.cloudstack.framework.jobs.impl.OutcomeImpl;
import org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO;
import org.apache.cloudstack.jobs.JobInfo;
import org.apache.cloudstack.storage.command.AttachAnswer;
import org.apache.cloudstack.storage.command.AttachCommand;
import org.apache.cloudstack.storage.command.DettachCommand;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO;
import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity;
import org.apache.cloudstack.utils.identity.ManagementServerNode;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.to.DataTO;
import com.cloud.agent.api.to.DiskTO;
import com.cloud.api.ApiDBUtils;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.dc.ClusterDetailsDao;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.domain.Domain;
import com.cloud.event.ActionEvent;
import com.cloud.event.EventTypes;
import com.cloud.event.UsageEventUtils;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.StorageUnavailableException;
import com.cloud.gpu.GPU;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.HypervisorCapabilitiesVO;
import com.cloud.hypervisor.dao.HypervisorCapabilitiesDao;
import com.cloud.org.Grouping;
import com.cloud.service.dao.ServiceOfferingDetailsDao;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.storage.dao.SnapshotDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.snapshot.SnapshotApiService;
import com.cloud.storage.snapshot.SnapshotManager;
import com.cloud.template.TemplateManager;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.ResourceLimitService;
import com.cloud.user.User;
import com.cloud.user.VmDiskStatisticsVO;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.VmDiskStatisticsDao;
import com.cloud.utils.DateUtil;
import com.cloud.utils.EnumUtils;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.Predicate;
import com.cloud.utils.ReflectionUse;
import com.cloud.utils.StringUtils;
import com.cloud.utils.UriUtils;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallback;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.db.UUIDManager;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.fsm.NoTransitionException;
import com.cloud.utils.fsm.StateMachine2;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.VmWork;
import com.cloud.vm.VmWorkAttachVolume;
import com.cloud.vm.VmWorkConstants;
import com.cloud.vm.VmWorkDetachVolume;
import com.cloud.vm.VmWorkExtractVolume;
import com.cloud.vm.VmWorkJobHandler;
import com.cloud.vm.VmWorkJobHandlerProxy;
import com.cloud.vm.VmWorkMigrateVolume;
import com.cloud.vm.VmWorkResizeVolume;
import com.cloud.vm.VmWorkSerializer;
import com.cloud.vm.VmWorkTakeVolumeSnapshot;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.vm.snapshot.VMSnapshotVO;
import com.cloud.vm.snapshot.dao.VMSnapshotDao;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiService, VmWorkJobHandler {
private final static Logger s_logger = Logger.getLogger(VolumeApiServiceImpl.class);
public static final String VM_WORK_JOB_HANDLER = VolumeApiServiceImpl.class.getSimpleName();
@Inject
VolumeOrchestrationService _volumeMgr;
@Inject
EntityManager _entityMgr;
@Inject
AgentManager _agentMgr;
@Inject
TemplateManager _tmpltMgr;
@Inject
SnapshotManager _snapshotMgr;
@Inject
AccountManager _accountMgr;
@Inject
ConfigurationManager _configMgr;
@Inject
VolumeDao _volsDao;
@Inject
HostDao _hostDao;
@Inject
SnapshotDao _snapshotDao;
@Inject
ServiceOfferingDetailsDao _serviceOfferingDetailsDao;
@Inject
StoragePoolDetailsDao storagePoolDetailsDao;
@Inject
UserVmDao _userVmDao;
@Inject
VolumeDataStoreDao _volumeStoreDao;
@Inject
VMInstanceDao _vmInstanceDao;
@Inject
PrimaryDataStoreDao _storagePoolDao;
@Inject
DiskOfferingDao _diskOfferingDao;
@Inject
AccountDao _accountDao;
@Inject
final DataCenterDao _dcDao = null;
@Inject
VMTemplateDao _templateDao;
@Inject
ResourceLimitService _resourceLimitMgr;
@Inject
VmDiskStatisticsDao _vmDiskStatsDao;
@Inject
VMSnapshotDao _vmSnapshotDao;
@Inject
ConfigurationDao _configDao;
@Inject
DataStoreManager dataStoreMgr;
@Inject
VolumeService volService;
@Inject
VolumeDataFactory volFactory;
@Inject
SnapshotApiService snapshotMgr;
@Inject
UUIDManager _uuidMgr;
@Inject
HypervisorCapabilitiesDao _hypervisorCapabilitiesDao;
@Inject
AsyncJobManager _jobMgr;
@Inject
VmWorkJobDao _workJobDao;
@Inject
ClusterDetailsDao _clusterDetailsDao;
private List<StoragePoolAllocator> _storagePoolAllocators;
VmWorkJobHandlerProxy _jobHandlerProxy = new VmWorkJobHandlerProxy(this);
static final ConfigKey<Long> VmJobCheckInterval = new ConfigKey<Long>("Advanced", Long.class, "vm.job.check.interval", "3000",
"Interval in milliseconds to check if the job is complete", false);
private long _maxVolumeSizeInGb;
private final StateMachine2<Volume.State, Volume.Event, Volume> _volStateMachine;
protected VolumeApiServiceImpl() {
_volStateMachine = Volume.State.getStateMachine();
}
/*
* Upload the volume to secondary storage.
*/
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_UPLOAD, eventDescription = "uploading volume", async = true)
public VolumeVO uploadVolume(UploadVolumeCmd cmd) throws ResourceAllocationException {
Account caller = CallContext.current().getCallingAccount();
long ownerId = cmd.getEntityOwnerId();
Account owner = _entityMgr.findById(Account.class, ownerId);
Long zoneId = cmd.getZoneId();
String volumeName = cmd.getVolumeName();
String url = cmd.getUrl();
String format = cmd.getFormat();
Long diskOfferingId = cmd.getDiskOfferingId();
String imageStoreUuid = cmd.getImageStoreUuid();
DataStore store = _tmpltMgr.getImageStore(imageStoreUuid, zoneId);
validateVolume(caller, ownerId, zoneId, volumeName, url, format, diskOfferingId);
VolumeVO volume = persistVolume(owner, zoneId, volumeName, url, cmd.getFormat(), diskOfferingId, Volume.State.Allocated);
VolumeInfo vol = volFactory.getVolume(volume.getId());
RegisterVolumePayload payload = new RegisterVolumePayload(cmd.getUrl(), cmd.getChecksum(), cmd.getFormat());
vol.addPayload(payload);
volService.registerVolume(vol, store);
return volume;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_UPLOAD, eventDescription = "uploading volume for post upload", async = true)
public GetUploadParamsResponse uploadVolume(final GetUploadParamsForVolumeCmd cmd) throws ResourceAllocationException, MalformedURLException {
Account caller = CallContext.current().getCallingAccount();
long ownerId = cmd.getEntityOwnerId();
final Account owner = _entityMgr.findById(Account.class, ownerId);
final Long zoneId = cmd.getZoneId();
final String volumeName = cmd.getName();
String format = cmd.getFormat();
final Long diskOfferingId = cmd.getDiskOfferingId();
String imageStoreUuid = cmd.getImageStoreUuid();
final DataStore store = _tmpltMgr.getImageStore(imageStoreUuid, zoneId);
validateVolume(caller, ownerId, zoneId, volumeName, null, format, diskOfferingId);
return Transaction.execute(new TransactionCallbackWithException<GetUploadParamsResponse, MalformedURLException>() {
@Override
public GetUploadParamsResponse doInTransaction(TransactionStatus status) throws MalformedURLException {
VolumeVO volume = persistVolume(owner, zoneId, volumeName, null, cmd.getFormat(), diskOfferingId, Volume.State.NotUploaded);
VolumeInfo vol = volFactory.getVolume(volume.getId());
RegisterVolumePayload payload = new RegisterVolumePayload(null, cmd.getChecksum(), cmd.getFormat());
vol.addPayload(payload);
Pair<EndPoint, DataObject> pair = volService.registerVolumeForPostUpload(vol, store);
EndPoint ep = pair.first();
DataObject dataObject = pair.second();
GetUploadParamsResponse response = new GetUploadParamsResponse();
String ssvmUrlDomain = _configDao.getValue(Config.SecStorageSecureCopyCert.key());
String url = ImageStoreUtil.generatePostUploadUrl(ssvmUrlDomain, ep.getPublicAddr(), vol.getUuid());
response.setPostURL(new URL(url));
// set the post url, this is used in the monitoring thread to determine the SSVM
VolumeDataStoreVO volumeStore = _volumeStoreDao.findByVolume(vol.getId());
assert (volumeStore != null) : "sincle volume is registered, volumestore cannot be null at this stage";
volumeStore.setExtractUrl(url);
_volumeStoreDao.persist(volumeStore);
response.setId(UUID.fromString(vol.getUuid()));
int timeout = ImageStoreUploadMonitorImpl.getUploadOperationTimeout();
DateTime currentDateTime = new DateTime(DateTimeZone.UTC);
String expires = currentDateTime.plusMinutes(timeout).toString();
response.setTimeout(expires);
String key = _configDao.getValue(Config.SSVMPSK.key());
/*
* encoded metadata using the post upload config key
*/
TemplateOrVolumePostUploadCommand command =
new TemplateOrVolumePostUploadCommand(vol.getId(), vol.getUuid(), volumeStore.getInstallPath(), cmd.getChecksum(), vol.getType().toString(),
vol.getName(), vol.getFormat().toString(), dataObject.getDataStore().getUri(),
dataObject.getDataStore().getRole().toString());
command.setLocalPath(volumeStore.getLocalDownloadPath());
//using the existing max upload size configuration
command.setMaxUploadSize(_configDao.getValue(Config.MaxUploadVolumeSize.key()));
command.setDefaultMaxAccountSecondaryStorage(_configDao.getValue(Config.DefaultMaxAccountSecondaryStorage.key()));
command.setAccountId(vol.getAccountId());
Gson gson = new GsonBuilder().create();
String metadata = EncryptionUtil.encodeData(gson.toJson(command), key);
response.setMetadata(metadata);
/*
* signature calculated on the url, expiry, metadata.
*/
response.setSignature(EncryptionUtil.generateSignature(metadata + url + expires, key));
return response;
}
});
}
private boolean validateVolume(Account caller, long ownerId, Long zoneId, String volumeName, String url,
String format, Long diskOfferingId) throws ResourceAllocationException {
// permission check
Account volumeOwner = _accountMgr.getActiveAccountById(ownerId);
_accountMgr.checkAccess(caller, null, true, volumeOwner);
// Check that the resource limit for volumes won't be exceeded
_resourceLimitMgr.checkResourceLimit(volumeOwner, ResourceType.volume);
// Verify that zone exists
DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Unable to find zone by id " + zoneId);
}
// Check if zone is disabled
if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
}
//validating the url only when url is not null. url can be null incase of form based post upload
if (url != null ) {
if( url.toLowerCase().contains("file://")) {
throw new InvalidParameterValueException("File:// type urls are currently unsupported");
}
UriUtils.validateUrl(format, url);
// check URL existence
UriUtils.checkUrlExistence(url);
// Check that the resource limit for secondary storage won't be exceeded
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(ownerId), ResourceType.secondary_storage, UriUtils.getRemoteSize(url));
} else {
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(ownerId), ResourceType.secondary_storage);
}
try {
ImageFormat.valueOf(format.toUpperCase());
} catch (IllegalArgumentException e) {
s_logger.debug("ImageFormat IllegalArgumentException: " + e.getMessage());
throw new IllegalArgumentException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values()));
}
// Check that the the disk offering specified is valid
if (diskOfferingId != null) {
DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId);
if ((diskOffering == null) || diskOffering.getRemoved() != null
|| !DiskOfferingVO.Type.Disk.equals(diskOffering.getType())) {
throw new InvalidParameterValueException("Please specify a valid disk offering.");
}
if (!diskOffering.isCustomized()) {
throw new InvalidParameterValueException("Please specify a custom sized disk offering.");
}
if (diskOffering.getDomainId() == null) {
// do nothing as offering is public
} else {
_configMgr.checkDiskOfferingAccess(volumeOwner, diskOffering);
}
}
return false;
}
public String getRandomVolumeName() {
return UUID.randomUUID().toString();
}
@DB
protected VolumeVO persistVolume(final Account owner, final Long zoneId, final String volumeName, final String url,
final String format, final Long diskOfferingId, final Volume.State state) {
return Transaction.execute(new TransactionCallback<VolumeVO>() {
@Override
public VolumeVO doInTransaction(TransactionStatus status) {
VolumeVO volume = new VolumeVO(volumeName, zoneId, -1, -1, -1, new Long(-1), null, null, Storage.ProvisioningType.THIN, 0, Volume.Type.DATADISK);
volume.setPoolId(null);
volume.setDataCenterId(zoneId);
volume.setPodId(null);
volume.setState(state); // initialize the state
// to prevent a null pointer deref I put the system account id here when no owner is given.
// TODO Decide if this is valid or whether throwing a CloudRuntimeException is more appropriate
volume.setAccountId((owner == null) ? Account.ACCOUNT_ID_SYSTEM : owner.getAccountId());
volume.setDomainId((owner == null) ? Domain.ROOT_DOMAIN : owner.getDomainId());
if (diskOfferingId == null) {
DiskOfferingVO diskOfferingVO = _diskOfferingDao.findByUniqueName("Cloud.com-Custom");
if (diskOfferingVO != null) {
long defaultDiskOfferingId = diskOfferingVO.getId();
volume.setDiskOfferingId(defaultDiskOfferingId);
}
} else {
volume.setDiskOfferingId(diskOfferingId);
}
// volume.setSize(size);
volume.setInstanceId(null);
volume.setUpdated(new Date());
volume.setDomainId((owner == null) ? Domain.ROOT_DOMAIN : owner.getDomainId());
volume.setFormat(ImageFormat.valueOf(format));
volume = _volsDao.persist(volume);
CallContext.current().setEventDetails("Volume Id: " + volume.getId());
// Increment resource count during allocation; if actual creation fails,
// decrement it
_resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.volume);
//url can be null incase of postupload
if(url!=null) {
_resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.secondary_storage, UriUtils.getRemoteSize(url));
}
return volume;
}
});
}
/*
* Just allocate a volume in the database, don't send the createvolume cmd
* to hypervisor. The volume will be finally created only when it's attached
* to a VM.
*/
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_CREATE, eventDescription = "creating volume", create = true)
public VolumeVO allocVolume(CreateVolumeCmd cmd) throws ResourceAllocationException {
// FIXME: some of the scheduled event stuff might be missing here...
Account caller = CallContext.current().getCallingAccount();
long ownerId = cmd.getEntityOwnerId();
Account owner = _accountMgr.getActiveAccountById(ownerId);
Boolean displayVolume = cmd.getDisplayVolume();
// permission check
_accountMgr.checkAccess(caller, null, true, _accountMgr.getActiveAccountById(ownerId));
if (displayVolume == null) {
displayVolume = true;
} else {
if (!_accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot update parameter displayvolume, only admin permitted ");
}
}
// Check that the resource limit for volumes won't be exceeded
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, displayVolume);
Long zoneId = cmd.getZoneId();
Long diskOfferingId = null;
DiskOfferingVO diskOffering = null;
Storage.ProvisioningType provisioningType;
Long size = null;
Long minIops = null;
Long maxIops = null;
// Volume VO used for extracting the source template id
VolumeVO parentVolume = null;
// validate input parameters before creating the volume
if ((cmd.getSnapshotId() == null && cmd.getDiskOfferingId() == null) || (cmd.getSnapshotId() != null && cmd.getDiskOfferingId() != null)) {
throw new InvalidParameterValueException("Either disk Offering Id or snapshot Id must be passed whilst creating volume");
}
if (cmd.getSnapshotId() == null) {// create a new volume
diskOfferingId = cmd.getDiskOfferingId();
size = cmd.getSize();
Long sizeInGB = size;
if (size != null) {
if (size > 0) {
size = size * 1024 * 1024 * 1024; // user specify size in GB
} else {
throw new InvalidParameterValueException("Disk size must be larger than 0");
}
}
// Check that the the disk offering is specified
diskOffering = _diskOfferingDao.findById(diskOfferingId);
if ((diskOffering == null) || diskOffering.getRemoved() != null || !DiskOfferingVO.Type.Disk.equals(diskOffering.getType())) {
throw new InvalidParameterValueException("Please specify a valid disk offering.");
}
if (diskOffering.isCustomized()) {
if (size == null) {
throw new InvalidParameterValueException("This disk offering requires a custom size specified");
}
Long customDiskOfferingMaxSize = _volumeMgr.CustomDiskOfferingMaxSize.value();
Long customDiskOfferingMinSize = _volumeMgr.CustomDiskOfferingMinSize.value();
if ((sizeInGB < customDiskOfferingMinSize) || (sizeInGB > customDiskOfferingMaxSize)) {
throw new InvalidParameterValueException("Volume size: " + sizeInGB + "GB is out of allowed range. Max: " + customDiskOfferingMaxSize + " Min:"
+ customDiskOfferingMinSize);
}
}
if (!diskOffering.isCustomized() && size != null) {
throw new InvalidParameterValueException("This disk offering does not allow custom size");
}
if (diskOffering.getDomainId() == null) {
// do nothing as offering is public
} else {
_configMgr.checkDiskOfferingAccess(caller, diskOffering);
}
if (diskOffering.getDiskSize() > 0) {
size = diskOffering.getDiskSize();
}
Boolean isCustomizedIops = diskOffering.isCustomizedIops();
if (isCustomizedIops != null) {
if (isCustomizedIops) {
minIops = cmd.getMinIops();
maxIops = cmd.getMaxIops();
if (minIops == null && maxIops == null) {
minIops = 0L;
maxIops = 0L;
} else {
if (minIops == null || minIops <= 0) {
throw new InvalidParameterValueException("The min IOPS must be greater than 0.");
}
if (maxIops == null) {
maxIops = 0L;
}
if (minIops > maxIops) {
throw new InvalidParameterValueException("The min IOPS must be less than or equal to the max IOPS.");
}
}
} else {
minIops = diskOffering.getMinIops();
maxIops = diskOffering.getMaxIops();
}
}
provisioningType = diskOffering.getProvisioningType();
if (!validateVolumeSizeRange(size)) {// convert size from mb to gb
// for validation
throw new InvalidParameterValueException("Invalid size for custom volume creation: " + size + " ,max volume size is:" + _maxVolumeSizeInGb);
}
} else { // create volume from snapshot
Long snapshotId = cmd.getSnapshotId();
SnapshotVO snapshotCheck = _snapshotDao.findById(snapshotId);
if (snapshotCheck == null) {
throw new InvalidParameterValueException("unable to find a snapshot with id " + snapshotId);
}
if (snapshotCheck.getState() != Snapshot.State.BackedUp) {
throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.State.BackedUp + " state yet and can't be used for volume creation");
}
parentVolume = _volsDao.findByIdIncludingRemoved(snapshotCheck.getVolumeId());
diskOfferingId = snapshotCheck.getDiskOfferingId();
diskOffering = _diskOfferingDao.findById(diskOfferingId);
if (zoneId == null) {
// if zoneId is not provided, we default to create volume in the same zone as the snapshot zone.
zoneId = snapshotCheck.getDataCenterId();
}
size = snapshotCheck.getSize(); // ; disk offering is used for tags
// purposes
minIops = snapshotCheck.getMinIops();
maxIops = snapshotCheck.getMaxIops();
provisioningType = diskOffering.getProvisioningType();
// check snapshot permissions
_accountMgr.checkAccess(caller, null, true, snapshotCheck);
// one step operation - create volume in VM's cluster and attach it
// to the VM
Long vmId = cmd.getVirtualMachineId();
if (vmId != null) {
// Check that the virtual machine ID is valid and it's a user vm
UserVmVO vm = _userVmDao.findById(vmId);
if (vm == null || vm.getType() != VirtualMachine.Type.User) {
throw new InvalidParameterValueException("Please specify a valid User VM.");
}
// Check that the VM is in the correct state
if (vm.getState() != State.Running && vm.getState() != State.Stopped) {
throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.");
}
// permission check
_accountMgr.checkAccess(caller, null, false, vm);
}
}
// Check that the resource limit for primary storage won't be exceeded
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, displayVolume, new Long(size));
// Verify that zone exists
DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Unable to find zone by id " + zoneId);
}
// Check if zone is disabled
if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
}
// If local storage is disabled then creation of volume with local disk
// offering not allowed
if (!zone.isLocalStorageEnabled() && diskOffering.getUseLocalStorage()) {
throw new InvalidParameterValueException("Zone is not configured to use local storage but volume's disk offering " + diskOffering.getName() + " uses it");
}
String userSpecifiedName = cmd.getVolumeName();
if (userSpecifiedName == null) {
userSpecifiedName = getRandomVolumeName();
}
VolumeVO volume = commitVolume(cmd, caller, owner, displayVolume, zoneId, diskOfferingId, provisioningType, size,
minIops, maxIops, parentVolume, userSpecifiedName, _uuidMgr.generateUuid(Volume.class, cmd.getCustomId()));
return volume;
}
private VolumeVO commitVolume(final CreateVolumeCmd cmd, final Account caller, final Account owner, final Boolean displayVolume,
final Long zoneId, final Long diskOfferingId, final Storage.ProvisioningType provisioningType, final Long size, final Long minIops, final Long maxIops, final VolumeVO parentVolume,
final String userSpecifiedName, final String uuid) {
return Transaction.execute(new TransactionCallback<VolumeVO>() {
@Override
public VolumeVO doInTransaction(TransactionStatus status) {
VolumeVO volume = new VolumeVO(userSpecifiedName, -1, -1, -1, -1, new Long(-1), null, null, provisioningType, 0, Volume.Type.DATADISK);
volume.setPoolId(null);
volume.setUuid(uuid);
volume.setDataCenterId(zoneId);
volume.setPodId(null);
volume.setAccountId(owner.getId());
volume.setDomainId(owner.getDomainId());
volume.setDiskOfferingId(diskOfferingId);
volume.setSize(size);
volume.setMinIops(minIops);
volume.setMaxIops(maxIops);
volume.setInstanceId(null);
volume.setUpdated(new Date());
volume.setDisplayVolume(displayVolume);
if (parentVolume != null) {
volume.setTemplateId(parentVolume.getTemplateId());
volume.setFormat(parentVolume.getFormat());
} else {
volume.setTemplateId(null);
}
volume = _volsDao.persist(volume);
if (cmd.getSnapshotId() == null && displayVolume) {
// for volume created from snapshot, create usage event after volume creation
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(),
diskOfferingId, null, size, Volume.class.getName(), volume.getUuid(), displayVolume);
}
CallContext.current().setEventDetails("Volume Id: " + volume.getId());
// Increment resource count during allocation; if actual creation fails,
// decrement it
_resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.volume, displayVolume);
_resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.primary_storage, displayVolume, new Long(volume.getSize()));
return volume;
}
});
}
public boolean validateVolumeSizeRange(long size) {
if (size < 0 || (size > 0 && size < (1024 * 1024 * 1024))) {
throw new InvalidParameterValueException("Please specify a size of at least 1 GB.");
} else if (size > (_maxVolumeSizeInGb * 1024 * 1024 * 1024)) {
throw new InvalidParameterValueException("Requested volume size is " + size + ", but the maximum size allowed is " + _maxVolumeSizeInGb + " GB.");
}
return true;
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_CREATE, eventDescription = "creating volume", async = true)
public VolumeVO createVolume(CreateVolumeCmd cmd) {
VolumeVO volume = _volsDao.findById(cmd.getEntityId());
boolean created = true;
try {
if (cmd.getSnapshotId() != null) {
volume = createVolumeFromSnapshot(volume, cmd.getSnapshotId(), cmd.getVirtualMachineId());
if (volume.getState() != Volume.State.Ready) {
created = false;
}
// if VM Id is provided, attach the volume to the VM
if (cmd.getVirtualMachineId() != null) {
try {
attachVolumeToVM(cmd.getVirtualMachineId(), volume.getId(), volume.getDeviceId());
} catch (Exception ex) {
StringBuilder message = new StringBuilder("Volume: ");
message.append(volume.getUuid());
message.append(" created successfully, but failed to attach the newly created volume to VM: ");
message.append(cmd.getVirtualMachineId());
message.append(" due to error: ");
message.append(ex.getMessage());
if (s_logger.isDebugEnabled()) {
s_logger.debug(message, ex);
}
throw new CloudRuntimeException(message.toString());
}
}
}
return volume;
} catch (Exception e) {
created = false;
VolumeInfo vol = volFactory.getVolume(cmd.getEntityId());
vol.stateTransit(Volume.Event.DestroyRequested);
throw new CloudRuntimeException("Failed to create volume: " + volume.getId(), e);
} finally {
if (!created) {
s_logger.trace("Decrementing volume resource count for account id=" + volume.getAccountId() + " as volume failed to create on the backend");
_resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.volume, cmd.getDisplayVolume());
_resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(), ResourceType.primary_storage.getOrdinal());
}
}
}
protected VolumeVO createVolumeFromSnapshot(VolumeVO volume, long snapshotId, Long vmId) throws StorageUnavailableException {
VolumeInfo createdVolume = null;
SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
snapshot.getVolumeId();
UserVmVO vm = null;
if (vmId != null) {
vm = _userVmDao.findById(vmId);
}
// sync old snapshots to region store if necessary
createdVolume = _volumeMgr.createVolumeFromSnapshot(volume, snapshot, vm);
VolumeVO volumeVo = _volsDao.findById(createdVolume.getId());
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, createdVolume.getAccountId(), createdVolume.getDataCenterId(), createdVolume.getId(),
createdVolume.getName(), createdVolume.getDiskOfferingId(), null, createdVolume.getSize(), Volume.class.getName(), createdVolume.getUuid(), volumeVo.isDisplayVolume());
return volumeVo;
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_RESIZE, eventDescription = "resizing volume", async = true)
public VolumeVO resizeVolume(ResizeVolumeCmd cmd) throws ResourceAllocationException {
Long newSize = null;
Long newMinIops = null;
Long newMaxIops = null;
boolean shrinkOk = cmd.getShrinkOk();
VolumeVO volume = _volsDao.findById(cmd.getEntityId());
if (volume == null) {
throw new InvalidParameterValueException("No such volume");
}
/* Does the caller have authority to act on this volume? */
_accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
if(volume.getInstanceId() != null) {
// Check that Vm to which this volume is attached does not have VM Snapshots
if (_vmSnapshotDao.findByVm(volume.getInstanceId()).size() > 0) {
throw new InvalidParameterValueException("Volume cannot be resized which is attached to VM with VM Snapshots");
}
}
DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId());
DiskOfferingVO newDiskOffering = null;
if (cmd.getNewDiskOfferingId() != null && volume.getDiskOfferingId() != cmd.getNewDiskOfferingId()) {
newDiskOffering = _diskOfferingDao.findById(cmd.getNewDiskOfferingId());
}
/* Only works for KVM/XenServer/VMware (or "Any") for now, and volumes with 'None' since they're just allocated in DB */
HypervisorType hypervisorType = _volsDao.getHypervisorType(volume.getId());
if (hypervisorType != HypervisorType.KVM && hypervisorType != HypervisorType.XenServer &&
hypervisorType != HypervisorType.VMware && hypervisorType != HypervisorType.Any && hypervisorType != HypervisorType.None) {
throw new InvalidParameterValueException("CloudStack currently supports volume resize only on KVM, VMware, or XenServer.");
}
if (volume.getState() != Volume.State.Ready && volume.getState() != Volume.State.Allocated) {
throw new InvalidParameterValueException("Volume should be in ready or allocated state before attempting a resize. Volume " +
volume.getUuid() + " is in state " + volume.getState() + ".");
}
// if we are to use the existing disk offering
if (newDiskOffering == null) {
newSize = cmd.getSize();
// if the caller is looking to change the size of the volume
if (newSize != null) {
if (!diskOffering.isCustomized() && !volume.getVolumeType().equals(Volume.Type.ROOT)) {
throw new InvalidParameterValueException("To change a volume's size without providing a new disk offering, its current disk offering must be " +
"customizable or it must be a root volume (if providing a disk offering, make sure it is different from the current disk offering).");
}
// convert from bytes to GiB
newSize = newSize << 30;
}
else {
// no parameter provided; just use the original size of the volume
newSize = volume.getSize();
}
newMinIops = cmd.getMinIops();
if (newMinIops != null) {
if (diskOffering.isCustomizedIops() == null || !diskOffering.isCustomizedIops()) {
throw new InvalidParameterValueException("The current disk offering does not support customization of the 'Min IOPS' parameter.");
}
}
else {
// no parameter provided; just use the original min IOPS of the volume
newMinIops = volume.getMinIops();
}
newMaxIops = cmd.getMaxIops();
if (newMaxIops != null) {
if (diskOffering.isCustomizedIops() == null || !diskOffering.isCustomizedIops()) {
throw new InvalidParameterValueException("The current disk offering does not support customization of the 'Max IOPS' parameter.");
}
}
else {
// no parameter provided; just use the original max IOPS of the volume
newMaxIops = volume.getMaxIops();
}
validateIops(newMinIops, newMaxIops);
} else {
if (newDiskOffering.getRemoved() != null) {
throw new InvalidParameterValueException("Requested disk offering has been removed.");
}
if (!DiskOfferingVO.Type.Disk.equals(newDiskOffering.getType())) {
throw new InvalidParameterValueException("Requested disk offering type is invalid.");
}
if (diskOffering.getTags() != null) {
if (!StringUtils.areTagsEqual(diskOffering.getTags(), newDiskOffering.getTags())) {
throw new InvalidParameterValueException("The tags on the new and old disk offerings must match.");
}
} else if (newDiskOffering.getTags() != null) {
throw new InvalidParameterValueException("There are no tags on the current disk offering. The new disk offering needs to have no tags, as well.");
}
if (!areIntegersEqual(diskOffering.getHypervisorSnapshotReserve(), newDiskOffering.getHypervisorSnapshotReserve())) {
throw new InvalidParameterValueException("The hypervisor snapshot reverse on the new and old disk offerings must be equal.");
}
if (newDiskOffering.getDomainId() != null) {
// not a public offering; check access
_configMgr.checkDiskOfferingAccess(CallContext.current().getCallingAccount(), newDiskOffering);
}
if (newDiskOffering.isCustomized()) {
newSize = cmd.getSize();
if (newSize == null) {
throw new InvalidParameterValueException("The new disk offering requires that a size be specified.");
}
// convert from bytes to GiB
newSize = newSize << 30;
} else {
newSize = newDiskOffering.getDiskSize();
}
if (!volume.getSize().equals(newSize) && !volume.getVolumeType().equals(Volume.Type.DATADISK)) {
throw new InvalidParameterValueException("Only data volumes can be resized via a new disk offering.");
}
if (newDiskOffering.isCustomizedIops() != null && newDiskOffering.isCustomizedIops()) {
newMinIops = cmd.getMinIops() != null ? cmd.getMinIops() : volume.getMinIops();
newMaxIops = cmd.getMaxIops() != null ? cmd.getMaxIops() : volume.getMaxIops();
validateIops(newMinIops, newMaxIops);
}
else {
newMinIops = newDiskOffering.getMinIops();
newMaxIops = newDiskOffering.getMaxIops();
}
}
long currentSize = volume.getSize();
// if the caller is looking to change the size of the volume
if (currentSize != newSize) {
if (!validateVolumeSizeRange(newSize)) {
throw new InvalidParameterValueException("Requested size out of range");
}
/*
* Let's make certain they (think they) know what they're doing if they
* want to shrink by forcing them to provide the shrinkok parameter.
* This will be checked again at the hypervisor level where we can see
* the actual disk size.
*/
if (currentSize > newSize && !shrinkOk) {
throw new InvalidParameterValueException("Going from existing size of " + currentSize + " to size of " + newSize + " would shrink the volume." +
"Need to sign off by supplying the shrinkok parameter with value of true.");
}
if (newSize > currentSize) {
/* Check resource limit for this account on primary storage resource */
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(volume.getAccountId()), ResourceType.primary_storage, volume.isDisplayVolume(),
new Long(newSize - currentSize).longValue());
}
}
// Note: The storage plug-in in question should perform validation on the IOPS to check if a sufficient number of IOPS is available to perform
// the requested change
/* If this volume has never been beyond allocated state, short circuit everything and simply update the database. */
if (volume.getState() == Volume.State.Allocated) {
s_logger.debug("Volume is in the allocated state, but has never been created. Simply updating database with new size and IOPS.");
volume.setSize(newSize);
volume.setMinIops(newMinIops);
volume.setMaxIops(newMaxIops);
if (newDiskOffering != null) {
volume.setDiskOfferingId(cmd.getNewDiskOfferingId());
}
_volsDao.update(volume.getId(), volume);
return volume;
}
UserVmVO userVm = _userVmDao.findById(volume.getInstanceId());
if (userVm != null) {
// serialize VM operation
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if ( jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
VmWorkJobVO placeHolder = null;
placeHolder = createPlaceHolderWork(userVm.getId());
try {
return orchestrateResizeVolume(volume.getId(), currentSize, newSize, newMinIops, newMaxIops,
newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk);
} finally {
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<Volume> outcome = resizeVolumeThroughJobQueue(userVm.getId(), volume.getId(), currentSize, newSize, newMinIops, newMaxIops,
newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk);
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation was interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution exception", e);
}
Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
if (jobResult != null) {
if (jobResult instanceof ConcurrentOperationException) {
throw (ConcurrentOperationException)jobResult;
}
else if (jobResult instanceof ResourceAllocationException) {
throw (ResourceAllocationException)jobResult;
}
else if (jobResult instanceof RuntimeException) {
throw (RuntimeException)jobResult;
}
else if (jobResult instanceof Throwable) {
throw new RuntimeException("Unexpected exception", (Throwable)jobResult);
}
else if (jobResult instanceof Long) {
return _volsDao.findById((Long)jobResult);
}
}
return volume;
}
}
return orchestrateResizeVolume(volume.getId(), currentSize, newSize, newMinIops, newMaxIops,
newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk);
}
private static boolean areIntegersEqual(Integer i1, Integer i2) {
if (i1 == null) {
i1 = 0;
}
if (i2 == null) {
i2 = 0;
}
return i1.equals(i2);
}
private void validateIops(Long minIops, Long maxIops) {
if ((minIops == null && maxIops != null) || (minIops != null && maxIops == null)) {
throw new InvalidParameterValueException("Either 'miniops' and 'maxiops' must both be provided or neither must be provided.");
}
if (minIops != null && maxIops != null) {
if (minIops > maxIops) {
throw new InvalidParameterValueException("The 'miniops' parameter must be less than or equal to the 'maxiops' parameter.");
}
}
}
private VolumeVO orchestrateResizeVolume(long volumeId, long currentSize, long newSize, Long newMinIops, Long newMaxIops, Long newDiskOfferingId, boolean shrinkOk) {
VolumeVO volume = _volsDao.findById(volumeId);
UserVmVO userVm = _userVmDao.findById(volume.getInstanceId());
/*
* get a list of hosts to send the commands to, try the system the
* associated vm is running on first, then the last known place it ran.
* If not attached to a userVm, we pass 'none' and resizevolume.sh is ok
* with that since it only needs the vm name to live resize
*/
long[] hosts = null;
String instanceName = "none";
if (userVm != null) {
instanceName = userVm.getInstanceName();
if (userVm.getHostId() != null) {
hosts = new long[] {userVm.getHostId()};
} else if (userVm.getLastHostId() != null) {
hosts = new long[] {userVm.getLastHostId()};
}
final String errorMsg = "The VM must be stopped or the disk detached in order to resize with the XenServer Hypervisor.";
StoragePoolVO storagePool = _storagePoolDao.findById(volume.getPoolId());
if (storagePool.isManaged() && storagePool.getHypervisor() == HypervisorType.Any && hosts != null && hosts.length > 0) {
HostVO host = _hostDao.findById(hosts[0]);
if (currentSize != newSize && host.getHypervisorType() == HypervisorType.XenServer && !userVm.getState().equals(State.Stopped)) {
throw new InvalidParameterValueException(errorMsg);
}
}
/* Xen only works offline, SR does not support VDI.resizeOnline */
if (currentSize != newSize && _volsDao.getHypervisorType(volume.getId()) == HypervisorType.XenServer && !userVm.getState().equals(State.Stopped)) {
throw new InvalidParameterValueException(errorMsg);
}
}
ResizeVolumePayload payload = new ResizeVolumePayload(newSize, newMinIops, newMaxIops, shrinkOk, instanceName, hosts);
try {
VolumeInfo vol = volFactory.getVolume(volume.getId());
vol.addPayload(payload);
StoragePoolVO storagePool = _storagePoolDao.findById(vol.getPoolId());
// managed storage is designed in such a way that the storage plug-in does not
// talk to the hypervisor layer; as such, if the storage is managed and the
// current and new sizes are different, then CloudStack (i.e. not a storage plug-in)
// needs to tell the hypervisor to resize the disk
if (storagePool.isManaged() && currentSize != newSize) {
if (hosts != null && hosts.length > 0) {
volService.resizeVolumeOnHypervisor(volumeId, newSize, hosts[0], instanceName);
}
volume.setSize(newSize);
_volsDao.update(volume.getId(), volume);
}
// this call to resize has a different impact depending on whether the
// underlying primary storage is managed or not
// if managed, this is the chance for the plug-in to change IOPS value, if applicable
// if not managed, this is the chance for the plug-in to talk to the hypervisor layer
// to change the size of the disk
AsyncCallFuture<VolumeApiResult> future = volService.resize(vol);
VolumeApiResult result = future.get();
if (result.isFailed()) {
s_logger.warn("Failed to resize the volume " + volume);
String details = "";
if (result.getResult() != null && !result.getResult().isEmpty()) {
details = result.getResult();
}
throw new CloudRuntimeException(details);
}
volume = _volsDao.findById(volume.getId());
if (newDiskOfferingId != null) {
volume.setDiskOfferingId(newDiskOfferingId);
}
_volsDao.update(volume.getId(), volume);
/* Update resource count for the account on primary storage resource */
if (!shrinkOk) {
_resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.primary_storage, volume.isDisplayVolume(), new Long(newSize - currentSize));
} else {
_resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.primary_storage, volume.isDisplayVolume(), new Long(currentSize - newSize));
}
return volume;
} catch (InterruptedException e) {
s_logger.warn("failed get resize volume result", e);
throw new CloudRuntimeException(e.getMessage());
} catch (ExecutionException e) {
s_logger.warn("failed get resize volume result", e);
throw new CloudRuntimeException(e.getMessage());
} catch (Exception e) {
s_logger.warn("failed get resize volume result", e);
throw new CloudRuntimeException(e.getMessage());
}
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_DELETE, eventDescription = "deleting volume")
public boolean deleteVolume(long volumeId, Account caller) throws ConcurrentOperationException {
VolumeVO volume = _volsDao.findById(volumeId);
if (volume == null) {
throw new InvalidParameterValueException("Unable to find volume with ID: " + volumeId);
}
if (!_snapshotMgr.canOperateOnVolume(volume)) {
throw new InvalidParameterValueException("There are snapshot operations in progress on the volume, unable to delete it");
}
_accountMgr.checkAccess(caller, null, true, volume);
if (volume.getInstanceId() != null) {
throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM.");
}
if (volume.getState() == Volume.State.UploadOp) {
VolumeDataStoreVO volumeStore = _volumeStoreDao.findByVolume(volume.getId());
if (volumeStore.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_IN_PROGRESS) {
throw new InvalidParameterValueException("Please specify a volume that is not uploading");
}
}
if (volume.getState() == Volume.State.NotUploaded || volume.getState() == Volume.State.UploadInProgress) {
throw new InvalidParameterValueException("The volume is either getting uploaded or it may be initiated shortly, please wait for it to be completed");
}
try {
if (volume.getState() != Volume.State.Destroy && volume.getState() != Volume.State.Expunging && volume.getState() != Volume.State.Expunged) {
Long instanceId = volume.getInstanceId();
if (!volService.destroyVolume(volume.getId())) {
return false;
}
VMInstanceVO vmInstance = _vmInstanceDao.findById(instanceId);
if (instanceId == null || (vmInstance.getType().equals(VirtualMachine.Type.User))) {
// Decrement the resource count for volumes and primary storage belonging user VM's only
_resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.volume, volume.isDisplayVolume());
}
}
// Mark volume as removed if volume has not been created on primary or secondary
if (volume.getState() == Volume.State.Allocated) {
_volsDao.remove(volumeId);
stateTransitTo(volume, Volume.Event.DestroyRequested);
return true;
}
// expunge volume from primary if volume is on primary
VolumeInfo volOnPrimary = volFactory.getVolume(volume.getId(), DataStoreRole.Primary);
if (volOnPrimary != null) {
s_logger.info("Expunging volume " + volume.getId() + " from primary data store");
AsyncCallFuture<VolumeApiResult> future = volService.expungeVolumeAsync(volOnPrimary);
future.get();
//decrement primary storage count
_resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(), ResourceType.primary_storage.getOrdinal());
}
// expunge volume from secondary if volume is on image store
VolumeInfo volOnSecondary = volFactory.getVolume(volume.getId(), DataStoreRole.Image);
if (volOnSecondary != null) {
s_logger.info("Expunging volume " + volume.getId() + " from secondary data store");
AsyncCallFuture<VolumeApiResult> future2 = volService.expungeVolumeAsync(volOnSecondary);
future2.get();
//decrement secondary storage count
_resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(), ResourceType.secondary_storage.getOrdinal());
}
// delete all cache entries for this volume
List<VolumeInfo> cacheVols = volFactory.listVolumeOnCache(volume.getId());
for (VolumeInfo volOnCache : cacheVols) {
s_logger.info("Delete volume from image cache store: " + volOnCache.getDataStore().getName());
volOnCache.delete();
}
} catch (InterruptedException | ExecutionException | NoTransitionException e) {
s_logger.warn("Failed to expunge volume:", e);
return false;
}
return true;
}
private boolean stateTransitTo(Volume vol, Volume.Event event) throws NoTransitionException {
return _volStateMachine.transitTo(vol, event, null, _volsDao);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_ATTACH, eventDescription = "attaching volume", async = true)
public Volume attachVolumeToVM(AttachVolumeCmd command) {
return attachVolumeToVM(command.getVirtualMachineId(), command.getId(), command.getDeviceId());
}
private Volume orchestrateAttachVolumeToVM(Long vmId, Long volumeId, Long deviceId) {
VolumeInfo volumeToAttach = volFactory.getVolume(volumeId);
if (volumeToAttach.isAttachedVM()) {
throw new CloudRuntimeException("This volume is already attached to a VM.");
}
UserVmVO vm = _userVmDao.findById(vmId);
VolumeVO exstingVolumeOfVm = null;
List<VolumeVO> rootVolumesOfVm = _volsDao.findByInstanceAndType(vmId, Volume.Type.ROOT);
if (rootVolumesOfVm.size() > 1) {
throw new CloudRuntimeException("The VM " + vm.getHostName() + " has more than one ROOT volume and is in an invalid state.");
} else {
if (!rootVolumesOfVm.isEmpty()) {
exstingVolumeOfVm = rootVolumesOfVm.get(0);
} else {
// locate data volume of the vm
List<VolumeVO> diskVolumesOfVm = _volsDao.findByInstanceAndType(vmId, Volume.Type.DATADISK);
for (VolumeVO diskVolume : diskVolumesOfVm) {
if (diskVolume.getState() != Volume.State.Allocated) {
exstingVolumeOfVm = diskVolume;
break;
}
}
}
}
HypervisorType rootDiskHyperType = vm.getHypervisorType();
HypervisorType volumeToAttachHyperType = _volsDao.getHypervisorType(volumeToAttach.getId());
VolumeInfo newVolumeOnPrimaryStorage = volumeToAttach;
//don't create volume on primary storage if its being attached to the vm which Root's volume hasn't been created yet
StoragePoolVO destPrimaryStorage = null;
if (exstingVolumeOfVm != null && !exstingVolumeOfVm.getState().equals(Volume.State.Allocated)) {
destPrimaryStorage = _storagePoolDao.findById(exstingVolumeOfVm.getPoolId());
}
boolean volumeOnSecondary = volumeToAttach.getState() == Volume.State.Uploaded;
if (destPrimaryStorage != null && (volumeToAttach.getState() == Volume.State.Allocated || volumeOnSecondary)) {
try {
newVolumeOnPrimaryStorage = _volumeMgr.createVolumeOnPrimaryStorage(vm, volumeToAttach, rootDiskHyperType, destPrimaryStorage);
} catch (NoTransitionException e) {
s_logger.debug("Failed to create volume on primary storage", e);
throw new CloudRuntimeException("Failed to create volume on primary storage", e);
}
}
// reload the volume from db
newVolumeOnPrimaryStorage = volFactory.getVolume(newVolumeOnPrimaryStorage.getId());
boolean moveVolumeNeeded = needMoveVolume(exstingVolumeOfVm, newVolumeOnPrimaryStorage);
if (moveVolumeNeeded) {
PrimaryDataStoreInfo primaryStore = (PrimaryDataStoreInfo)newVolumeOnPrimaryStorage.getDataStore();
if (primaryStore.isLocal()) {
throw new CloudRuntimeException("Failed to attach local data volume " + volumeToAttach.getName() + " to VM " + vm.getDisplayName()
+ " as migration of local data volume is not allowed");
}
StoragePoolVO vmRootVolumePool = _storagePoolDao.findById(exstingVolumeOfVm.getPoolId());
try {
newVolumeOnPrimaryStorage = _volumeMgr.moveVolume(newVolumeOnPrimaryStorage, vmRootVolumePool.getDataCenterId(), vmRootVolumePool.getPodId(),
vmRootVolumePool.getClusterId(), volumeToAttachHyperType);
} catch (ConcurrentOperationException e) {
s_logger.debug("move volume failed", e);
throw new CloudRuntimeException("move volume failed", e);
} catch (StorageUnavailableException e) {
s_logger.debug("move volume failed", e);
throw new CloudRuntimeException("move volume failed", e);
}
}
VolumeVO newVol = _volsDao.findById(newVolumeOnPrimaryStorage.getId());
// Getting the fresh vm object in case of volume migration to check the current state of VM
if (moveVolumeNeeded || volumeOnSecondary) {
vm = _userVmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("VM not found.");
}
}
newVol = sendAttachVolumeCommand(vm, newVol, deviceId);
return newVol;
}
public Volume attachVolumeToVM(Long vmId, Long volumeId, Long deviceId) {
Account caller = CallContext.current().getCallingAccount();
// Check that the volume ID is valid
VolumeInfo volumeToAttach = volFactory.getVolume(volumeId);
// Check that the volume is a data volume
if (volumeToAttach == null || !(volumeToAttach.getVolumeType() == Volume.Type.DATADISK || volumeToAttach.getVolumeType() == Volume.Type.ROOT)) {
throw new InvalidParameterValueException("Please specify a volume with the valid type: " + Volume.Type.ROOT.toString() + " or " + Volume.Type.DATADISK.toString());
}
// Check that the volume is not currently attached to any VM
if (volumeToAttach.getInstanceId() != null) {
throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM.");
}
// Check that the volume is not destroyed
if (volumeToAttach.getState() == Volume.State.Destroy) {
throw new InvalidParameterValueException("Please specify a volume that is not destroyed.");
}
// Check that the virtual machine ID is valid and it's a user vm
UserVmVO vm = _userVmDao.findById(vmId);
if (vm == null || vm.getType() != VirtualMachine.Type.User) {
throw new InvalidParameterValueException("Please specify a valid User VM.");
}
// Check that the VM is in the correct state
if (vm.getState() != State.Running && vm.getState() != State.Stopped) {
throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.");
}
// Check that the VM and the volume are in the same zone
if (vm.getDataCenterId() != volumeToAttach.getDataCenterId()) {
throw new InvalidParameterValueException("Please specify a VM that is in the same zone as the volume.");
}
// Check that the device ID is valid
if (deviceId != null) {
// validate ROOT volume type
if (deviceId.longValue() == 0) {
validateRootVolumeDetachAttach(_volsDao.findById(volumeToAttach.getId()), vm);
// vm shouldn't have any volume with deviceId 0
if (!_volsDao.findByInstanceAndDeviceId(vm.getId(), 0).isEmpty()) {
throw new InvalidParameterValueException("Vm already has root volume attached to it");
}
// volume can't be in Uploaded state
if (volumeToAttach.getState() == Volume.State.Uploaded) {
throw new InvalidParameterValueException("No support for Root volume attach in state " + Volume.State.Uploaded);
}
}
}
// Check that the number of data volumes attached to VM is less than
// that supported by hypervisor
if (deviceId == null || deviceId.longValue() != 0) {
List<VolumeVO> existingDataVolumes = _volsDao.findByInstanceAndType(vmId, Volume.Type.DATADISK);
int maxDataVolumesSupported = getMaxDataVolumesSupported(vm);
if (existingDataVolumes.size() >= maxDataVolumesSupported) {
throw new InvalidParameterValueException("The specified VM already has the maximum number of data disks (" + maxDataVolumesSupported + "). Please specify another VM.");
}
}
// If local storage is disabled then attaching a volume with local disk
// offering not allowed
DataCenterVO dataCenter = _dcDao.findById(volumeToAttach.getDataCenterId());
if (!dataCenter.isLocalStorageEnabled()) {
DiskOfferingVO diskOffering = _diskOfferingDao.findById(volumeToAttach.getDiskOfferingId());
if (diskOffering.getUseLocalStorage()) {
throw new InvalidParameterValueException("Zone is not configured to use local storage but volume's disk offering " + diskOffering.getName() + " uses it");
}
}
// if target VM has associated VM snapshots
List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.findByVm(vmId);
if (vmSnapshots.size() > 0) {
throw new InvalidParameterValueException("Unable to attach volume, please specify a VM that does not have VM snapshots");
}
// permission check
_accountMgr.checkAccess(caller, null, true, volumeToAttach, vm);
if (!(Volume.State.Allocated.equals(volumeToAttach.getState()) || Volume.State.Ready.equals(volumeToAttach.getState()) || Volume.State.Uploaded.equals(volumeToAttach
.getState()))) {
throw new InvalidParameterValueException("Volume state must be in Allocated, Ready or in Uploaded state");
}
HypervisorType rootDiskHyperType = vm.getHypervisorType();
HypervisorType volumeToAttachHyperType = _volsDao.getHypervisorType(volumeToAttach.getId());
StoragePoolVO volumeToAttachStoragePool = _storagePoolDao.findById(volumeToAttach.getPoolId());
// managed storage can be used for different types of hypervisors
// only perform this check if the volume's storage pool is not null and not managed
if (volumeToAttachStoragePool != null && !volumeToAttachStoragePool.isManaged()) {
if (volumeToAttachHyperType != HypervisorType.None && rootDiskHyperType != volumeToAttachHyperType) {
throw new InvalidParameterValueException("Can't attach a volume created by: " + volumeToAttachHyperType + " to a " + rootDiskHyperType + " vm");
}
}
AsyncJobExecutionContext asyncExecutionContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (asyncExecutionContext != null) {
AsyncJob job = asyncExecutionContext.getJob();
if (s_logger.isInfoEnabled()) {
s_logger.info("Trying to attaching volume " + volumeId + " to vm instance:" + vm.getId() + ", update async job-" + job.getId() + " progress status");
}
_jobMgr.updateAsyncJobAttachment(job.getId(), "Volume", volumeId);
}
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
VmWorkJobVO placeHolder = null;
placeHolder = createPlaceHolderWork(vmId);
try {
return orchestrateAttachVolumeToVM(vmId, volumeId, deviceId);
} finally {
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<Volume> outcome = attachVolumeToVmThroughJobQueue(vmId, volumeId, deviceId);
Volume vol = null;
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
if (jobResult != null) {
if (jobResult instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobResult;
else if (jobResult instanceof InvalidParameterValueException)
throw (InvalidParameterValueException)jobResult;
else if (jobResult instanceof RuntimeException)
throw (RuntimeException)jobResult;
else if (jobResult instanceof Throwable)
throw new RuntimeException("Unexpected exception", (Throwable)jobResult);
else if (jobResult instanceof Long) {
vol = _volsDao.findById((Long)jobResult);
}
}
return vol;
}
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_UPDATE, eventDescription = "updating volume", async = true)
public Volume updateVolume(long volumeId, String path, String state, Long storageId, Boolean displayVolume, String customId, long entityOwnerId, String chainInfo) {
VolumeVO volume = _volsDao.findById(volumeId);
if(volume == null)
throw new InvalidParameterValueException("The volume id doesn't exist");
if (path != null) {
volume.setPath(path);
}
if(chainInfo != null){
volume.setChainInfo(chainInfo);
}
if (state != null) {
try {
Volume.State volumeState = Volume.State.valueOf(state);
volume.setState(volumeState);
} catch (IllegalArgumentException ex) {
throw new InvalidParameterValueException("Invalid volume state specified");
}
}
if (storageId != null) {
StoragePool pool = _storagePoolDao.findById(storageId);
if (pool.getDataCenterId() != volume.getDataCenterId()) {
throw new InvalidParameterValueException("Invalid storageId specified; refers to the pool outside of the volume's zone");
}
volume.setPoolId(pool.getId());
}
if (customId != null) {
volume.setUuid(customId);
}
updateDisplay(volume, displayVolume);
_volsDao.update(volumeId, volume);
return volume;
}
@Override
public void updateDisplay(Volume volume, Boolean displayVolume){
// 1. Resource limit changes
updateResourceCount(volume, displayVolume);
// 2. generate usage event if not in destroyed state
saveUsageEvent(volume, displayVolume);
// 3. Set the flag
if (displayVolume != null && displayVolume != volume.isDisplayVolume()){
// FIXME - Confused - typecast for now.
((VolumeVO)volume).setDisplayVolume(displayVolume);
_volsDao.update(volume.getId(), (VolumeVO) volume);
}
}
private void updateResourceCount(Volume volume, Boolean displayVolume){
// Update only when the flag has changed.
if (displayVolume != null && displayVolume != volume.isDisplayVolume()){
_resourceLimitMgr.changeResourceCount(volume.getAccountId(), ResourceType.volume, displayVolume);
_resourceLimitMgr.changeResourceCount(volume.getAccountId(), ResourceType.primary_storage, displayVolume, new Long(volume.getSize()));
}
}
private void saveUsageEvent(Volume volume, Boolean displayVolume){
// Update only when the flag has changed && only when volume in a non-destroyed state.
if ((displayVolume != null && displayVolume != volume.isDisplayVolume()) && !isVolumeDestroyed(volume)){
if (displayVolume){
// flag turned 1 equivalent to freshly created volume
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(),
volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize(), Volume.class.getName(), volume.getUuid());
}else {
// flag turned 0 equivalent to deleting a volume
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(),
Volume.class.getName(), volume.getUuid());
}
}
}
private boolean isVolumeDestroyed(Volume volume){
if(volume.getState() == Volume.State.Destroy || volume.getState() == Volume.State.Expunging && volume.getState() == Volume.State.Expunged)
return true;
return false;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_DETACH, eventDescription = "detaching volume", async = true)
public Volume detachVolumeFromVM(DetachVolumeCmd cmmd) {
Account caller = CallContext.current().getCallingAccount();
if ((cmmd.getId() == null && cmmd.getDeviceId() == null && cmmd.getVirtualMachineId() == null)
|| (cmmd.getId() != null && (cmmd.getDeviceId() != null || cmmd.getVirtualMachineId() != null))
|| (cmmd.getId() == null && (cmmd.getDeviceId() == null || cmmd.getVirtualMachineId() == null))) {
throw new InvalidParameterValueException("Please provide either a volume id, or a tuple(device id, instance id)");
}
Long volumeId = cmmd.getId();
VolumeVO volume = null;
if (volumeId != null) {
volume = _volsDao.findById(volumeId);
} else {
volume = _volsDao.findByInstanceAndDeviceId(cmmd.getVirtualMachineId(), cmmd.getDeviceId()).get(0);
}
// Check that the volume ID is valid
if (volume == null) {
throw new InvalidParameterValueException("Unable to find volume with ID: " + volumeId);
}
Long vmId = null;
if (cmmd.getVirtualMachineId() == null) {
vmId = volume.getInstanceId();
} else {
vmId = cmmd.getVirtualMachineId();
}
// Permissions check
_accountMgr.checkAccess(caller, null, true, volume);
// Check that the volume is currently attached to a VM
if (vmId == null) {
throw new InvalidParameterValueException("The specified volume is not attached to a VM.");
}
// Check that the VM is in the correct state
UserVmVO vm = _userVmDao.findById(vmId);
if (vm.getState() != State.Running && vm.getState() != State.Stopped && vm.getState() != State.Destroyed) {
throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.");
}
// Check that the volume is a data/root volume
if (!(volume.getVolumeType() == Volume.Type.ROOT || volume.getVolumeType() == Volume.Type.DATADISK)) {
throw new InvalidParameterValueException("Please specify volume of type " + Volume.Type.DATADISK.toString() + " or " + Volume.Type.ROOT.toString());
}
// Root volume detach is allowed for following hypervisors: Xen/KVM/VmWare
if (volume.getVolumeType() == Volume.Type.ROOT) {
validateRootVolumeDetachAttach(volume, vm);
}
// Don't allow detach if target VM has associated VM snapshots
List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.findByVm(vmId);
if (vmSnapshots.size() > 0) {
throw new InvalidParameterValueException("Unable to detach volume, please specify a VM that does not have VM snapshots");
}
AsyncJobExecutionContext asyncExecutionContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (asyncExecutionContext != null) {
AsyncJob job = asyncExecutionContext.getJob();
if (s_logger.isInfoEnabled()) {
s_logger.info("Trying to attaching volume " + volumeId + "to vm instance:" + vm.getId() + ", update async job-" + job.getId() + " progress status");
}
_jobMgr.updateAsyncJobAttachment(job.getId(), "Volume", volumeId);
}
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
VmWorkJobVO placeHolder = null;
placeHolder = createPlaceHolderWork(vmId);
try {
return orchestrateDetachVolumeFromVM(vmId, volumeId);
} finally {
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<Volume> outcome = detachVolumeFromVmThroughJobQueue(vmId, volumeId);
Volume vol = null;
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
if (jobResult != null) {
if (jobResult instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobResult;
else if (jobResult instanceof RuntimeException)
throw (RuntimeException)jobResult;
else if (jobResult instanceof Throwable)
throw new RuntimeException("Unexpected exception", (Throwable)jobResult);
else if (jobResult instanceof Long) {
vol = _volsDao.findById((Long) jobResult);
}
}
return vol;
}
}
private void validateRootVolumeDetachAttach(VolumeVO volume, UserVmVO vm) {
if (!(vm.getHypervisorType() == HypervisorType.XenServer || vm.getHypervisorType() == HypervisorType.VMware)) {
throw new InvalidParameterValueException("Root volume detach is allowed for hypervisor type " + HypervisorType.XenServer + " only");
}
if (!(vm.getState() == State.Stopped) || (vm.getState() == State.Destroyed)) {
throw new InvalidParameterValueException("Root volume detach can happen only when vm is in states: " + State.Stopped.toString() + " or " + State.Destroyed.toString());
}
if (volume.getPoolId() != null) {
StoragePoolVO pool = _storagePoolDao.findById(volume.getPoolId());
if (pool.isManaged()) {
throw new InvalidParameterValueException("Root volume detach is not supported for Managed DataStores");
}
}
}
private Volume orchestrateDetachVolumeFromVM(long vmId, long volumeId) {
Volume volume = _volsDao.findById(volumeId);
VMInstanceVO vm = _vmInstanceDao.findById(vmId);
String errorMsg = "Failed to detach volume " + volume.getName() + " from VM " + vm.getHostName();
boolean sendCommand = vm.getState() == State.Running;
Long hostId = vm.getHostId();
if (hostId == null) {
hostId = vm.getLastHostId();
HostVO host = _hostDao.findById(hostId);
if (host != null && host.getHypervisorType() == HypervisorType.VMware) {
sendCommand = true;
}
}
HostVO host = null;
StoragePoolVO volumePool = _storagePoolDao.findByIdIncludingRemoved(volume.getPoolId());
if (hostId != null) {
host = _hostDao.findById(hostId);
if (host != null && host.getHypervisorType() == HypervisorType.XenServer && volumePool != null && volumePool.isManaged()) {
sendCommand = true;
}
}
Answer answer = null;
if (sendCommand) {
DataTO volTO = volFactory.getVolume(volume.getId()).getTO();
DiskTO disk = new DiskTO(volTO, volume.getDeviceId(), volume.getPath(), volume.getVolumeType());
DettachCommand cmd = new DettachCommand(disk, vm.getInstanceName());
cmd.setManaged(volumePool.isManaged());
cmd.setStorageHost(volumePool.getHostAddress());
cmd.setStoragePort(volumePool.getPort());
cmd.set_iScsiName(volume.get_iScsiName());
try {
answer = _agentMgr.send(hostId, cmd);
} catch (Exception e) {
throw new CloudRuntimeException(errorMsg + " due to: " + e.getMessage());
}
}
if (!sendCommand || (answer != null && answer.getResult())) {
// Mark the volume as detached
_volsDao.detachVolume(volume.getId());
// volume.getPoolId() should be null if the VM we are detaching the disk from has never been started before
DataStore dataStore = volume.getPoolId() != null ? dataStoreMgr.getDataStore(volume.getPoolId(), DataStoreRole.Primary) : null;
volService.revokeAccess(volFactory.getVolume(volume.getId()), host, dataStore);
return _volsDao.findById(volumeId);
} else {
if (answer != null) {
String details = answer.getDetails();
if (details != null && !details.isEmpty()) {
errorMsg += "; " + details;
}
}
throw new CloudRuntimeException(errorMsg);
}
}
@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_MIGRATE, eventDescription = "migrating volume", async = true)
public Volume migrateVolume(MigrateVolumeCmd cmd) {
Long volumeId = cmd.getVolumeId();
Long storagePoolId = cmd.getStoragePoolId();
VolumeVO vol = _volsDao.findById(volumeId);
if (vol == null) {
throw new InvalidParameterValueException("Failed to find the volume id: " + volumeId);
}
if (vol.getState() != Volume.State.Ready) {
throw new InvalidParameterValueException("Volume must be in ready state");
}
boolean liveMigrateVolume = false;
Long instanceId = vol.getInstanceId();
Long srcClusterId = null;
VMInstanceVO vm = null;
if (instanceId != null) {
vm = _vmInstanceDao.findById(instanceId);
}
// Check that Vm to which this volume is attached does not have VM Snapshots
if (vm != null && _vmSnapshotDao.findByVm(vm.getId()).size() > 0) {
throw new InvalidParameterValueException("Volume cannot be migrated, please remove all VM snapshots for VM to which this volume is attached");
}
if (vm != null && vm.getState() == State.Running) {
// Check if the VM is GPU enabled.
if(_serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()) != null) {
throw new InvalidParameterValueException("Live Migration of GPU enabled VM is not supported");
}
// Check if the underlying hypervisor supports storage motion.
Long hostId = vm.getHostId();
if (hostId != null) {
HostVO host = _hostDao.findById(hostId);
HypervisorCapabilitiesVO capabilities = null;
if (host != null) {
capabilities = _hypervisorCapabilitiesDao.findByHypervisorTypeAndVersion(host.getHypervisorType(), host.getHypervisorVersion());
srcClusterId = host.getClusterId();
}
if (capabilities != null) {
liveMigrateVolume = capabilities.isStorageMotionSupported();
}
}
// If vm is running, and hypervisor doesn't support live migration, then return error
if (!liveMigrateVolume) {
throw new InvalidParameterValueException("Volume needs to be detached from VM");
}
}
if (liveMigrateVolume && !cmd.isLiveMigrate()) {
throw new InvalidParameterValueException("The volume " + vol + "is attached to a vm and for migrating it " + "the parameter livemigrate should be specified");
}
StoragePool destPool = (StoragePool)dataStoreMgr.getDataStore(storagePoolId, DataStoreRole.Primary);
if (destPool == null) {
throw new InvalidParameterValueException("Failed to find the destination storage pool: " + storagePoolId);
}
if (_volumeMgr.volumeOnSharedStoragePool(vol)) {
if (destPool.isLocal()) {
throw new InvalidParameterValueException("Migration of volume from shared to local storage pool is not supported");
} else {
// If the volume is attached to a running vm and the volume is on a shared storage pool, check
// to make sure that the destination storage pool is in the same cluster as the vm.
if (liveMigrateVolume && destPool.getClusterId() != null && srcClusterId != null) {
if (!srcClusterId.equals(destPool.getClusterId())) {
throw new InvalidParameterValueException("Cannot migrate a volume of a virtual machine to a storage pool in a different cluster");
}
}
// In case of VMware, if ROOT volume is being cold-migrated, then ensure destination storage pool is in the same Datacenter as the VM.
if (vm != null && vm.getHypervisorType().equals(HypervisorType.VMware)) {
if (!liveMigrateVolume && vol.volumeType.equals(Volume.Type.ROOT)) {
Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId();
HostVO host = _hostDao.findById(hostId);
if (host != null)
srcClusterId = host.getClusterId();
if (srcClusterId != null && destPool.getClusterId() != null && !srcClusterId.equals(destPool.getClusterId())) {
String srcDcName = _clusterDetailsDao.getVmwareDcName(srcClusterId);
String destDcName = _clusterDetailsDao.getVmwareDcName(destPool.getClusterId());
if (srcDcName != null && destDcName != null && !srcDcName.equals(destDcName)) {
throw new InvalidParameterValueException("Cannot migrate ROOT volume of a stopped VM to a storage pool in a different VMware datacenter");
}
}
}
}
}
} else {
throw new InvalidParameterValueException("Migration of volume from local storage pool is not supported");
}
if (vm != null) {
// serialize VM operation
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
VmWorkJobVO placeHolder = null;
placeHolder = createPlaceHolderWork(vm.getId());
try {
return orchestrateMigrateVolume(vol.getId(), destPool.getId(), liveMigrateVolume);
} finally {
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<Volume> outcome = migrateVolumeThroughJobQueue(vm.getId(), vol.getId(), destPool.getId(), liveMigrateVolume);
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
if (jobResult != null) {
if (jobResult instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobResult;
else if (jobResult instanceof RuntimeException)
throw (RuntimeException)jobResult;
else if (jobResult instanceof Throwable)
throw new RuntimeException("Unexpected exception", (Throwable)jobResult);
}
// retrieve the migrated new volume from job result
if (jobResult != null && jobResult instanceof Long) {
return _entityMgr.findById(VolumeVO.class, ((Long)jobResult));
}
return null;
}
}
return orchestrateMigrateVolume(vol.getId(), destPool.getId(), liveMigrateVolume);
}
private Volume orchestrateMigrateVolume(long volumeId, long destPoolId, boolean liveMigrateVolume) {
VolumeVO vol = _volsDao.findById(volumeId);
assert (vol != null);
StoragePool destPool = (StoragePool)dataStoreMgr.getDataStore(destPoolId, DataStoreRole.Primary);
assert (destPool != null);
Volume newVol = null;
try {
if (liveMigrateVolume) {
newVol = liveMigrateVolume(vol, destPool);
} else {
newVol = _volumeMgr.migrateVolume(vol, destPool);
}
} catch (StorageUnavailableException e) {
s_logger.debug("Failed to migrate volume", e);
throw new CloudRuntimeException(e.getMessage());
} catch (Exception e) {
s_logger.debug("Failed to migrate volume", e);
throw new CloudRuntimeException(e.getMessage());
}
return newVol;
}
@DB
protected Volume liveMigrateVolume(Volume volume, StoragePool destPool) throws StorageUnavailableException {
VolumeInfo vol = volFactory.getVolume(volume.getId());
AsyncCallFuture<VolumeApiResult> future = volService.migrateVolume(vol, (DataStore)destPool);
try {
VolumeApiResult result = future.get();
if (result.isFailed()) {
s_logger.debug("migrate volume failed:" + result.getResult());
throw new StorageUnavailableException("Migrate volume failed: " + result.getResult(), destPool.getId());
}
return result.getVolume();
} catch (InterruptedException e) {
s_logger.debug("migrate volume failed", e);
throw new CloudRuntimeException(e.getMessage());
} catch (ExecutionException e) {
s_logger.debug("migrate volume failed", e);
throw new CloudRuntimeException(e.getMessage());
}
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_SNAPSHOT_CREATE, eventDescription = "taking snapshot", async = true)
public Snapshot takeSnapshot(Long volumeId, Long policyId, Long snapshotId, Account account, boolean quiescevm) throws ResourceAllocationException {
VolumeInfo volume = volFactory.getVolume(volumeId);
if (volume == null) {
throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
}
if (volume.getState() != Volume.State.Ready) {
throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
}
VMInstanceVO vm = null;
if (volume.getInstanceId() != null)
vm = _vmInstanceDao.findById(volume.getInstanceId());
if (vm != null) {
// serialize VM operation
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
VmWorkJobVO placeHolder = null;
placeHolder = createPlaceHolderWork(vm.getId());
try {
return orchestrateTakeVolumeSnapshot(volumeId, policyId, snapshotId, account, quiescevm);
} finally {
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<Snapshot> outcome = takeVolumeSnapshotThroughJobQueue(vm.getId(), volumeId, policyId, snapshotId, account.getId(), quiescevm);
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
if (jobResult != null) {
if (jobResult instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobResult;
else if (jobResult instanceof ResourceAllocationException)
throw (ResourceAllocationException)jobResult;
else if (jobResult instanceof Throwable)
throw new RuntimeException("Unexpected exception", (Throwable)jobResult);
}
return _snapshotDao.findById(snapshotId);
}
} else {
CreateSnapshotPayload payload = new CreateSnapshotPayload();
payload.setSnapshotId(snapshotId);
payload.setSnapshotPolicyId(policyId);
payload.setAccount(account);
payload.setQuiescevm(quiescevm);
volume.addPayload(payload);
return volService.takeSnapshot(volume);
}
}
private Snapshot orchestrateTakeVolumeSnapshot(Long volumeId, Long policyId, Long snapshotId, Account account, boolean quiescevm)
throws ResourceAllocationException {
VolumeInfo volume = volFactory.getVolume(volumeId);
if (volume == null) {
throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
}
if (volume.getState() != Volume.State.Ready) {
throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
}
CreateSnapshotPayload payload = new CreateSnapshotPayload();
payload.setSnapshotId(snapshotId);
payload.setSnapshotPolicyId(policyId);
payload.setAccount(account);
payload.setQuiescevm(quiescevm);
volume.addPayload(payload);
return volService.takeSnapshot(volume);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_SNAPSHOT_CREATE, eventDescription = "allocating snapshot", create = true)
public Snapshot allocSnapshot(Long volumeId, Long policyId, String snapshotName) throws ResourceAllocationException {
Account caller = CallContext.current().getCallingAccount();
VolumeInfo volume = volFactory.getVolume(volumeId);
if (volume == null) {
throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
}
DataCenter zone = _dcDao.findById(volume.getDataCenterId());
if (zone == null) {
throw new InvalidParameterValueException("Can't find zone by id " + volume.getDataCenterId());
}
if (volume.getInstanceId() != null) {
// Check that Vm to which this volume is attached does not have VM Snapshots
if (_vmSnapshotDao.findByVm(volume.getInstanceId()).size() > 0) {
throw new InvalidParameterValueException("Volume snapshot is not allowed, please detach it from VM with VM Snapshots");
}
}
if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getName());
}
if (volume.getState() != Volume.State.Ready) {
throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
}
if (ImageFormat.DIR.equals(volume.getFormat())){
throw new InvalidParameterValueException("Snapshot not supported for volume:" + volumeId);
}
if (volume.getTemplateId() != null) {
VMTemplateVO template = _templateDao.findById(volume.getTemplateId());
if (template != null && template.getTemplateType() == Storage.TemplateType.SYSTEM) {
throw new InvalidParameterValueException("VolumeId: " + volumeId + " is for System VM , Creating snapshot against System VM volumes is not supported");
}
}
StoragePool storagePool = (StoragePool)volume.getDataStore();
if (storagePool == null) {
throw new InvalidParameterValueException("VolumeId: " + volumeId + " please attach this volume to a VM before create snapshot for it");
}
return snapshotMgr.allocSnapshot(volumeId, policyId, snapshotName);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_EXTRACT, eventDescription = "extracting volume", async = true)
public String extractVolume(ExtractVolumeCmd cmd) {
Long volumeId = cmd.getId();
Long zoneId = cmd.getZoneId();
String mode = cmd.getMode();
Account account = CallContext.current().getCallingAccount();
if (!_accountMgr.isRootAdmin(account.getId()) && ApiDBUtils.isExtractionDisabled()) {
throw new PermissionDeniedException("Extraction has been disabled by admin");
}
VolumeVO volume = _volsDao.findById(volumeId);
if (volume == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId");
ex.addProxyObject(volumeId.toString(), "volumeId");
throw ex;
}
// perform permission check
_accountMgr.checkAccess(account, null, true, volume);
if (_dcDao.findById(zoneId) == null) {
throw new InvalidParameterValueException("Please specify a valid zone.");
}
if (volume.getPoolId() == null) {
throw new InvalidParameterValueException("The volume doesnt belong to a storage pool so cant extract it");
}
// Extract activity only for detached volumes or for volumes whose
// instance is stopped
if (volume.getInstanceId() != null && ApiDBUtils.findVMInstanceById(volume.getInstanceId()).getState() != State.Stopped) {
s_logger.debug("Invalid state of the volume with ID: " + volumeId + ". It should be either detached or the VM should be in stopped state.");
PermissionDeniedException ex = new PermissionDeniedException(
"Invalid state of the volume with specified ID. It should be either detached or the VM should be in stopped state.");
ex.addProxyObject(volume.getUuid(), "volumeId");
throw ex;
}
if (volume.getVolumeType() != Volume.Type.DATADISK) {
// Datadisk dont have any template dependence.
VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
if (template != null) { // For ISO based volumes template = null and
// we allow extraction of all ISO based
// volumes
boolean isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM;
if (!isExtractable && account != null && !_accountMgr.isRootAdmin(account.getId())) {
// Global admins are always allowed to extract
PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted");
ex.addProxyObject(volume.getUuid(), "volumeId");
throw ex;
}
}
}
if (mode == null || (!mode.equals(Upload.Mode.FTP_UPLOAD.toString()) && !mode.equals(Upload.Mode.HTTP_DOWNLOAD.toString()))) {
throw new InvalidParameterValueException("Please specify a valid extract Mode ");
}
// Check if the url already exists
VolumeDataStoreVO volumeStoreRef = _volumeStoreDao.findByVolume(volumeId);
if (volumeStoreRef != null && volumeStoreRef.getExtractUrl() != null) {
return volumeStoreRef.getExtractUrl();
}
VMInstanceVO vm = null;
if (volume.getInstanceId() != null) {
vm = _vmInstanceDao.findById(volume.getInstanceId());
}
if (vm != null) {
// serialize VM operation
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
VmWorkJobVO placeHolder = null;
placeHolder = createPlaceHolderWork(vm.getId());
try {
return orchestrateExtractVolume(volume.getId(), zoneId);
} finally {
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<String> outcome = extractVolumeThroughJobQueue(vm.getId(), volume.getId(), zoneId);
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
if (jobResult != null) {
if (jobResult instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobResult;
else if (jobResult instanceof RuntimeException)
throw (RuntimeException)jobResult;
else if (jobResult instanceof Throwable)
throw new RuntimeException("Unexpected exception", (Throwable)jobResult);
}
// retrieve the entity url from job result
if (jobResult != null && jobResult instanceof String) {
return (String)jobResult;
}
return null;
}
}
return orchestrateExtractVolume(volume.getId(), zoneId);
}
private String orchestrateExtractVolume(long volumeId, long zoneId) {
// get latest volume state to make sure that it is not updated by other parallel operations
VolumeVO volume = _volsDao.findById(volumeId);
if (volume == null || volume.getState() != Volume.State.Ready) {
throw new InvalidParameterValueException("Volume to be extracted has been removed or not in right state!");
}
// perform extraction
ImageStoreEntity secStore = (ImageStoreEntity)dataStoreMgr.getImageStore(zoneId);
String value = _configDao.getValue(Config.CopyVolumeWait.toString());
NumbersUtil.parseInt(value, Integer.parseInt(Config.CopyVolumeWait.getDefaultValue()));
// Copy volume from primary to secondary storage
VolumeInfo srcVol = volFactory.getVolume(volumeId);
AsyncCallFuture<VolumeApiResult> cvAnswer = volService.copyVolume(srcVol, secStore);
// Check if you got a valid answer.
VolumeApiResult cvResult = null;
try {
cvResult = cvAnswer.get();
} catch (InterruptedException e1) {
s_logger.debug("failed copy volume", e1);
throw new CloudRuntimeException("Failed to copy volume", e1);
} catch (ExecutionException e1) {
s_logger.debug("failed copy volume", e1);
throw new CloudRuntimeException("Failed to copy volume", e1);
}
if (cvResult == null || cvResult.isFailed()) {
String errorString = "Failed to copy the volume from the source primary storage pool to secondary storage.";
throw new CloudRuntimeException(errorString);
}
VolumeInfo vol = cvResult.getVolume();
String extractUrl = secStore.createEntityExtractUrl(vol.getPath(), vol.getFormat(), vol);
VolumeDataStoreVO volumeStoreRef = _volumeStoreDao.findByVolume(volumeId);
volumeStoreRef.setExtractUrl(extractUrl);
volumeStoreRef.setExtractUrlCreated(DateUtil.now());
_volumeStoreDao.update(volumeStoreRef.getId(), volumeStoreRef);
return extractUrl;
}
@Override
public boolean isDisplayResourceEnabled(Long id) {
Volume volume = _volsDao.findById(id);
if (volume == null) {
return true; // bad id given, default to true
}
return volume.isDisplayVolume();
}
private String getFormatForPool(StoragePool pool) {
ClusterVO cluster = ApiDBUtils.findClusterById(pool.getClusterId());
if (cluster.getHypervisorType() == HypervisorType.XenServer) {
return "vhd";
} else if (cluster.getHypervisorType() == HypervisorType.KVM) {
return "qcow2";
} else if (cluster.getHypervisorType() == HypervisorType.Hyperv) {
return "vhdx";
} else if (cluster.getHypervisorType() == HypervisorType.VMware) {
return "ova";
} else if (cluster.getHypervisorType() == HypervisorType.Ovm) {
return "raw";
} else {
return null;
}
}
private boolean needMoveVolume(VolumeVO existingVolume, VolumeInfo newVolume) {
if (existingVolume == null || existingVolume.getPoolId() == null || newVolume.getPoolId() == null) {
return false;
}
DataStore storeForExistingVol = dataStoreMgr.getPrimaryDataStore(existingVolume.getPoolId());
DataStore storeForNewVol = dataStoreMgr.getPrimaryDataStore(newVolume.getPoolId());
Scope storeForExistingStoreScope = storeForExistingVol.getScope();
if (storeForExistingStoreScope == null) {
throw new CloudRuntimeException("Can't get scope of data store: " + storeForExistingVol.getId());
}
Scope storeForNewStoreScope = storeForNewVol.getScope();
if (storeForNewStoreScope == null) {
throw new CloudRuntimeException("Can't get scope of data store: " + storeForNewVol.getId());
}
if (storeForNewStoreScope.getScopeType() == ScopeType.ZONE) {
return false;
}
if (storeForExistingStoreScope.getScopeType() != storeForNewStoreScope.getScopeType()) {
if (storeForNewStoreScope.getScopeType() == ScopeType.CLUSTER) {
Long vmClusterId = null;
if (storeForExistingStoreScope.getScopeType() == ScopeType.HOST) {
HostScope hs = (HostScope)storeForExistingStoreScope;
vmClusterId = hs.getClusterId();
} else if (storeForExistingStoreScope.getScopeType() == ScopeType.ZONE) {
Long hostId = _vmInstanceDao.findById(existingVolume.getInstanceId()).getHostId();
if (hostId != null) {
HostVO host = _hostDao.findById(hostId);
vmClusterId = host.getClusterId();
}
}
if (storeForNewStoreScope.getScopeId().equals(vmClusterId)) {
return false;
} else {
return true;
}
} else if (storeForNewStoreScope.getScopeType() == ScopeType.HOST
&& (storeForExistingStoreScope.getScopeType() == ScopeType.CLUSTER || storeForExistingStoreScope.getScopeType() == ScopeType.ZONE)) {
Long hostId = _vmInstanceDao.findById(existingVolume.getInstanceId()).getHostId();
if (storeForNewStoreScope.getScopeId().equals(hostId)) {
return false;
}
}
throw new InvalidParameterValueException("Can't move volume between scope: " + storeForNewStoreScope.getScopeType() + " and " + storeForExistingStoreScope.getScopeType());
}
return !storeForExistingStoreScope.isSameScope(storeForNewStoreScope);
}
private VolumeVO sendAttachVolumeCommand(UserVmVO vm, VolumeVO volumeToAttach, Long deviceId) {
String errorMsg = "Failed to attach volume " + volumeToAttach.getName() + " to VM " + vm.getHostName();
boolean sendCommand = vm.getState() == State.Running;
AttachAnswer answer = null;
Long hostId = vm.getHostId();
if (hostId == null) {
hostId = vm.getLastHostId();
HostVO host = _hostDao.findById(hostId);
if (host != null && host.getHypervisorType() == HypervisorType.VMware) {
sendCommand = true;
}
}
HostVO host = null;
StoragePoolVO volumeToAttachStoragePool = _storagePoolDao.findById(volumeToAttach.getPoolId());
if (hostId != null) {
host = _hostDao.findById(hostId);
if (host != null && host.getHypervisorType() == HypervisorType.XenServer && volumeToAttachStoragePool != null && volumeToAttachStoragePool.isManaged()) {
sendCommand = true;
}
}
// volumeToAttachStoragePool should be null if the VM we are attaching the disk to has never been started before
DataStore dataStore = volumeToAttachStoragePool != null ? dataStoreMgr.getDataStore(volumeToAttachStoragePool.getId(), DataStoreRole.Primary) : null;
// if we don't have a host, the VM we are attaching the disk to has never been started before
if (host != null) {
try {
volService.grantAccess(volFactory.getVolume(volumeToAttach.getId()), host, dataStore);
}
catch (Exception e) {
volService.revokeAccess(volFactory.getVolume(volumeToAttach.getId()), host, dataStore);
throw new CloudRuntimeException(e.getMessage());
}
}
if (sendCommand) {
if (host != null && host.getHypervisorType() == HypervisorType.KVM &&
volumeToAttachStoragePool.isManaged() &&
volumeToAttach.getPath() == null) {
volumeToAttach.setPath(volumeToAttach.get_iScsiName());
_volsDao.update(volumeToAttach.getId(), volumeToAttach);
}
DataTO volTO = volFactory.getVolume(volumeToAttach.getId()).getTO();
deviceId = getDeviceId(vm.getId(), deviceId);
DiskTO disk = new DiskTO(volTO, deviceId, volumeToAttach.getPath(), volumeToAttach.getVolumeType());
AttachCommand cmd = new AttachCommand(disk, vm.getInstanceName());
ChapInfo chapInfo = volService.getChapInfo(volFactory.getVolume(volumeToAttach.getId()), dataStore);
Map<String, String> details = new HashMap<String, String>();
disk.setDetails(details);
details.put(DiskTO.MANAGED, String.valueOf(volumeToAttachStoragePool.isManaged()));
details.put(DiskTO.STORAGE_HOST, volumeToAttachStoragePool.getHostAddress());
details.put(DiskTO.STORAGE_PORT, String.valueOf(volumeToAttachStoragePool.getPort()));
details.put(DiskTO.VOLUME_SIZE, String.valueOf(volumeToAttach.getSize()));
details.put(DiskTO.IQN, volumeToAttach.get_iScsiName());
details.put(DiskTO.MOUNT_POINT, volumeToAttach.get_iScsiName());
details.put(DiskTO.PROTOCOL_TYPE, (volumeToAttach.getPoolType() != null) ? volumeToAttach.getPoolType().toString() : null);
if (chapInfo != null) {
details.put(DiskTO.CHAP_INITIATOR_USERNAME, chapInfo.getInitiatorUsername());
details.put(DiskTO.CHAP_INITIATOR_SECRET, chapInfo.getInitiatorSecret());
details.put(DiskTO.CHAP_TARGET_USERNAME, chapInfo.getTargetUsername());
details.put(DiskTO.CHAP_TARGET_SECRET, chapInfo.getTargetSecret());
}
try {
answer = (AttachAnswer)_agentMgr.send(hostId, cmd);
} catch (Exception e) {
if(host!=null) {
volService.revokeAccess(volFactory.getVolume(volumeToAttach.getId()), host, dataStore);
}
throw new CloudRuntimeException(errorMsg + " due to: " + e.getMessage());
}
}
if (!sendCommand || (answer != null && answer.getResult())) {
// Mark the volume as attached
if (sendCommand) {
DiskTO disk = answer.getDisk();
_volsDao.attachVolume(volumeToAttach.getId(), vm.getId(), disk.getDiskSeq());
volumeToAttach = _volsDao.findById(volumeToAttach.getId());
if (volumeToAttachStoragePool.isManaged() && volumeToAttach.getPath() == null) {
volumeToAttach.setPath(answer.getDisk().getPath());
_volsDao.update(volumeToAttach.getId(), volumeToAttach);
}
} else {
deviceId = getDeviceId(vm.getId(), deviceId);
_volsDao.attachVolume(volumeToAttach.getId(), vm.getId(), deviceId);
}
// insert record for disk I/O statistics
VmDiskStatisticsVO diskstats = _vmDiskStatsDao.findBy(vm.getAccountId(), vm.getDataCenterId(), vm.getId(), volumeToAttach.getId());
if (diskstats == null) {
diskstats = new VmDiskStatisticsVO(vm.getAccountId(), vm.getDataCenterId(), vm.getId(), volumeToAttach.getId());
_vmDiskStatsDao.persist(diskstats);
}
return _volsDao.findById(volumeToAttach.getId());
} else {
if (answer != null) {
String details = answer.getDetails();
if (details != null && !details.isEmpty()) {
errorMsg += "; " + details;
}
}
if(host!= null) {
volService.revokeAccess(volFactory.getVolume(volumeToAttach.getId()), host, dataStore);
}
throw new CloudRuntimeException(errorMsg);
}
}
private int getMaxDataVolumesSupported(UserVmVO vm) {
Long hostId = vm.getHostId();
if (hostId == null) {
hostId = vm.getLastHostId();
}
HostVO host = _hostDao.findById(hostId);
Integer maxDataVolumesSupported = null;
if (host != null) {
_hostDao.loadDetails(host);
maxDataVolumesSupported = _hypervisorCapabilitiesDao.getMaxDataVolumesLimit(host.getHypervisorType(), host.getDetail("product_version"));
}
if (maxDataVolumesSupported == null) {
maxDataVolumesSupported = 6; // 6 data disks by default if nothing
// is specified in
// 'hypervisor_capabilities' table
}
return maxDataVolumesSupported.intValue();
}
private Long getDeviceId(long vmId, Long deviceId) {
// allocate deviceId
List<VolumeVO> vols = _volsDao.findByInstance(vmId);
if (deviceId != null) {
if (deviceId.longValue() > 15 || deviceId.longValue() == 3) {
throw new RuntimeException("deviceId should be 1,2,4-15");
}
for (VolumeVO vol : vols) {
if (vol.getDeviceId().equals(deviceId)) {
throw new RuntimeException("deviceId " + deviceId + " is used by vm" + vmId);
}
}
} else {
// allocate deviceId here
List<String> devIds = new ArrayList<String>();
for (int i = 1; i < 15; i++) {
devIds.add(String.valueOf(i));
}
devIds.remove("3");
for (VolumeVO vol : vols) {
devIds.remove(vol.getDeviceId().toString().trim());
}
deviceId = Long.parseLong(devIds.iterator().next());
}
return deviceId;
}
@Override
public boolean configure(String name, Map<String, Object> params) {
String maxVolumeSizeInGbString = _configDao.getValue(Config.MaxVolumeSize.toString());
_maxVolumeSizeInGb = NumbersUtil.parseLong(maxVolumeSizeInGbString, 2000);
return true;
}
public List<StoragePoolAllocator> getStoragePoolAllocators() {
return _storagePoolAllocators;
}
@Inject
public void setStoragePoolAllocators(List<StoragePoolAllocator> storagePoolAllocators) {
_storagePoolAllocators = storagePoolAllocators;
}
public class VmJobVolumeUrlOutcome extends OutcomeImpl<String> {
public VmJobVolumeUrlOutcome(final AsyncJob job) {
super(String.class, job, VmJobCheckInterval.value(), new Predicate() {
@Override
public boolean checkCondition() {
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId());
assert (jobVo != null);
if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS)
return true;
return false;
}
}, AsyncJob.Topics.JOB_STATE);
}
}
public class VmJobVolumeOutcome extends OutcomeImpl<Volume> {
private long _volumeId;
public VmJobVolumeOutcome(final AsyncJob job, final long volumeId) {
super(Volume.class, job, VmJobCheckInterval.value(), new Predicate() {
@Override
public boolean checkCondition() {
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId());
assert (jobVo != null);
if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS)
return true;
return false;
}
}, AsyncJob.Topics.JOB_STATE);
_volumeId = volumeId;
}
@Override
protected Volume retrieve() {
return _volsDao.findById(_volumeId);
}
}
public class VmJobSnapshotOutcome extends OutcomeImpl<Snapshot> {
private long _snapshotId;
public VmJobSnapshotOutcome(final AsyncJob job, final long snapshotId) {
super(Snapshot.class, job, VmJobCheckInterval.value(), new Predicate() {
@Override
public boolean checkCondition() {
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId());
assert (jobVo != null);
if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS)
return true;
return false;
}
}, AsyncJob.Topics.JOB_STATE);
_snapshotId = snapshotId;
}
@Override
protected Snapshot retrieve() {
return _snapshotDao.findById(_snapshotId);
}
}
public Outcome<Volume> attachVolumeToVmThroughJobQueue(final Long vmId, final Long volumeId, final Long deviceId) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
final Account callingAccount = context.getCallingAccount();
final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkAttachVolume.class.getName());
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
// save work context info (there are some duplications)
VmWorkAttachVolume workInfo = new VmWorkAttachVolume(callingUser.getId(), callingAccount.getId(), vm.getId(),
VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, deviceId);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
AsyncJobVO jobVo = _jobMgr.getAsyncJob(workJob.getId());
s_logger.debug("New job " + workJob.getId() + ", result field: " + jobVo.getResult());
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
return new VmJobVolumeOutcome(workJob, volumeId);
}
public Outcome<Volume> detachVolumeFromVmThroughJobQueue(final Long vmId, final Long volumeId) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
final Account callingAccount = context.getCallingAccount();
final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkDetachVolume.class.getName());
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
// save work context info (there are some duplications)
VmWorkDetachVolume workInfo = new VmWorkDetachVolume(callingUser.getId(), callingAccount.getId(), vm.getId(),
VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
return new VmJobVolumeOutcome(workJob, volumeId);
}
public Outcome<Volume> resizeVolumeThroughJobQueue(final Long vmId, final long volumeId,
final long currentSize, final long newSize, final Long newMinIops, final Long newMaxIops, final Long newServiceOfferingId, final boolean shrinkOk) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
final Account callingAccount = context.getCallingAccount();
final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkResizeVolume.class.getName());
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
// save work context info (there are some duplications)
VmWorkResizeVolume workInfo = new VmWorkResizeVolume(callingUser.getId(), callingAccount.getId(), vm.getId(),
VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, currentSize, newSize, newMinIops, newMaxIops, newServiceOfferingId, shrinkOk);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
return new VmJobVolumeOutcome(workJob,volumeId);
}
public Outcome<String> extractVolumeThroughJobQueue(final Long vmId, final long volumeId,
final long zoneId) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
final Account callingAccount = context.getCallingAccount();
final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkExtractVolume.class.getName());
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
// save work context info (there are some duplications)
VmWorkExtractVolume workInfo = new VmWorkExtractVolume(callingUser.getId(), callingAccount.getId(), vm.getId(),
VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, zoneId);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
return new VmJobVolumeUrlOutcome(workJob);
}
public Outcome<Volume> migrateVolumeThroughJobQueue(final Long vmId, final long volumeId,
final long destPoolId, final boolean liveMigrate) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
final Account callingAccount = context.getCallingAccount();
final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkMigrateVolume.class.getName());
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
// save work context info (there are some duplications)
VmWorkMigrateVolume workInfo = new VmWorkMigrateVolume(callingUser.getId(), callingAccount.getId(), vm.getId(),
VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, destPoolId, liveMigrate);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
return new VmJobVolumeOutcome(workJob,volumeId);
}
public Outcome<Snapshot> takeVolumeSnapshotThroughJobQueue(final Long vmId, final Long volumeId,
final Long policyId, final Long snapshotId, final Long accountId, final boolean quiesceVm) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
final Account callingAccount = context.getCallingAccount();
final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkTakeVolumeSnapshot.class.getName());
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
// save work context info (there are some duplications)
VmWorkTakeVolumeSnapshot workInfo = new VmWorkTakeVolumeSnapshot(
callingUser.getId(), accountId != null ? accountId : callingAccount.getId(), vm.getId(),
VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, policyId, snapshotId, quiesceVm);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
return new VmJobSnapshotOutcome(workJob,snapshotId);
}
@ReflectionUse
private Pair<JobInfo.Status, String> orchestrateExtractVolume(VmWorkExtractVolume work) throws Exception {
String volUrl = orchestrateExtractVolume(work.getVolumeId(), work.getZoneId());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, _jobMgr.marshallResultObject(volUrl));
}
@ReflectionUse
private Pair<JobInfo.Status, String> orchestrateAttachVolumeToVM(VmWorkAttachVolume work) throws Exception {
Volume vol = orchestrateAttachVolumeToVM(work.getVmId(), work.getVolumeId(), work.getDeviceId());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED,
_jobMgr.marshallResultObject(new Long(vol.getId())));
}
@ReflectionUse
private Pair<JobInfo.Status, String> orchestrateDetachVolumeFromVM(VmWorkDetachVolume work) throws Exception {
Volume vol = orchestrateDetachVolumeFromVM(work.getVmId(), work.getVolumeId());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED,
_jobMgr.marshallResultObject(new Long(vol.getId())));
}
@ReflectionUse
private Pair<JobInfo.Status, String> orchestrateResizeVolume(VmWorkResizeVolume work) throws Exception {
Volume vol = orchestrateResizeVolume(work.getVolumeId(), work.getCurrentSize(), work.getNewSize(), work.getNewMinIops(), work.getNewMaxIops(),
work.getNewServiceOfferingId(), work.isShrinkOk());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED,
_jobMgr.marshallResultObject(new Long(vol.getId())));
}
@ReflectionUse
private Pair<JobInfo.Status, String> orchestrateMigrateVolume(VmWorkMigrateVolume work) throws Exception {
Volume newVol = orchestrateMigrateVolume(work.getVolumeId(), work.getDestPoolId(), work.isLiveMigrate());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED,
_jobMgr.marshallResultObject(new Long(newVol.getId())));
}
@ReflectionUse
private Pair<JobInfo.Status, String> orchestrateTakeVolumeSnapshot(VmWorkTakeVolumeSnapshot work) throws Exception {
Account account = _accountDao.findById(work.getAccountId());
orchestrateTakeVolumeSnapshot(work.getVolumeId(), work.getPolicyId(), work.getSnapshotId(),
account, work.isQuiesceVm());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED,
_jobMgr.marshallResultObject(work.getSnapshotId()));
}
@Override
public Pair<JobInfo.Status, String> handleVmWorkJob(VmWork work) throws Exception {
return _jobHandlerProxy.handleVmWorkJob(work);
}
private VmWorkJobVO createPlaceHolderWork(long instanceId) {
VmWorkJobVO workJob = new VmWorkJobVO("");
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_PLACEHOLDER);
workJob.setCmd("");
workJob.setCmdInfo("");
workJob.setAccountId(0);
workJob.setUserId(0);
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(instanceId);
workJob.setInitMsid(ManagementServerNode.getManagementServerId());
_workJobDao.persist(workJob);
return workJob;
}
}
| server/src/com/cloud/storage/VolumeApiServiceImpl.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 com.cloud.storage;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import javax.inject.Inject;
import com.cloud.utils.EncryptionUtil;
import com.cloud.utils.db.TransactionCallbackWithException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.cloudstack.api.command.user.volume.GetUploadParamsForVolumeCmd;
import org.apache.cloudstack.api.response.GetUploadParamsResponse;
import org.apache.cloudstack.engine.subsystem.api.storage.DataObject;
import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint;
import org.apache.cloudstack.storage.command.TemplateOrVolumePostUploadCommand;
import org.apache.cloudstack.utils.imagestore.ImageStoreUtil;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.MigrateVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.ResizeVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.UploadVolumeCmd;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService;
import org.apache.cloudstack.engine.subsystem.api.storage.ChapInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.HostScope;
import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.Scope;
import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult;
import org.apache.cloudstack.framework.async.AsyncCallFuture;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.framework.jobs.AsyncJob;
import org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext;
import org.apache.cloudstack.framework.jobs.AsyncJobManager;
import org.apache.cloudstack.framework.jobs.Outcome;
import org.apache.cloudstack.framework.jobs.dao.VmWorkJobDao;
import org.apache.cloudstack.framework.jobs.impl.AsyncJobVO;
import org.apache.cloudstack.framework.jobs.impl.OutcomeImpl;
import org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO;
import org.apache.cloudstack.jobs.JobInfo;
import org.apache.cloudstack.storage.command.AttachAnswer;
import org.apache.cloudstack.storage.command.AttachCommand;
import org.apache.cloudstack.storage.command.DettachCommand;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO;
import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity;
import org.apache.cloudstack.utils.identity.ManagementServerNode;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.to.DataTO;
import com.cloud.agent.api.to.DiskTO;
import com.cloud.api.ApiDBUtils;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.dc.ClusterDetailsDao;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.domain.Domain;
import com.cloud.event.ActionEvent;
import com.cloud.event.EventTypes;
import com.cloud.event.UsageEventUtils;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.StorageUnavailableException;
import com.cloud.gpu.GPU;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.HypervisorCapabilitiesVO;
import com.cloud.hypervisor.dao.HypervisorCapabilitiesDao;
import com.cloud.org.Grouping;
import com.cloud.service.dao.ServiceOfferingDetailsDao;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.storage.dao.SnapshotDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.snapshot.SnapshotApiService;
import com.cloud.storage.snapshot.SnapshotManager;
import com.cloud.template.TemplateManager;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.ResourceLimitService;
import com.cloud.user.User;
import com.cloud.user.VmDiskStatisticsVO;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.VmDiskStatisticsDao;
import com.cloud.utils.DateUtil;
import com.cloud.utils.EnumUtils;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.Predicate;
import com.cloud.utils.ReflectionUse;
import com.cloud.utils.StringUtils;
import com.cloud.utils.UriUtils;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallback;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.db.UUIDManager;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.fsm.NoTransitionException;
import com.cloud.utils.fsm.StateMachine2;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.VmWork;
import com.cloud.vm.VmWorkAttachVolume;
import com.cloud.vm.VmWorkConstants;
import com.cloud.vm.VmWorkDetachVolume;
import com.cloud.vm.VmWorkExtractVolume;
import com.cloud.vm.VmWorkJobHandler;
import com.cloud.vm.VmWorkJobHandlerProxy;
import com.cloud.vm.VmWorkMigrateVolume;
import com.cloud.vm.VmWorkResizeVolume;
import com.cloud.vm.VmWorkSerializer;
import com.cloud.vm.VmWorkTakeVolumeSnapshot;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.vm.snapshot.VMSnapshotVO;
import com.cloud.vm.snapshot.dao.VMSnapshotDao;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiService, VmWorkJobHandler {
private final static Logger s_logger = Logger.getLogger(VolumeApiServiceImpl.class);
public static final String VM_WORK_JOB_HANDLER = VolumeApiServiceImpl.class.getSimpleName();
@Inject
VolumeOrchestrationService _volumeMgr;
@Inject
EntityManager _entityMgr;
@Inject
AgentManager _agentMgr;
@Inject
TemplateManager _tmpltMgr;
@Inject
SnapshotManager _snapshotMgr;
@Inject
AccountManager _accountMgr;
@Inject
ConfigurationManager _configMgr;
@Inject
VolumeDao _volsDao;
@Inject
HostDao _hostDao;
@Inject
SnapshotDao _snapshotDao;
@Inject
ServiceOfferingDetailsDao _serviceOfferingDetailsDao;
@Inject
StoragePoolDetailsDao storagePoolDetailsDao;
@Inject
UserVmDao _userVmDao;
@Inject
VolumeDataStoreDao _volumeStoreDao;
@Inject
VMInstanceDao _vmInstanceDao;
@Inject
PrimaryDataStoreDao _storagePoolDao;
@Inject
DiskOfferingDao _diskOfferingDao;
@Inject
AccountDao _accountDao;
@Inject
final DataCenterDao _dcDao = null;
@Inject
VMTemplateDao _templateDao;
@Inject
ResourceLimitService _resourceLimitMgr;
@Inject
VmDiskStatisticsDao _vmDiskStatsDao;
@Inject
VMSnapshotDao _vmSnapshotDao;
@Inject
ConfigurationDao _configDao;
@Inject
DataStoreManager dataStoreMgr;
@Inject
VolumeService volService;
@Inject
VolumeDataFactory volFactory;
@Inject
SnapshotApiService snapshotMgr;
@Inject
UUIDManager _uuidMgr;
@Inject
HypervisorCapabilitiesDao _hypervisorCapabilitiesDao;
@Inject
AsyncJobManager _jobMgr;
@Inject
VmWorkJobDao _workJobDao;
@Inject
ClusterDetailsDao _clusterDetailsDao;
private List<StoragePoolAllocator> _storagePoolAllocators;
VmWorkJobHandlerProxy _jobHandlerProxy = new VmWorkJobHandlerProxy(this);
static final ConfigKey<Long> VmJobCheckInterval = new ConfigKey<Long>("Advanced", Long.class, "vm.job.check.interval", "3000",
"Interval in milliseconds to check if the job is complete", false);
private long _maxVolumeSizeInGb;
private final StateMachine2<Volume.State, Volume.Event, Volume> _volStateMachine;
protected VolumeApiServiceImpl() {
_volStateMachine = Volume.State.getStateMachine();
}
/*
* Upload the volume to secondary storage.
*/
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_UPLOAD, eventDescription = "uploading volume", async = true)
public VolumeVO uploadVolume(UploadVolumeCmd cmd) throws ResourceAllocationException {
Account caller = CallContext.current().getCallingAccount();
long ownerId = cmd.getEntityOwnerId();
Account owner = _entityMgr.findById(Account.class, ownerId);
Long zoneId = cmd.getZoneId();
String volumeName = cmd.getVolumeName();
String url = cmd.getUrl();
String format = cmd.getFormat();
Long diskOfferingId = cmd.getDiskOfferingId();
String imageStoreUuid = cmd.getImageStoreUuid();
DataStore store = _tmpltMgr.getImageStore(imageStoreUuid, zoneId);
validateVolume(caller, ownerId, zoneId, volumeName, url, format, diskOfferingId);
VolumeVO volume = persistVolume(owner, zoneId, volumeName, url, cmd.getFormat(), diskOfferingId, Volume.State.Allocated);
VolumeInfo vol = volFactory.getVolume(volume.getId());
RegisterVolumePayload payload = new RegisterVolumePayload(cmd.getUrl(), cmd.getChecksum(), cmd.getFormat());
vol.addPayload(payload);
volService.registerVolume(vol, store);
return volume;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_UPLOAD, eventDescription = "uploading volume for post upload", async = true)
public GetUploadParamsResponse uploadVolume(final GetUploadParamsForVolumeCmd cmd) throws ResourceAllocationException, MalformedURLException {
Account caller = CallContext.current().getCallingAccount();
long ownerId = cmd.getEntityOwnerId();
final Account owner = _entityMgr.findById(Account.class, ownerId);
final Long zoneId = cmd.getZoneId();
final String volumeName = cmd.getName();
String format = cmd.getFormat();
final Long diskOfferingId = cmd.getDiskOfferingId();
String imageStoreUuid = cmd.getImageStoreUuid();
final DataStore store = _tmpltMgr.getImageStore(imageStoreUuid, zoneId);
validateVolume(caller, ownerId, zoneId, volumeName, null, format, diskOfferingId);
return Transaction.execute(new TransactionCallbackWithException<GetUploadParamsResponse, MalformedURLException>() {
@Override
public GetUploadParamsResponse doInTransaction(TransactionStatus status) throws MalformedURLException {
VolumeVO volume = persistVolume(owner, zoneId, volumeName, null, cmd.getFormat(), diskOfferingId, Volume.State.NotUploaded);
VolumeInfo vol = volFactory.getVolume(volume.getId());
RegisterVolumePayload payload = new RegisterVolumePayload(null, cmd.getChecksum(), cmd.getFormat());
vol.addPayload(payload);
Pair<EndPoint, DataObject> pair = volService.registerVolumeForPostUpload(vol, store);
EndPoint ep = pair.first();
DataObject dataObject = pair.second();
GetUploadParamsResponse response = new GetUploadParamsResponse();
String ssvmUrlDomain = _configDao.getValue(Config.SecStorageSecureCopyCert.key());
String url = ImageStoreUtil.generatePostUploadUrl(ssvmUrlDomain, ep.getPublicAddr(), vol.getUuid());
response.setPostURL(new URL(url));
// set the post url, this is used in the monitoring thread to determine the SSVM
VolumeDataStoreVO volumeStore = _volumeStoreDao.findByVolume(vol.getId());
assert (volumeStore != null) : "sincle volume is registered, volumestore cannot be null at this stage";
volumeStore.setExtractUrl(url);
_volumeStoreDao.persist(volumeStore);
response.setId(UUID.fromString(vol.getUuid()));
int timeout = ImageStoreUploadMonitorImpl.getUploadOperationTimeout();
DateTime currentDateTime = new DateTime(DateTimeZone.UTC);
String expires = currentDateTime.plusMinutes(timeout).toString();
response.setTimeout(expires);
String key = _configDao.getValue(Config.SSVMPSK.key());
/*
* encoded metadata using the post upload config key
*/
TemplateOrVolumePostUploadCommand command =
new TemplateOrVolumePostUploadCommand(vol.getId(), vol.getUuid(), volumeStore.getInstallPath(), cmd.getChecksum(), vol.getType().toString(),
vol.getName(), vol.getFormat().toString(), dataObject.getDataStore().getUri(),
dataObject.getDataStore().getRole().toString());
command.setLocalPath(volumeStore.getLocalDownloadPath());
//using the existing max upload size configuration
command.setMaxUploadSize(_configDao.getValue(Config.MaxUploadVolumeSize.key()));
command.setDefaultMaxAccountSecondaryStorage(_configDao.getValue(Config.DefaultMaxAccountSecondaryStorage.key()));
command.setAccountId(vol.getAccountId());
Gson gson = new GsonBuilder().create();
String metadata = EncryptionUtil.encodeData(gson.toJson(command), key);
response.setMetadata(metadata);
/*
* signature calculated on the url, expiry, metadata.
*/
response.setSignature(EncryptionUtil.generateSignature(metadata + url + expires, key));
return response;
}
});
}
private boolean validateVolume(Account caller, long ownerId, Long zoneId, String volumeName, String url,
String format, Long diskOfferingId) throws ResourceAllocationException {
// permission check
Account volumeOwner = _accountMgr.getActiveAccountById(ownerId);
_accountMgr.checkAccess(caller, null, true, volumeOwner);
// Check that the resource limit for volumes won't be exceeded
_resourceLimitMgr.checkResourceLimit(volumeOwner, ResourceType.volume);
// Verify that zone exists
DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Unable to find zone by id " + zoneId);
}
// Check if zone is disabled
if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
}
//validating the url only when url is not null. url can be null incase of form based post upload
if (url != null ) {
if( url.toLowerCase().contains("file://")) {
throw new InvalidParameterValueException("File:// type urls are currently unsupported");
}
UriUtils.validateUrl(format, url);
// check URL existence
UriUtils.checkUrlExistence(url);
// Check that the resource limit for secondary storage won't be exceeded
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(ownerId), ResourceType.secondary_storage, UriUtils.getRemoteSize(url));
} else {
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(ownerId), ResourceType.secondary_storage);
}
try {
ImageFormat.valueOf(format.toUpperCase());
} catch (IllegalArgumentException e) {
s_logger.debug("ImageFormat IllegalArgumentException: " + e.getMessage());
throw new IllegalArgumentException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values()));
}
// Check that the the disk offering specified is valid
if (diskOfferingId != null) {
DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId);
if ((diskOffering == null) || diskOffering.getRemoved() != null
|| !DiskOfferingVO.Type.Disk.equals(diskOffering.getType())) {
throw new InvalidParameterValueException("Please specify a valid disk offering.");
}
if (!diskOffering.isCustomized()) {
throw new InvalidParameterValueException("Please specify a custom sized disk offering.");
}
if (diskOffering.getDomainId() == null) {
// do nothing as offering is public
} else {
_configMgr.checkDiskOfferingAccess(volumeOwner, diskOffering);
}
}
return false;
}
public String getRandomVolumeName() {
return UUID.randomUUID().toString();
}
@DB
protected VolumeVO persistVolume(final Account owner, final Long zoneId, final String volumeName, final String url,
final String format, final Long diskOfferingId, final Volume.State state) {
return Transaction.execute(new TransactionCallback<VolumeVO>() {
@Override
public VolumeVO doInTransaction(TransactionStatus status) {
VolumeVO volume = new VolumeVO(volumeName, zoneId, -1, -1, -1, new Long(-1), null, null, Storage.ProvisioningType.THIN, 0, Volume.Type.DATADISK);
volume.setPoolId(null);
volume.setDataCenterId(zoneId);
volume.setPodId(null);
volume.setState(state); // initialize the state
// to prevent a null pointer deref I put the system account id here when no owner is given.
// TODO Decide if this is valid or whether throwing a CloudRuntimeException is more appropriate
volume.setAccountId((owner == null) ? Account.ACCOUNT_ID_SYSTEM : owner.getAccountId());
volume.setDomainId((owner == null) ? Domain.ROOT_DOMAIN : owner.getDomainId());
if (diskOfferingId == null) {
DiskOfferingVO diskOfferingVO = _diskOfferingDao.findByUniqueName("Cloud.com-Custom");
if (diskOfferingVO != null) {
long defaultDiskOfferingId = diskOfferingVO.getId();
volume.setDiskOfferingId(defaultDiskOfferingId);
}
} else {
volume.setDiskOfferingId(diskOfferingId);
}
// volume.setSize(size);
volume.setInstanceId(null);
volume.setUpdated(new Date());
volume.setDomainId((owner == null) ? Domain.ROOT_DOMAIN : owner.getDomainId());
volume.setFormat(ImageFormat.valueOf(format));
volume = _volsDao.persist(volume);
CallContext.current().setEventDetails("Volume Id: " + volume.getId());
// Increment resource count during allocation; if actual creation fails,
// decrement it
_resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.volume);
//url can be null incase of postupload
if(url!=null) {
_resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.secondary_storage, UriUtils.getRemoteSize(url));
}
return volume;
}
});
}
/*
* Just allocate a volume in the database, don't send the createvolume cmd
* to hypervisor. The volume will be finally created only when it's attached
* to a VM.
*/
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_CREATE, eventDescription = "creating volume", create = true)
public VolumeVO allocVolume(CreateVolumeCmd cmd) throws ResourceAllocationException {
// FIXME: some of the scheduled event stuff might be missing here...
Account caller = CallContext.current().getCallingAccount();
long ownerId = cmd.getEntityOwnerId();
Account owner = _accountMgr.getActiveAccountById(ownerId);
Boolean displayVolume = cmd.getDisplayVolume();
// permission check
_accountMgr.checkAccess(caller, null, true, _accountMgr.getActiveAccountById(ownerId));
if (displayVolume == null) {
displayVolume = true;
} else {
if (!_accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot update parameter displayvolume, only admin permitted ");
}
}
// Check that the resource limit for volumes won't be exceeded
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, displayVolume);
Long zoneId = cmd.getZoneId();
Long diskOfferingId = null;
DiskOfferingVO diskOffering = null;
Storage.ProvisioningType provisioningType;
Long size = null;
Long minIops = null;
Long maxIops = null;
// Volume VO used for extracting the source template id
VolumeVO parentVolume = null;
// validate input parameters before creating the volume
if ((cmd.getSnapshotId() == null && cmd.getDiskOfferingId() == null) || (cmd.getSnapshotId() != null && cmd.getDiskOfferingId() != null)) {
throw new InvalidParameterValueException("Either disk Offering Id or snapshot Id must be passed whilst creating volume");
}
if (cmd.getSnapshotId() == null) {// create a new volume
diskOfferingId = cmd.getDiskOfferingId();
size = cmd.getSize();
Long sizeInGB = size;
if (size != null) {
if (size > 0) {
size = size * 1024 * 1024 * 1024; // user specify size in GB
} else {
throw new InvalidParameterValueException("Disk size must be larger than 0");
}
}
// Check that the the disk offering is specified
diskOffering = _diskOfferingDao.findById(diskOfferingId);
if ((diskOffering == null) || diskOffering.getRemoved() != null || !DiskOfferingVO.Type.Disk.equals(diskOffering.getType())) {
throw new InvalidParameterValueException("Please specify a valid disk offering.");
}
if (diskOffering.isCustomized()) {
if (size == null) {
throw new InvalidParameterValueException("This disk offering requires a custom size specified");
}
Long customDiskOfferingMaxSize = _volumeMgr.CustomDiskOfferingMaxSize.value();
Long customDiskOfferingMinSize = _volumeMgr.CustomDiskOfferingMinSize.value();
if ((sizeInGB < customDiskOfferingMinSize) || (sizeInGB > customDiskOfferingMaxSize)) {
throw new InvalidParameterValueException("Volume size: " + sizeInGB + "GB is out of allowed range. Max: " + customDiskOfferingMaxSize + " Min:"
+ customDiskOfferingMinSize);
}
}
if (!diskOffering.isCustomized() && size != null) {
throw new InvalidParameterValueException("This disk offering does not allow custom size");
}
if (diskOffering.getDomainId() == null) {
// do nothing as offering is public
} else {
_configMgr.checkDiskOfferingAccess(caller, diskOffering);
}
if (diskOffering.getDiskSize() > 0) {
size = diskOffering.getDiskSize();
}
Boolean isCustomizedIops = diskOffering.isCustomizedIops();
if (isCustomizedIops != null) {
if (isCustomizedIops) {
minIops = cmd.getMinIops();
maxIops = cmd.getMaxIops();
if (minIops == null && maxIops == null) {
minIops = 0L;
maxIops = 0L;
} else {
if (minIops == null || minIops <= 0) {
throw new InvalidParameterValueException("The min IOPS must be greater than 0.");
}
if (maxIops == null) {
maxIops = 0L;
}
if (minIops > maxIops) {
throw new InvalidParameterValueException("The min IOPS must be less than or equal to the max IOPS.");
}
}
} else {
minIops = diskOffering.getMinIops();
maxIops = diskOffering.getMaxIops();
}
}
provisioningType = diskOffering.getProvisioningType();
if (!validateVolumeSizeRange(size)) {// convert size from mb to gb
// for validation
throw new InvalidParameterValueException("Invalid size for custom volume creation: " + size + " ,max volume size is:" + _maxVolumeSizeInGb);
}
} else { // create volume from snapshot
Long snapshotId = cmd.getSnapshotId();
SnapshotVO snapshotCheck = _snapshotDao.findById(snapshotId);
if (snapshotCheck == null) {
throw new InvalidParameterValueException("unable to find a snapshot with id " + snapshotId);
}
if (snapshotCheck.getState() != Snapshot.State.BackedUp) {
throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.State.BackedUp + " state yet and can't be used for volume creation");
}
parentVolume = _volsDao.findByIdIncludingRemoved(snapshotCheck.getVolumeId());
diskOfferingId = snapshotCheck.getDiskOfferingId();
diskOffering = _diskOfferingDao.findById(diskOfferingId);
if (zoneId == null) {
// if zoneId is not provided, we default to create volume in the same zone as the snapshot zone.
zoneId = snapshotCheck.getDataCenterId();
}
size = snapshotCheck.getSize(); // ; disk offering is used for tags
// purposes
minIops = snapshotCheck.getMinIops();
maxIops = snapshotCheck.getMaxIops();
provisioningType = diskOffering.getProvisioningType();
// check snapshot permissions
_accountMgr.checkAccess(caller, null, true, snapshotCheck);
// one step operation - create volume in VM's cluster and attach it
// to the VM
Long vmId = cmd.getVirtualMachineId();
if (vmId != null) {
// Check that the virtual machine ID is valid and it's a user vm
UserVmVO vm = _userVmDao.findById(vmId);
if (vm == null || vm.getType() != VirtualMachine.Type.User) {
throw new InvalidParameterValueException("Please specify a valid User VM.");
}
// Check that the VM is in the correct state
if (vm.getState() != State.Running && vm.getState() != State.Stopped) {
throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.");
}
// permission check
_accountMgr.checkAccess(caller, null, false, vm);
}
}
// Check that the resource limit for primary storage won't be exceeded
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, displayVolume, new Long(size));
// Verify that zone exists
DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Unable to find zone by id " + zoneId);
}
// Check if zone is disabled
if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
}
// If local storage is disabled then creation of volume with local disk
// offering not allowed
if (!zone.isLocalStorageEnabled() && diskOffering.getUseLocalStorage()) {
throw new InvalidParameterValueException("Zone is not configured to use local storage but volume's disk offering " + diskOffering.getName() + " uses it");
}
String userSpecifiedName = cmd.getVolumeName();
if (userSpecifiedName == null) {
userSpecifiedName = getRandomVolumeName();
}
VolumeVO volume = commitVolume(cmd, caller, owner, displayVolume, zoneId, diskOfferingId, provisioningType, size,
minIops, maxIops, parentVolume, userSpecifiedName, _uuidMgr.generateUuid(Volume.class, cmd.getCustomId()));
return volume;
}
private VolumeVO commitVolume(final CreateVolumeCmd cmd, final Account caller, final Account owner, final Boolean displayVolume,
final Long zoneId, final Long diskOfferingId, final Storage.ProvisioningType provisioningType, final Long size, final Long minIops, final Long maxIops, final VolumeVO parentVolume,
final String userSpecifiedName, final String uuid) {
return Transaction.execute(new TransactionCallback<VolumeVO>() {
@Override
public VolumeVO doInTransaction(TransactionStatus status) {
VolumeVO volume = new VolumeVO(userSpecifiedName, -1, -1, -1, -1, new Long(-1), null, null, provisioningType, 0, Volume.Type.DATADISK);
volume.setPoolId(null);
volume.setUuid(uuid);
volume.setDataCenterId(zoneId);
volume.setPodId(null);
volume.setAccountId(owner.getId());
volume.setDomainId(owner.getDomainId());
volume.setDiskOfferingId(diskOfferingId);
volume.setSize(size);
volume.setMinIops(minIops);
volume.setMaxIops(maxIops);
volume.setInstanceId(null);
volume.setUpdated(new Date());
volume.setDisplayVolume(displayVolume);
if (parentVolume != null) {
volume.setTemplateId(parentVolume.getTemplateId());
volume.setFormat(parentVolume.getFormat());
} else {
volume.setTemplateId(null);
}
volume = _volsDao.persist(volume);
if (cmd.getSnapshotId() == null && displayVolume) {
// for volume created from snapshot, create usage event after volume creation
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(),
diskOfferingId, null, size, Volume.class.getName(), volume.getUuid(), displayVolume);
}
CallContext.current().setEventDetails("Volume Id: " + volume.getId());
// Increment resource count during allocation; if actual creation fails,
// decrement it
_resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.volume, displayVolume);
_resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.primary_storage, displayVolume, new Long(volume.getSize()));
return volume;
}
});
}
public boolean validateVolumeSizeRange(long size) {
if (size < 0 || (size > 0 && size < (1024 * 1024 * 1024))) {
throw new InvalidParameterValueException("Please specify a size of at least 1 GB.");
} else if (size > (_maxVolumeSizeInGb * 1024 * 1024 * 1024)) {
throw new InvalidParameterValueException("Requested volume size is " + size + ", but the maximum size allowed is " + _maxVolumeSizeInGb + " GB.");
}
return true;
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_CREATE, eventDescription = "creating volume", async = true)
public VolumeVO createVolume(CreateVolumeCmd cmd) {
VolumeVO volume = _volsDao.findById(cmd.getEntityId());
boolean created = true;
try {
if (cmd.getSnapshotId() != null) {
volume = createVolumeFromSnapshot(volume, cmd.getSnapshotId(), cmd.getVirtualMachineId());
if (volume.getState() != Volume.State.Ready) {
created = false;
}
// if VM Id is provided, attach the volume to the VM
if (cmd.getVirtualMachineId() != null) {
try {
attachVolumeToVM(cmd.getVirtualMachineId(), volume.getId(), volume.getDeviceId());
} catch (Exception ex) {
StringBuilder message = new StringBuilder("Volume: ");
message.append(volume.getUuid());
message.append(" created successfully, but failed to attach the newly created volume to VM: ");
message.append(cmd.getVirtualMachineId());
message.append(" due to error: ");
message.append(ex.getMessage());
if (s_logger.isDebugEnabled()) {
s_logger.debug(message, ex);
}
throw new CloudRuntimeException(message.toString());
}
}
}
return volume;
} catch (Exception e) {
created = false;
VolumeInfo vol = volFactory.getVolume(cmd.getEntityId());
vol.stateTransit(Volume.Event.DestroyRequested);
throw new CloudRuntimeException("Failed to create volume: " + volume.getId(), e);
} finally {
if (!created) {
s_logger.trace("Decrementing volume resource count for account id=" + volume.getAccountId() + " as volume failed to create on the backend");
_resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.volume, cmd.getDisplayVolume());
_resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(), ResourceType.primary_storage.getOrdinal());
}
}
}
protected VolumeVO createVolumeFromSnapshot(VolumeVO volume, long snapshotId, Long vmId) throws StorageUnavailableException {
VolumeInfo createdVolume = null;
SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
snapshot.getVolumeId();
UserVmVO vm = null;
if (vmId != null) {
vm = _userVmDao.findById(vmId);
}
// sync old snapshots to region store if necessary
createdVolume = _volumeMgr.createVolumeFromSnapshot(volume, snapshot, vm);
VolumeVO volumeVo = _volsDao.findById(createdVolume.getId());
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, createdVolume.getAccountId(), createdVolume.getDataCenterId(), createdVolume.getId(),
createdVolume.getName(), createdVolume.getDiskOfferingId(), null, createdVolume.getSize(), Volume.class.getName(), createdVolume.getUuid(), volumeVo.isDisplayVolume());
return volumeVo;
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_RESIZE, eventDescription = "resizing volume", async = true)
public VolumeVO resizeVolume(ResizeVolumeCmd cmd) throws ResourceAllocationException {
Long newSize = null;
Long newMinIops = null;
Long newMaxIops = null;
boolean shrinkOk = cmd.getShrinkOk();
VolumeVO volume = _volsDao.findById(cmd.getEntityId());
if (volume == null) {
throw new InvalidParameterValueException("No such volume");
}
/* Does the caller have authority to act on this volume? */
_accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
if(volume.getInstanceId() != null) {
// Check that Vm to which this volume is attached does not have VM Snapshots
if (_vmSnapshotDao.findByVm(volume.getInstanceId()).size() > 0) {
throw new InvalidParameterValueException("Volume cannot be resized which is attached to VM with VM Snapshots");
}
}
DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId());
DiskOfferingVO newDiskOffering = null;
if (cmd.getNewDiskOfferingId() != null && volume.getDiskOfferingId() != cmd.getNewDiskOfferingId()) {
newDiskOffering = _diskOfferingDao.findById(cmd.getNewDiskOfferingId());
}
/* Only works for KVM/XenServer/VMware (or "Any") for now, and volumes with 'None' since they're just allocated in DB */
HypervisorType hypervisorType = _volsDao.getHypervisorType(volume.getId());
if (hypervisorType != HypervisorType.KVM && hypervisorType != HypervisorType.XenServer &&
hypervisorType != HypervisorType.VMware && hypervisorType != HypervisorType.Any && hypervisorType != HypervisorType.None) {
throw new InvalidParameterValueException("CloudStack currently supports volume resize only on KVM, VMware, or XenServer.");
}
if (volume.getState() != Volume.State.Ready && volume.getState() != Volume.State.Allocated) {
throw new InvalidParameterValueException("Volume should be in ready or allocated state before attempting a resize. Volume " +
volume.getUuid() + " is in state " + volume.getState() + ".");
}
// if we are to use the existing disk offering
if (newDiskOffering == null) {
newSize = cmd.getSize();
// if the caller is looking to change the size of the volume
if (newSize != null) {
if (!diskOffering.isCustomized() && !volume.getVolumeType().equals(Volume.Type.ROOT)) {
throw new InvalidParameterValueException("To change a volume's size without providing a new disk offering, its current disk offering must be " +
"customizable or it must be a root volume (if providing a disk offering, make sure it is different from the current disk offering).");
}
// convert from bytes to GiB
newSize = newSize << 30;
}
else {
// no parameter provided; just use the original size of the volume
newSize = volume.getSize();
}
newMinIops = cmd.getMinIops();
if (newMinIops != null) {
if (diskOffering.isCustomizedIops() == null || !diskOffering.isCustomizedIops()) {
throw new InvalidParameterValueException("The current disk offering does not support customization of the 'Min IOPS' parameter.");
}
}
else {
// no parameter provided; just use the original min IOPS of the volume
newMinIops = volume.getMinIops();
}
newMaxIops = cmd.getMaxIops();
if (newMaxIops != null) {
if (diskOffering.isCustomizedIops() == null || !diskOffering.isCustomizedIops()) {
throw new InvalidParameterValueException("The current disk offering does not support customization of the 'Max IOPS' parameter.");
}
}
else {
// no parameter provided; just use the original max IOPS of the volume
newMaxIops = volume.getMaxIops();
}
validateIops(newMinIops, newMaxIops);
} else {
if (newDiskOffering.getRemoved() != null) {
throw new InvalidParameterValueException("Requested disk offering has been removed.");
}
if (!DiskOfferingVO.Type.Disk.equals(newDiskOffering.getType())) {
throw new InvalidParameterValueException("Requested disk offering type is invalid.");
}
if (diskOffering.getTags() != null) {
if (!StringUtils.areTagsEqual(diskOffering.getTags(), newDiskOffering.getTags())) {
throw new InvalidParameterValueException("The tags on the new and old disk offerings must match.");
}
} else if (newDiskOffering.getTags() != null) {
throw new InvalidParameterValueException("There are no tags on the current disk offering. The new disk offering needs to have no tags, as well.");
}
if (!areIntegersEqual(diskOffering.getHypervisorSnapshotReserve(), newDiskOffering.getHypervisorSnapshotReserve())) {
throw new InvalidParameterValueException("The hypervisor snapshot reverse on the new and old disk offerings must be equal.");
}
if (newDiskOffering.getDomainId() != null) {
// not a public offering; check access
_configMgr.checkDiskOfferingAccess(CallContext.current().getCallingAccount(), newDiskOffering);
}
if (newDiskOffering.isCustomized()) {
newSize = cmd.getSize();
if (newSize == null) {
throw new InvalidParameterValueException("The new disk offering requires that a size be specified.");
}
// convert from bytes to GiB
newSize = newSize << 30;
} else {
newSize = newDiskOffering.getDiskSize();
}
if (!volume.getSize().equals(newSize) && !volume.getVolumeType().equals(Volume.Type.DATADISK)) {
throw new InvalidParameterValueException("Only data volumes can be resized via a new disk offering.");
}
if (newDiskOffering.isCustomizedIops() != null && newDiskOffering.isCustomizedIops()) {
newMinIops = cmd.getMinIops() != null ? cmd.getMinIops() : volume.getMinIops();
newMaxIops = cmd.getMaxIops() != null ? cmd.getMaxIops() : volume.getMaxIops();
validateIops(newMinIops, newMaxIops);
}
else {
newMinIops = newDiskOffering.getMinIops();
newMaxIops = newDiskOffering.getMaxIops();
}
}
long currentSize = volume.getSize();
// if the caller is looking to change the size of the volume
if (currentSize != newSize) {
if (!validateVolumeSizeRange(newSize)) {
throw new InvalidParameterValueException("Requested size out of range");
}
/*
* Let's make certain they (think they) know what they're doing if they
* want to shrink by forcing them to provide the shrinkok parameter.
* This will be checked again at the hypervisor level where we can see
* the actual disk size.
*/
if (currentSize > newSize && !shrinkOk) {
throw new InvalidParameterValueException("Going from existing size of " + currentSize + " to size of " + newSize + " would shrink the volume." +
"Need to sign off by supplying the shrinkok parameter with value of true.");
}
if (newSize > currentSize) {
/* Check resource limit for this account on primary storage resource */
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(volume.getAccountId()), ResourceType.primary_storage, volume.isDisplayVolume(),
new Long(newSize - currentSize).longValue());
}
}
// Note: The storage plug-in in question should perform validation on the IOPS to check if a sufficient number of IOPS is available to perform
// the requested change
/* If this volume has never been beyond allocated state, short circuit everything and simply update the database. */
if (volume.getState() == Volume.State.Allocated) {
s_logger.debug("Volume is in the allocated state, but has never been created. Simply updating database with new size and IOPS.");
volume.setSize(newSize);
volume.setMinIops(newMinIops);
volume.setMaxIops(newMaxIops);
if (newDiskOffering != null) {
volume.setDiskOfferingId(cmd.getNewDiskOfferingId());
}
_volsDao.update(volume.getId(), volume);
return volume;
}
UserVmVO userVm = _userVmDao.findById(volume.getInstanceId());
if (userVm != null) {
// serialize VM operation
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if ( jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
VmWorkJobVO placeHolder = null;
placeHolder = createPlaceHolderWork(userVm.getId());
try {
return orchestrateResizeVolume(volume.getId(), currentSize, newSize, newMinIops, newMaxIops,
newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk);
} finally {
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<Volume> outcome = resizeVolumeThroughJobQueue(userVm.getId(), volume.getId(), currentSize, newSize, newMinIops, newMaxIops,
newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk);
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation was interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution exception", e);
}
Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
if (jobResult != null) {
if (jobResult instanceof ConcurrentOperationException) {
throw (ConcurrentOperationException)jobResult;
}
else if (jobResult instanceof ResourceAllocationException) {
throw (ResourceAllocationException)jobResult;
}
else if (jobResult instanceof RuntimeException) {
throw (RuntimeException)jobResult;
}
else if (jobResult instanceof Throwable) {
throw new RuntimeException("Unexpected exception", (Throwable)jobResult);
}
else if (jobResult instanceof Long) {
return _volsDao.findById((Long)jobResult);
}
}
return volume;
}
}
return orchestrateResizeVolume(volume.getId(), currentSize, newSize, newMinIops, newMaxIops,
newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk);
}
private static boolean areIntegersEqual(Integer i1, Integer i2) {
if (i1 == null) {
i1 = 0;
}
if (i2 == null) {
i2 = 0;
}
return i1.equals(i2);
}
private void validateIops(Long minIops, Long maxIops) {
if ((minIops == null && maxIops != null) || (minIops != null && maxIops == null)) {
throw new InvalidParameterValueException("Either 'miniops' and 'maxiops' must both be provided or neither must be provided.");
}
if (minIops != null && maxIops != null) {
if (minIops > maxIops) {
throw new InvalidParameterValueException("The 'miniops' parameter must be less than or equal to the 'maxiops' parameter.");
}
}
}
private VolumeVO orchestrateResizeVolume(long volumeId, long currentSize, long newSize, Long newMinIops, Long newMaxIops, Long newDiskOfferingId, boolean shrinkOk) {
VolumeVO volume = _volsDao.findById(volumeId);
UserVmVO userVm = _userVmDao.findById(volume.getInstanceId());
/*
* get a list of hosts to send the commands to, try the system the
* associated vm is running on first, then the last known place it ran.
* If not attached to a userVm, we pass 'none' and resizevolume.sh is ok
* with that since it only needs the vm name to live resize
*/
long[] hosts = null;
String instanceName = "none";
if (userVm != null) {
instanceName = userVm.getInstanceName();
if (userVm.getHostId() != null) {
hosts = new long[] {userVm.getHostId()};
} else if (userVm.getLastHostId() != null) {
hosts = new long[] {userVm.getLastHostId()};
}
final String errorMsg = "The VM must be stopped or the disk detached in order to resize with the XenServer Hypervisor.";
StoragePoolVO storagePool = _storagePoolDao.findById(volume.getPoolId());
if (storagePool.isManaged() && storagePool.getHypervisor() == HypervisorType.Any && hosts != null && hosts.length > 0) {
HostVO host = _hostDao.findById(hosts[0]);
if (currentSize != newSize && host.getHypervisorType() == HypervisorType.XenServer && !userVm.getState().equals(State.Stopped)) {
throw new InvalidParameterValueException(errorMsg);
}
}
/* Xen only works offline, SR does not support VDI.resizeOnline */
if (currentSize != newSize && _volsDao.getHypervisorType(volume.getId()) == HypervisorType.XenServer && !userVm.getState().equals(State.Stopped)) {
throw new InvalidParameterValueException(errorMsg);
}
}
ResizeVolumePayload payload = new ResizeVolumePayload(newSize, newMinIops, newMaxIops, shrinkOk, instanceName, hosts);
try {
VolumeInfo vol = volFactory.getVolume(volume.getId());
vol.addPayload(payload);
StoragePoolVO storagePool = _storagePoolDao.findById(vol.getPoolId());
// managed storage is designed in such a way that the storage plug-in does not
// talk to the hypervisor layer; as such, if the storage is managed and the
// current and new sizes are different, then CloudStack (i.e. not a storage plug-in)
// needs to tell the hypervisor to resize the disk
if (storagePool.isManaged() && currentSize != newSize) {
if (hosts != null && hosts.length > 0) {
volService.resizeVolumeOnHypervisor(volumeId, newSize, hosts[0], instanceName);
}
volume.setSize(newSize);
_volsDao.update(volume.getId(), volume);
}
// this call to resize has a different impact depending on whether the
// underlying primary storage is managed or not
// if managed, this is the chance for the plug-in to change IOPS value, if applicable
// if not managed, this is the chance for the plug-in to talk to the hypervisor layer
// to change the size of the disk
AsyncCallFuture<VolumeApiResult> future = volService.resize(vol);
VolumeApiResult result = future.get();
if (result.isFailed()) {
s_logger.warn("Failed to resize the volume " + volume);
String details = "";
if (result.getResult() != null && !result.getResult().isEmpty()) {
details = result.getResult();
}
throw new CloudRuntimeException(details);
}
volume = _volsDao.findById(volume.getId());
if (newDiskOfferingId != null) {
volume.setDiskOfferingId(newDiskOfferingId);
}
_volsDao.update(volume.getId(), volume);
/* Update resource count for the account on primary storage resource */
if (!shrinkOk) {
_resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.primary_storage, volume.isDisplayVolume(), new Long(newSize - currentSize));
} else {
_resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.primary_storage, volume.isDisplayVolume(), new Long(currentSize - newSize));
}
return volume;
} catch (InterruptedException e) {
s_logger.warn("failed get resize volume result", e);
throw new CloudRuntimeException(e.getMessage());
} catch (ExecutionException e) {
s_logger.warn("failed get resize volume result", e);
throw new CloudRuntimeException(e.getMessage());
} catch (Exception e) {
s_logger.warn("failed get resize volume result", e);
throw new CloudRuntimeException(e.getMessage());
}
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_DELETE, eventDescription = "deleting volume")
public boolean deleteVolume(long volumeId, Account caller) throws ConcurrentOperationException {
VolumeVO volume = _volsDao.findById(volumeId);
if (volume == null) {
throw new InvalidParameterValueException("Unable to find volume with ID: " + volumeId);
}
if (!_snapshotMgr.canOperateOnVolume(volume)) {
throw new InvalidParameterValueException("There are snapshot operations in progress on the volume, unable to delete it");
}
_accountMgr.checkAccess(caller, null, true, volume);
if (volume.getInstanceId() != null) {
throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM.");
}
if (volume.getState() == Volume.State.UploadOp) {
VolumeDataStoreVO volumeStore = _volumeStoreDao.findByVolume(volume.getId());
if (volumeStore.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_IN_PROGRESS) {
throw new InvalidParameterValueException("Please specify a volume that is not uploading");
}
}
if (volume.getState() == Volume.State.NotUploaded || volume.getState() == Volume.State.UploadInProgress) {
throw new InvalidParameterValueException("The volume is either getting uploaded or it may be initiated shortly, please wait for it to be completed");
}
try {
if (volume.getState() != Volume.State.Destroy && volume.getState() != Volume.State.Expunging && volume.getState() != Volume.State.Expunged) {
Long instanceId = volume.getInstanceId();
if (!volService.destroyVolume(volume.getId())) {
return false;
}
VMInstanceVO vmInstance = _vmInstanceDao.findById(instanceId);
if (instanceId == null || (vmInstance.getType().equals(VirtualMachine.Type.User))) {
// Decrement the resource count for volumes and primary storage belonging user VM's only
_resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.volume, volume.isDisplayVolume());
}
}
// Mark volume as removed if volume has not been created on primary or secondary
if (volume.getState() == Volume.State.Allocated) {
_volsDao.remove(volumeId);
stateTransitTo(volume, Volume.Event.DestroyRequested);
return true;
}
// expunge volume from primary if volume is on primary
VolumeInfo volOnPrimary = volFactory.getVolume(volume.getId(), DataStoreRole.Primary);
if (volOnPrimary != null) {
s_logger.info("Expunging volume " + volume.getId() + " from primary data store");
AsyncCallFuture<VolumeApiResult> future = volService.expungeVolumeAsync(volOnPrimary);
future.get();
//decrement primary storage count
_resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(), ResourceType.primary_storage.getOrdinal());
}
// expunge volume from secondary if volume is on image store
VolumeInfo volOnSecondary = volFactory.getVolume(volume.getId(), DataStoreRole.Image);
if (volOnSecondary != null) {
s_logger.info("Expunging volume " + volume.getId() + " from secondary data store");
AsyncCallFuture<VolumeApiResult> future2 = volService.expungeVolumeAsync(volOnSecondary);
future2.get();
//decrement secondary storage count
_resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(), ResourceType.secondary_storage.getOrdinal());
}
// delete all cache entries for this volume
List<VolumeInfo> cacheVols = volFactory.listVolumeOnCache(volume.getId());
for (VolumeInfo volOnCache : cacheVols) {
s_logger.info("Delete volume from image cache store: " + volOnCache.getDataStore().getName());
volOnCache.delete();
}
} catch (Exception e) {
s_logger.warn("Failed to expunge volume:", e);
return false;
}
return true;
}
private boolean stateTransitTo(Volume vol, Volume.Event event) throws NoTransitionException {
return _volStateMachine.transitTo(vol, event, null, _volsDao);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_ATTACH, eventDescription = "attaching volume", async = true)
public Volume attachVolumeToVM(AttachVolumeCmd command) {
return attachVolumeToVM(command.getVirtualMachineId(), command.getId(), command.getDeviceId());
}
private Volume orchestrateAttachVolumeToVM(Long vmId, Long volumeId, Long deviceId) {
VolumeInfo volumeToAttach = volFactory.getVolume(volumeId);
if (volumeToAttach.isAttachedVM()) {
throw new CloudRuntimeException("This volume is already attached to a VM.");
}
UserVmVO vm = _userVmDao.findById(vmId);
VolumeVO exstingVolumeOfVm = null;
List<VolumeVO> rootVolumesOfVm = _volsDao.findByInstanceAndType(vmId, Volume.Type.ROOT);
if (rootVolumesOfVm.size() > 1) {
throw new CloudRuntimeException("The VM " + vm.getHostName() + " has more than one ROOT volume and is in an invalid state.");
} else {
if (!rootVolumesOfVm.isEmpty()) {
exstingVolumeOfVm = rootVolumesOfVm.get(0);
} else {
// locate data volume of the vm
List<VolumeVO> diskVolumesOfVm = _volsDao.findByInstanceAndType(vmId, Volume.Type.DATADISK);
for (VolumeVO diskVolume : diskVolumesOfVm) {
if (diskVolume.getState() != Volume.State.Allocated) {
exstingVolumeOfVm = diskVolume;
break;
}
}
}
}
HypervisorType rootDiskHyperType = vm.getHypervisorType();
HypervisorType volumeToAttachHyperType = _volsDao.getHypervisorType(volumeToAttach.getId());
VolumeInfo newVolumeOnPrimaryStorage = volumeToAttach;
//don't create volume on primary storage if its being attached to the vm which Root's volume hasn't been created yet
StoragePoolVO destPrimaryStorage = null;
if (exstingVolumeOfVm != null && !exstingVolumeOfVm.getState().equals(Volume.State.Allocated)) {
destPrimaryStorage = _storagePoolDao.findById(exstingVolumeOfVm.getPoolId());
}
boolean volumeOnSecondary = volumeToAttach.getState() == Volume.State.Uploaded;
if (destPrimaryStorage != null && (volumeToAttach.getState() == Volume.State.Allocated || volumeOnSecondary)) {
try {
newVolumeOnPrimaryStorage = _volumeMgr.createVolumeOnPrimaryStorage(vm, volumeToAttach, rootDiskHyperType, destPrimaryStorage);
} catch (NoTransitionException e) {
s_logger.debug("Failed to create volume on primary storage", e);
throw new CloudRuntimeException("Failed to create volume on primary storage", e);
}
}
// reload the volume from db
newVolumeOnPrimaryStorage = volFactory.getVolume(newVolumeOnPrimaryStorage.getId());
boolean moveVolumeNeeded = needMoveVolume(exstingVolumeOfVm, newVolumeOnPrimaryStorage);
if (moveVolumeNeeded) {
PrimaryDataStoreInfo primaryStore = (PrimaryDataStoreInfo)newVolumeOnPrimaryStorage.getDataStore();
if (primaryStore.isLocal()) {
throw new CloudRuntimeException("Failed to attach local data volume " + volumeToAttach.getName() + " to VM " + vm.getDisplayName()
+ " as migration of local data volume is not allowed");
}
StoragePoolVO vmRootVolumePool = _storagePoolDao.findById(exstingVolumeOfVm.getPoolId());
try {
newVolumeOnPrimaryStorage = _volumeMgr.moveVolume(newVolumeOnPrimaryStorage, vmRootVolumePool.getDataCenterId(), vmRootVolumePool.getPodId(),
vmRootVolumePool.getClusterId(), volumeToAttachHyperType);
} catch (ConcurrentOperationException e) {
s_logger.debug("move volume failed", e);
throw new CloudRuntimeException("move volume failed", e);
} catch (StorageUnavailableException e) {
s_logger.debug("move volume failed", e);
throw new CloudRuntimeException("move volume failed", e);
}
}
VolumeVO newVol = _volsDao.findById(newVolumeOnPrimaryStorage.getId());
// Getting the fresh vm object in case of volume migration to check the current state of VM
if (moveVolumeNeeded || volumeOnSecondary) {
vm = _userVmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("VM not found.");
}
}
newVol = sendAttachVolumeCommand(vm, newVol, deviceId);
return newVol;
}
public Volume attachVolumeToVM(Long vmId, Long volumeId, Long deviceId) {
Account caller = CallContext.current().getCallingAccount();
// Check that the volume ID is valid
VolumeInfo volumeToAttach = volFactory.getVolume(volumeId);
// Check that the volume is a data volume
if (volumeToAttach == null || !(volumeToAttach.getVolumeType() == Volume.Type.DATADISK || volumeToAttach.getVolumeType() == Volume.Type.ROOT)) {
throw new InvalidParameterValueException("Please specify a volume with the valid type: " + Volume.Type.ROOT.toString() + " or " + Volume.Type.DATADISK.toString());
}
// Check that the volume is not currently attached to any VM
if (volumeToAttach.getInstanceId() != null) {
throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM.");
}
// Check that the volume is not destroyed
if (volumeToAttach.getState() == Volume.State.Destroy) {
throw new InvalidParameterValueException("Please specify a volume that is not destroyed.");
}
// Check that the virtual machine ID is valid and it's a user vm
UserVmVO vm = _userVmDao.findById(vmId);
if (vm == null || vm.getType() != VirtualMachine.Type.User) {
throw new InvalidParameterValueException("Please specify a valid User VM.");
}
// Check that the VM is in the correct state
if (vm.getState() != State.Running && vm.getState() != State.Stopped) {
throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.");
}
// Check that the VM and the volume are in the same zone
if (vm.getDataCenterId() != volumeToAttach.getDataCenterId()) {
throw new InvalidParameterValueException("Please specify a VM that is in the same zone as the volume.");
}
// Check that the device ID is valid
if (deviceId != null) {
// validate ROOT volume type
if (deviceId.longValue() == 0) {
validateRootVolumeDetachAttach(_volsDao.findById(volumeToAttach.getId()), vm);
// vm shouldn't have any volume with deviceId 0
if (!_volsDao.findByInstanceAndDeviceId(vm.getId(), 0).isEmpty()) {
throw new InvalidParameterValueException("Vm already has root volume attached to it");
}
// volume can't be in Uploaded state
if (volumeToAttach.getState() == Volume.State.Uploaded) {
throw new InvalidParameterValueException("No support for Root volume attach in state " + Volume.State.Uploaded);
}
}
}
// Check that the number of data volumes attached to VM is less than
// that supported by hypervisor
if (deviceId == null || deviceId.longValue() != 0) {
List<VolumeVO> existingDataVolumes = _volsDao.findByInstanceAndType(vmId, Volume.Type.DATADISK);
int maxDataVolumesSupported = getMaxDataVolumesSupported(vm);
if (existingDataVolumes.size() >= maxDataVolumesSupported) {
throw new InvalidParameterValueException("The specified VM already has the maximum number of data disks (" + maxDataVolumesSupported + "). Please specify another VM.");
}
}
// If local storage is disabled then attaching a volume with local disk
// offering not allowed
DataCenterVO dataCenter = _dcDao.findById(volumeToAttach.getDataCenterId());
if (!dataCenter.isLocalStorageEnabled()) {
DiskOfferingVO diskOffering = _diskOfferingDao.findById(volumeToAttach.getDiskOfferingId());
if (diskOffering.getUseLocalStorage()) {
throw new InvalidParameterValueException("Zone is not configured to use local storage but volume's disk offering " + diskOffering.getName() + " uses it");
}
}
// if target VM has associated VM snapshots
List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.findByVm(vmId);
if (vmSnapshots.size() > 0) {
throw new InvalidParameterValueException("Unable to attach volume, please specify a VM that does not have VM snapshots");
}
// permission check
_accountMgr.checkAccess(caller, null, true, volumeToAttach, vm);
if (!(Volume.State.Allocated.equals(volumeToAttach.getState()) || Volume.State.Ready.equals(volumeToAttach.getState()) || Volume.State.Uploaded.equals(volumeToAttach
.getState()))) {
throw new InvalidParameterValueException("Volume state must be in Allocated, Ready or in Uploaded state");
}
HypervisorType rootDiskHyperType = vm.getHypervisorType();
HypervisorType volumeToAttachHyperType = _volsDao.getHypervisorType(volumeToAttach.getId());
StoragePoolVO volumeToAttachStoragePool = _storagePoolDao.findById(volumeToAttach.getPoolId());
// managed storage can be used for different types of hypervisors
// only perform this check if the volume's storage pool is not null and not managed
if (volumeToAttachStoragePool != null && !volumeToAttachStoragePool.isManaged()) {
if (volumeToAttachHyperType != HypervisorType.None && rootDiskHyperType != volumeToAttachHyperType) {
throw new InvalidParameterValueException("Can't attach a volume created by: " + volumeToAttachHyperType + " to a " + rootDiskHyperType + " vm");
}
}
AsyncJobExecutionContext asyncExecutionContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (asyncExecutionContext != null) {
AsyncJob job = asyncExecutionContext.getJob();
if (s_logger.isInfoEnabled()) {
s_logger.info("Trying to attaching volume " + volumeId + " to vm instance:" + vm.getId() + ", update async job-" + job.getId() + " progress status");
}
_jobMgr.updateAsyncJobAttachment(job.getId(), "Volume", volumeId);
}
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
VmWorkJobVO placeHolder = null;
placeHolder = createPlaceHolderWork(vmId);
try {
return orchestrateAttachVolumeToVM(vmId, volumeId, deviceId);
} finally {
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<Volume> outcome = attachVolumeToVmThroughJobQueue(vmId, volumeId, deviceId);
Volume vol = null;
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
if (jobResult != null) {
if (jobResult instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobResult;
else if (jobResult instanceof InvalidParameterValueException)
throw (InvalidParameterValueException)jobResult;
else if (jobResult instanceof RuntimeException)
throw (RuntimeException)jobResult;
else if (jobResult instanceof Throwable)
throw new RuntimeException("Unexpected exception", (Throwable)jobResult);
else if (jobResult instanceof Long) {
vol = _volsDao.findById((Long)jobResult);
}
}
return vol;
}
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_UPDATE, eventDescription = "updating volume", async = true)
public Volume updateVolume(long volumeId, String path, String state, Long storageId, Boolean displayVolume, String customId, long entityOwnerId, String chainInfo) {
VolumeVO volume = _volsDao.findById(volumeId);
if(volume == null)
throw new InvalidParameterValueException("The volume id doesn't exist");
if (path != null) {
volume.setPath(path);
}
if(chainInfo != null){
volume.setChainInfo(chainInfo);
}
if (state != null) {
try {
Volume.State volumeState = Volume.State.valueOf(state);
volume.setState(volumeState);
} catch (IllegalArgumentException ex) {
throw new InvalidParameterValueException("Invalid volume state specified");
}
}
if (storageId != null) {
StoragePool pool = _storagePoolDao.findById(storageId);
if (pool.getDataCenterId() != volume.getDataCenterId()) {
throw new InvalidParameterValueException("Invalid storageId specified; refers to the pool outside of the volume's zone");
}
volume.setPoolId(pool.getId());
}
if (customId != null) {
volume.setUuid(customId);
}
updateDisplay(volume, displayVolume);
_volsDao.update(volumeId, volume);
return volume;
}
@Override
public void updateDisplay(Volume volume, Boolean displayVolume){
// 1. Resource limit changes
updateResourceCount(volume, displayVolume);
// 2. generate usage event if not in destroyed state
saveUsageEvent(volume, displayVolume);
// 3. Set the flag
if (displayVolume != null && displayVolume != volume.isDisplayVolume()){
// FIXME - Confused - typecast for now.
((VolumeVO)volume).setDisplayVolume(displayVolume);
_volsDao.update(volume.getId(), (VolumeVO) volume);
}
}
private void updateResourceCount(Volume volume, Boolean displayVolume){
// Update only when the flag has changed.
if (displayVolume != null && displayVolume != volume.isDisplayVolume()){
_resourceLimitMgr.changeResourceCount(volume.getAccountId(), ResourceType.volume, displayVolume);
_resourceLimitMgr.changeResourceCount(volume.getAccountId(), ResourceType.primary_storage, displayVolume, new Long(volume.getSize()));
}
}
private void saveUsageEvent(Volume volume, Boolean displayVolume){
// Update only when the flag has changed && only when volume in a non-destroyed state.
if ((displayVolume != null && displayVolume != volume.isDisplayVolume()) && !isVolumeDestroyed(volume)){
if (displayVolume){
// flag turned 1 equivalent to freshly created volume
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(),
volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize(), Volume.class.getName(), volume.getUuid());
}else {
// flag turned 0 equivalent to deleting a volume
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(),
Volume.class.getName(), volume.getUuid());
}
}
}
private boolean isVolumeDestroyed(Volume volume){
if(volume.getState() == Volume.State.Destroy || volume.getState() == Volume.State.Expunging && volume.getState() == Volume.State.Expunged)
return true;
return false;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_DETACH, eventDescription = "detaching volume", async = true)
public Volume detachVolumeFromVM(DetachVolumeCmd cmmd) {
Account caller = CallContext.current().getCallingAccount();
if ((cmmd.getId() == null && cmmd.getDeviceId() == null && cmmd.getVirtualMachineId() == null)
|| (cmmd.getId() != null && (cmmd.getDeviceId() != null || cmmd.getVirtualMachineId() != null))
|| (cmmd.getId() == null && (cmmd.getDeviceId() == null || cmmd.getVirtualMachineId() == null))) {
throw new InvalidParameterValueException("Please provide either a volume id, or a tuple(device id, instance id)");
}
Long volumeId = cmmd.getId();
VolumeVO volume = null;
if (volumeId != null) {
volume = _volsDao.findById(volumeId);
} else {
volume = _volsDao.findByInstanceAndDeviceId(cmmd.getVirtualMachineId(), cmmd.getDeviceId()).get(0);
}
// Check that the volume ID is valid
if (volume == null) {
throw new InvalidParameterValueException("Unable to find volume with ID: " + volumeId);
}
Long vmId = null;
if (cmmd.getVirtualMachineId() == null) {
vmId = volume.getInstanceId();
} else {
vmId = cmmd.getVirtualMachineId();
}
// Permissions check
_accountMgr.checkAccess(caller, null, true, volume);
// Check that the volume is currently attached to a VM
if (vmId == null) {
throw new InvalidParameterValueException("The specified volume is not attached to a VM.");
}
// Check that the VM is in the correct state
UserVmVO vm = _userVmDao.findById(vmId);
if (vm.getState() != State.Running && vm.getState() != State.Stopped && vm.getState() != State.Destroyed) {
throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.");
}
// Check that the volume is a data/root volume
if (!(volume.getVolumeType() == Volume.Type.ROOT || volume.getVolumeType() == Volume.Type.DATADISK)) {
throw new InvalidParameterValueException("Please specify volume of type " + Volume.Type.DATADISK.toString() + " or " + Volume.Type.ROOT.toString());
}
// Root volume detach is allowed for following hypervisors: Xen/KVM/VmWare
if (volume.getVolumeType() == Volume.Type.ROOT) {
validateRootVolumeDetachAttach(volume, vm);
}
// Don't allow detach if target VM has associated VM snapshots
List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.findByVm(vmId);
if (vmSnapshots.size() > 0) {
throw new InvalidParameterValueException("Unable to detach volume, please specify a VM that does not have VM snapshots");
}
AsyncJobExecutionContext asyncExecutionContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (asyncExecutionContext != null) {
AsyncJob job = asyncExecutionContext.getJob();
if (s_logger.isInfoEnabled()) {
s_logger.info("Trying to attaching volume " + volumeId + "to vm instance:" + vm.getId() + ", update async job-" + job.getId() + " progress status");
}
_jobMgr.updateAsyncJobAttachment(job.getId(), "Volume", volumeId);
}
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
VmWorkJobVO placeHolder = null;
placeHolder = createPlaceHolderWork(vmId);
try {
return orchestrateDetachVolumeFromVM(vmId, volumeId);
} finally {
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<Volume> outcome = detachVolumeFromVmThroughJobQueue(vmId, volumeId);
Volume vol = null;
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
if (jobResult != null) {
if (jobResult instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobResult;
else if (jobResult instanceof RuntimeException)
throw (RuntimeException)jobResult;
else if (jobResult instanceof Throwable)
throw new RuntimeException("Unexpected exception", (Throwable)jobResult);
else if (jobResult instanceof Long) {
vol = _volsDao.findById((Long) jobResult);
}
}
return vol;
}
}
private void validateRootVolumeDetachAttach(VolumeVO volume, UserVmVO vm) {
if (!(vm.getHypervisorType() == HypervisorType.XenServer || vm.getHypervisorType() == HypervisorType.VMware)) {
throw new InvalidParameterValueException("Root volume detach is allowed for hypervisor type " + HypervisorType.XenServer + " only");
}
if (!(vm.getState() == State.Stopped) || (vm.getState() == State.Destroyed)) {
throw new InvalidParameterValueException("Root volume detach can happen only when vm is in states: " + State.Stopped.toString() + " or " + State.Destroyed.toString());
}
if (volume.getPoolId() != null) {
StoragePoolVO pool = _storagePoolDao.findById(volume.getPoolId());
if (pool.isManaged()) {
throw new InvalidParameterValueException("Root volume detach is not supported for Managed DataStores");
}
}
}
private Volume orchestrateDetachVolumeFromVM(long vmId, long volumeId) {
Volume volume = _volsDao.findById(volumeId);
VMInstanceVO vm = _vmInstanceDao.findById(vmId);
String errorMsg = "Failed to detach volume " + volume.getName() + " from VM " + vm.getHostName();
boolean sendCommand = vm.getState() == State.Running;
Long hostId = vm.getHostId();
if (hostId == null) {
hostId = vm.getLastHostId();
HostVO host = _hostDao.findById(hostId);
if (host != null && host.getHypervisorType() == HypervisorType.VMware) {
sendCommand = true;
}
}
HostVO host = null;
StoragePoolVO volumePool = _storagePoolDao.findByIdIncludingRemoved(volume.getPoolId());
if (hostId != null) {
host = _hostDao.findById(hostId);
if (host != null && host.getHypervisorType() == HypervisorType.XenServer && volumePool != null && volumePool.isManaged()) {
sendCommand = true;
}
}
Answer answer = null;
if (sendCommand) {
DataTO volTO = volFactory.getVolume(volume.getId()).getTO();
DiskTO disk = new DiskTO(volTO, volume.getDeviceId(), volume.getPath(), volume.getVolumeType());
DettachCommand cmd = new DettachCommand(disk, vm.getInstanceName());
cmd.setManaged(volumePool.isManaged());
cmd.setStorageHost(volumePool.getHostAddress());
cmd.setStoragePort(volumePool.getPort());
cmd.set_iScsiName(volume.get_iScsiName());
try {
answer = _agentMgr.send(hostId, cmd);
} catch (Exception e) {
throw new CloudRuntimeException(errorMsg + " due to: " + e.getMessage());
}
}
if (!sendCommand || (answer != null && answer.getResult())) {
// Mark the volume as detached
_volsDao.detachVolume(volume.getId());
// volume.getPoolId() should be null if the VM we are detaching the disk from has never been started before
DataStore dataStore = volume.getPoolId() != null ? dataStoreMgr.getDataStore(volume.getPoolId(), DataStoreRole.Primary) : null;
volService.revokeAccess(volFactory.getVolume(volume.getId()), host, dataStore);
return _volsDao.findById(volumeId);
} else {
if (answer != null) {
String details = answer.getDetails();
if (details != null && !details.isEmpty()) {
errorMsg += "; " + details;
}
}
throw new CloudRuntimeException(errorMsg);
}
}
@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_MIGRATE, eventDescription = "migrating volume", async = true)
public Volume migrateVolume(MigrateVolumeCmd cmd) {
Long volumeId = cmd.getVolumeId();
Long storagePoolId = cmd.getStoragePoolId();
VolumeVO vol = _volsDao.findById(volumeId);
if (vol == null) {
throw new InvalidParameterValueException("Failed to find the volume id: " + volumeId);
}
if (vol.getState() != Volume.State.Ready) {
throw new InvalidParameterValueException("Volume must be in ready state");
}
boolean liveMigrateVolume = false;
Long instanceId = vol.getInstanceId();
Long srcClusterId = null;
VMInstanceVO vm = null;
if (instanceId != null) {
vm = _vmInstanceDao.findById(instanceId);
}
// Check that Vm to which this volume is attached does not have VM Snapshots
if (vm != null && _vmSnapshotDao.findByVm(vm.getId()).size() > 0) {
throw new InvalidParameterValueException("Volume cannot be migrated, please remove all VM snapshots for VM to which this volume is attached");
}
if (vm != null && vm.getState() == State.Running) {
// Check if the VM is GPU enabled.
if(_serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()) != null) {
throw new InvalidParameterValueException("Live Migration of GPU enabled VM is not supported");
}
// Check if the underlying hypervisor supports storage motion.
Long hostId = vm.getHostId();
if (hostId != null) {
HostVO host = _hostDao.findById(hostId);
HypervisorCapabilitiesVO capabilities = null;
if (host != null) {
capabilities = _hypervisorCapabilitiesDao.findByHypervisorTypeAndVersion(host.getHypervisorType(), host.getHypervisorVersion());
srcClusterId = host.getClusterId();
}
if (capabilities != null) {
liveMigrateVolume = capabilities.isStorageMotionSupported();
}
}
// If vm is running, and hypervisor doesn't support live migration, then return error
if (!liveMigrateVolume) {
throw new InvalidParameterValueException("Volume needs to be detached from VM");
}
}
if (liveMigrateVolume && !cmd.isLiveMigrate()) {
throw new InvalidParameterValueException("The volume " + vol + "is attached to a vm and for migrating it " + "the parameter livemigrate should be specified");
}
StoragePool destPool = (StoragePool)dataStoreMgr.getDataStore(storagePoolId, DataStoreRole.Primary);
if (destPool == null) {
throw new InvalidParameterValueException("Failed to find the destination storage pool: " + storagePoolId);
}
if (_volumeMgr.volumeOnSharedStoragePool(vol)) {
if (destPool.isLocal()) {
throw new InvalidParameterValueException("Migration of volume from shared to local storage pool is not supported");
} else {
// If the volume is attached to a running vm and the volume is on a shared storage pool, check
// to make sure that the destination storage pool is in the same cluster as the vm.
if (liveMigrateVolume && destPool.getClusterId() != null && srcClusterId != null) {
if (!srcClusterId.equals(destPool.getClusterId())) {
throw new InvalidParameterValueException("Cannot migrate a volume of a virtual machine to a storage pool in a different cluster");
}
}
// In case of VMware, if ROOT volume is being cold-migrated, then ensure destination storage pool is in the same Datacenter as the VM.
if (vm != null && vm.getHypervisorType().equals(HypervisorType.VMware)) {
if (!liveMigrateVolume && vol.volumeType.equals(Volume.Type.ROOT)) {
Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId();
HostVO host = _hostDao.findById(hostId);
if (host != null)
srcClusterId = host.getClusterId();
if (srcClusterId != null && destPool.getClusterId() != null && !srcClusterId.equals(destPool.getClusterId())) {
String srcDcName = _clusterDetailsDao.getVmwareDcName(srcClusterId);
String destDcName = _clusterDetailsDao.getVmwareDcName(destPool.getClusterId());
if (srcDcName != null && destDcName != null && !srcDcName.equals(destDcName)) {
throw new InvalidParameterValueException("Cannot migrate ROOT volume of a stopped VM to a storage pool in a different VMware datacenter");
}
}
}
}
}
} else {
throw new InvalidParameterValueException("Migration of volume from local storage pool is not supported");
}
if (vm != null) {
// serialize VM operation
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
VmWorkJobVO placeHolder = null;
placeHolder = createPlaceHolderWork(vm.getId());
try {
return orchestrateMigrateVolume(vol.getId(), destPool.getId(), liveMigrateVolume);
} finally {
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<Volume> outcome = migrateVolumeThroughJobQueue(vm.getId(), vol.getId(), destPool.getId(), liveMigrateVolume);
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
if (jobResult != null) {
if (jobResult instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobResult;
else if (jobResult instanceof RuntimeException)
throw (RuntimeException)jobResult;
else if (jobResult instanceof Throwable)
throw new RuntimeException("Unexpected exception", (Throwable)jobResult);
}
// retrieve the migrated new volume from job result
if (jobResult != null && jobResult instanceof Long) {
return _entityMgr.findById(VolumeVO.class, ((Long)jobResult));
}
return null;
}
}
return orchestrateMigrateVolume(vol.getId(), destPool.getId(), liveMigrateVolume);
}
private Volume orchestrateMigrateVolume(long volumeId, long destPoolId, boolean liveMigrateVolume) {
VolumeVO vol = _volsDao.findById(volumeId);
assert (vol != null);
StoragePool destPool = (StoragePool)dataStoreMgr.getDataStore(destPoolId, DataStoreRole.Primary);
assert (destPool != null);
Volume newVol = null;
try {
if (liveMigrateVolume) {
newVol = liveMigrateVolume(vol, destPool);
} else {
newVol = _volumeMgr.migrateVolume(vol, destPool);
}
} catch (StorageUnavailableException e) {
s_logger.debug("Failed to migrate volume", e);
throw new CloudRuntimeException(e.getMessage());
} catch (Exception e) {
s_logger.debug("Failed to migrate volume", e);
throw new CloudRuntimeException(e.getMessage());
}
return newVol;
}
@DB
protected Volume liveMigrateVolume(Volume volume, StoragePool destPool) throws StorageUnavailableException {
VolumeInfo vol = volFactory.getVolume(volume.getId());
AsyncCallFuture<VolumeApiResult> future = volService.migrateVolume(vol, (DataStore)destPool);
try {
VolumeApiResult result = future.get();
if (result.isFailed()) {
s_logger.debug("migrate volume failed:" + result.getResult());
throw new StorageUnavailableException("Migrate volume failed: " + result.getResult(), destPool.getId());
}
return result.getVolume();
} catch (InterruptedException e) {
s_logger.debug("migrate volume failed", e);
throw new CloudRuntimeException(e.getMessage());
} catch (ExecutionException e) {
s_logger.debug("migrate volume failed", e);
throw new CloudRuntimeException(e.getMessage());
}
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_SNAPSHOT_CREATE, eventDescription = "taking snapshot", async = true)
public Snapshot takeSnapshot(Long volumeId, Long policyId, Long snapshotId, Account account, boolean quiescevm) throws ResourceAllocationException {
VolumeInfo volume = volFactory.getVolume(volumeId);
if (volume == null) {
throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
}
if (volume.getState() != Volume.State.Ready) {
throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
}
VMInstanceVO vm = null;
if (volume.getInstanceId() != null)
vm = _vmInstanceDao.findById(volume.getInstanceId());
if (vm != null) {
// serialize VM operation
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
VmWorkJobVO placeHolder = null;
placeHolder = createPlaceHolderWork(vm.getId());
try {
return orchestrateTakeVolumeSnapshot(volumeId, policyId, snapshotId, account, quiescevm);
} finally {
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<Snapshot> outcome = takeVolumeSnapshotThroughJobQueue(vm.getId(), volumeId, policyId, snapshotId, account.getId(), quiescevm);
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
if (jobResult != null) {
if (jobResult instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobResult;
else if (jobResult instanceof ResourceAllocationException)
throw (ResourceAllocationException)jobResult;
else if (jobResult instanceof Throwable)
throw new RuntimeException("Unexpected exception", (Throwable)jobResult);
}
return _snapshotDao.findById(snapshotId);
}
} else {
CreateSnapshotPayload payload = new CreateSnapshotPayload();
payload.setSnapshotId(snapshotId);
payload.setSnapshotPolicyId(policyId);
payload.setAccount(account);
payload.setQuiescevm(quiescevm);
volume.addPayload(payload);
return volService.takeSnapshot(volume);
}
}
private Snapshot orchestrateTakeVolumeSnapshot(Long volumeId, Long policyId, Long snapshotId, Account account, boolean quiescevm)
throws ResourceAllocationException {
VolumeInfo volume = volFactory.getVolume(volumeId);
if (volume == null) {
throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
}
if (volume.getState() != Volume.State.Ready) {
throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
}
CreateSnapshotPayload payload = new CreateSnapshotPayload();
payload.setSnapshotId(snapshotId);
payload.setSnapshotPolicyId(policyId);
payload.setAccount(account);
payload.setQuiescevm(quiescevm);
volume.addPayload(payload);
return volService.takeSnapshot(volume);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_SNAPSHOT_CREATE, eventDescription = "allocating snapshot", create = true)
public Snapshot allocSnapshot(Long volumeId, Long policyId, String snapshotName) throws ResourceAllocationException {
Account caller = CallContext.current().getCallingAccount();
VolumeInfo volume = volFactory.getVolume(volumeId);
if (volume == null) {
throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
}
DataCenter zone = _dcDao.findById(volume.getDataCenterId());
if (zone == null) {
throw new InvalidParameterValueException("Can't find zone by id " + volume.getDataCenterId());
}
if (volume.getInstanceId() != null) {
// Check that Vm to which this volume is attached does not have VM Snapshots
if (_vmSnapshotDao.findByVm(volume.getInstanceId()).size() > 0) {
throw new InvalidParameterValueException("Volume snapshot is not allowed, please detach it from VM with VM Snapshots");
}
}
if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getName());
}
if (volume.getState() != Volume.State.Ready) {
throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
}
if (ImageFormat.DIR.equals(volume.getFormat())){
throw new InvalidParameterValueException("Snapshot not supported for volume:" + volumeId);
}
if (volume.getTemplateId() != null) {
VMTemplateVO template = _templateDao.findById(volume.getTemplateId());
if (template != null && template.getTemplateType() == Storage.TemplateType.SYSTEM) {
throw new InvalidParameterValueException("VolumeId: " + volumeId + " is for System VM , Creating snapshot against System VM volumes is not supported");
}
}
StoragePool storagePool = (StoragePool)volume.getDataStore();
if (storagePool == null) {
throw new InvalidParameterValueException("VolumeId: " + volumeId + " please attach this volume to a VM before create snapshot for it");
}
return snapshotMgr.allocSnapshot(volumeId, policyId, snapshotName);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_EXTRACT, eventDescription = "extracting volume", async = true)
public String extractVolume(ExtractVolumeCmd cmd) {
Long volumeId = cmd.getId();
Long zoneId = cmd.getZoneId();
String mode = cmd.getMode();
Account account = CallContext.current().getCallingAccount();
if (!_accountMgr.isRootAdmin(account.getId()) && ApiDBUtils.isExtractionDisabled()) {
throw new PermissionDeniedException("Extraction has been disabled by admin");
}
VolumeVO volume = _volsDao.findById(volumeId);
if (volume == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId");
ex.addProxyObject(volumeId.toString(), "volumeId");
throw ex;
}
// perform permission check
_accountMgr.checkAccess(account, null, true, volume);
if (_dcDao.findById(zoneId) == null) {
throw new InvalidParameterValueException("Please specify a valid zone.");
}
if (volume.getPoolId() == null) {
throw new InvalidParameterValueException("The volume doesnt belong to a storage pool so cant extract it");
}
// Extract activity only for detached volumes or for volumes whose
// instance is stopped
if (volume.getInstanceId() != null && ApiDBUtils.findVMInstanceById(volume.getInstanceId()).getState() != State.Stopped) {
s_logger.debug("Invalid state of the volume with ID: " + volumeId + ". It should be either detached or the VM should be in stopped state.");
PermissionDeniedException ex = new PermissionDeniedException(
"Invalid state of the volume with specified ID. It should be either detached or the VM should be in stopped state.");
ex.addProxyObject(volume.getUuid(), "volumeId");
throw ex;
}
if (volume.getVolumeType() != Volume.Type.DATADISK) {
// Datadisk dont have any template dependence.
VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
if (template != null) { // For ISO based volumes template = null and
// we allow extraction of all ISO based
// volumes
boolean isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM;
if (!isExtractable && account != null && !_accountMgr.isRootAdmin(account.getId())) {
// Global admins are always allowed to extract
PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted");
ex.addProxyObject(volume.getUuid(), "volumeId");
throw ex;
}
}
}
if (mode == null || (!mode.equals(Upload.Mode.FTP_UPLOAD.toString()) && !mode.equals(Upload.Mode.HTTP_DOWNLOAD.toString()))) {
throw new InvalidParameterValueException("Please specify a valid extract Mode ");
}
// Check if the url already exists
VolumeDataStoreVO volumeStoreRef = _volumeStoreDao.findByVolume(volumeId);
if (volumeStoreRef != null && volumeStoreRef.getExtractUrl() != null) {
return volumeStoreRef.getExtractUrl();
}
VMInstanceVO vm = null;
if (volume.getInstanceId() != null) {
vm = _vmInstanceDao.findById(volume.getInstanceId());
}
if (vm != null) {
// serialize VM operation
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
VmWorkJobVO placeHolder = null;
placeHolder = createPlaceHolderWork(vm.getId());
try {
return orchestrateExtractVolume(volume.getId(), zoneId);
} finally {
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<String> outcome = extractVolumeThroughJobQueue(vm.getId(), volume.getId(), zoneId);
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
if (jobResult != null) {
if (jobResult instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobResult;
else if (jobResult instanceof RuntimeException)
throw (RuntimeException)jobResult;
else if (jobResult instanceof Throwable)
throw new RuntimeException("Unexpected exception", (Throwable)jobResult);
}
// retrieve the entity url from job result
if (jobResult != null && jobResult instanceof String) {
return (String)jobResult;
}
return null;
}
}
return orchestrateExtractVolume(volume.getId(), zoneId);
}
private String orchestrateExtractVolume(long volumeId, long zoneId) {
// get latest volume state to make sure that it is not updated by other parallel operations
VolumeVO volume = _volsDao.findById(volumeId);
if (volume == null || volume.getState() != Volume.State.Ready) {
throw new InvalidParameterValueException("Volume to be extracted has been removed or not in right state!");
}
// perform extraction
ImageStoreEntity secStore = (ImageStoreEntity)dataStoreMgr.getImageStore(zoneId);
String value = _configDao.getValue(Config.CopyVolumeWait.toString());
NumbersUtil.parseInt(value, Integer.parseInt(Config.CopyVolumeWait.getDefaultValue()));
// Copy volume from primary to secondary storage
VolumeInfo srcVol = volFactory.getVolume(volumeId);
AsyncCallFuture<VolumeApiResult> cvAnswer = volService.copyVolume(srcVol, secStore);
// Check if you got a valid answer.
VolumeApiResult cvResult = null;
try {
cvResult = cvAnswer.get();
} catch (InterruptedException e1) {
s_logger.debug("failed copy volume", e1);
throw new CloudRuntimeException("Failed to copy volume", e1);
} catch (ExecutionException e1) {
s_logger.debug("failed copy volume", e1);
throw new CloudRuntimeException("Failed to copy volume", e1);
}
if (cvResult == null || cvResult.isFailed()) {
String errorString = "Failed to copy the volume from the source primary storage pool to secondary storage.";
throw new CloudRuntimeException(errorString);
}
VolumeInfo vol = cvResult.getVolume();
String extractUrl = secStore.createEntityExtractUrl(vol.getPath(), vol.getFormat(), vol);
VolumeDataStoreVO volumeStoreRef = _volumeStoreDao.findByVolume(volumeId);
volumeStoreRef.setExtractUrl(extractUrl);
volumeStoreRef.setExtractUrlCreated(DateUtil.now());
_volumeStoreDao.update(volumeStoreRef.getId(), volumeStoreRef);
return extractUrl;
}
@Override
public boolean isDisplayResourceEnabled(Long id) {
Volume volume = _volsDao.findById(id);
if (volume == null) {
return true; // bad id given, default to true
}
return volume.isDisplayVolume();
}
private String getFormatForPool(StoragePool pool) {
ClusterVO cluster = ApiDBUtils.findClusterById(pool.getClusterId());
if (cluster.getHypervisorType() == HypervisorType.XenServer) {
return "vhd";
} else if (cluster.getHypervisorType() == HypervisorType.KVM) {
return "qcow2";
} else if (cluster.getHypervisorType() == HypervisorType.Hyperv) {
return "vhdx";
} else if (cluster.getHypervisorType() == HypervisorType.VMware) {
return "ova";
} else if (cluster.getHypervisorType() == HypervisorType.Ovm) {
return "raw";
} else {
return null;
}
}
private boolean needMoveVolume(VolumeVO existingVolume, VolumeInfo newVolume) {
if (existingVolume == null || existingVolume.getPoolId() == null || newVolume.getPoolId() == null) {
return false;
}
DataStore storeForExistingVol = dataStoreMgr.getPrimaryDataStore(existingVolume.getPoolId());
DataStore storeForNewVol = dataStoreMgr.getPrimaryDataStore(newVolume.getPoolId());
Scope storeForExistingStoreScope = storeForExistingVol.getScope();
if (storeForExistingStoreScope == null) {
throw new CloudRuntimeException("Can't get scope of data store: " + storeForExistingVol.getId());
}
Scope storeForNewStoreScope = storeForNewVol.getScope();
if (storeForNewStoreScope == null) {
throw new CloudRuntimeException("Can't get scope of data store: " + storeForNewVol.getId());
}
if (storeForNewStoreScope.getScopeType() == ScopeType.ZONE) {
return false;
}
if (storeForExistingStoreScope.getScopeType() != storeForNewStoreScope.getScopeType()) {
if (storeForNewStoreScope.getScopeType() == ScopeType.CLUSTER) {
Long vmClusterId = null;
if (storeForExistingStoreScope.getScopeType() == ScopeType.HOST) {
HostScope hs = (HostScope)storeForExistingStoreScope;
vmClusterId = hs.getClusterId();
} else if (storeForExistingStoreScope.getScopeType() == ScopeType.ZONE) {
Long hostId = _vmInstanceDao.findById(existingVolume.getInstanceId()).getHostId();
if (hostId != null) {
HostVO host = _hostDao.findById(hostId);
vmClusterId = host.getClusterId();
}
}
if (storeForNewStoreScope.getScopeId().equals(vmClusterId)) {
return false;
} else {
return true;
}
} else if (storeForNewStoreScope.getScopeType() == ScopeType.HOST
&& (storeForExistingStoreScope.getScopeType() == ScopeType.CLUSTER || storeForExistingStoreScope.getScopeType() == ScopeType.ZONE)) {
Long hostId = _vmInstanceDao.findById(existingVolume.getInstanceId()).getHostId();
if (storeForNewStoreScope.getScopeId().equals(hostId)) {
return false;
}
}
throw new InvalidParameterValueException("Can't move volume between scope: " + storeForNewStoreScope.getScopeType() + " and " + storeForExistingStoreScope.getScopeType());
}
return !storeForExistingStoreScope.isSameScope(storeForNewStoreScope);
}
private VolumeVO sendAttachVolumeCommand(UserVmVO vm, VolumeVO volumeToAttach, Long deviceId) {
String errorMsg = "Failed to attach volume " + volumeToAttach.getName() + " to VM " + vm.getHostName();
boolean sendCommand = vm.getState() == State.Running;
AttachAnswer answer = null;
Long hostId = vm.getHostId();
if (hostId == null) {
hostId = vm.getLastHostId();
HostVO host = _hostDao.findById(hostId);
if (host != null && host.getHypervisorType() == HypervisorType.VMware) {
sendCommand = true;
}
}
HostVO host = null;
StoragePoolVO volumeToAttachStoragePool = _storagePoolDao.findById(volumeToAttach.getPoolId());
if (hostId != null) {
host = _hostDao.findById(hostId);
if (host != null && host.getHypervisorType() == HypervisorType.XenServer && volumeToAttachStoragePool != null && volumeToAttachStoragePool.isManaged()) {
sendCommand = true;
}
}
// volumeToAttachStoragePool should be null if the VM we are attaching the disk to has never been started before
DataStore dataStore = volumeToAttachStoragePool != null ? dataStoreMgr.getDataStore(volumeToAttachStoragePool.getId(), DataStoreRole.Primary) : null;
// if we don't have a host, the VM we are attaching the disk to has never been started before
if (host != null) {
try {
volService.grantAccess(volFactory.getVolume(volumeToAttach.getId()), host, dataStore);
}
catch (Exception e) {
volService.revokeAccess(volFactory.getVolume(volumeToAttach.getId()), host, dataStore);
throw new CloudRuntimeException(e.getMessage());
}
}
if (sendCommand) {
if (host != null && host.getHypervisorType() == HypervisorType.KVM &&
volumeToAttachStoragePool.isManaged() &&
volumeToAttach.getPath() == null) {
volumeToAttach.setPath(volumeToAttach.get_iScsiName());
_volsDao.update(volumeToAttach.getId(), volumeToAttach);
}
DataTO volTO = volFactory.getVolume(volumeToAttach.getId()).getTO();
deviceId = getDeviceId(vm.getId(), deviceId);
DiskTO disk = new DiskTO(volTO, deviceId, volumeToAttach.getPath(), volumeToAttach.getVolumeType());
AttachCommand cmd = new AttachCommand(disk, vm.getInstanceName());
ChapInfo chapInfo = volService.getChapInfo(volFactory.getVolume(volumeToAttach.getId()), dataStore);
Map<String, String> details = new HashMap<String, String>();
disk.setDetails(details);
details.put(DiskTO.MANAGED, String.valueOf(volumeToAttachStoragePool.isManaged()));
details.put(DiskTO.STORAGE_HOST, volumeToAttachStoragePool.getHostAddress());
details.put(DiskTO.STORAGE_PORT, String.valueOf(volumeToAttachStoragePool.getPort()));
details.put(DiskTO.VOLUME_SIZE, String.valueOf(volumeToAttach.getSize()));
details.put(DiskTO.IQN, volumeToAttach.get_iScsiName());
details.put(DiskTO.MOUNT_POINT, volumeToAttach.get_iScsiName());
details.put(DiskTO.PROTOCOL_TYPE, (volumeToAttach.getPoolType() != null) ? volumeToAttach.getPoolType().toString() : null);
if (chapInfo != null) {
details.put(DiskTO.CHAP_INITIATOR_USERNAME, chapInfo.getInitiatorUsername());
details.put(DiskTO.CHAP_INITIATOR_SECRET, chapInfo.getInitiatorSecret());
details.put(DiskTO.CHAP_TARGET_USERNAME, chapInfo.getTargetUsername());
details.put(DiskTO.CHAP_TARGET_SECRET, chapInfo.getTargetSecret());
}
try {
answer = (AttachAnswer)_agentMgr.send(hostId, cmd);
} catch (Exception e) {
if(host!=null) {
volService.revokeAccess(volFactory.getVolume(volumeToAttach.getId()), host, dataStore);
}
throw new CloudRuntimeException(errorMsg + " due to: " + e.getMessage());
}
}
if (!sendCommand || (answer != null && answer.getResult())) {
// Mark the volume as attached
if (sendCommand) {
DiskTO disk = answer.getDisk();
_volsDao.attachVolume(volumeToAttach.getId(), vm.getId(), disk.getDiskSeq());
volumeToAttach = _volsDao.findById(volumeToAttach.getId());
if (volumeToAttachStoragePool.isManaged() && volumeToAttach.getPath() == null) {
volumeToAttach.setPath(answer.getDisk().getPath());
_volsDao.update(volumeToAttach.getId(), volumeToAttach);
}
} else {
deviceId = getDeviceId(vm.getId(), deviceId);
_volsDao.attachVolume(volumeToAttach.getId(), vm.getId(), deviceId);
}
// insert record for disk I/O statistics
VmDiskStatisticsVO diskstats = _vmDiskStatsDao.findBy(vm.getAccountId(), vm.getDataCenterId(), vm.getId(), volumeToAttach.getId());
if (diskstats == null) {
diskstats = new VmDiskStatisticsVO(vm.getAccountId(), vm.getDataCenterId(), vm.getId(), volumeToAttach.getId());
_vmDiskStatsDao.persist(diskstats);
}
return _volsDao.findById(volumeToAttach.getId());
} else {
if (answer != null) {
String details = answer.getDetails();
if (details != null && !details.isEmpty()) {
errorMsg += "; " + details;
}
}
if(host!= null) {
volService.revokeAccess(volFactory.getVolume(volumeToAttach.getId()), host, dataStore);
}
throw new CloudRuntimeException(errorMsg);
}
}
private int getMaxDataVolumesSupported(UserVmVO vm) {
Long hostId = vm.getHostId();
if (hostId == null) {
hostId = vm.getLastHostId();
}
HostVO host = _hostDao.findById(hostId);
Integer maxDataVolumesSupported = null;
if (host != null) {
_hostDao.loadDetails(host);
maxDataVolumesSupported = _hypervisorCapabilitiesDao.getMaxDataVolumesLimit(host.getHypervisorType(), host.getDetail("product_version"));
}
if (maxDataVolumesSupported == null) {
maxDataVolumesSupported = 6; // 6 data disks by default if nothing
// is specified in
// 'hypervisor_capabilities' table
}
return maxDataVolumesSupported.intValue();
}
private Long getDeviceId(long vmId, Long deviceId) {
// allocate deviceId
List<VolumeVO> vols = _volsDao.findByInstance(vmId);
if (deviceId != null) {
if (deviceId.longValue() > 15 || deviceId.longValue() == 3) {
throw new RuntimeException("deviceId should be 1,2,4-15");
}
for (VolumeVO vol : vols) {
if (vol.getDeviceId().equals(deviceId)) {
throw new RuntimeException("deviceId " + deviceId + " is used by vm" + vmId);
}
}
} else {
// allocate deviceId here
List<String> devIds = new ArrayList<String>();
for (int i = 1; i < 15; i++) {
devIds.add(String.valueOf(i));
}
devIds.remove("3");
for (VolumeVO vol : vols) {
devIds.remove(vol.getDeviceId().toString().trim());
}
deviceId = Long.parseLong(devIds.iterator().next());
}
return deviceId;
}
@Override
public boolean configure(String name, Map<String, Object> params) {
String maxVolumeSizeInGbString = _configDao.getValue(Config.MaxVolumeSize.toString());
_maxVolumeSizeInGb = NumbersUtil.parseLong(maxVolumeSizeInGbString, 2000);
return true;
}
public List<StoragePoolAllocator> getStoragePoolAllocators() {
return _storagePoolAllocators;
}
@Inject
public void setStoragePoolAllocators(List<StoragePoolAllocator> storagePoolAllocators) {
_storagePoolAllocators = storagePoolAllocators;
}
public class VmJobVolumeUrlOutcome extends OutcomeImpl<String> {
public VmJobVolumeUrlOutcome(final AsyncJob job) {
super(String.class, job, VmJobCheckInterval.value(), new Predicate() {
@Override
public boolean checkCondition() {
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId());
assert (jobVo != null);
if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS)
return true;
return false;
}
}, AsyncJob.Topics.JOB_STATE);
}
}
public class VmJobVolumeOutcome extends OutcomeImpl<Volume> {
private long _volumeId;
public VmJobVolumeOutcome(final AsyncJob job, final long volumeId) {
super(Volume.class, job, VmJobCheckInterval.value(), new Predicate() {
@Override
public boolean checkCondition() {
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId());
assert (jobVo != null);
if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS)
return true;
return false;
}
}, AsyncJob.Topics.JOB_STATE);
_volumeId = volumeId;
}
@Override
protected Volume retrieve() {
return _volsDao.findById(_volumeId);
}
}
public class VmJobSnapshotOutcome extends OutcomeImpl<Snapshot> {
private long _snapshotId;
public VmJobSnapshotOutcome(final AsyncJob job, final long snapshotId) {
super(Snapshot.class, job, VmJobCheckInterval.value(), new Predicate() {
@Override
public boolean checkCondition() {
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId());
assert (jobVo != null);
if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS)
return true;
return false;
}
}, AsyncJob.Topics.JOB_STATE);
_snapshotId = snapshotId;
}
@Override
protected Snapshot retrieve() {
return _snapshotDao.findById(_snapshotId);
}
}
public Outcome<Volume> attachVolumeToVmThroughJobQueue(final Long vmId, final Long volumeId, final Long deviceId) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
final Account callingAccount = context.getCallingAccount();
final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkAttachVolume.class.getName());
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
// save work context info (there are some duplications)
VmWorkAttachVolume workInfo = new VmWorkAttachVolume(callingUser.getId(), callingAccount.getId(), vm.getId(),
VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, deviceId);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
AsyncJobVO jobVo = _jobMgr.getAsyncJob(workJob.getId());
s_logger.debug("New job " + workJob.getId() + ", result field: " + jobVo.getResult());
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
return new VmJobVolumeOutcome(workJob, volumeId);
}
public Outcome<Volume> detachVolumeFromVmThroughJobQueue(final Long vmId, final Long volumeId) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
final Account callingAccount = context.getCallingAccount();
final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkDetachVolume.class.getName());
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
// save work context info (there are some duplications)
VmWorkDetachVolume workInfo = new VmWorkDetachVolume(callingUser.getId(), callingAccount.getId(), vm.getId(),
VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
return new VmJobVolumeOutcome(workJob, volumeId);
}
public Outcome<Volume> resizeVolumeThroughJobQueue(final Long vmId, final long volumeId,
final long currentSize, final long newSize, final Long newMinIops, final Long newMaxIops, final Long newServiceOfferingId, final boolean shrinkOk) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
final Account callingAccount = context.getCallingAccount();
final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkResizeVolume.class.getName());
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
// save work context info (there are some duplications)
VmWorkResizeVolume workInfo = new VmWorkResizeVolume(callingUser.getId(), callingAccount.getId(), vm.getId(),
VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, currentSize, newSize, newMinIops, newMaxIops, newServiceOfferingId, shrinkOk);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
return new VmJobVolumeOutcome(workJob,volumeId);
}
public Outcome<String> extractVolumeThroughJobQueue(final Long vmId, final long volumeId,
final long zoneId) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
final Account callingAccount = context.getCallingAccount();
final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkExtractVolume.class.getName());
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
// save work context info (there are some duplications)
VmWorkExtractVolume workInfo = new VmWorkExtractVolume(callingUser.getId(), callingAccount.getId(), vm.getId(),
VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, zoneId);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
return new VmJobVolumeUrlOutcome(workJob);
}
public Outcome<Volume> migrateVolumeThroughJobQueue(final Long vmId, final long volumeId,
final long destPoolId, final boolean liveMigrate) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
final Account callingAccount = context.getCallingAccount();
final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkMigrateVolume.class.getName());
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
// save work context info (there are some duplications)
VmWorkMigrateVolume workInfo = new VmWorkMigrateVolume(callingUser.getId(), callingAccount.getId(), vm.getId(),
VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, destPoolId, liveMigrate);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
return new VmJobVolumeOutcome(workJob,volumeId);
}
public Outcome<Snapshot> takeVolumeSnapshotThroughJobQueue(final Long vmId, final Long volumeId,
final Long policyId, final Long snapshotId, final Long accountId, final boolean quiesceVm) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
final Account callingAccount = context.getCallingAccount();
final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkTakeVolumeSnapshot.class.getName());
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
// save work context info (there are some duplications)
VmWorkTakeVolumeSnapshot workInfo = new VmWorkTakeVolumeSnapshot(
callingUser.getId(), accountId != null ? accountId : callingAccount.getId(), vm.getId(),
VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, policyId, snapshotId, quiesceVm);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
return new VmJobSnapshotOutcome(workJob,snapshotId);
}
@ReflectionUse
private Pair<JobInfo.Status, String> orchestrateExtractVolume(VmWorkExtractVolume work) throws Exception {
String volUrl = orchestrateExtractVolume(work.getVolumeId(), work.getZoneId());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, _jobMgr.marshallResultObject(volUrl));
}
@ReflectionUse
private Pair<JobInfo.Status, String> orchestrateAttachVolumeToVM(VmWorkAttachVolume work) throws Exception {
Volume vol = orchestrateAttachVolumeToVM(work.getVmId(), work.getVolumeId(), work.getDeviceId());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED,
_jobMgr.marshallResultObject(new Long(vol.getId())));
}
@ReflectionUse
private Pair<JobInfo.Status, String> orchestrateDetachVolumeFromVM(VmWorkDetachVolume work) throws Exception {
Volume vol = orchestrateDetachVolumeFromVM(work.getVmId(), work.getVolumeId());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED,
_jobMgr.marshallResultObject(new Long(vol.getId())));
}
@ReflectionUse
private Pair<JobInfo.Status, String> orchestrateResizeVolume(VmWorkResizeVolume work) throws Exception {
Volume vol = orchestrateResizeVolume(work.getVolumeId(), work.getCurrentSize(), work.getNewSize(), work.getNewMinIops(), work.getNewMaxIops(),
work.getNewServiceOfferingId(), work.isShrinkOk());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED,
_jobMgr.marshallResultObject(new Long(vol.getId())));
}
@ReflectionUse
private Pair<JobInfo.Status, String> orchestrateMigrateVolume(VmWorkMigrateVolume work) throws Exception {
Volume newVol = orchestrateMigrateVolume(work.getVolumeId(), work.getDestPoolId(), work.isLiveMigrate());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED,
_jobMgr.marshallResultObject(new Long(newVol.getId())));
}
@ReflectionUse
private Pair<JobInfo.Status, String> orchestrateTakeVolumeSnapshot(VmWorkTakeVolumeSnapshot work) throws Exception {
Account account = _accountDao.findById(work.getAccountId());
orchestrateTakeVolumeSnapshot(work.getVolumeId(), work.getPolicyId(), work.getSnapshotId(),
account, work.isQuiesceVm());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED,
_jobMgr.marshallResultObject(work.getSnapshotId()));
}
@Override
public Pair<JobInfo.Status, String> handleVmWorkJob(VmWork work) throws Exception {
return _jobHandlerProxy.handleVmWorkJob(work);
}
private VmWorkJobVO createPlaceHolderWork(long instanceId) {
VmWorkJobVO workJob = new VmWorkJobVO("");
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_PLACEHOLDER);
workJob.setCmd("");
workJob.setCmdInfo("");
workJob.setAccountId(0);
workJob.setUserId(0);
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(instanceId);
workJob.setInitMsid(ManagementServerNode.getManagementServerId());
_workJobDao.persist(workJob);
return workJob;
}
}
| CID 1338016: multi catch instead of pokemon
| server/src/com/cloud/storage/VolumeApiServiceImpl.java | CID 1338016: multi catch instead of pokemon | <ide><path>erver/src/com/cloud/storage/VolumeApiServiceImpl.java
<ide> volOnCache.delete();
<ide> }
<ide>
<del> } catch (Exception e) {
<add> } catch (InterruptedException | ExecutionException | NoTransitionException e) {
<ide> s_logger.warn("Failed to expunge volume:", e);
<ide> return false;
<ide> } |
|
Java | mit | 7ac6ee90b90c8a2bc321a92e2243aa2f7836f0d9 | 0 | nulab/zxcvbn4j | package com.nulabinc.zxcvbn;
import java.math.BigDecimal;
public class TimeEstimates {
public static AttackTimes estimateAttackTimes(double guesses) {
AttackTimes.CrackTimeSeconds crackTimeSeconds = new AttackTimes.CrackTimeSeconds(
divide(guesses, 100.0 / 3600.0),
guesses / 10,
guesses / 1e4,
guesses / 1e10
);
AttackTimes.CrackTimesDisplay crackTimesDisplay = new AttackTimes.CrackTimesDisplay(
displayTime(crackTimeSeconds.getOnlineThrottling100perHour()),
displayTime(crackTimeSeconds.getOnlineNoThrottling10perSecond()),
displayTime(crackTimeSeconds.getOfflineSlowHashing1e4perSecond()),
displayTime(crackTimeSeconds.getOfflineFastHashing1e10PerSecond())
);
return new AttackTimes(crackTimeSeconds, crackTimesDisplay, guessesToScore(guesses));
}
public static int guessesToScore(double guesses) {
int DELTA = 5;
if (guesses < 1e3 + DELTA) return 0;
else if (guesses < 1e6 + DELTA) return 1;
else if (guesses < 1e8 + DELTA) return 2;
else if (guesses < 1e10 + DELTA) return 3;
else return 4;
}
public static String displayTime(final double seconds) {
final Double minute = 60.0;
final Double hour = minute * 60;
final Double day = hour * 24;
final Double month = day * 31;
final Double year = month * 12;
final Double century = year * 100;
if (seconds < 1) return format(null, "less than a second");
else if (seconds < minute) return format(seconds, "%s seconds");
else if (seconds < hour) return format(divide(seconds, minute), "%s minute");
else if (seconds < day) return format(divide(seconds, hour), "%s hour");
else if (seconds < month) return format(divide(seconds, day), "%s day");
else if (seconds < year) return format(divide(seconds, month), "%s monty");
else if (seconds < century) return format(divide(seconds, year), "%s year");
else return format(null, "centuries");
}
private static String format(Double number, String text) {
if (number != null) {
text = String.format(text, Math.round(number)) + (number != 1 ? "s" : "");
}
return text;
}
private static double divide(double dividend, double divisor) {
BigDecimal dividendDecimal = new BigDecimal(dividend);
BigDecimal divisorDecimal = new BigDecimal(divisor);
return dividendDecimal.divide(divisorDecimal, BigDecimal.ROUND_HALF_DOWN).doubleValue();
}
}
| src/main/java/com/nulabinc/zxcvbn/TimeEstimates.java | package com.nulabinc.zxcvbn;
import java.math.BigDecimal;
public class TimeEstimates {
public static AttackTimes estimateAttackTimes(double guesses) {
AttackTimes.CrackTimeSeconds crackTimeSeconds = new AttackTimes.CrackTimeSeconds(
divide(guesses, 100.0 / 3600.0),
guesses / 1e2,
guesses / 1e4,
guesses / 1e10
);
AttackTimes.CrackTimesDisplay crackTimesDisplay = new AttackTimes.CrackTimesDisplay(
displayTime(crackTimeSeconds.getOnlineThrottling100perHour()),
displayTime(crackTimeSeconds.getOnlineNoThrottling10perSecond()),
displayTime(crackTimeSeconds.getOfflineSlowHashing1e4perSecond()),
displayTime(crackTimeSeconds.getOfflineFastHashing1e10PerSecond())
);
return new AttackTimes(crackTimeSeconds, crackTimesDisplay, guessesToScore(guesses));
}
public static int guessesToScore(double guesses) {
int DELTA = 5;
if (guesses < 1e3 + DELTA) return 0;
else if (guesses < 1e6 + DELTA) return 1;
else if (guesses < 1e8 + DELTA) return 2;
else if (guesses < 1e10 + DELTA) return 3;
else return 4;
}
public static String displayTime(final double seconds) {
final Double minute = 60.0;
final Double hour = minute * 60;
final Double day = hour * 24;
final Double month = day * 31;
final Double year = month * 12;
final Double century = year * 100;
if (seconds < 1) return format(null, "less than a second");
else if (seconds < minute) return format(seconds, "%s seconds");
else if (seconds < hour) return format(divide(seconds, minute), "%s minute");
else if (seconds < day) return format(divide(seconds, hour), "%s hour");
else if (seconds < month) return format(divide(seconds, day), "%s day");
else if (seconds < year) return format(divide(seconds, month), "%s monty");
else if (seconds < century) return format(divide(seconds, year), "%s year");
else return format(null, "centuries");
}
private static String format(Double number, String text) {
if (number != null) {
text = String.format(text, Math.round(number)) + (number != 1 ? "s" : "");
}
return text;
}
private static double divide(double dividend, double divisor) {
BigDecimal dividendDecimal = new BigDecimal(dividend);
BigDecimal divisorDecimal = new BigDecimal(divisor);
return dividendDecimal.divide(divisorDecimal, BigDecimal.ROUND_HALF_DOWN).doubleValue();
}
}
| Fix online_no_throttling_10_per_second calculation
Port: https://github.com/dropbox/zxcvbn/commit/e85caca8beb081c2602180a9fb06dd75d5e38c42
| src/main/java/com/nulabinc/zxcvbn/TimeEstimates.java | Fix online_no_throttling_10_per_second calculation Port: https://github.com/dropbox/zxcvbn/commit/e85caca8beb081c2602180a9fb06dd75d5e38c42 | <ide><path>rc/main/java/com/nulabinc/zxcvbn/TimeEstimates.java
<ide> public static AttackTimes estimateAttackTimes(double guesses) {
<ide> AttackTimes.CrackTimeSeconds crackTimeSeconds = new AttackTimes.CrackTimeSeconds(
<ide> divide(guesses, 100.0 / 3600.0),
<del> guesses / 1e2,
<add> guesses / 10,
<ide> guesses / 1e4,
<ide> guesses / 1e10
<ide> ); |
|
Java | bsd-3-clause | c770aae2ce364fcfb17dcfb548a364a13c3a5f57 | 0 | EmilHernvall/tregmine,EmilHernvall/tregmine,Clunker5/tregmine-2.0,EmilHernvall/tregmine,Clunker5/tregmine-2.0 | package info.tregmine;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.InetAddress;
import java.io.File;
import java.io.IOException;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World.Environment;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.world.WorldSaveEvent;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import com.maxmind.geoip.LookupService;
import info.tregmine.api.FishyBlock;
import info.tregmine.api.PlayerBannedException;
import info.tregmine.api.PlayerReport;
import info.tregmine.api.Rank;
import info.tregmine.api.TregminePlayer;
import info.tregmine.database.DAOException;
import info.tregmine.database.IBlessedBlockDAO;
import info.tregmine.database.IContext;
import info.tregmine.database.IContextFactory;
import info.tregmine.database.IFishyBlockDAO;
import info.tregmine.database.IInventoryDAO;
import info.tregmine.database.ILogDAO;
import info.tregmine.database.IPlayerDAO;
import info.tregmine.database.IPlayerReportDAO;
import info.tregmine.database.IZonesDAO;
import info.tregmine.database.db.DBContextFactory;
import info.tregmine.quadtree.IntersectionException;
import info.tregmine.zones.Lot;
import info.tregmine.zones.Zone;
import info.tregmine.zones.ZoneWorld;
import static info.tregmine.database.IInventoryDAO.InventoryType;
import info.tregmine.listeners.*;
import info.tregmine.commands.*;
/**
* @author Ein Andersson
* @author Emil Hernvall
*/
public class Tregmine extends JavaPlugin
{
public final static int VERSION = 0;
public final static int AMOUNT = 0;
public final static Logger LOGGER = Logger.getLogger("Minecraft");
private IContextFactory contextFactory;
private Server server;
private WebServer webServer;
private Map<String, TregminePlayer> players;
private Map<Integer, TregminePlayer> playersById;
private Map<Location, Integer> blessedBlocks;
private Map<Location, FishyBlock> fishyBlocks;
private Map<String, ZoneWorld> worlds;
private Map<Integer, Zone> zones;
private Queue<TregminePlayer> mentors;
private Queue<TregminePlayer> students;
private LookupService cl = null;
@Override
public void onLoad()
{
File folder = getDataFolder();
Tregmine.LOGGER.info("Data folder is: " + folder);
reloadConfig();
FileConfiguration config = getConfig();
contextFactory = new DBContextFactory(config);
// Set up all data structures
players = new HashMap<>();
playersById = new HashMap<>();
mentors = new LinkedList<>();
students = new LinkedList<>();
worlds = new TreeMap<>(
new Comparator<String>() {
@Override
public int compare(String a, String b)
{
return a.compareToIgnoreCase(b);
}
});
zones = new HashMap<>();
Player[] players = getServer().getOnlinePlayers();
for (Player player : players) {
try {
TregminePlayer tp =
addPlayer(player, player.getAddress().getAddress());
if (tp.getRank() == Rank.TOURIST) {
students.offer(tp);
}
} catch (PlayerBannedException e) {
player.kickPlayer(e.getMessage());
}
}
try {
cl = new LookupService(new File(folder,"GeoIPCity.dat"),
LookupService.GEOIP_MEMORY_CACHE);
} catch (IOException e) {
Tregmine.LOGGER.warning("GeoIPCity.dat was not found! " +
"Geo location will not function as expected.");
}
}
@Override
public void onEnable()
{
this.server = getServer();
// Load blessed blocks
try (IContext ctx = contextFactory.createContext()) {
IBlessedBlockDAO blessedBlockDAO = ctx.getBlessedBlockDAO();
this.blessedBlocks = blessedBlockDAO.load(getServer());
LOGGER.info("Loaded " + blessedBlocks.size() + " blessed blocks");
IFishyBlockDAO fishyBlockDAO = ctx.getFishyBlockDAO();
this.fishyBlocks = fishyBlockDAO.loadFishyBlocks(getServer());
LOGGER.info("Loaded " + fishyBlocks.size() + " fishy blocks");
} catch (DAOException e) {
throw new RuntimeException(e);
}
// Set up web server
webServer = new WebServer(this);
webServer.start();
// Register all listeners
PluginManager pluginMgm = server.getPluginManager();
pluginMgm.registerEvents(new BlessedBlockListener(this), this);
pluginMgm.registerEvents(new BoxFillBlockListener(this), this);
pluginMgm.registerEvents(new ChatListener(this), this);
pluginMgm.registerEvents(new CompassListener(this), this);
pluginMgm.registerEvents(new PlayerLookupListener(this), this);
pluginMgm.registerEvents(new SetupListener(this), this);
pluginMgm.registerEvents(new SignColorListener(), this);
pluginMgm.registerEvents(new TabListener(this), this);
pluginMgm.registerEvents(new TauntListener(this), this);
pluginMgm.registerEvents(new TregmineBlockListener(this), this);
pluginMgm.registerEvents(new TregminePlayerListener(this), this);
pluginMgm.registerEvents(new ZoneBlockListener(this), this);
pluginMgm.registerEvents(new ZoneEntityListener(this), this);
pluginMgm.registerEvents(new ZonePlayerListener(this), this);
pluginMgm.registerEvents(new FishyBlockListener(this), this);
pluginMgm.registerEvents(new InventoryListener(this), this);
pluginMgm.registerEvents(new DonationSigns(this), this);
pluginMgm.registerEvents(new ExpListener(this), this);
pluginMgm.registerEvents(new ItemFrameListener(this), this);
pluginMgm.registerEvents(new EggListener(this), this);
// Declaration of all commands
getCommand("admins").setExecutor(
new NotifyCommand(this, "admins") {
@Override
public boolean isTarget(TregminePlayer player)
{
return player.getRank() == Rank.JUNIOR_ADMIN ||
player.getRank() == Rank.SENIOR_ADMIN;
}
});
getCommand("guardians").setExecutor(
new NotifyCommand(this, "guardians") {
@Override
public boolean isTarget(TregminePlayer player)
{
return player.getRank() == Rank.GUARDIAN;
}
});
getCommand("action").setExecutor(new ActionCommand(this));
getCommand("ban").setExecutor(new BanCommand(this));
getCommand("bless").setExecutor(new BlessCommand(this));
getCommand("blockhere").setExecutor(new BlockHereCommand(this));
getCommand("brush").setExecutor(new BrushCommand(this));
getCommand("channel").setExecutor(new ChannelCommand(this));
getCommand("clean").setExecutor(new CleanInventoryCommand(this));
getCommand("cname").setExecutor(new ChangeNameCommand(this));
getCommand("createmob").setExecutor(new CreateMobCommand(this));
getCommand("createwarp").setExecutor(new CreateWarpCommand(this));
getCommand("creative").setExecutor(new GameModeCommand(this, "creative", GameMode.CREATIVE));
getCommand("fill").setExecutor(new FillCommand(this, "fill"));
getCommand("force").setExecutor(new ForceCommand(this));
getCommand("give").setExecutor(new GiveCommand(this));
getCommand("head").setExecutor(new HeadCommand(this));
getCommand("home").setExecutor(new HomeCommand(this));
getCommand("inv").setExecutor(new InventoryCommand(this));
getCommand("item").setExecutor(new ItemCommand(this));
getCommand("keyword").setExecutor(new KeywordCommand(this));
getCommand("kick").setExecutor(new KickCommand(this));
getCommand("lot").setExecutor(new LotCommand(this));
getCommand("lottery").setExecutor(new LotteryCommand(this));
getCommand("mentor").setExecutor(new MentorCommand(this));
getCommand("msg").setExecutor(new MsgCommand(this));
getCommand("newspawn").setExecutor(new NewSpawnCommand(this));
getCommand("normal").setExecutor(new NormalCommand(this));
getCommand("nuke").setExecutor(new NukeCommand(this));
getCommand("password").setExecutor(new PasswordCommand(this));
getCommand("pos").setExecutor(new PositionCommand(this));
getCommand("quitmessage").setExecutor(new QuitMessageCommand(this));
getCommand("regeneratechunk").setExecutor(new RegenerateChunkCommand(this));
getCommand("remitems").setExecutor(new RemItemsCommand(this));
getCommand("report").setExecutor(new ReportCommand(this));
getCommand("say").setExecutor(new SayCommand(this));
getCommand("seen").setExecutor(new SeenCommand(this));
getCommand("sell").setExecutor(new SellCommand(this));
getCommand("sendto").setExecutor(new SendToCommand(this));
getCommand("setbiome").setExecutor(new SetBiomeCommand(this));
getCommand("setspawner").setExecutor(new SetSpawnerCommand(this));
getCommand("spawn").setExecutor(new SpawnCommand(this));
getCommand("summon").setExecutor(new SummonCommand(this));
getCommand("support").setExecutor(new SupportCommand(this));
getCommand("survival").setExecutor(new GameModeCommand(this, "survival", GameMode.SURVIVAL));
getCommand("testfill").setExecutor(new FillCommand(this, "testfill"));
getCommand("time").setExecutor(new TimeCommand(this));
getCommand("town").setExecutor(new ZoneCommand(this, "town"));
getCommand("tp").setExecutor(new TeleportCommand(this));
getCommand("tpshield").setExecutor(new TeleportShieldCommand(this));
getCommand("tpto").setExecutor(new TeleportToCommand(this));
getCommand("trade").setExecutor(new TradeCommand(this));
getCommand("vanish").setExecutor(new VanishCommand(this));
getCommand("wallet").setExecutor(new WalletCommand(this));
getCommand("warn").setExecutor(new WarnCommand(this));
getCommand("warp").setExecutor(new WarpCommand(this));
getCommand("weather").setExecutor(new WeatherCommand(this));
getCommand("who").setExecutor(new WhoCommand(this));
getCommand("zone").setExecutor(new ZoneCommand(this, "zone"));
}
// run when plugin is disabled
@Override
public void onDisable()
{
server.getScheduler().cancelTasks(this);
// Add a record of logout to db for all players
for (TregminePlayer player : getOnlinePlayers()) {
player.sendMessage(ChatColor.AQUA
+ "Tregmine successfully unloaded. Build "
+ getDescription().getVersion());
removePlayer(player);
}
try {
webServer.stop();
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to start web server!", e);
}
}
public WebServer getWebServer()
{
return webServer;
}
public IContextFactory getContextFactory()
{
return contextFactory;
}
public IContext createContext()
throws DAOException
{
return contextFactory.createContext();
}
// ============================================================================
// Data structure accessors
// ============================================================================
public Map<Location, Integer> getBlessedBlocks()
{
return blessedBlocks;
}
public Map<Location, FishyBlock> getFishyBlocks()
{
return fishyBlocks;
}
public Queue<TregminePlayer> getMentorQueue()
{
return mentors;
}
public Queue<TregminePlayer> getStudentQueue()
{
return students;
}
// ============================================================================
// Player methods
// ============================================================================
public void reloadPlayer(TregminePlayer player)
{
try {
addPlayer(player.getDelegate(), player.getAddress().getAddress());
} catch (PlayerBannedException e) {
player.kickPlayer(e.getMessage());
}
}
public List<TregminePlayer> getOnlinePlayers()
{
List<TregminePlayer> players = new ArrayList<>();
for (Player player : server.getOnlinePlayers()) {
players.add(getPlayer(player));
}
return players;
}
public TregminePlayer addPlayer(Player srcPlayer, InetAddress addr)
throws PlayerBannedException
{
if (players.containsKey(srcPlayer.getName())) {
return players.get(srcPlayer.getName());
}
try (IContext ctx = contextFactory.createContext()) {
IPlayerDAO playerDAO = ctx.getPlayerDAO();
TregminePlayer player = playerDAO.getPlayer(srcPlayer.getPlayer());
if (player == null) {
player = playerDAO.createPlayer(srcPlayer);
}
player.removeFlag(TregminePlayer.Flags.SOFTWARNED);
player.removeFlag(TregminePlayer.Flags.HARDWARNED);
IPlayerReportDAO reportDAO = ctx.getPlayerReportDAO();
List<PlayerReport> reports = reportDAO.getReportsBySubject(player);
for (PlayerReport report : reports) {
Date validUntil = report.getValidUntil();
if (validUntil == null) {
continue;
}
if (validUntil.getTime() < System.currentTimeMillis()) {
continue;
}
if (report.getAction() == PlayerReport.Action.SOFTWARN) {
player.setFlag(TregminePlayer.Flags.SOFTWARNED);
}
else if (report.getAction() == PlayerReport.Action.HARDWARN) {
player.setFlag(TregminePlayer.Flags.HARDWARNED);
}
else if (report.getAction() == PlayerReport.Action.BAN) {
throw new PlayerBannedException(report.getMessage());
}
}
if (!"95.141.47.226".equals(addr.getHostAddress())) {
player.setIp(addr.getHostAddress());
player.setHost(addr.getCanonicalHostName());
if (cl != null) {
com.maxmind.geoip.Location l1 = cl.getLocation(player.getIp());
if (l1 != null) {
Tregmine.LOGGER.info(player.getName() + ": " + l1.countryName +
", " + l1.city + ", " + player.getIp() + ", " +
player.getHost());
player.setCountry(l1.countryName);
player.setCity(l1.city);
} else {
Tregmine.LOGGER.info(player.getName() + ": " +
player.getIp() + ", " + player.getHost());
}
} else {
Tregmine.LOGGER.info(player.getName() + ": " +
player.getIp() + ", " + player.getHost());
}
}
int onlinePlayerCount = 0;
Player[] onlinePlayers = getServer().getOnlinePlayers();
if (onlinePlayers != null) {
onlinePlayerCount = onlinePlayers.length;
}
ILogDAO logDAO = ctx.getLogDAO();
logDAO.insertLogin(player, false, onlinePlayerCount);
player.setTemporaryChatName(player.getNameColor()
+ player.getName());
players.put(player.getName(), player);
playersById.put(player.getId(), player);
return player;
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
public void removePlayer(TregminePlayer player)
{
try (IContext ctx = contextFactory.createContext()) {
int onlinePlayerCount = 0;
Player[] onlinePlayers = getServer().getOnlinePlayers();
if (onlinePlayers != null) {
onlinePlayerCount = onlinePlayers.length;
}
ILogDAO logDAO = ctx.getLogDAO();
logDAO.insertLogin(player, true, onlinePlayerCount);
PlayerInventory inv = (PlayerInventory) player.getInventory();
// Insert regular inventory
IInventoryDAO invDAO = ctx.getInventoryDAO();
int invId = invDAO.getInventoryId(player.getId(), InventoryType.PLAYER);
if (invId == -1) {
invId = invDAO.insertInventory(player, null, InventoryType.PLAYER);
}
invDAO.insertStacks(invId, inv.getContents());
// Insert armor inventory
int armorId = invDAO.getInventoryId(player.getId(),
InventoryType.PLAYER_ARMOR);
if (armorId == -1) {
armorId = invDAO.insertInventory(player, null,
InventoryType.PLAYER_ARMOR);
}
invDAO.insertStacks(armorId, inv.getArmorContents());
IPlayerDAO playerDAO = ctx.getPlayerDAO();
playerDAO.updatePlayTime(player);
} catch (DAOException e) {
throw new RuntimeException(e);
}
player.setValid(false);
players.remove(player.getName());
playersById.remove(player.getId());
mentors.remove(player);
students.remove(player);
}
public TregminePlayer getPlayer(String name)
{
return players.get(name);
}
public TregminePlayer getPlayer(Player player)
{
return players.get(player.getName());
}
public TregminePlayer getPlayer(int id)
{
return playersById.get(id);
}
public TregminePlayer getPlayerOffline(String name)
{
if (players.containsKey(name)) {
return players.get(name);
}
try (IContext ctx = contextFactory.createContext()) {
IPlayerDAO playerDAO = ctx.getPlayerDAO();
return playerDAO.getPlayer(name);
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
public TregminePlayer getPlayerOffline(int id)
{
if (playersById.containsKey(id)) {
return playersById.get(id);
}
try (IContext ctx = contextFactory.createContext()) {
IPlayerDAO playerDAO = ctx.getPlayerDAO();
return playerDAO.getPlayer(id);
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
public List<TregminePlayer> matchPlayer(String pattern)
{
List<Player> matches = server.matchPlayer(pattern);
if (matches.size() == 0) {
return new ArrayList<>();
}
List<TregminePlayer> decoratedMatches = new ArrayList<>();
for (Player match : matches) {
TregminePlayer decoratedMatch = getPlayer(match);
if (decoratedMatch == null) {
continue;
}
decoratedMatches.add(decoratedMatch);
}
return decoratedMatches;
}
// ============================================================================
// Zone methods
// ============================================================================
public ZoneWorld getWorld(World world)
{
ZoneWorld zoneWorld = worlds.get(world.getName());
// lazy load zone worlds as required
if (zoneWorld == null) {
try (IContext ctx = contextFactory.createContext()) {
IZonesDAO dao = ctx.getZonesDAO();
zoneWorld = new ZoneWorld(world);
List<Zone> zones = dao.getZones(world.getName());
for (Zone zone : zones) {
try {
zoneWorld.addZone(zone);
this.zones.put(zone.getId(), zone);
} catch (IntersectionException e) {
LOGGER.warning("Failed to load zone " + zone.getName()
+ " with id " + zone.getId() + ".");
}
}
List<Lot> lots = dao.getLots(world.getName());
for (Lot lot : lots) {
try {
zoneWorld.addLot(lot);
} catch (IntersectionException e) {
LOGGER.warning("Failed to load lot " + lot.getName()
+ " with id " + lot.getId() + ".");
}
}
worlds.put(world.getName(), zoneWorld);
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
return zoneWorld;
}
public Zone getZone(int zoneId)
{
return zones.get(zoneId);
}
// ============================================================================
// Auto Save Alert
// ============================================================================
@EventHandler
public void autoSave(WorldSaveEvent event){
Bukkit.broadcastMessage(ChatColor.DARK_RED + "Tregmine is saving, You may experience some slowness.");
}
}
| src/info/tregmine/Tregmine.java | package info.tregmine;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.InetAddress;
import java.io.File;
import java.io.IOException;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World.Environment;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import com.maxmind.geoip.LookupService;
import info.tregmine.api.FishyBlock;
import info.tregmine.api.PlayerBannedException;
import info.tregmine.api.PlayerReport;
import info.tregmine.api.Rank;
import info.tregmine.api.TregminePlayer;
import info.tregmine.database.DAOException;
import info.tregmine.database.IBlessedBlockDAO;
import info.tregmine.database.IContext;
import info.tregmine.database.IContextFactory;
import info.tregmine.database.IFishyBlockDAO;
import info.tregmine.database.IInventoryDAO;
import info.tregmine.database.ILogDAO;
import info.tregmine.database.IPlayerDAO;
import info.tregmine.database.IPlayerReportDAO;
import info.tregmine.database.IZonesDAO;
import info.tregmine.database.db.DBContextFactory;
import info.tregmine.quadtree.IntersectionException;
import info.tregmine.zones.Lot;
import info.tregmine.zones.Zone;
import info.tregmine.zones.ZoneWorld;
import static info.tregmine.database.IInventoryDAO.InventoryType;
import info.tregmine.listeners.*;
import info.tregmine.commands.*;
/**
* @author Ein Andersson
* @author Emil Hernvall
*/
public class Tregmine extends JavaPlugin
{
public final static int VERSION = 0;
public final static int AMOUNT = 0;
public final static Logger LOGGER = Logger.getLogger("Minecraft");
private IContextFactory contextFactory;
private Server server;
private WebServer webServer;
private Map<String, TregminePlayer> players;
private Map<Integer, TregminePlayer> playersById;
private Map<Location, Integer> blessedBlocks;
private Map<Location, FishyBlock> fishyBlocks;
private Map<String, ZoneWorld> worlds;
private Map<Integer, Zone> zones;
private Queue<TregminePlayer> mentors;
private Queue<TregminePlayer> students;
private LookupService cl = null;
@Override
public void onLoad()
{
File folder = getDataFolder();
Tregmine.LOGGER.info("Data folder is: " + folder);
reloadConfig();
FileConfiguration config = getConfig();
contextFactory = new DBContextFactory(config);
// Set up all data structures
players = new HashMap<>();
playersById = new HashMap<>();
mentors = new LinkedList<>();
students = new LinkedList<>();
worlds = new TreeMap<>(
new Comparator<String>() {
@Override
public int compare(String a, String b)
{
return a.compareToIgnoreCase(b);
}
});
zones = new HashMap<>();
Player[] players = getServer().getOnlinePlayers();
for (Player player : players) {
try {
TregminePlayer tp =
addPlayer(player, player.getAddress().getAddress());
if (tp.getRank() == Rank.TOURIST) {
students.offer(tp);
}
} catch (PlayerBannedException e) {
player.kickPlayer(e.getMessage());
}
}
try {
cl = new LookupService(new File(folder,"GeoIPCity.dat"),
LookupService.GEOIP_MEMORY_CACHE);
} catch (IOException e) {
Tregmine.LOGGER.warning("GeoIPCity.dat was not found! " +
"Geo location will not function as expected.");
}
}
@Override
public void onEnable()
{
this.server = getServer();
// Load blessed blocks
try (IContext ctx = contextFactory.createContext()) {
IBlessedBlockDAO blessedBlockDAO = ctx.getBlessedBlockDAO();
this.blessedBlocks = blessedBlockDAO.load(getServer());
LOGGER.info("Loaded " + blessedBlocks.size() + " blessed blocks");
IFishyBlockDAO fishyBlockDAO = ctx.getFishyBlockDAO();
this.fishyBlocks = fishyBlockDAO.loadFishyBlocks(getServer());
LOGGER.info("Loaded " + fishyBlocks.size() + " fishy blocks");
} catch (DAOException e) {
throw new RuntimeException(e);
}
// Set up web server
webServer = new WebServer(this);
webServer.start();
// Register all listeners
PluginManager pluginMgm = server.getPluginManager();
pluginMgm.registerEvents(new BlessedBlockListener(this), this);
pluginMgm.registerEvents(new BoxFillBlockListener(this), this);
pluginMgm.registerEvents(new ChatListener(this), this);
pluginMgm.registerEvents(new CompassListener(this), this);
pluginMgm.registerEvents(new PlayerLookupListener(this), this);
pluginMgm.registerEvents(new SetupListener(this), this);
pluginMgm.registerEvents(new SignColorListener(), this);
pluginMgm.registerEvents(new TabListener(this), this);
pluginMgm.registerEvents(new TauntListener(this), this);
pluginMgm.registerEvents(new TregmineBlockListener(this), this);
pluginMgm.registerEvents(new TregminePlayerListener(this), this);
pluginMgm.registerEvents(new ZoneBlockListener(this), this);
pluginMgm.registerEvents(new ZoneEntityListener(this), this);
pluginMgm.registerEvents(new ZonePlayerListener(this), this);
pluginMgm.registerEvents(new FishyBlockListener(this), this);
pluginMgm.registerEvents(new InventoryListener(this), this);
pluginMgm.registerEvents(new DonationSigns(this), this);
pluginMgm.registerEvents(new ExpListener(this), this);
pluginMgm.registerEvents(new ItemFrameListener(this), this);
pluginMgm.registerEvents(new EggListener(this), this);
// Declaration of all commands
getCommand("admins").setExecutor(
new NotifyCommand(this, "admins") {
@Override
public boolean isTarget(TregminePlayer player)
{
return player.getRank() == Rank.JUNIOR_ADMIN ||
player.getRank() == Rank.SENIOR_ADMIN;
}
});
getCommand("guardians").setExecutor(
new NotifyCommand(this, "guardians") {
@Override
public boolean isTarget(TregminePlayer player)
{
return player.getRank() == Rank.GUARDIAN;
}
});
getCommand("action").setExecutor(new ActionCommand(this));
getCommand("ban").setExecutor(new BanCommand(this));
getCommand("bless").setExecutor(new BlessCommand(this));
getCommand("blockhere").setExecutor(new BlockHereCommand(this));
getCommand("brush").setExecutor(new BrushCommand(this));
getCommand("channel").setExecutor(new ChannelCommand(this));
getCommand("clean").setExecutor(new CleanInventoryCommand(this));
getCommand("cname").setExecutor(new ChangeNameCommand(this));
getCommand("createmob").setExecutor(new CreateMobCommand(this));
getCommand("createwarp").setExecutor(new CreateWarpCommand(this));
getCommand("creative").setExecutor(new GameModeCommand(this, "creative", GameMode.CREATIVE));
getCommand("fill").setExecutor(new FillCommand(this, "fill"));
getCommand("force").setExecutor(new ForceCommand(this));
getCommand("give").setExecutor(new GiveCommand(this));
getCommand("head").setExecutor(new HeadCommand(this));
getCommand("home").setExecutor(new HomeCommand(this));
getCommand("inv").setExecutor(new InventoryCommand(this));
getCommand("item").setExecutor(new ItemCommand(this));
getCommand("keyword").setExecutor(new KeywordCommand(this));
getCommand("kick").setExecutor(new KickCommand(this));
getCommand("lot").setExecutor(new LotCommand(this));
getCommand("lottery").setExecutor(new LotteryCommand(this));
getCommand("mentor").setExecutor(new MentorCommand(this));
getCommand("msg").setExecutor(new MsgCommand(this));
getCommand("newspawn").setExecutor(new NewSpawnCommand(this));
getCommand("normal").setExecutor(new NormalCommand(this));
getCommand("nuke").setExecutor(new NukeCommand(this));
getCommand("password").setExecutor(new PasswordCommand(this));
getCommand("pos").setExecutor(new PositionCommand(this));
getCommand("quitmessage").setExecutor(new QuitMessageCommand(this));
getCommand("regeneratechunk").setExecutor(new RegenerateChunkCommand(this));
getCommand("remitems").setExecutor(new RemItemsCommand(this));
getCommand("report").setExecutor(new ReportCommand(this));
getCommand("say").setExecutor(new SayCommand(this));
getCommand("seen").setExecutor(new SeenCommand(this));
getCommand("sell").setExecutor(new SellCommand(this));
getCommand("sendto").setExecutor(new SendToCommand(this));
getCommand("setbiome").setExecutor(new SetBiomeCommand(this));
getCommand("setspawner").setExecutor(new SetSpawnerCommand(this));
getCommand("spawn").setExecutor(new SpawnCommand(this));
getCommand("summon").setExecutor(new SummonCommand(this));
getCommand("support").setExecutor(new SupportCommand(this));
getCommand("survival").setExecutor(new GameModeCommand(this, "survival", GameMode.SURVIVAL));
getCommand("testfill").setExecutor(new FillCommand(this, "testfill"));
getCommand("time").setExecutor(new TimeCommand(this));
getCommand("town").setExecutor(new ZoneCommand(this, "town"));
getCommand("tp").setExecutor(new TeleportCommand(this));
getCommand("tpshield").setExecutor(new TeleportShieldCommand(this));
getCommand("tpto").setExecutor(new TeleportToCommand(this));
getCommand("trade").setExecutor(new TradeCommand(this));
getCommand("vanish").setExecutor(new VanishCommand(this));
getCommand("wallet").setExecutor(new WalletCommand(this));
getCommand("warn").setExecutor(new WarnCommand(this));
getCommand("warp").setExecutor(new WarpCommand(this));
getCommand("weather").setExecutor(new WeatherCommand(this));
getCommand("who").setExecutor(new WhoCommand(this));
getCommand("zone").setExecutor(new ZoneCommand(this, "zone"));
}
// run when plugin is disabled
@Override
public void onDisable()
{
server.getScheduler().cancelTasks(this);
// Add a record of logout to db for all players
for (TregminePlayer player : getOnlinePlayers()) {
player.sendMessage(ChatColor.AQUA
+ "Tregmine successfully unloaded. Build "
+ getDescription().getVersion());
removePlayer(player);
}
try {
webServer.stop();
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to start web server!", e);
}
}
public WebServer getWebServer()
{
return webServer;
}
public IContextFactory getContextFactory()
{
return contextFactory;
}
public IContext createContext()
throws DAOException
{
return contextFactory.createContext();
}
// ============================================================================
// Data structure accessors
// ============================================================================
public Map<Location, Integer> getBlessedBlocks()
{
return blessedBlocks;
}
public Map<Location, FishyBlock> getFishyBlocks()
{
return fishyBlocks;
}
public Queue<TregminePlayer> getMentorQueue()
{
return mentors;
}
public Queue<TregminePlayer> getStudentQueue()
{
return students;
}
// ============================================================================
// Player methods
// ============================================================================
public void reloadPlayer(TregminePlayer player)
{
try {
addPlayer(player.getDelegate(), player.getAddress().getAddress());
} catch (PlayerBannedException e) {
player.kickPlayer(e.getMessage());
}
}
public List<TregminePlayer> getOnlinePlayers()
{
List<TregminePlayer> players = new ArrayList<>();
for (Player player : server.getOnlinePlayers()) {
players.add(getPlayer(player));
}
return players;
}
public TregminePlayer addPlayer(Player srcPlayer, InetAddress addr)
throws PlayerBannedException
{
if (players.containsKey(srcPlayer.getName())) {
return players.get(srcPlayer.getName());
}
try (IContext ctx = contextFactory.createContext()) {
IPlayerDAO playerDAO = ctx.getPlayerDAO();
TregminePlayer player = playerDAO.getPlayer(srcPlayer.getPlayer());
if (player == null) {
player = playerDAO.createPlayer(srcPlayer);
}
player.removeFlag(TregminePlayer.Flags.SOFTWARNED);
player.removeFlag(TregminePlayer.Flags.HARDWARNED);
IPlayerReportDAO reportDAO = ctx.getPlayerReportDAO();
List<PlayerReport> reports = reportDAO.getReportsBySubject(player);
for (PlayerReport report : reports) {
Date validUntil = report.getValidUntil();
if (validUntil == null) {
continue;
}
if (validUntil.getTime() < System.currentTimeMillis()) {
continue;
}
if (report.getAction() == PlayerReport.Action.SOFTWARN) {
player.setFlag(TregminePlayer.Flags.SOFTWARNED);
}
else if (report.getAction() == PlayerReport.Action.HARDWARN) {
player.setFlag(TregminePlayer.Flags.HARDWARNED);
}
else if (report.getAction() == PlayerReport.Action.BAN) {
throw new PlayerBannedException(report.getMessage());
}
}
if (!"95.141.47.226".equals(addr.getHostAddress())) {
player.setIp(addr.getHostAddress());
player.setHost(addr.getCanonicalHostName());
if (cl != null) {
com.maxmind.geoip.Location l1 = cl.getLocation(player.getIp());
if (l1 != null) {
Tregmine.LOGGER.info(player.getName() + ": " + l1.countryName +
", " + l1.city + ", " + player.getIp() + ", " +
player.getHost());
player.setCountry(l1.countryName);
player.setCity(l1.city);
} else {
Tregmine.LOGGER.info(player.getName() + ": " +
player.getIp() + ", " + player.getHost());
}
} else {
Tregmine.LOGGER.info(player.getName() + ": " +
player.getIp() + ", " + player.getHost());
}
}
int onlinePlayerCount = 0;
Player[] onlinePlayers = getServer().getOnlinePlayers();
if (onlinePlayers != null) {
onlinePlayerCount = onlinePlayers.length;
}
ILogDAO logDAO = ctx.getLogDAO();
logDAO.insertLogin(player, false, onlinePlayerCount);
player.setTemporaryChatName(player.getNameColor()
+ player.getName());
players.put(player.getName(), player);
playersById.put(player.getId(), player);
return player;
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
public void removePlayer(TregminePlayer player)
{
try (IContext ctx = contextFactory.createContext()) {
int onlinePlayerCount = 0;
Player[] onlinePlayers = getServer().getOnlinePlayers();
if (onlinePlayers != null) {
onlinePlayerCount = onlinePlayers.length;
}
ILogDAO logDAO = ctx.getLogDAO();
logDAO.insertLogin(player, true, onlinePlayerCount);
PlayerInventory inv = (PlayerInventory) player.getInventory();
// Insert regular inventory
IInventoryDAO invDAO = ctx.getInventoryDAO();
int invId = invDAO.getInventoryId(player.getId(), InventoryType.PLAYER);
if (invId == -1) {
invId = invDAO.insertInventory(player, null, InventoryType.PLAYER);
}
invDAO.insertStacks(invId, inv.getContents());
// Insert armor inventory
int armorId = invDAO.getInventoryId(player.getId(),
InventoryType.PLAYER_ARMOR);
if (armorId == -1) {
armorId = invDAO.insertInventory(player, null,
InventoryType.PLAYER_ARMOR);
}
invDAO.insertStacks(armorId, inv.getArmorContents());
IPlayerDAO playerDAO = ctx.getPlayerDAO();
playerDAO.updatePlayTime(player);
} catch (DAOException e) {
throw new RuntimeException(e);
}
player.setValid(false);
players.remove(player.getName());
playersById.remove(player.getId());
mentors.remove(player);
students.remove(player);
}
public TregminePlayer getPlayer(String name)
{
return players.get(name);
}
public TregminePlayer getPlayer(Player player)
{
return players.get(player.getName());
}
public TregminePlayer getPlayer(int id)
{
return playersById.get(id);
}
public TregminePlayer getPlayerOffline(String name)
{
if (players.containsKey(name)) {
return players.get(name);
}
try (IContext ctx = contextFactory.createContext()) {
IPlayerDAO playerDAO = ctx.getPlayerDAO();
return playerDAO.getPlayer(name);
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
public TregminePlayer getPlayerOffline(int id)
{
if (playersById.containsKey(id)) {
return playersById.get(id);
}
try (IContext ctx = contextFactory.createContext()) {
IPlayerDAO playerDAO = ctx.getPlayerDAO();
return playerDAO.getPlayer(id);
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
public List<TregminePlayer> matchPlayer(String pattern)
{
List<Player> matches = server.matchPlayer(pattern);
if (matches.size() == 0) {
return new ArrayList<>();
}
List<TregminePlayer> decoratedMatches = new ArrayList<>();
for (Player match : matches) {
TregminePlayer decoratedMatch = getPlayer(match);
if (decoratedMatch == null) {
continue;
}
decoratedMatches.add(decoratedMatch);
}
return decoratedMatches;
}
// ============================================================================
// Zone methods
// ============================================================================
public ZoneWorld getWorld(World world)
{
ZoneWorld zoneWorld = worlds.get(world.getName());
// lazy load zone worlds as required
if (zoneWorld == null) {
try (IContext ctx = contextFactory.createContext()) {
IZonesDAO dao = ctx.getZonesDAO();
zoneWorld = new ZoneWorld(world);
List<Zone> zones = dao.getZones(world.getName());
for (Zone zone : zones) {
try {
zoneWorld.addZone(zone);
this.zones.put(zone.getId(), zone);
} catch (IntersectionException e) {
LOGGER.warning("Failed to load zone " + zone.getName()
+ " with id " + zone.getId() + ".");
}
}
List<Lot> lots = dao.getLots(world.getName());
for (Lot lot : lots) {
try {
zoneWorld.addLot(lot);
} catch (IntersectionException e) {
LOGGER.warning("Failed to load lot " + lot.getName()
+ " with id " + lot.getId() + ".");
}
}
worlds.put(world.getName(), zoneWorld);
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
return zoneWorld;
}
public Zone getZone(int zoneId)
{
return zones.get(zoneId);
}
}
| Added AutoSave Alert
It seems to be an ongoing (hourly) event where everyone spams chat with "LAGGG" "AUTOSAVE" bla bla. The code is like 3 lines so I thought it would be pointless in its own listener so I chucked it at the bottom of this. All it does is broadcast message when there is a save. Up to you whether you use but its there if you want. | src/info/tregmine/Tregmine.java | Added AutoSave Alert | <ide><path>rc/info/tregmine/Tregmine.java
<ide> import org.bukkit.configuration.ConfigurationSection;
<ide> import org.bukkit.configuration.file.FileConfiguration;
<ide> import org.bukkit.entity.Player;
<add>import org.bukkit.event.EventHandler;
<add>import org.bukkit.event.world.WorldSaveEvent;
<ide> import org.bukkit.inventory.PlayerInventory;
<ide> import org.bukkit.plugin.PluginManager;
<ide> import org.bukkit.plugin.java.JavaPlugin;
<ide> {
<ide> return zones.get(zoneId);
<ide> }
<add>
<add> // ============================================================================
<add> // Auto Save Alert
<add> // ============================================================================
<add>
<add> @EventHandler
<add> public void autoSave(WorldSaveEvent event){
<add> Bukkit.broadcastMessage(ChatColor.DARK_RED + "Tregmine is saving, You may experience some slowness.");
<add> }
<ide> } |
|
Java | apache-2.0 | 649c66abebbb4ff8b5081797e78a9ee72113858b | 0 | material-components/material-components-android,googlecodelabs/mdc-android-kotlin | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.design.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.R;
import android.support.design.widget.FloatingActionButtonImpl.InternalVisibilityChangedListener;
import android.support.v4.content.res.ConfigurationHelper;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.AppCompatDrawableManager;
import android.support.v7.widget.AppCompatImageHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
/**
* Floating action buttons are used for a special type of promoted action. They are distinguished
* by a circled icon floating above the UI and have special motion behaviors related to morphing,
* launching, and the transferring anchor point.
*
* <p>Floating action buttons come in two sizes: the default and the mini. The size can be
* controlled with the {@code fabSize} attribute.</p>
*
* <p>As this class descends from {@link ImageView}, you can control the icon which is displayed
* via {@link #setImageDrawable(Drawable)}.</p>
*
* <p>The background color of this view defaults to the your theme's {@code colorAccent}. If you
* wish to change this at runtime then you can do so via
* {@link #setBackgroundTintList(ColorStateList)}.</p>
*/
@CoordinatorLayout.DefaultBehavior(FloatingActionButton.Behavior.class)
public class FloatingActionButton extends VisibilityAwareImageButton {
private static final String LOG_TAG = "FloatingActionButton";
/**
* Callback to be invoked when the visibility of a FloatingActionButton changes.
*/
public abstract static class OnVisibilityChangedListener {
/**
* Called when a FloatingActionButton has been
* {@link #show(OnVisibilityChangedListener) shown}.
*
* @param fab the FloatingActionButton that was shown.
*/
public void onShown(FloatingActionButton fab) {}
/**
* Called when a FloatingActionButton has been
* {@link #hide(OnVisibilityChangedListener) hidden}.
*
* @param fab the FloatingActionButton that was hidden.
*/
public void onHidden(FloatingActionButton fab) {}
}
// These values must match those in the attrs declaration
/**
* The mini sized button. Will always been smaller than {@link #SIZE_NORMAL}.
*
* @see #setSize(int)
*/
public static final int SIZE_MINI = 1;
/**
* The normal sized button. Will always been larger than {@link #SIZE_MINI}.
*
* @see #setSize(int)
*/
public static final int SIZE_NORMAL = 0;
/**
* Size which will change based on the window size. For small sized windows
* (largest screen dimension < 470dp) this will select a small sized button, and for
* larger sized windows it will select a larger size.
*
* @see #setSize(int)
*/
public static final int SIZE_AUTO = -1;
/**
* The switch point for the largest screen edge where SIZE_AUTO switches from mini to normal.
*/
private static final int AUTO_MINI_LARGEST_SCREEN_WIDTH = 470;
/** @hide */
@Retention(RetentionPolicy.SOURCE)
@IntDef({SIZE_MINI, SIZE_NORMAL, SIZE_AUTO})
public @interface Size {}
private ColorStateList mBackgroundTint;
private PorterDuff.Mode mBackgroundTintMode;
private int mBorderWidth;
private int mRippleColor;
private int mSize;
private int mImagePadding;
private int mMaxImageSize;
private boolean mCompatPadding;
private final Rect mShadowPadding = new Rect();
private final Rect mTouchArea = new Rect();
private AppCompatImageHelper mImageHelper;
private FloatingActionButtonImpl mImpl;
public FloatingActionButton(Context context) {
this(context, null);
}
public FloatingActionButton(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FloatingActionButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
ThemeUtils.checkAppCompatTheme(context);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.FloatingActionButton, defStyleAttr,
R.style.Widget_Design_FloatingActionButton);
mBackgroundTint = a.getColorStateList(R.styleable.FloatingActionButton_backgroundTint);
mBackgroundTintMode = parseTintMode(a.getInt(
R.styleable.FloatingActionButton_backgroundTintMode, -1), null);
mRippleColor = a.getColor(R.styleable.FloatingActionButton_rippleColor, 0);
mSize = a.getInt(R.styleable.FloatingActionButton_fabSize, SIZE_AUTO);
mBorderWidth = a.getDimensionPixelSize(R.styleable.FloatingActionButton_borderWidth, 0);
final float elevation = a.getDimension(R.styleable.FloatingActionButton_elevation, 0f);
final float pressedTranslationZ = a.getDimension(
R.styleable.FloatingActionButton_pressedTranslationZ, 0f);
mCompatPadding = a.getBoolean(R.styleable.FloatingActionButton_useCompatPadding, false);
a.recycle();
mImageHelper = new AppCompatImageHelper(this, AppCompatDrawableManager.get());
mImageHelper.loadFromAttributes(attrs, defStyleAttr);
mMaxImageSize = (int) getResources().getDimension(R.dimen.design_fab_image_size);
getImpl().setBackgroundDrawable(mBackgroundTint, mBackgroundTintMode,
mRippleColor, mBorderWidth);
getImpl().setElevation(elevation);
getImpl().setPressedTranslationZ(pressedTranslationZ);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int preferredSize = getSizeDimension();
mImagePadding = (preferredSize - mMaxImageSize) / 2;
getImpl().updatePadding();
final int w = resolveAdjustedSize(preferredSize, widthMeasureSpec);
final int h = resolveAdjustedSize(preferredSize, heightMeasureSpec);
// As we want to stay circular, we set both dimensions to be the
// smallest resolved dimension
final int d = Math.min(w, h);
// We add the shadow's padding to the measured dimension
setMeasuredDimension(
d + mShadowPadding.left + mShadowPadding.right,
d + mShadowPadding.top + mShadowPadding.bottom);
}
/**
* Set the ripple color for this {@link FloatingActionButton}.
* <p>
* When running on devices with KitKat or below, we draw a fill rather than a ripple.
*
* @param color ARGB color to use for the ripple.
*
* @attr ref android.support.design.R.styleable#FloatingActionButton_rippleColor
*/
public void setRippleColor(@ColorInt int color) {
if (mRippleColor != color) {
mRippleColor = color;
getImpl().setRippleColor(color);
}
}
/**
* Return the tint applied to the background drawable, if specified.
*
* @return the tint applied to the background drawable
* @see #setBackgroundTintList(ColorStateList)
*/
@Nullable
@Override
public ColorStateList getBackgroundTintList() {
return mBackgroundTint;
}
/**
* Applies a tint to the background drawable. Does not modify the current tint
* mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
*
* @param tint the tint to apply, may be {@code null} to clear tint
*/
public void setBackgroundTintList(@Nullable ColorStateList tint) {
if (mBackgroundTint != tint) {
mBackgroundTint = tint;
getImpl().setBackgroundTintList(tint);
}
}
/**
* Return the blending mode used to apply the tint to the background
* drawable, if specified.
*
* @return the blending mode used to apply the tint to the background
* drawable
* @see #setBackgroundTintMode(PorterDuff.Mode)
*/
@Nullable
@Override
public PorterDuff.Mode getBackgroundTintMode() {
return mBackgroundTintMode;
}
/**
* Specifies the blending mode used to apply the tint specified by
* {@link #setBackgroundTintList(ColorStateList)}} to the background
* drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
*
* @param tintMode the blending mode used to apply the tint, may be
* {@code null} to clear tint
*/
public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
if (mBackgroundTintMode != tintMode) {
mBackgroundTintMode = tintMode;
getImpl().setBackgroundTintMode(tintMode);
}
}
@Override
public void setBackgroundDrawable(Drawable background) {
Log.i(LOG_TAG, "Setting a custom background is not supported.");
}
@Override
public void setBackgroundResource(int resid) {
Log.i(LOG_TAG, "Setting a custom background is not supported.");
}
@Override
public void setBackgroundColor(int color) {
Log.i(LOG_TAG, "Setting a custom background is not supported.");
}
@Override
public void setImageResource(@DrawableRes int resId) {
// Intercept this call and instead retrieve the Drawable via the image helper
mImageHelper.setImageResource(resId);
}
/**
* Shows the button.
* <p>This method will animate the button show if the view has already been laid out.</p>
*/
public void show() {
show(null);
}
/**
* Shows the button.
* <p>This method will animate the button show if the view has already been laid out.</p>
*
* @param listener the listener to notify when this view is shown
*/
public void show(@Nullable final OnVisibilityChangedListener listener) {
show(listener, true);
}
private void show(OnVisibilityChangedListener listener, boolean fromUser) {
getImpl().show(wrapOnVisibilityChangedListener(listener), fromUser);
}
/**
* Hides the button.
* <p>This method will animate the button hide if the view has already been laid out.</p>
*/
public void hide() {
hide(null);
}
/**
* Hides the button.
* <p>This method will animate the button hide if the view has already been laid out.</p>
*
* @param listener the listener to notify when this view is hidden
*/
public void hide(@Nullable OnVisibilityChangedListener listener) {
hide(listener, true);
}
private void hide(@Nullable OnVisibilityChangedListener listener, boolean fromUser) {
getImpl().hide(wrapOnVisibilityChangedListener(listener), fromUser);
}
/**
* Set whether FloatingActionButton should add inner padding on platforms Lollipop and after,
* to ensure consistent dimensions on all platforms.
*
* @param useCompatPadding true if FloatingActionButton is adding inner padding on platforms
* Lollipop and after, to ensure consistent dimensions on all platforms.
*
* @attr ref android.support.design.R.styleable#FloatingActionButton_useCompatPadding
* @see #getUseCompatPadding()
*/
public void setUseCompatPadding(boolean useCompatPadding) {
if (mCompatPadding != useCompatPadding) {
mCompatPadding = useCompatPadding;
getImpl().onCompatShadowChanged();
}
}
/**
* Returns whether FloatingActionButton will add inner padding on platforms Lollipop and after.
*
* @return true if FloatingActionButton is adding inner padding on platforms Lollipop and after,
* to ensure consistent dimensions on all platforms.
*
* @attr ref android.support.design.R.styleable#FloatingActionButton_useCompatPadding
* @see #setUseCompatPadding(boolean)
*/
public boolean getUseCompatPadding() {
return mCompatPadding;
}
/**
* Sets the size of the button.
*
* <p>The options relate to the options available on the material design specification.
* {@link #SIZE_NORMAL} is larger than {@link #SIZE_MINI}. {@link #SIZE_AUTO} will choose
* an appropriate size based on the screen size.</p>
*
* @param size one of {@link #SIZE_NORMAL}, {@link #SIZE_MINI} or {@link #SIZE_AUTO}
*
* @attr ref android.support.design.R.styleable#FloatingActionButton_fabSize
*/
public void setSize(@Size int size) {
if (size != mSize) {
mSize = size;
requestLayout();
}
}
/**
* Returns the chosen size for this button.
*
* @return one of {@link #SIZE_NORMAL}, {@link #SIZE_MINI} or {@link #SIZE_AUTO}
* @see #setSize(int)
*/
@Size
public int getSize() {
return mSize;
}
@Nullable
private InternalVisibilityChangedListener wrapOnVisibilityChangedListener(
@Nullable final OnVisibilityChangedListener listener) {
if (listener == null) {
return null;
}
return new InternalVisibilityChangedListener() {
@Override
public void onShown() {
listener.onShown(FloatingActionButton.this);
}
@Override
public void onHidden() {
listener.onHidden(FloatingActionButton.this);
}
};
}
private int getSizeDimension() {
return getSizeDimension(mSize);
}
private int getSizeDimension(@Size final int size) {
final Resources res = getResources();
switch (size) {
case SIZE_AUTO:
// If we're set to auto, grab the size from resources and refresh
final int width = ConfigurationHelper.getScreenWidthDp(res);
final int height = ConfigurationHelper.getScreenHeightDp(res);
return Math.max(width, height) < AUTO_MINI_LARGEST_SCREEN_WIDTH
? getSizeDimension(SIZE_MINI)
: getSizeDimension(SIZE_NORMAL);
case SIZE_MINI:
return res.getDimensionPixelSize(R.dimen.design_fab_size_mini);
case SIZE_NORMAL:
default:
return res.getDimensionPixelSize(R.dimen.design_fab_size_normal);
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
getImpl().onAttachedToWindow();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
getImpl().onDetachedFromWindow();
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
getImpl().onDrawableStateChanged(getDrawableState());
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void jumpDrawablesToCurrentState() {
super.jumpDrawablesToCurrentState();
getImpl().jumpDrawableToCurrentState();
}
/**
* Return in {@code rect} the bounds of the actual floating action button content in view-local
* coordinates. This is defined as anything within any visible shadow.
*
* @return true if this view actually has been laid out and has a content rect, else false.
*/
public boolean getContentRect(@NonNull Rect rect) {
if (ViewCompat.isLaidOut(this)) {
rect.set(0, 0, getWidth(), getHeight());
rect.left += mShadowPadding.left;
rect.top += mShadowPadding.top;
rect.right -= mShadowPadding.right;
rect.bottom -= mShadowPadding.bottom;
return true;
} else {
return false;
}
}
/**
* Returns the FloatingActionButton's background, minus any compatible shadow implementation.
*/
@NonNull
public Drawable getContentBackground() {
return getImpl().getContentBackground();
}
private static int resolveAdjustedSize(int desiredSize, int measureSpec) {
int result = desiredSize;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
// Parent says we can be as big as we want. Just don't be larger
// than max size imposed on ourselves.
result = desiredSize;
break;
case MeasureSpec.AT_MOST:
// Parent says we can be as big as we want, up to specSize.
// Don't be larger than specSize, and don't be larger than
// the max size imposed on ourselves.
result = Math.min(desiredSize, specSize);
break;
case MeasureSpec.EXACTLY:
// No choice. Do what we are told.
result = specSize;
break;
}
return result;
}
static PorterDuff.Mode parseTintMode(int value, PorterDuff.Mode defaultMode) {
switch (value) {
case 3:
return PorterDuff.Mode.SRC_OVER;
case 5:
return PorterDuff.Mode.SRC_IN;
case 9:
return PorterDuff.Mode.SRC_ATOP;
case 14:
return PorterDuff.Mode.MULTIPLY;
case 15:
return PorterDuff.Mode.SCREEN;
default:
return defaultMode;
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if(getContentRect(mTouchArea) && !mTouchArea.contains((int) ev.getX(), (int) ev.getY())) {
return false;
}
return super.onTouchEvent(ev);
}
/**
* Behavior designed for use with {@link FloatingActionButton} instances. Its main function
* is to move {@link FloatingActionButton} views so that any displayed {@link Snackbar}s do
* not cover them.
*/
public static class Behavior extends CoordinatorLayout.Behavior<FloatingActionButton> {
// We only support the FAB <> Snackbar shift movement on Honeycomb and above. This is
// because we can use view translation properties which greatly simplifies the code.
private static final boolean SNACKBAR_BEHAVIOR_ENABLED = Build.VERSION.SDK_INT >= 11;
private ValueAnimatorCompat mFabTranslationYAnimator;
private float mFabTranslationY;
private Rect mTmpRect;
@Override
public boolean layoutDependsOn(CoordinatorLayout parent,
FloatingActionButton child, View dependency) {
// We're dependent on all SnackbarLayouts (if enabled)
return SNACKBAR_BEHAVIOR_ENABLED && dependency instanceof Snackbar.SnackbarLayout;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton child,
View dependency) {
if (dependency instanceof Snackbar.SnackbarLayout) {
updateFabTranslationForSnackbar(parent, child, true);
} else if (dependency instanceof AppBarLayout) {
// If we're depending on an AppBarLayout we will show/hide it automatically
// if the FAB is anchored to the AppBarLayout
updateFabVisibility(parent, (AppBarLayout) dependency, child);
}
return false;
}
@Override
public void onDependentViewRemoved(CoordinatorLayout parent, FloatingActionButton child,
View dependency) {
if (dependency instanceof Snackbar.SnackbarLayout) {
updateFabTranslationForSnackbar(parent, child, true);
}
}
private boolean updateFabVisibility(CoordinatorLayout parent,
AppBarLayout appBarLayout, FloatingActionButton child) {
final CoordinatorLayout.LayoutParams lp =
(CoordinatorLayout.LayoutParams) child.getLayoutParams();
if (lp.getAnchorId() != appBarLayout.getId()) {
// The anchor ID doesn't match the dependency, so we won't automatically
// show/hide the FAB
return false;
}
if (child.getUserSetVisibility() != VISIBLE) {
// The view isn't set to be visible so skip changing its visibility
return false;
}
if (mTmpRect == null) {
mTmpRect = new Rect();
}
// First, let's get the visible rect of the dependency
final Rect rect = mTmpRect;
ViewGroupUtils.getDescendantRect(parent, appBarLayout, rect);
if (rect.bottom <= appBarLayout.getMinimumHeightForVisibleOverlappingContent()) {
// If the anchor's bottom is below the seam, we'll animate our FAB out
child.hide(null, false);
} else {
// Else, we'll animate our FAB back in
child.show(null, false);
}
return true;
}
private void updateFabTranslationForSnackbar(CoordinatorLayout parent,
final FloatingActionButton fab, boolean animationAllowed) {
final float targetTransY = getFabTranslationYForSnackbar(parent, fab);
if (mFabTranslationY == targetTransY) {
// We're already at (or currently animating to) the target value, return...
return;
}
final float currentTransY = ViewCompat.getTranslationY(fab);
// Make sure that any current animation is cancelled
if (mFabTranslationYAnimator != null && mFabTranslationYAnimator.isRunning()) {
mFabTranslationYAnimator.cancel();
}
if (animationAllowed && fab.isShown()
&& Math.abs(currentTransY - targetTransY) > (fab.getHeight() * 0.667f)) {
// If the FAB will be travelling by more than 2/3 of its height, let's animate
// it instead
if (mFabTranslationYAnimator == null) {
mFabTranslationYAnimator = ViewUtils.createAnimator();
mFabTranslationYAnimator.setInterpolator(
AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR);
mFabTranslationYAnimator.setUpdateListener(
new ValueAnimatorCompat.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimatorCompat animator) {
ViewCompat.setTranslationY(fab,
animator.getAnimatedFloatValue());
}
});
}
mFabTranslationYAnimator.setFloatValues(currentTransY, targetTransY);
mFabTranslationYAnimator.start();
} else {
// Now update the translation Y
ViewCompat.setTranslationY(fab, targetTransY);
}
mFabTranslationY = targetTransY;
}
private float getFabTranslationYForSnackbar(CoordinatorLayout parent,
FloatingActionButton fab) {
float minOffset = 0;
final List<View> dependencies = parent.getDependencies(fab);
for (int i = 0, z = dependencies.size(); i < z; i++) {
final View view = dependencies.get(i);
if (view instanceof Snackbar.SnackbarLayout && parent.doViewsOverlap(fab, view)) {
minOffset = Math.min(minOffset,
ViewCompat.getTranslationY(view) - view.getHeight());
}
}
return minOffset;
}
@Override
public boolean onLayoutChild(CoordinatorLayout parent, FloatingActionButton child,
int layoutDirection) {
// First, let's make sure that the visibility of the FAB is consistent
final List<View> dependencies = parent.getDependencies(child);
for (int i = 0, count = dependencies.size(); i < count; i++) {
final View dependency = dependencies.get(i);
if (dependency instanceof AppBarLayout
&& updateFabVisibility(parent, (AppBarLayout) dependency, child)) {
break;
}
}
// Now let the CoordinatorLayout lay out the FAB
parent.onLayoutChild(child, layoutDirection);
// Now offset it if needed
offsetIfNeeded(parent, child);
// Make sure we translate the FAB for any displayed Snackbars (without an animation)
updateFabTranslationForSnackbar(parent, child, false);
return true;
}
/**
* Pre-Lollipop we use padding so that the shadow has enough space to be drawn. This method
* offsets our layout position so that we're positioned correctly if we're on one of
* our parent's edges.
*/
private void offsetIfNeeded(CoordinatorLayout parent, FloatingActionButton fab) {
final Rect padding = fab.mShadowPadding;
if (padding != null && padding.centerX() > 0 && padding.centerY() > 0) {
final CoordinatorLayout.LayoutParams lp =
(CoordinatorLayout.LayoutParams) fab.getLayoutParams();
int offsetTB = 0, offsetLR = 0;
if (fab.getRight() >= parent.getWidth() - lp.rightMargin) {
// If we're on the left edge, shift it the right
offsetLR = padding.right;
} else if (fab.getLeft() <= lp.leftMargin) {
// If we're on the left edge, shift it the left
offsetLR = -padding.left;
}
if (fab.getBottom() >= parent.getBottom() - lp.bottomMargin) {
// If we're on the bottom edge, shift it down
offsetTB = padding.bottom;
} else if (fab.getTop() <= lp.topMargin) {
// If we're on the top edge, shift it up
offsetTB = -padding.top;
}
fab.offsetTopAndBottom(offsetTB);
fab.offsetLeftAndRight(offsetLR);
}
}
}
/**
* Returns the backward compatible elevation of the FloatingActionButton.
*
* @return the backward compatible elevation in pixels.
* @attr ref android.support.design.R.styleable#FloatingActionButton_elevation
* @see #setCompatElevation(float)
*/
public float getCompatElevation() {
return getImpl().getElevation();
}
/**
* Updates the backward compatible elevation of the FloatingActionButton.
*
* @param elevation The backward compatible elevation in pixels.
* @attr ref android.support.design.R.styleable#FloatingActionButton_elevation
* @see #getCompatElevation()
* @see #setUseCompatPadding(boolean)
*/
public void setCompatElevation(float elevation) {
getImpl().setElevation(elevation);
}
private FloatingActionButtonImpl getImpl() {
if (mImpl == null) {
mImpl = createImpl();
}
return mImpl;
}
private FloatingActionButtonImpl createImpl() {
final int sdk = Build.VERSION.SDK_INT;
if (sdk >= 21) {
return new FloatingActionButtonLollipop(this, new ShadowDelegateImpl());
} else if (sdk >= 14) {
return new FloatingActionButtonIcs(this, new ShadowDelegateImpl());
} else {
return new FloatingActionButtonEclairMr1(this, new ShadowDelegateImpl());
}
}
private class ShadowDelegateImpl implements ShadowViewDelegate {
@Override
public float getRadius() {
return getSizeDimension() / 2f;
}
@Override
public void setShadowPadding(int left, int top, int right, int bottom) {
mShadowPadding.set(left, top, right, bottom);
setPadding(left + mImagePadding, top + mImagePadding,
right + mImagePadding, bottom + mImagePadding);
}
@Override
public void setBackgroundDrawable(Drawable background) {
FloatingActionButton.super.setBackgroundDrawable(background);
}
@Override
public boolean isCompatPaddingEnabled() {
return mCompatPadding;
}
}
}
| src/android/support/design/widget/FloatingActionButton.java | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.design.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.R;
import android.support.design.widget.FloatingActionButtonImpl.InternalVisibilityChangedListener;
import android.support.v4.content.res.ConfigurationHelper;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.AppCompatDrawableManager;
import android.support.v7.widget.AppCompatImageHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
/**
* Floating action buttons are used for a special type of promoted action. They are distinguished
* by a circled icon floating above the UI and have special motion behaviors related to morphing,
* launching, and the transferring anchor point.
*
* <p>Floating action buttons come in two sizes: the default and the mini. The size can be
* controlled with the {@code fabSize} attribute.</p>
*
* <p>As this class descends from {@link ImageView}, you can control the icon which is displayed
* via {@link #setImageDrawable(Drawable)}.</p>
*
* <p>The background color of this view defaults to the your theme's {@code colorAccent}. If you
* wish to change this at runtime then you can do so via
* {@link #setBackgroundTintList(ColorStateList)}.</p>
*/
@CoordinatorLayout.DefaultBehavior(FloatingActionButton.Behavior.class)
public class FloatingActionButton extends VisibilityAwareImageButton {
private static final String LOG_TAG = "FloatingActionButton";
/**
* Callback to be invoked when the visibility of a FloatingActionButton changes.
*/
public abstract static class OnVisibilityChangedListener {
/**
* Called when a FloatingActionButton has been
* {@link #show(OnVisibilityChangedListener) shown}.
*
* @param fab the FloatingActionButton that was shown.
*/
public void onShown(FloatingActionButton fab) {}
/**
* Called when a FloatingActionButton has been
* {@link #hide(OnVisibilityChangedListener) hidden}.
*
* @param fab the FloatingActionButton that was hidden.
*/
public void onHidden(FloatingActionButton fab) {}
}
// These values must match those in the attrs declaration
/**
* The mini sized button. Will always been smaller than {@link #SIZE_NORMAL}.
*
* @see #setSize(int)
*/
public static final int SIZE_MINI = 1;
/**
* The normal sized button. Will always been larger than {@link #SIZE_MINI}.
*
* @see #setSize(int)
*/
public static final int SIZE_NORMAL = 0;
/**
* Size which will change based on the window size. For small sized windows
* (largest screen dimension < 470dp) this will select a small sized button, and for
* larger sized windows it will select a larger size.
*
* @see #setSize(int)
*/
public static final int SIZE_AUTO = -1;
/**
* The switch point for the largest screen edge where SIZE_AUTO switches from mini to normal.
*/
private static final int AUTO_MINI_LARGEST_SCREEN_WIDTH = 470;
/** @hide */
@Retention(RetentionPolicy.SOURCE)
@IntDef({SIZE_MINI, SIZE_NORMAL, SIZE_AUTO})
public @interface Size {}
private ColorStateList mBackgroundTint;
private PorterDuff.Mode mBackgroundTintMode;
private int mBorderWidth;
private int mRippleColor;
private int mSize;
private int mImagePadding;
private int mMaxImageSize;
private boolean mCompatPadding;
private final Rect mShadowPadding = new Rect();
private final Rect mTouchArea = new Rect();
private AppCompatImageHelper mImageHelper;
private FloatingActionButtonImpl mImpl;
public FloatingActionButton(Context context) {
this(context, null);
}
public FloatingActionButton(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FloatingActionButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
ThemeUtils.checkAppCompatTheme(context);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.FloatingActionButton, defStyleAttr,
R.style.Widget_Design_FloatingActionButton);
mBackgroundTint = a.getColorStateList(R.styleable.FloatingActionButton_backgroundTint);
mBackgroundTintMode = parseTintMode(a.getInt(
R.styleable.FloatingActionButton_backgroundTintMode, -1), null);
mRippleColor = a.getColor(R.styleable.FloatingActionButton_rippleColor, 0);
mSize = a.getInt(R.styleable.FloatingActionButton_fabSize, SIZE_AUTO);
mBorderWidth = a.getDimensionPixelSize(R.styleable.FloatingActionButton_borderWidth, 0);
final float elevation = a.getDimension(R.styleable.FloatingActionButton_elevation, 0f);
final float pressedTranslationZ = a.getDimension(
R.styleable.FloatingActionButton_pressedTranslationZ, 0f);
mCompatPadding = a.getBoolean(R.styleable.FloatingActionButton_useCompatPadding, false);
a.recycle();
mImageHelper = new AppCompatImageHelper(this, AppCompatDrawableManager.get());
mImageHelper.loadFromAttributes(attrs, defStyleAttr);
mMaxImageSize = (int) getResources().getDimension(R.dimen.design_fab_image_size);
getImpl().setBackgroundDrawable(mBackgroundTint, mBackgroundTintMode,
mRippleColor, mBorderWidth);
getImpl().setElevation(elevation);
getImpl().setPressedTranslationZ(pressedTranslationZ);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int preferredSize = getSizeDimension();
mImagePadding = (preferredSize - mMaxImageSize) / 2;
getImpl().updatePadding();
final int w = resolveAdjustedSize(preferredSize, widthMeasureSpec);
final int h = resolveAdjustedSize(preferredSize, heightMeasureSpec);
// As we want to stay circular, we set both dimensions to be the
// smallest resolved dimension
final int d = Math.min(w, h);
// We add the shadow's padding to the measured dimension
setMeasuredDimension(
d + mShadowPadding.left + mShadowPadding.right,
d + mShadowPadding.top + mShadowPadding.bottom);
}
/**
* Set the ripple color for this {@link FloatingActionButton}.
* <p>
* When running on devices with KitKat or below, we draw a fill rather than a ripple.
*
* @param color ARGB color to use for the ripple.
*
* @attr ref android.support.design.R.styleable#FloatingActionButton_rippleColor
*/
public void setRippleColor(@ColorInt int color) {
if (mRippleColor != color) {
mRippleColor = color;
getImpl().setRippleColor(color);
}
}
/**
* Return the tint applied to the background drawable, if specified.
*
* @return the tint applied to the background drawable
* @see #setBackgroundTintList(ColorStateList)
*/
@Nullable
@Override
public ColorStateList getBackgroundTintList() {
return mBackgroundTint;
}
/**
* Applies a tint to the background drawable. Does not modify the current tint
* mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
*
* @param tint the tint to apply, may be {@code null} to clear tint
*/
public void setBackgroundTintList(@Nullable ColorStateList tint) {
if (mBackgroundTint != tint) {
mBackgroundTint = tint;
getImpl().setBackgroundTintList(tint);
}
}
/**
* Return the blending mode used to apply the tint to the background
* drawable, if specified.
*
* @return the blending mode used to apply the tint to the background
* drawable
* @see #setBackgroundTintMode(PorterDuff.Mode)
*/
@Nullable
@Override
public PorterDuff.Mode getBackgroundTintMode() {
return mBackgroundTintMode;
}
/**
* Specifies the blending mode used to apply the tint specified by
* {@link #setBackgroundTintList(ColorStateList)}} to the background
* drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
*
* @param tintMode the blending mode used to apply the tint, may be
* {@code null} to clear tint
*/
public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
if (mBackgroundTintMode != tintMode) {
mBackgroundTintMode = tintMode;
getImpl().setBackgroundTintMode(tintMode);
}
}
@Override
public void setBackgroundDrawable(Drawable background) {
Log.i(LOG_TAG, "Setting a custom background is not supported.");
}
@Override
public void setBackgroundResource(int resid) {
Log.i(LOG_TAG, "Setting a custom background is not supported.");
}
@Override
public void setBackgroundColor(int color) {
Log.i(LOG_TAG, "Setting a custom background is not supported.");
}
@Override
public void setImageResource(@DrawableRes int resId) {
// Intercept this call and instead retrieve the Drawable via the image helper
mImageHelper.setImageResource(resId);
}
/**
* Shows the button.
* <p>This method will animate the button show if the view has already been laid out.</p>
*/
public void show() {
show(null);
}
/**
* Shows the button.
* <p>This method will animate the button show if the view has already been laid out.</p>
*
* @param listener the listener to notify when this view is shown
*/
public void show(@Nullable final OnVisibilityChangedListener listener) {
show(listener, true);
}
private void show(OnVisibilityChangedListener listener, boolean fromUser) {
getImpl().show(wrapOnVisibilityChangedListener(listener), fromUser);
}
/**
* Hides the button.
* <p>This method will animate the button hide if the view has already been laid out.</p>
*/
public void hide() {
hide(null);
}
/**
* Hides the button.
* <p>This method will animate the button hide if the view has already been laid out.</p>
*
* @param listener the listener to notify when this view is hidden
*/
public void hide(@Nullable OnVisibilityChangedListener listener) {
hide(listener, true);
}
private void hide(@Nullable OnVisibilityChangedListener listener, boolean fromUser) {
getImpl().hide(wrapOnVisibilityChangedListener(listener), fromUser);
}
/**
* Set whether FloatingActionButton should add inner padding on platforms Lollipop and after,
* to ensure consistent dimensions on all platforms.
*
* @param useCompatPadding true if FloatingActionButton is adding inner padding on platforms
* Lollipop and after, to ensure consistent dimensions on all platforms.
*
* @attr ref android.support.design.R.styleable#FloatingActionButton_useCompatPadding
* @see #getUseCompatPadding()
*/
public void setUseCompatPadding(boolean useCompatPadding) {
if (mCompatPadding != useCompatPadding) {
mCompatPadding = useCompatPadding;
getImpl().onCompatShadowChanged();
}
}
/**
* Returns whether FloatingActionButton will add inner padding on platforms Lollipop and after.
*
* @return true if FloatingActionButton is adding inner padding on platforms Lollipop and after,
* to ensure consistent dimensions on all platforms.
*
* @attr ref android.support.design.R.styleable#FloatingActionButton_useCompatPadding
* @see #setUseCompatPadding(boolean)
*/
public boolean getUseCompatPadding() {
return mCompatPadding;
}
/**
* Sets the size of the button.
*
* <p>The options relate to the options available on the material design specification.
* {@link #SIZE_NORMAL} is larger than {@link #SIZE_MINI}. {@link #SIZE_AUTO} will choose
* an appropriate size based on the screen size.</p>
*
* @param size one of {@link #SIZE_NORMAL}, {@link #SIZE_MINI} or {@link #SIZE_AUTO}
*
* @attr ref android.support.design.R.styleable#FloatingActionButton_fabSize
*/
public void setSize(@Size int size) {
if (size != mSize) {
mSize = size;
requestLayout();
}
}
/**
* Returns the chosen size for this button.
*
* @return one of {@link #SIZE_NORMAL}, {@link #SIZE_MINI} or {@link #SIZE_AUTO}
* @see #setSize(int)
*/
@Size
public int getSize() {
return mSize;
}
@Nullable
private InternalVisibilityChangedListener wrapOnVisibilityChangedListener(
@Nullable final OnVisibilityChangedListener listener) {
if (listener == null) {
return null;
}
return new InternalVisibilityChangedListener() {
@Override
public void onShown() {
listener.onShown(FloatingActionButton.this);
}
@Override
public void onHidden() {
listener.onHidden(FloatingActionButton.this);
}
};
}
private int getSizeDimension() {
return getSizeDimension(mSize);
}
private int getSizeDimension(@Size final int size) {
final Resources res = getResources();
switch (size) {
case SIZE_AUTO:
// If we're set to auto, grab the size from resources and refresh
final int width = ConfigurationHelper.getScreenWidthDp(res);
final int height = ConfigurationHelper.getScreenHeightDp(res);
return Math.max(width, height) < AUTO_MINI_LARGEST_SCREEN_WIDTH
? getSizeDimension(SIZE_MINI)
: getSizeDimension(SIZE_NORMAL);
case SIZE_MINI:
return res.getDimensionPixelSize(R.dimen.design_fab_size_mini);
case SIZE_NORMAL:
default:
return res.getDimensionPixelSize(R.dimen.design_fab_size_normal);
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
getImpl().onAttachedToWindow();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
getImpl().onDetachedFromWindow();
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
getImpl().onDrawableStateChanged(getDrawableState());
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void jumpDrawablesToCurrentState() {
super.jumpDrawablesToCurrentState();
getImpl().jumpDrawableToCurrentState();
}
/**
* Return in {@code rect} the bounds of the actual floating action button content in view-local
* coordinates. This is defined as anything within any visible shadow.
*
* @return true if this view actually has been laid out and has a content rect, else false.
*/
public boolean getContentRect(@NonNull Rect rect) {
if (ViewCompat.isLaidOut(this)) {
rect.set(0, 0, getWidth(), getHeight());
rect.left += mShadowPadding.left;
rect.top += mShadowPadding.top;
rect.right -= mShadowPadding.right;
rect.bottom -= mShadowPadding.bottom;
return true;
} else {
return false;
}
}
/**
* Returns the FloatingActionButton's background, minus any compatible shadow implementation.
*/
@NonNull
public Drawable getContentBackground() {
return getImpl().getContentBackground();
}
private static int resolveAdjustedSize(int desiredSize, int measureSpec) {
int result = desiredSize;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
// Parent says we can be as big as we want. Just don't be larger
// than max size imposed on ourselves.
result = desiredSize;
break;
case MeasureSpec.AT_MOST:
// Parent says we can be as big as we want, up to specSize.
// Don't be larger than specSize, and don't be larger than
// the max size imposed on ourselves.
result = Math.min(desiredSize, specSize);
break;
case MeasureSpec.EXACTLY:
// No choice. Do what we are told.
result = specSize;
break;
}
return result;
}
static PorterDuff.Mode parseTintMode(int value, PorterDuff.Mode defaultMode) {
switch (value) {
case 3:
return PorterDuff.Mode.SRC_OVER;
case 5:
return PorterDuff.Mode.SRC_IN;
case 9:
return PorterDuff.Mode.SRC_ATOP;
case 14:
return PorterDuff.Mode.MULTIPLY;
case 15:
return PorterDuff.Mode.SCREEN;
default:
return defaultMode;
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if(getContentRect(mTouchArea) && !mTouchArea.contains((int) ev.getX(), (int) ev.getY())) {
return false;
}
return super.onTouchEvent(ev);
}
/**
* Behavior designed for use with {@link FloatingActionButton} instances. Its main function
* is to move {@link FloatingActionButton} views so that any displayed {@link Snackbar}s do
* not cover them.
*/
public static class Behavior extends CoordinatorLayout.Behavior<FloatingActionButton> {
// We only support the FAB <> Snackbar shift movement on Honeycomb and above. This is
// because we can use view translation properties which greatly simplifies the code.
private static final boolean SNACKBAR_BEHAVIOR_ENABLED = Build.VERSION.SDK_INT >= 11;
private ValueAnimatorCompat mFabTranslationYAnimator;
private float mFabTranslationY;
private Rect mTmpRect;
@Override
public boolean layoutDependsOn(CoordinatorLayout parent,
FloatingActionButton child, View dependency) {
// We're dependent on all SnackbarLayouts (if enabled)
return SNACKBAR_BEHAVIOR_ENABLED && dependency instanceof Snackbar.SnackbarLayout;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton child,
View dependency) {
if (dependency instanceof Snackbar.SnackbarLayout) {
updateFabTranslationForSnackbar(parent, child, true);
} else if (dependency instanceof AppBarLayout) {
// If we're depending on an AppBarLayout we will show/hide it automatically
// if the FAB is anchored to the AppBarLayout
updateFabVisibility(parent, (AppBarLayout) dependency, child);
}
return false;
}
@Override
public void onDependentViewRemoved(CoordinatorLayout parent, FloatingActionButton child,
View dependency) {
if (dependency instanceof Snackbar.SnackbarLayout) {
updateFabTranslationForSnackbar(parent, child, dependency);
}
}
private boolean updateFabVisibility(CoordinatorLayout parent,
AppBarLayout appBarLayout, FloatingActionButton child) {
final CoordinatorLayout.LayoutParams lp =
(CoordinatorLayout.LayoutParams) child.getLayoutParams();
if (lp.getAnchorId() != appBarLayout.getId()) {
// The anchor ID doesn't match the dependency, so we won't automatically
// show/hide the FAB
return false;
}
if (child.getUserSetVisibility() != VISIBLE) {
// The view isn't set to be visible so skip changing its visibility
return false;
}
if (mTmpRect == null) {
mTmpRect = new Rect();
}
// First, let's get the visible rect of the dependency
final Rect rect = mTmpRect;
ViewGroupUtils.getDescendantRect(parent, appBarLayout, rect);
if (rect.bottom <= appBarLayout.getMinimumHeightForVisibleOverlappingContent()) {
// If the anchor's bottom is below the seam, we'll animate our FAB out
child.hide(null, false);
} else {
// Else, we'll animate our FAB back in
child.show(null, false);
}
return true;
}
private void updateFabTranslationForSnackbar(CoordinatorLayout parent,
final FloatingActionButton fab, boolean animationAllowed) {
final float targetTransY = getFabTranslationYForSnackbar(parent, fab);
if (mFabTranslationY == targetTransY) {
// We're already at (or currently animating to) the target value, return...
return;
}
final float currentTransY = ViewCompat.getTranslationY(fab);
// Make sure that any current animation is cancelled
if (mFabTranslationYAnimator != null && mFabTranslationYAnimator.isRunning()) {
mFabTranslationYAnimator.cancel();
}
if (animationAllowed && fab.isShown()
&& Math.abs(currentTransY - targetTransY) > (fab.getHeight() * 0.667f)) {
// If the FAB will be travelling by more than 2/3 of its height, let's animate
// it instead
if (mFabTranslationYAnimator == null) {
mFabTranslationYAnimator = ViewUtils.createAnimator();
mFabTranslationYAnimator.setInterpolator(
AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR);
mFabTranslationYAnimator.setUpdateListener(
new ValueAnimatorCompat.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimatorCompat animator) {
ViewCompat.setTranslationY(fab,
animator.getAnimatedFloatValue());
}
});
}
mFabTranslationYAnimator.setFloatValues(currentTransY, targetTransY);
mFabTranslationYAnimator.start();
} else {
// Now update the translation Y
ViewCompat.setTranslationY(fab, targetTransY);
}
mFabTranslationY = targetTransY;
}
private float getFabTranslationYForSnackbar(CoordinatorLayout parent,
FloatingActionButton fab) {
float minOffset = 0;
final List<View> dependencies = parent.getDependencies(fab);
for (int i = 0, z = dependencies.size(); i < z; i++) {
final View view = dependencies.get(i);
if (view instanceof Snackbar.SnackbarLayout && parent.doViewsOverlap(fab, view)) {
minOffset = Math.min(minOffset,
ViewCompat.getTranslationY(view) - view.getHeight());
}
}
return minOffset;
}
@Override
public boolean onLayoutChild(CoordinatorLayout parent, FloatingActionButton child,
int layoutDirection) {
// First, let's make sure that the visibility of the FAB is consistent
final List<View> dependencies = parent.getDependencies(child);
for (int i = 0, count = dependencies.size(); i < count; i++) {
final View dependency = dependencies.get(i);
if (dependency instanceof AppBarLayout
&& updateFabVisibility(parent, (AppBarLayout) dependency, child)) {
break;
}
}
// Now let the CoordinatorLayout lay out the FAB
parent.onLayoutChild(child, layoutDirection);
// Now offset it if needed
offsetIfNeeded(parent, child);
// Make sure we translate the FAB for any displayed Snackbars (without an animation)
updateFabTranslationForSnackbar(parent, child, false);
return true;
}
/**
* Pre-Lollipop we use padding so that the shadow has enough space to be drawn. This method
* offsets our layout position so that we're positioned correctly if we're on one of
* our parent's edges.
*/
private void offsetIfNeeded(CoordinatorLayout parent, FloatingActionButton fab) {
final Rect padding = fab.mShadowPadding;
if (padding != null && padding.centerX() > 0 && padding.centerY() > 0) {
final CoordinatorLayout.LayoutParams lp =
(CoordinatorLayout.LayoutParams) fab.getLayoutParams();
int offsetTB = 0, offsetLR = 0;
if (fab.getRight() >= parent.getWidth() - lp.rightMargin) {
// If we're on the left edge, shift it the right
offsetLR = padding.right;
} else if (fab.getLeft() <= lp.leftMargin) {
// If we're on the left edge, shift it the left
offsetLR = -padding.left;
}
if (fab.getBottom() >= parent.getBottom() - lp.bottomMargin) {
// If we're on the bottom edge, shift it down
offsetTB = padding.bottom;
} else if (fab.getTop() <= lp.topMargin) {
// If we're on the top edge, shift it up
offsetTB = -padding.top;
}
fab.offsetTopAndBottom(offsetTB);
fab.offsetLeftAndRight(offsetLR);
}
}
}
/**
* Returns the backward compatible elevation of the FloatingActionButton.
*
* @return the backward compatible elevation in pixels.
* @attr ref android.support.design.R.styleable#FloatingActionButton_elevation
* @see #setCompatElevation(float)
*/
public float getCompatElevation() {
return getImpl().getElevation();
}
/**
* Updates the backward compatible elevation of the FloatingActionButton.
*
* @param elevation The backward compatible elevation in pixels.
* @attr ref android.support.design.R.styleable#FloatingActionButton_elevation
* @see #getCompatElevation()
* @see #setUseCompatPadding(boolean)
*/
public void setCompatElevation(float elevation) {
getImpl().setElevation(elevation);
}
private FloatingActionButtonImpl getImpl() {
if (mImpl == null) {
mImpl = createImpl();
}
return mImpl;
}
private FloatingActionButtonImpl createImpl() {
final int sdk = Build.VERSION.SDK_INT;
if (sdk >= 21) {
return new FloatingActionButtonLollipop(this, new ShadowDelegateImpl());
} else if (sdk >= 14) {
return new FloatingActionButtonIcs(this, new ShadowDelegateImpl());
} else {
return new FloatingActionButtonEclairMr1(this, new ShadowDelegateImpl());
}
}
private class ShadowDelegateImpl implements ShadowViewDelegate {
@Override
public float getRadius() {
return getSizeDimension() / 2f;
}
@Override
public void setShadowPadding(int left, int top, int right, int bottom) {
mShadowPadding.set(left, top, right, bottom);
setPadding(left + mImagePadding, top + mImagePadding,
right + mImagePadding, bottom + mImagePadding);
}
@Override
public void setBackgroundDrawable(Drawable background) {
FloatingActionButton.super.setBackgroundDrawable(background);
}
@Override
public boolean isCompatPaddingEnabled() {
return mCompatPadding;
}
}
}
| Fix build for FloatingActionButton
Change-Id: Ie87f7dcd3615b8c72d6a8165c441678b8cb98fcb
GitOrigin-RevId=9cf7823a2b044e550dd5c1ba3a7a91d45b4d9673
PiperOrigin-RevId: 140560749
| src/android/support/design/widget/FloatingActionButton.java | Fix build for FloatingActionButton | <ide><path>rc/android/support/design/widget/FloatingActionButton.java
<ide> public void onDependentViewRemoved(CoordinatorLayout parent, FloatingActionButton child,
<ide> View dependency) {
<ide> if (dependency instanceof Snackbar.SnackbarLayout) {
<del> updateFabTranslationForSnackbar(parent, child, dependency);
<add> updateFabTranslationForSnackbar(parent, child, true);
<ide> }
<ide> }
<ide> |
|
JavaScript | mit | a19db5a482c66bed348c3eadeeaada9dbc3d5805 | 0 | silverbux/rsjs | baf0e1ca-2e9c-11e5-9f96-a45e60cdfd11 | helloWorld.js | bae5fbd4-2e9c-11e5-86e3-a45e60cdfd11 | baf0e1ca-2e9c-11e5-9f96-a45e60cdfd11 | helloWorld.js | baf0e1ca-2e9c-11e5-9f96-a45e60cdfd11 | <ide><path>elloWorld.js
<del>bae5fbd4-2e9c-11e5-86e3-a45e60cdfd11
<add>baf0e1ca-2e9c-11e5-9f96-a45e60cdfd11 |
|
Java | apache-2.0 | 9c631b41e6ed6bd15a85d0b1d223c8bcb5c50f0f | 0 | robovm/robovm-studio,MER-GROUP/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,akosyakov/intellij-community,signed/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,consulo/consulo,allotria/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,signed/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,fnouama/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,diorcety/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,supersven/intellij-community,slisson/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,kdwink/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,xfournet/intellij-community,holmes/intellij-community,blademainer/intellij-community,asedunov/intellij-community,retomerz/intellij-community,fitermay/intellij-community,hurricup/intellij-community,semonte/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,amith01994/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,slisson/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,ernestp/consulo,ryano144/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,allotria/intellij-community,kool79/intellij-community,da1z/intellij-community,nicolargo/intellij-community,izonder/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,kool79/intellij-community,robovm/robovm-studio,dslomov/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,consulo/consulo,apixandru/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,caot/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,supersven/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,da1z/intellij-community,apixandru/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,kool79/intellij-community,ernestp/consulo,retomerz/intellij-community,adedayo/intellij-community,fnouama/intellij-community,da1z/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,kool79/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,samthor/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,holmes/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,kdwink/intellij-community,izonder/intellij-community,izonder/intellij-community,signed/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,robovm/robovm-studio,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ahb0327/intellij-community,supersven/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,holmes/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,apixandru/intellij-community,samthor/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,ibinti/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,consulo/consulo,kdwink/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,caot/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,adedayo/intellij-community,allotria/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,asedunov/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,izonder/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,signed/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,slisson/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,supersven/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,caot/intellij-community,amith01994/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,caot/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,semonte/intellij-community,amith01994/intellij-community,hurricup/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,semonte/intellij-community,ryano144/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,ernestp/consulo,robovm/robovm-studio,robovm/robovm-studio,MER-GROUP/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,hurricup/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,dslomov/intellij-community,samthor/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,apixandru/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,nicolargo/intellij-community,holmes/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,holmes/intellij-community,fitermay/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,jagguli/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,kool79/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,signed/intellij-community,amith01994/intellij-community,allotria/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,akosyakov/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,caot/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,allotria/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,fitermay/intellij-community,slisson/intellij-community,adedayo/intellij-community,blademainer/intellij-community,FHannes/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,signed/intellij-community,FHannes/intellij-community,ernestp/consulo,suncycheng/intellij-community,blademainer/intellij-community,kdwink/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,signed/intellij-community,da1z/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,signed/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,signed/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,diorcety/intellij-community,ernestp/consulo,supersven/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,consulo/consulo,ryano144/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,youdonghai/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,supersven/intellij-community,semonte/intellij-community,akosyakov/intellij-community,da1z/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,hurricup/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,samthor/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,xfournet/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,kool79/intellij-community,izonder/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,ibinti/intellij-community,fnouama/intellij-community,consulo/consulo,alphafoobar/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,samthor/intellij-community,ibinti/intellij-community,jagguli/intellij-community,xfournet/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,retomerz/intellij-community,kool79/intellij-community,petteyg/intellij-community,FHannes/intellij-community,ibinti/intellij-community,xfournet/intellij-community,samthor/intellij-community,supersven/intellij-community,clumsy/intellij-community,da1z/intellij-community,apixandru/intellij-community,slisson/intellij-community,consulo/consulo,ibinti/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,allotria/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,petteyg/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,izonder/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,FHannes/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,izonder/intellij-community,semonte/intellij-community,vladmm/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,kool79/intellij-community,dslomov/intellij-community,caot/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,adedayo/intellij-community,jagguli/intellij-community,asedunov/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,ryano144/intellij-community,semonte/intellij-community,dslomov/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,samthor/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,semonte/intellij-community,kdwink/intellij-community,slisson/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,wreckJ/intellij-community,allotria/intellij-community,caot/intellij-community,clumsy/intellij-community,semonte/intellij-community,fnouama/intellij-community,signed/intellij-community,jagguli/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,vladmm/intellij-community,da1z/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,signed/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,da1z/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,kdwink/intellij-community,samthor/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,izonder/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,caot/intellij-community,retomerz/intellij-community | /*
* Copyright 2000-2009 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.codeInsight.documentation;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.hint.ElementLocationUtil;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.ide.actions.ExternalJavaDocAction;
import com.intellij.ide.ui.UISettings;
import com.intellij.lang.documentation.CompositeDocumentationProvider;
import com.intellij.lang.documentation.DocumentationProvider;
import com.intellij.lang.documentation.ExternalDocumentationHandler;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.options.FontSize;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.psi.PsiElement;
import com.intellij.psi.SmartPointerManager;
import com.intellij.psi.SmartPsiElementPointer;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.SideBorder;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.Consumer;
import com.intellij.util.containers.HashMap;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.Stack;
public class DocumentationComponent extends JPanel implements Disposable {
private static final int MAX_WIDTH = 500;
private static final int MAX_HEIGHT = 300;
private static final int MIN_HEIGHT = 45;
private DocumentationManager myManager;
private SmartPsiElementPointer myElement;
private final Stack<Context> myBackStack = new Stack<Context>();
private final Stack<Context> myForwardStack = new Stack<Context>();
private ActionToolbar myToolBar;
private boolean myIsEmpty;
private boolean myIsShown;
private final JLabel myElementLabel;
private Style myFontSizeStyle;
private static class Context {
final SmartPsiElementPointer element;
final String text;
final Rectangle viewRect;
public Context(SmartPsiElementPointer element, String text, Rectangle viewRect) {
this.element = element;
this.text = text;
this.viewRect = viewRect;
}
}
private final JScrollPane myScrollPane;
private final JEditorPane myEditorPane;
private String myText; // myEditorPane.getText() surprisingly crashes.., let's cache the text
private final JPanel myControlPanel;
private boolean myControlPanelVisible;
private final ExternalDocAction myExternalDocAction;
private Consumer<PsiElement> myNavigateCallback;
private JBPopup myHint;
private final HashMap<KeyStroke, ActionListener> myKeyboardActions = new HashMap<KeyStroke, ActionListener>();
// KeyStroke --> ActionListener
public boolean requestFocusInWindow() {
return myScrollPane.requestFocusInWindow();
}
public void requestFocus() {
myScrollPane.requestFocus();
}
public DocumentationComponent(final DocumentationManager manager, final AnAction[] additionalActions) {
myManager = manager;
myIsEmpty = true;
myIsShown = false;
myEditorPane = new JEditorPane(UIUtil.HTML_MIME, "") {
public Dimension getPreferredScrollableViewportSize() {
if (getWidth() == 0 || getHeight() == 0) {
setSize(MAX_WIDTH, MAX_HEIGHT);
}
Insets ins = myEditorPane.getInsets();
View rootView = myEditorPane.getUI().getRootView(myEditorPane);
rootView.setSize(MAX_WIDTH,
MAX_HEIGHT); // Necessary! Without this line, size will not increase then you go from small page to bigger one
int prefHeight = (int)rootView.getPreferredSpan(View.Y_AXIS);
prefHeight += ins.bottom + ins.top + myScrollPane.getHorizontalScrollBar().getMaximumSize().height;
return new Dimension(MAX_WIDTH, Math.max(MIN_HEIGHT, Math.min(MAX_HEIGHT, prefHeight)));
}
{
enableEvents(KeyEvent.KEY_EVENT_MASK);
}
protected void processKeyEvent(KeyEvent e) {
KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e);
ActionListener listener = myKeyboardActions.get(keyStroke);
if (listener != null) {
listener.actionPerformed(new ActionEvent(DocumentationComponent.this, 0, ""));
e.consume();
return;
}
super.processKeyEvent(e);
}
@Override
protected void paintComponent(Graphics g) {
UISettings.setupAntialiasing(g);
super.paintComponent(g);
}
};
myText = "";
myEditorPane.setEditable(false);
myEditorPane.setBackground(HintUtil.INFORMATION_COLOR);
myEditorPane.setEditorKit(UIUtil.getHTMLEditorKit());
myScrollPane = new JBScrollPane(myEditorPane) {
@Override
protected void processMouseWheelEvent(MouseWheelEvent e) {
if (!EditorSettingsExternalizable.getInstance().isWheelFontChangeEnabled() || !EditorUtil.isChangeFontSize(e)) {
super.processMouseWheelEvent(e);
return;
}
int change = Math.abs(e.getWheelRotation());
boolean increase = e.getWheelRotation() <= 0;
EditorColorsManager colorsManager = EditorColorsManager.getInstance();
EditorColorsScheme scheme = colorsManager.getGlobalScheme();
FontSize newFontSize = scheme.getQuickDocFontSize();
for (; change > 0; change--) {
if (increase) {
newFontSize = newFontSize.larger();
}
else {
newFontSize = newFontSize.smaller();
}
}
if (newFontSize == scheme.getQuickDocFontSize()) {
return;
}
scheme.setQuickDocFontSize(newFontSize);
applyFontSize();
}
};
myScrollPane.setBorder(null);
final MouseAdapter mouseAdapter = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
myManager.requestFocus();
}
};
myEditorPane.addMouseListener(mouseAdapter);
Disposer.register(this, new Disposable() {
public void dispose() {
myEditorPane.removeMouseListener(mouseAdapter);
}
});
final FocusAdapter focusAdapter = new FocusAdapter() {
public void focusLost(FocusEvent e) {
Component previouslyFocused = WindowManagerEx.getInstanceEx().getFocusedComponent(manager.getProject(getElement()));
if (!(previouslyFocused == myEditorPane)) {
if (myHint != null && !myHint.isDisposed()) myHint.cancel();
}
}
};
myEditorPane.addFocusListener(focusAdapter);
Disposer.register(this, new Disposable() {
public void dispose() {
myEditorPane.removeFocusListener(focusAdapter);
}
});
setLayout(new BorderLayout());
add(myScrollPane, BorderLayout.CENTER);
myScrollPane.setViewportBorder(JBScrollPane.createIndentBorder());
final DefaultActionGroup actions = new DefaultActionGroup();
actions.add(new BackAction());
actions.add(new ForwardAction());
actions.add(myExternalDocAction = new ExternalDocAction());
if (additionalActions != null) {
for (final AnAction action : additionalActions) {
actions.add(action);
}
}
myToolBar = ActionManager.getInstance().createActionToolbar(ActionPlaces.JAVADOC_TOOLBAR, actions, true);
myControlPanel = new JPanel();
myControlPanel.setLayout(new BorderLayout());
myControlPanel.setBorder(IdeBorderFactory.createBorder(SideBorder.BOTTOM));
JPanel dummyPanel = new JPanel();
myElementLabel = new JLabel();
dummyPanel.setLayout(new BorderLayout());
dummyPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
dummyPanel.add(myElementLabel, BorderLayout.EAST);
myControlPanel.add(myToolBar.getComponent(), BorderLayout.WEST);
myControlPanel.add(dummyPanel, BorderLayout.CENTER);
myControlPanelVisible = false;
final HyperlinkListener hyperlinkListener = new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
HyperlinkEvent.EventType type = e.getEventType();
if (type == HyperlinkEvent.EventType.ACTIVATED) {
manager.navigateByLink(DocumentationComponent.this, e.getDescription());
}
else if (type == HyperlinkEvent.EventType.ENTERED) {
myEditorPane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
else if (type == HyperlinkEvent.EventType.EXITED) {
myEditorPane.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
};
myEditorPane.addHyperlinkListener(hyperlinkListener);
Disposer.register(this, new Disposable() {
public void dispose() {
myEditorPane.removeHyperlinkListener(hyperlinkListener);
}
});
registerActions();
updateControlState();
}
public DocumentationComponent(final DocumentationManager manager) {
this(manager, null);
}
public synchronized boolean isEmpty() {
return myIsEmpty;
}
public synchronized void startWait() {
myIsEmpty = true;
}
private void setControlPanelVisible(boolean visible) {
if (visible == myControlPanelVisible) return;
if (visible) {
add(myControlPanel, BorderLayout.NORTH);
}
else {
remove(myControlPanel);
}
myControlPanelVisible = visible;
}
public void setHint(JBPopup hint) {
myHint = hint;
}
public JComponent getComponent() {
return myEditorPane;
}
@Nullable
public PsiElement getElement() {
return myElement != null ? myElement.getElement() : null;
}
public void setNavigateCallback(Consumer<PsiElement> navigateCallback) {
myNavigateCallback = navigateCallback;
}
public void setText(String text, PsiElement element, boolean clearHistory) {
setText(text, element, false, clearHistory);
}
public void setText(String text, PsiElement element, boolean clean, boolean clearHistory) {
if (clean && myElement != null) {
myBackStack.push(saveContext());
myForwardStack.clear();
}
updateControlState();
setData(element, text, clearHistory);
if (clean) {
myIsEmpty = false;
}
if (clearHistory) clearHistory();
}
private void clearHistory() {
myForwardStack.clear();
myBackStack.clear();
}
public void setData(PsiElement _element, String text, final boolean clearHistory) {
if (myElement != null) {
myBackStack.push(saveContext());
myForwardStack.clear();
}
final SmartPsiElementPointer element = _element != null && _element.isValid()
? SmartPointerManager.getInstance(_element.getProject()).createSmartPsiElementPointer(_element)
: null;
if (element != null) {
myElement = element;
}
myIsEmpty = false;
updateControlState();
setDataInternal(element, text, new Rectangle(0, 0));
if (clearHistory) clearHistory();
}
private void setDataInternal(SmartPsiElementPointer element, String text, final Rectangle viewRect) {
setDataInternal(element, text, viewRect, false);
}
private void setDataInternal(SmartPsiElementPointer element, String text, final Rectangle viewRect, boolean skip) {
boolean justShown = false;
myElement = element;
if (!myIsShown && myHint != null) {
myEditorPane.setText(text);
applyFontSize();
myManager.showHint(myHint);
myIsShown = justShown = true;
}
if (!justShown) {
myEditorPane.setText(text);
applyFontSize();
}
if (!skip) {
myText = text;
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
myEditorPane.scrollRectToVisible(viewRect);
}
});
}
private void applyFontSize() {
Document document = myEditorPane.getDocument();
if (!(document instanceof StyledDocument)) {
return;
}
StyledDocument styledDocument = (StyledDocument)document;
if (myFontSizeStyle == null) {
myFontSizeStyle = styledDocument.addStyle("active", null);
}
EditorColorsManager colorsManager = EditorColorsManager.getInstance();
EditorColorsScheme scheme = colorsManager.getGlobalScheme();
StyleConstants.setFontSize(myFontSizeStyle, scheme.getQuickDocFontSize().getSize());
styledDocument.setCharacterAttributes(0, document.getLength(), myFontSizeStyle, false);
}
private void goBack() {
if (myBackStack.isEmpty()) return;
Context context = myBackStack.pop();
myForwardStack.push(saveContext());
restoreContext(context);
updateControlState();
}
private void goForward() {
if (myForwardStack.isEmpty()) return;
Context context = myForwardStack.pop();
myBackStack.push(saveContext());
restoreContext(context);
updateControlState();
}
private Context saveContext() {
Rectangle rect = myScrollPane.getViewport().getViewRect();
return new Context(myElement, myText, rect);
}
private void restoreContext(Context context) {
setDataInternal(context.element, context.text, context.viewRect);
if (myNavigateCallback != null) {
final PsiElement element = context.element.getElement();
if (element != null) {
myNavigateCallback.consume(element);
}
}
}
private void updateControlState() {
ElementLocationUtil.customizeElementLabel(myElement != null ? myElement.getElement() : null, myElementLabel);
myToolBar.updateActionsImmediately(); // update faster
setControlPanelVisible(true);//(!myBackStack.isEmpty() || !myForwardStack.isEmpty());
}
private class BackAction extends AnAction implements HintManagerImpl.ActionToIgnore {
public BackAction() {
super(CodeInsightBundle.message("javadoc.action.back"), null, IconLoader.getIcon("/actions/back.png"));
}
public void actionPerformed(AnActionEvent e) {
goBack();
}
public void update(AnActionEvent e) {
Presentation presentation = e.getPresentation();
presentation.setEnabled(!myBackStack.isEmpty());
}
}
private class ForwardAction extends AnAction implements HintManagerImpl.ActionToIgnore {
public ForwardAction() {
super(CodeInsightBundle.message("javadoc.action.forward"), null, IconLoader.getIcon("/actions/forward.png"));
}
public void actionPerformed(AnActionEvent e) {
goForward();
}
public void update(AnActionEvent e) {
Presentation presentation = e.getPresentation();
presentation.setEnabled(!myForwardStack.isEmpty());
}
}
private class ExternalDocAction extends AnAction implements HintManagerImpl.ActionToIgnore {
public ExternalDocAction() {
super(CodeInsightBundle.message("javadoc.action.view.external"), null, IconLoader.getIcon("/actions/browser-externalJavaDoc.png"));
registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_EXTERNAL_JAVADOC).getShortcutSet(), null);
}
public void actionPerformed(AnActionEvent e) {
if (myElement != null) {
final PsiElement element = myElement.getElement();
final DocumentationProvider provider = DocumentationManager.getProviderFromElement(element);
final PsiElement originalElement = DocumentationManager.getOriginalElement(element);
boolean processed = false;
if (provider instanceof CompositeDocumentationProvider) {
for (final DocumentationProvider documentationProvider : ((CompositeDocumentationProvider)provider).getProviders()) {
if (documentationProvider instanceof ExternalDocumentationHandler && ((ExternalDocumentationHandler)documentationProvider).handleExternal(element, originalElement)) {
processed = true;
break;
}
}
}
if (!processed) {
final List<String> urls = provider.getUrlFor(element, originalElement);
assert urls != null;
assert !urls.isEmpty();
ExternalJavaDocAction.showExternalJavadoc(urls);
}
}
}
public void update(AnActionEvent e) {
final Presentation presentation = e.getPresentation();
presentation.setEnabled(false);
if (myElement != null) {
final PsiElement element = myElement.getElement();
final DocumentationProvider provider = DocumentationManager.getProviderFromElement(element);
final List<String> urls = provider.getUrlFor(element, DocumentationManager.getOriginalElement(element));
presentation.setEnabled(element != null && urls != null && !urls.isEmpty());
}
}
}
private void registerActions() {
myExternalDocAction
.registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_EXTERNAL_JAVADOC).getShortcutSet(), myEditorPane);
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
int value = scrollBar.getValue() - scrollBar.getUnitIncrement(-1);
value = Math.max(value, 0);
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
int value = scrollBar.getValue() + scrollBar.getUnitIncrement(+1);
value = Math.min(value, scrollBar.getMaximum());
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
int value = scrollBar.getValue() - scrollBar.getUnitIncrement(-1);
value = Math.max(value, 0);
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
int value = scrollBar.getValue() + scrollBar.getUnitIncrement(+1);
value = Math.min(value, scrollBar.getMaximum());
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
int value = scrollBar.getValue() - scrollBar.getBlockIncrement(-1);
value = Math.max(value, 0);
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
int value = scrollBar.getValue() + scrollBar.getBlockIncrement(+1);
value = Math.min(value, scrollBar.getMaximum());
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
scrollBar.setValue(0);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
scrollBar.setValue(scrollBar.getMaximum());
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, KeyEvent.CTRL_MASK), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
scrollBar.setValue(0);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, KeyEvent.CTRL_MASK), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
scrollBar.setValue(scrollBar.getMaximum());
}
});
}
public String getText() {
return myText;
}
public void dispose() {
myBackStack.clear();
myForwardStack.clear();
myKeyboardActions.clear();
myElement = null;
myManager = null;
myHint = null;
myNavigateCallback = null;
}
}
| platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java | /*
* Copyright 2000-2009 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.codeInsight.documentation;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.hint.ElementLocationUtil;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.ide.actions.ExternalJavaDocAction;
import com.intellij.ide.ui.UISettings;
import com.intellij.lang.documentation.CompositeDocumentationProvider;
import com.intellij.lang.documentation.DocumentationProvider;
import com.intellij.lang.documentation.ExternalDocumentationHandler;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.options.FontSize;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.psi.PsiElement;
import com.intellij.psi.SmartPointerManager;
import com.intellij.psi.SmartPsiElementPointer;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.SideBorder;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.Consumer;
import com.intellij.util.containers.HashMap;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.Stack;
public class DocumentationComponent extends JPanel implements Disposable {
private static final int MAX_WIDTH = 500;
private static final int MAX_HEIGHT = 300;
private static final int MIN_HEIGHT = 45;
private DocumentationManager myManager;
private SmartPsiElementPointer myElement;
private final Stack<Context> myBackStack = new Stack<Context>();
private final Stack<Context> myForwardStack = new Stack<Context>();
private ActionToolbar myToolBar;
private boolean myIsEmpty;
private boolean myIsShown;
private final JLabel myElementLabel;
private Style myFontSizeStyle;
private static class Context {
final SmartPsiElementPointer element;
final String text;
final Rectangle viewRect;
public Context(SmartPsiElementPointer element, String text, Rectangle viewRect) {
this.element = element;
this.text = text;
this.viewRect = viewRect;
}
}
private final JScrollPane myScrollPane;
private final JEditorPane myEditorPane;
private String myText; // myEditorPane.getText() surprisingly crashes.., let's cache the text
private final JPanel myControlPanel;
private boolean myControlPanelVisible;
private final ExternalDocAction myExternalDocAction;
private Consumer<PsiElement> myNavigateCallback;
private JBPopup myHint;
private final HashMap<KeyStroke, ActionListener> myKeyboardActions = new HashMap<KeyStroke, ActionListener>();
// KeyStroke --> ActionListener
public boolean requestFocusInWindow() {
return myScrollPane.requestFocusInWindow();
}
public void requestFocus() {
myScrollPane.requestFocus();
}
public DocumentationComponent(final DocumentationManager manager, final AnAction[] additionalActions) {
myManager = manager;
myIsEmpty = true;
myIsShown = false;
myEditorPane = new JEditorPane(UIUtil.HTML_MIME, "") {
public Dimension getPreferredScrollableViewportSize() {
if (getWidth() == 0 || getHeight() == 0) {
setSize(MAX_WIDTH, MAX_HEIGHT);
}
Insets ins = myEditorPane.getInsets();
View rootView = myEditorPane.getUI().getRootView(myEditorPane);
rootView.setSize(MAX_WIDTH,
MAX_HEIGHT); // Necessary! Without this line, size will not increase then you go from small page to bigger one
int prefHeight = (int)rootView.getPreferredSpan(View.Y_AXIS);
prefHeight += ins.bottom + ins.top + myScrollPane.getHorizontalScrollBar().getMaximumSize().height;
return new Dimension(MAX_WIDTH, Math.max(MIN_HEIGHT, Math.min(MAX_HEIGHT, prefHeight)));
}
{
enableEvents(KeyEvent.KEY_EVENT_MASK);
}
protected void processKeyEvent(KeyEvent e) {
KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e);
ActionListener listener = myKeyboardActions.get(keyStroke);
if (listener != null) {
listener.actionPerformed(new ActionEvent(DocumentationComponent.this, 0, ""));
e.consume();
return;
}
super.processKeyEvent(e);
}
@Override
protected void paintComponent(Graphics g) {
UISettings.setupAntialiasing(g);
super.paintComponent(g);
}
};
myText = "";
myEditorPane.setEditable(false);
myEditorPane.setBackground(HintUtil.INFORMATION_COLOR);
myEditorPane.setEditorKit(UIUtil.getHTMLEditorKit());
myScrollPane = new JBScrollPane(myEditorPane) {
@Override
protected void processMouseWheelEvent(MouseWheelEvent e) {
if (!EditorSettingsExternalizable.getInstance().isWheelFontChangeEnabled() || !EditorUtil.isChangeFontSize(e)) {
super.processMouseWheelEvent(e);
return;
}
int change = Math.abs(e.getWheelRotation());
boolean increase = e.getWheelRotation() <= 0;
EditorColorsManager colorsManager = EditorColorsManager.getInstance();
EditorColorsScheme scheme = colorsManager.getGlobalScheme();
FontSize newFontSize = scheme.getQuickDocFontSize();
for (; change > 0; change--) {
if (increase) {
newFontSize = newFontSize.larger();
}
else {
newFontSize = newFontSize.smaller();
}
}
if (newFontSize == scheme.getQuickDocFontSize()) {
return;
}
scheme.setQuickDocFontSize(newFontSize);
applyFontSize();
}
};
myScrollPane.setBorder(null);
final MouseAdapter mouseAdapter = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
myManager.requestFocus();
}
};
myEditorPane.addMouseListener(mouseAdapter);
Disposer.register(this, new Disposable() {
public void dispose() {
myEditorPane.removeMouseListener(mouseAdapter);
}
});
final FocusAdapter focusAdapter = new FocusAdapter() {
public void focusLost(FocusEvent e) {
Component previouslyFocused = WindowManagerEx.getInstanceEx().getFocusedComponent(manager.getProject(getElement()));
if (!(previouslyFocused == myEditorPane)) {
if (myHint != null && !myHint.isDisposed()) myHint.cancel();
}
}
};
myEditorPane.addFocusListener(focusAdapter);
Disposer.register(this, new Disposable() {
public void dispose() {
myEditorPane.removeFocusListener(focusAdapter);
}
});
setLayout(new BorderLayout());
add(myScrollPane, BorderLayout.CENTER);
myScrollPane.setViewportBorder(JBScrollPane.createIndentBorder());
final DefaultActionGroup actions = new DefaultActionGroup();
actions.add(new BackAction());
actions.add(new ForwardAction());
actions.add(myExternalDocAction = new ExternalDocAction());
if (additionalActions != null) {
for (final AnAction action : additionalActions) {
actions.add(action);
}
}
myToolBar = ActionManager.getInstance().createActionToolbar(ActionPlaces.JAVADOC_TOOLBAR, actions, true);
myControlPanel = new JPanel();
myControlPanel.setLayout(new BorderLayout());
myControlPanel.setBorder(IdeBorderFactory.createBorder(SideBorder.BOTTOM));
JPanel dummyPanel = new JPanel();
myElementLabel = new JLabel();
dummyPanel.setLayout(new BorderLayout());
dummyPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
dummyPanel.add(myElementLabel, BorderLayout.EAST);
myControlPanel.add(myToolBar.getComponent(), BorderLayout.WEST);
myControlPanel.add(dummyPanel, BorderLayout.CENTER);
myControlPanelVisible = false;
final HyperlinkListener hyperlinkListener = new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
HyperlinkEvent.EventType type = e.getEventType();
if (type == HyperlinkEvent.EventType.ACTIVATED) {
manager.navigateByLink(DocumentationComponent.this, e.getDescription());
}
else if (type == HyperlinkEvent.EventType.ENTERED) {
myEditorPane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
else if (type == HyperlinkEvent.EventType.EXITED) {
myEditorPane.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
};
myEditorPane.addHyperlinkListener(hyperlinkListener);
Disposer.register(this, new Disposable() {
public void dispose() {
myEditorPane.removeHyperlinkListener(hyperlinkListener);
}
});
registerActions();
updateControlState();
}
public DocumentationComponent(final DocumentationManager manager) {
this(manager, null);
}
public synchronized boolean isEmpty() {
return myIsEmpty;
}
public synchronized void startWait() {
myIsEmpty = true;
}
private void setControlPanelVisible(boolean visible) {
if (visible == myControlPanelVisible) return;
if (visible) {
add(myControlPanel, BorderLayout.NORTH);
}
else {
remove(myControlPanel);
}
myControlPanelVisible = visible;
}
public void setHint(JBPopup hint) {
myHint = hint;
}
public JComponent getComponent() {
return myEditorPane;
}
@Nullable
public PsiElement getElement() {
return myElement != null ? myElement.getElement() : null;
}
public void setNavigateCallback(Consumer<PsiElement> navigateCallback) {
myNavigateCallback = navigateCallback;
}
public void setText(String text, PsiElement element, boolean clearHistory) {
setText(text, element, false, clearHistory);
}
public void setText(String text, PsiElement element, boolean clean, boolean clearHistory) {
if (clean && myElement != null) {
myBackStack.push(saveContext());
myForwardStack.clear();
}
updateControlState();
setData(element, text, clearHistory);
if (clean) {
myIsEmpty = false;
}
if (clearHistory) clearHistory();
}
private void clearHistory() {
myForwardStack.clear();
myBackStack.clear();
}
public void setData(PsiElement _element, String text, final boolean clearHistory) {
if (myElement != null) {
myBackStack.push(saveContext());
myForwardStack.clear();
}
final SmartPsiElementPointer element = _element != null && _element.isValid()
? SmartPointerManager.getInstance(_element.getProject()).createSmartPsiElementPointer(_element)
: null;
if (element != null) {
myElement = element;
}
myIsEmpty = false;
updateControlState();
setDataInternal(element, text, new Rectangle(0, 0));
if (clearHistory) clearHistory();
}
private void setDataInternal(SmartPsiElementPointer element, String text, final Rectangle viewRect) {
setDataInternal(element, text, viewRect, false);
}
private void setDataInternal(SmartPsiElementPointer element, String text, final Rectangle viewRect, boolean skip) {
boolean justShown = false;
myElement = element;
if (!myIsShown && myHint != null) {
myEditorPane.setText(text);
applyFontSize();
myManager.showHint(myHint);
myIsShown = justShown = true;
}
if (!justShown) {
myEditorPane.setText(text);
applyFontSize();
}
if (!skip) {
myText = text;
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
myEditorPane.scrollRectToVisible(viewRect);
}
});
}
private void applyFontSize() {
Document document = myEditorPane.getDocument();
if (!(document instanceof StyledDocument)) {
return;
}
StyledDocument styledDocument = (StyledDocument)document;
if (myFontSizeStyle == null) {
myFontSizeStyle = styledDocument.addStyle("active", null);
}
EditorColorsManager colorsManager = EditorColorsManager.getInstance();
EditorColorsScheme scheme = colorsManager.getGlobalScheme();
StyleConstants.setFontSize(myFontSizeStyle, scheme.getQuickDocFontSize().getSize());
styledDocument.setCharacterAttributes(0, document.getLength(), myFontSizeStyle, true);
}
private void goBack() {
if (myBackStack.isEmpty()) return;
Context context = myBackStack.pop();
myForwardStack.push(saveContext());
restoreContext(context);
updateControlState();
}
private void goForward() {
if (myForwardStack.isEmpty()) return;
Context context = myForwardStack.pop();
myBackStack.push(saveContext());
restoreContext(context);
updateControlState();
}
private Context saveContext() {
Rectangle rect = myScrollPane.getViewport().getViewRect();
return new Context(myElement, myText, rect);
}
private void restoreContext(Context context) {
setDataInternal(context.element, context.text, context.viewRect);
if (myNavigateCallback != null) {
final PsiElement element = context.element.getElement();
if (element != null) {
myNavigateCallback.consume(element);
}
}
}
private void updateControlState() {
ElementLocationUtil.customizeElementLabel(myElement != null ? myElement.getElement() : null, myElementLabel);
myToolBar.updateActionsImmediately(); // update faster
setControlPanelVisible(true);//(!myBackStack.isEmpty() || !myForwardStack.isEmpty());
}
private class BackAction extends AnAction implements HintManagerImpl.ActionToIgnore {
public BackAction() {
super(CodeInsightBundle.message("javadoc.action.back"), null, IconLoader.getIcon("/actions/back.png"));
}
public void actionPerformed(AnActionEvent e) {
goBack();
}
public void update(AnActionEvent e) {
Presentation presentation = e.getPresentation();
presentation.setEnabled(!myBackStack.isEmpty());
}
}
private class ForwardAction extends AnAction implements HintManagerImpl.ActionToIgnore {
public ForwardAction() {
super(CodeInsightBundle.message("javadoc.action.forward"), null, IconLoader.getIcon("/actions/forward.png"));
}
public void actionPerformed(AnActionEvent e) {
goForward();
}
public void update(AnActionEvent e) {
Presentation presentation = e.getPresentation();
presentation.setEnabled(!myForwardStack.isEmpty());
}
}
private class ExternalDocAction extends AnAction implements HintManagerImpl.ActionToIgnore {
public ExternalDocAction() {
super(CodeInsightBundle.message("javadoc.action.view.external"), null, IconLoader.getIcon("/actions/browser-externalJavaDoc.png"));
registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_EXTERNAL_JAVADOC).getShortcutSet(), null);
}
public void actionPerformed(AnActionEvent e) {
if (myElement != null) {
final PsiElement element = myElement.getElement();
final DocumentationProvider provider = DocumentationManager.getProviderFromElement(element);
final PsiElement originalElement = DocumentationManager.getOriginalElement(element);
boolean processed = false;
if (provider instanceof CompositeDocumentationProvider) {
for (final DocumentationProvider documentationProvider : ((CompositeDocumentationProvider)provider).getProviders()) {
if (documentationProvider instanceof ExternalDocumentationHandler && ((ExternalDocumentationHandler)documentationProvider).handleExternal(element, originalElement)) {
processed = true;
break;
}
}
}
if (!processed) {
final List<String> urls = provider.getUrlFor(element, originalElement);
assert urls != null;
assert !urls.isEmpty();
ExternalJavaDocAction.showExternalJavadoc(urls);
}
}
}
public void update(AnActionEvent e) {
final Presentation presentation = e.getPresentation();
presentation.setEnabled(false);
if (myElement != null) {
final PsiElement element = myElement.getElement();
final DocumentationProvider provider = DocumentationManager.getProviderFromElement(element);
final List<String> urls = provider.getUrlFor(element, DocumentationManager.getOriginalElement(element));
presentation.setEnabled(element != null && urls != null && !urls.isEmpty());
}
}
}
private void registerActions() {
myExternalDocAction
.registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_EXTERNAL_JAVADOC).getShortcutSet(), myEditorPane);
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
int value = scrollBar.getValue() - scrollBar.getUnitIncrement(-1);
value = Math.max(value, 0);
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
int value = scrollBar.getValue() + scrollBar.getUnitIncrement(+1);
value = Math.min(value, scrollBar.getMaximum());
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
int value = scrollBar.getValue() - scrollBar.getUnitIncrement(-1);
value = Math.max(value, 0);
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
int value = scrollBar.getValue() + scrollBar.getUnitIncrement(+1);
value = Math.min(value, scrollBar.getMaximum());
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
int value = scrollBar.getValue() - scrollBar.getBlockIncrement(-1);
value = Math.max(value, 0);
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
int value = scrollBar.getValue() + scrollBar.getBlockIncrement(+1);
value = Math.min(value, scrollBar.getMaximum());
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
scrollBar.setValue(0);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
scrollBar.setValue(scrollBar.getMaximum());
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, KeyEvent.CTRL_MASK), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
scrollBar.setValue(0);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, KeyEvent.CTRL_MASK), new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
scrollBar.setValue(scrollBar.getMaximum());
}
});
}
public String getText() {
return myText;
}
public void dispose() {
myBackStack.clear();
myForwardStack.clear();
myKeyboardActions.clear();
myElement = null;
myManager = null;
myHint = null;
myNavigateCallback = null;
}
}
| IDEA-61590 bigger font size for javadoc (ctrl+q)
Return urls processing to quick doc
| platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java | IDEA-61590 bigger font size for javadoc (ctrl+q) | <ide><path>latform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java
<ide> EditorColorsManager colorsManager = EditorColorsManager.getInstance();
<ide> EditorColorsScheme scheme = colorsManager.getGlobalScheme();
<ide> StyleConstants.setFontSize(myFontSizeStyle, scheme.getQuickDocFontSize().getSize());
<del> styledDocument.setCharacterAttributes(0, document.getLength(), myFontSizeStyle, true);
<add> styledDocument.setCharacterAttributes(0, document.getLength(), myFontSizeStyle, false);
<ide> }
<ide>
<ide> private void goBack() { |
|
Java | mit | bb5e1a07c2bfd6f36eb9df88468a5a2784a4052f | 0 | ja837/Heistr | package com.jamieadkins.heistr.Fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import com.jamieadkins.heistr.Activities.EditBuildActivity;
import com.jamieadkins.heistr.BuildObjects.Build;
import com.jamieadkins.heistr.BuildObjects.NewSkillSubTree;
import com.jamieadkins.heistr.BuildObjects.NewSkillTree;
import com.jamieadkins.heistr.BuildObjects.Skill;
import com.jamieadkins.heistr.Consts.Trees;
import com.jamieadkins.heistr.Fragments.ViewPagerFragments.ViewPagerLifecycle;
import com.jamieadkins.heistr.R;
import com.jamieadkins.heistr.utils.SkillCardView;
/**
* A simple {@link Fragment} subclass.
*/
public class NewSkillTreeFragment extends Fragment implements EditBuildActivity.BuildReadyCallbacks,
ViewPagerLifecycle {
private static final String ARG_TREE = "tree";
private static final String ARG_SUB_TREE = "subtree";
EditBuildActivity mActivity;
Build mCurrentBuild;
private int mSkillTreeIndex;
private int mSubTreeIndex;
NewSkillSubTree mCurrentSubTree;
TextView mTvPointsRemaining;
SkillCardView[] mSkillCardViews;
TextView[] mPointsRequired;
public NewSkillTreeFragment() {
// Required empty public constructor
}
public static NewSkillTreeFragment newInstance(int tree, int subtree) {
NewSkillTreeFragment fragment = new NewSkillTreeFragment();
Bundle args = new Bundle();
args.putInt(ARG_TREE, tree);
args.putInt(ARG_SUB_TREE, subtree);
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity = (EditBuildActivity) getActivity();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mSkillTreeIndex = getArguments().getInt(ARG_TREE);
mSubTreeIndex = getArguments().getInt(ARG_SUB_TREE);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String key = getString(R.string.pref_skill_layout);
boolean vertical = preferences.getBoolean(key, true);
int layout = vertical ? R.layout.fragment_new_skill_tree_vertical : R.layout.fragment_new_skill_tree;
// Inflate the layout for this fragment
View rootView = inflater.inflate(layout, container, false);
mTvPointsRemaining = (TextView) rootView.findViewById(R.id.tvPointsRemaining);
mSkillCardViews = new SkillCardView[Trees.SKILLS_PER_SUBTREE];
mSkillCardViews[0] = (SkillCardView) rootView.findViewById(R.id.skill_tier1_skill1);
mSkillCardViews[1] = (SkillCardView) rootView.findViewById(R.id.skill_tier2_skill1);
mSkillCardViews[2] = (SkillCardView) rootView.findViewById(R.id.skill_tier2_skill2);
mSkillCardViews[3] = (SkillCardView) rootView.findViewById(R.id.skill_tier3_skill1);
mSkillCardViews[4] = (SkillCardView) rootView.findViewById(R.id.skill_tier3_skill2);
mSkillCardViews[5] = (SkillCardView) rootView.findViewById(R.id.skill_tier4_skill1);
mPointsRequired = new TextView[3];
mPointsRequired[0] = (TextView) rootView.findViewById(R.id.tvPointsRequired2);
mPointsRequired[1] = (TextView) rootView.findViewById(R.id.tvPointsRequired3);
mPointsRequired[2] = (TextView) rootView.findViewById(R.id.tvPointsRequired4);
final NewSkillSubTree tree = NewSkillSubTree.newNonDBInstance(0);
for (Skill skill : tree.getSkillsInSubTree()) {
skill.setTaken(Skill.NORMAL);
}
SkillCardView skillCardView = (SkillCardView) rootView.findViewById(R.id.skill_tier1_skill1);
skillCardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mActivity.getCurrentBuild().updateSubTree(mActivity, 0, tree);
}
});
return rootView;
}
@Override
public void onResume() {
super.onResume();
if (mActivity.getCurrentBuild() == null) {
mActivity.listenIn(this);
} else {
onBuildReady();
}
}
@Override
public void onBuildReady() {
if (mActivity == null) {
return;
}
mCurrentBuild = mActivity.getCurrentBuild();
mCurrentSubTree = mCurrentBuild.getSkillBuild().getNewSkillTrees()
.get(mSkillTreeIndex).getSubTrees().get(mSubTreeIndex);
initialiseSkillViews();
updatePointsRemaining();
final ScrollView scrollView = (ScrollView) getView().findViewById(R.id.scrollView);
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(scrollView.FOCUS_DOWN);
}
});
}
private void initialiseSkillViews() {
for (int i = 0; i < mSkillCardViews.length; i++) {
final Skill skill = mCurrentSubTree.getSkillsInSubTree().get(i);
mSkillCardViews[i].setSkillName(skill.getName());
mSkillCardViews[i].setNormalDescription(skill.getNormalDescription());
mSkillCardViews[i].setAceDescription(skill.getAceDescription());
mSkillCardViews[i].setSkillStatus(skill.getTaken());
boolean unlocked = mCurrentSubTree.getPointsSpentInThisTree(skill.getTier()) >= skill.getUnlockRequirement();
mSkillCardViews[i].setSkillStatus(unlocked);
mSkillCardViews[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SkillCardView skillCardView = (SkillCardView) v;
int taken = skill.getTaken();
int skillCost = 0;
switch (taken) {
case Skill.NO:
skillCost = skill.getNormalCost();
break;
case Skill.NORMAL:
skillCost = skill.getAceCost();
break;
}
if (mCurrentSubTree.getPointsSpentInThisTree(skill.getTier()) >= skill.getUnlockRequirement()) { //if tier is unlocked
if (skillCost <= mCurrentBuild.getSkillBuild().getNewPointsRemaining()) { //if there are enough points left
switch (taken) {
case Skill.NO:
//Set to normal
skill.setTaken(Skill.NORMAL);
skillCardView.setSkillStatus(Skill.NORMAL);
break;
case Skill.NORMAL:
//Set to Ace
skill.setTaken(Skill.ACE);
skillCardView.setSkillStatus(Skill.ACE);
break;
case Skill.ACE:
//Set to none
skill.setTaken(Skill.NO);
skillCardView.setSkillStatus(Skill.NO);
break;
}
} else {
//Set to none
skill.setTaken(Skill.NO);
skillCardView.setSkillStatus(Skill.NO);
}
}
mCurrentBuild.updateSubTree(mActivity, mSkillTreeIndex, mCurrentSubTree);
updateOtherSkills();
updatePointsRemaining();
}
});
}
}
public void updateOtherSkills() {
for (int i = 0; i < mCurrentSubTree.getSkillsInSubTree().size(); i++) {
Skill skill = mCurrentSubTree.getSkillsInSubTree().get(i);
if (mCurrentSubTree.getPointsSpentInThisTree(skill.getTier()) < skill.getUnlockRequirement()) {
skill.setTaken(Skill.NO);
mSkillCardViews[i].setSkillStatus(skill.getTaken());
mSkillCardViews[i].setSkillStatus(Skill.LOCKED);
} else {
mSkillCardViews[i].setSkillStatus(Skill.UNLOCKED);
}
}
mCurrentBuild.updateSubTree(mActivity, mSkillTreeIndex, mCurrentSubTree);
}
@Override
public void onBuildUpdated() {
updatePointsRemaining();
}
@Override
public void onDetach() {
super.onDetach();
mActivity = null;
}
private void updatePointsRemaining() {
mTvPointsRemaining.setText(mActivity.getCurrentBuild().getSkillBuild().getNewPointsRemaining() +
"/" + mActivity.getCurrentBuild().getSkillBuild().getNewPointsAvailable());
int pointReq = mCurrentSubTree.getSkillsInSubTree().get(1).getUnlockRequirement() - mCurrentSubTree.getPointsSpentInThisTree(2);
if (pointReq < 0) {
pointReq = 0;
}
mPointsRequired[0].setText(pointReq + " more to unlock");
pointReq = mCurrentSubTree.getSkillsInSubTree().get(3).getUnlockRequirement() - mCurrentSubTree.getPointsSpentInThisTree(3);
if (pointReq < 0) {
pointReq = 0;
}
mPointsRequired[1].setText(pointReq + " more to unlock");
pointReq = mCurrentSubTree.getSkillsInSubTree().get(5).getUnlockRequirement() - mCurrentSubTree.getPointsSpentInThisTree(4);
if (pointReq < 0) {
pointReq = 0;
}
mPointsRequired[2].setText(pointReq + " more to unlock");
}
@Override
public void onHide() {
}
@Override
public void onShow() {
if (mActivity == null) {
return;
}
if (mActivity.getCurrentBuild() != null) {
updatePointsRemaining();
}
}
}
| app/src/main/java/com/jamieadkins/heistr/Fragments/NewSkillTreeFragment.java | package com.jamieadkins.heistr.Fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import com.jamieadkins.heistr.Activities.EditBuildActivity;
import com.jamieadkins.heistr.BuildObjects.Build;
import com.jamieadkins.heistr.BuildObjects.NewSkillSubTree;
import com.jamieadkins.heistr.BuildObjects.NewSkillTree;
import com.jamieadkins.heistr.BuildObjects.Skill;
import com.jamieadkins.heistr.Consts.Trees;
import com.jamieadkins.heistr.Fragments.ViewPagerFragments.ViewPagerLifecycle;
import com.jamieadkins.heistr.R;
import com.jamieadkins.heistr.utils.SkillCardView;
/**
* A simple {@link Fragment} subclass.
*/
public class NewSkillTreeFragment extends Fragment implements EditBuildActivity.BuildReadyCallbacks,
ViewPagerLifecycle {
private static final String ARG_TREE = "tree";
private static final String ARG_SUB_TREE = "subtree";
EditBuildActivity mActivity;
Build mCurrentBuild;
private int mSkillTreeIndex;
private int mSubTreeIndex;
NewSkillSubTree mCurrentSubTree;
TextView mTvPointsRemaining;
SkillCardView[] mSkillCardViews;
TextView[] mPointsRequired;
public NewSkillTreeFragment() {
// Required empty public constructor
}
public static NewSkillTreeFragment newInstance(int tree, int subtree) {
NewSkillTreeFragment fragment = new NewSkillTreeFragment();
Bundle args = new Bundle();
args.putInt(ARG_TREE, tree);
args.putInt(ARG_SUB_TREE, subtree);
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity = (EditBuildActivity) getActivity();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mSkillTreeIndex = getArguments().getInt(ARG_TREE);
mSubTreeIndex = getArguments().getInt(ARG_SUB_TREE);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String key = getString(R.string.pref_skill_layout);
boolean vertical = preferences.getBoolean(key, false);
int layout = vertical ? R.layout.fragment_new_skill_tree_vertical : R.layout.fragment_new_skill_tree;
// Inflate the layout for this fragment
View rootView = inflater.inflate(layout, container, false);
mTvPointsRemaining = (TextView) rootView.findViewById(R.id.tvPointsRemaining);
mSkillCardViews = new SkillCardView[Trees.SKILLS_PER_SUBTREE];
mSkillCardViews[0] = (SkillCardView) rootView.findViewById(R.id.skill_tier1_skill1);
mSkillCardViews[1] = (SkillCardView) rootView.findViewById(R.id.skill_tier2_skill1);
mSkillCardViews[2] = (SkillCardView) rootView.findViewById(R.id.skill_tier2_skill2);
mSkillCardViews[3] = (SkillCardView) rootView.findViewById(R.id.skill_tier3_skill1);
mSkillCardViews[4] = (SkillCardView) rootView.findViewById(R.id.skill_tier3_skill2);
mSkillCardViews[5] = (SkillCardView) rootView.findViewById(R.id.skill_tier4_skill1);
mPointsRequired = new TextView[3];
mPointsRequired[0] = (TextView) rootView.findViewById(R.id.tvPointsRequired2);
mPointsRequired[1] = (TextView) rootView.findViewById(R.id.tvPointsRequired3);
mPointsRequired[2] = (TextView) rootView.findViewById(R.id.tvPointsRequired4);
final NewSkillSubTree tree = NewSkillSubTree.newNonDBInstance(0);
for (Skill skill : tree.getSkillsInSubTree()) {
skill.setTaken(Skill.NORMAL);
}
SkillCardView skillCardView = (SkillCardView) rootView.findViewById(R.id.skill_tier1_skill1);
skillCardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mActivity.getCurrentBuild().updateSubTree(mActivity, 0, tree);
}
});
return rootView;
}
@Override
public void onResume() {
super.onResume();
if (mActivity.getCurrentBuild() == null) {
mActivity.listenIn(this);
} else {
onBuildReady();
}
}
@Override
public void onBuildReady() {
if (mActivity == null) {
return;
}
mCurrentBuild = mActivity.getCurrentBuild();
mCurrentSubTree = mCurrentBuild.getSkillBuild().getNewSkillTrees()
.get(mSkillTreeIndex).getSubTrees().get(mSubTreeIndex);
initialiseSkillViews();
updatePointsRemaining();
final ScrollView scrollView = (ScrollView) getView().findViewById(R.id.scrollView);
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(scrollView.FOCUS_DOWN);
}
});
}
private void initialiseSkillViews() {
for (int i = 0; i < mSkillCardViews.length; i++) {
final Skill skill = mCurrentSubTree.getSkillsInSubTree().get(i);
mSkillCardViews[i].setSkillName(skill.getName());
mSkillCardViews[i].setNormalDescription(skill.getNormalDescription());
mSkillCardViews[i].setAceDescription(skill.getAceDescription());
mSkillCardViews[i].setSkillStatus(skill.getTaken());
boolean unlocked = mCurrentSubTree.getPointsSpentInThisTree(skill.getTier()) >= skill.getUnlockRequirement();
mSkillCardViews[i].setSkillStatus(unlocked);
mSkillCardViews[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SkillCardView skillCardView = (SkillCardView) v;
int taken = skill.getTaken();
int skillCost = 0;
switch (taken) {
case Skill.NO:
skillCost = skill.getNormalCost();
break;
case Skill.NORMAL:
skillCost = skill.getAceCost();
break;
}
if (mCurrentSubTree.getPointsSpentInThisTree(skill.getTier()) >= skill.getUnlockRequirement()) { //if tier is unlocked
if (skillCost <= mCurrentBuild.getSkillBuild().getNewPointsRemaining()) { //if there are enough points left
switch (taken) {
case Skill.NO:
//Set to normal
skill.setTaken(Skill.NORMAL);
skillCardView.setSkillStatus(Skill.NORMAL);
break;
case Skill.NORMAL:
//Set to Ace
skill.setTaken(Skill.ACE);
skillCardView.setSkillStatus(Skill.ACE);
break;
case Skill.ACE:
//Set to none
skill.setTaken(Skill.NO);
skillCardView.setSkillStatus(Skill.NO);
break;
}
} else {
//Set to none
skill.setTaken(Skill.NO);
skillCardView.setSkillStatus(Skill.NO);
}
}
mCurrentBuild.updateSubTree(mActivity, mSkillTreeIndex, mCurrentSubTree);
updateOtherSkills();
updatePointsRemaining();
}
});
}
}
public void updateOtherSkills() {
for (int i = 0; i < mCurrentSubTree.getSkillsInSubTree().size(); i++) {
Skill skill = mCurrentSubTree.getSkillsInSubTree().get(i);
if (mCurrentSubTree.getPointsSpentInThisTree(skill.getTier()) < skill.getUnlockRequirement()) {
skill.setTaken(Skill.NO);
mSkillCardViews[i].setSkillStatus(skill.getTaken());
mSkillCardViews[i].setSkillStatus(Skill.LOCKED);
} else {
mSkillCardViews[i].setSkillStatus(Skill.UNLOCKED);
}
}
mCurrentBuild.updateSubTree(mActivity, mSkillTreeIndex, mCurrentSubTree);
}
@Override
public void onBuildUpdated() {
updatePointsRemaining();
}
@Override
public void onDetach() {
super.onDetach();
mActivity = null;
}
private void updatePointsRemaining() {
mTvPointsRemaining.setText(mActivity.getCurrentBuild().getSkillBuild().getNewPointsRemaining() +
"/" + mActivity.getCurrentBuild().getSkillBuild().getNewPointsAvailable());
int pointReq = mCurrentSubTree.getSkillsInSubTree().get(1).getUnlockRequirement() - mCurrentSubTree.getPointsSpentInThisTree(2);
if (pointReq < 0) {
pointReq = 0;
}
mPointsRequired[0].setText(pointReq + " more to unlock");
pointReq = mCurrentSubTree.getSkillsInSubTree().get(3).getUnlockRequirement() - mCurrentSubTree.getPointsSpentInThisTree(3);
if (pointReq < 0) {
pointReq = 0;
}
mPointsRequired[1].setText(pointReq + " more to unlock");
pointReq = mCurrentSubTree.getSkillsInSubTree().get(5).getUnlockRequirement() - mCurrentSubTree.getPointsSpentInThisTree(4);
if (pointReq < 0) {
pointReq = 0;
}
mPointsRequired[2].setText(pointReq + " more to unlock");
}
@Override
public void onHide() {
}
@Override
public void onShow() {
if (mActivity == null) {
return;
}
if (mActivity.getCurrentBuild() != null) {
updatePointsRemaining();
}
}
}
| Vertical sill trees by default
| app/src/main/java/com/jamieadkins/heistr/Fragments/NewSkillTreeFragment.java | Vertical sill trees by default | <ide><path>pp/src/main/java/com/jamieadkins/heistr/Fragments/NewSkillTreeFragment.java
<ide> Bundle savedInstanceState) {
<ide> SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
<ide> String key = getString(R.string.pref_skill_layout);
<del> boolean vertical = preferences.getBoolean(key, false);
<add> boolean vertical = preferences.getBoolean(key, true);
<ide> int layout = vertical ? R.layout.fragment_new_skill_tree_vertical : R.layout.fragment_new_skill_tree;
<ide>
<ide> // Inflate the layout for this fragment |
|
Java | agpl-3.0 | 99d8d38013ba603c86054ba10b349ebedcea6b5c | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 45621e60-2e60-11e5-9284-b827eb9e62be | hello.java | 455c9ee0-2e60-11e5-9284-b827eb9e62be | 45621e60-2e60-11e5-9284-b827eb9e62be | hello.java | 45621e60-2e60-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>455c9ee0-2e60-11e5-9284-b827eb9e62be
<add>45621e60-2e60-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | 767b1bad27cdaf42fd991e399a202dd57184cda4 | 0 | Whiley/WhileyCompiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler | package wyil.io;
import java.io.*;
import java.util.*;
import wyil.Transform;
import wybs.lang.Path;
import wyil.lang.*;
import wyil.util.Pair;
import wyjvm.io.BinaryOutputStream;
public class WyilFileWriter implements Transform {
private static final int MAJOR_VERSION = 0;
private static final int MINOR_VERSION = 1;
private BinaryOutputStream output;
private ArrayList<String> stringPool = new ArrayList<String>();
private HashMap<String,Integer> stringCache = new HashMap<String,Integer>();
private ArrayList<PATH_Item> pathPool = new ArrayList<PATH_Item>();
private HashMap<Path.ID,Integer> pathCache = new HashMap<Path.ID,Integer>();
private ArrayList<NAME_Item> namePool = new ArrayList<NAME_Item>();
private HashMap<Pair<NAME_Kind,Path.ID>,Integer> nameCache = new HashMap<Pair<NAME_Kind,Path.ID>,Integer>();
private ArrayList<CONSTANT_Item> constantPool = new ArrayList<CONSTANT_Item>();
private HashMap<Value,Integer> constantCache = new HashMap<Value,Integer>();
private ArrayList<TYPE_Item> typePool = new ArrayList<TYPE_Item>();
private HashMap<Type,Integer> typeCache = new HashMap<Type,Integer>();
@Override
public void apply(WyilFile module) throws IOException {
String filename = module.filename().replace(".whiley", ".wyasm");
output = new BinaryOutputStream(new FileOutputStream(filename));
buildPools(module);
writeHeader(module);
}
/**
* Write the header information for this WYIL file.
*
* @param module
* @throws IOException
*/
private void writeHeader(WyilFile module)
throws IOException {
// first, write magic number
output.write(0x57); // W
output.write(0x59); // Y
output.write(0x49); // I
output.write(0x4C); // L
output.write(0x46); // F
output.write(0x49); // I
output.write(0x4C); // L
output.write(0x45); // E
// second, write the file version number
output.write_uv(MAJOR_VERSION);
output.write_uv(MINOR_VERSION);
// third, write the various pool sizes
output.write_uv(stringPool.size());
output.write_uv(pathPool.size());
output.write_uv(namePool.size());
output.write_uv(constantPool.size());
output.write_uv(typePool.size());
// finally, write the number of blocks
output.write_uv(module.declarations().size());
}
private void buildPools(WyilFile module) {
stringPool.clear();
stringCache.clear();
pathPool.clear();
pathCache.clear();
namePool.clear();
nameCache.clear();
constantPool.clear();
constantCache.clear();
typePool.clear();
typeCache.clear();
addPathItem(NAME_Kind.MODULE,module.id());
for(WyilFile.Declaration d : module.declarations()) {
buildPools(d);
}
}
private void buildPools(WyilFile.Declaration declaration) {
if(declaration instanceof WyilFile.TypeDeclaration) {
buildPools((WyilFile.TypeDeclaration)declaration);
} else if(declaration instanceof WyilFile.ConstantDeclaration) {
buildPools((WyilFile.ConstantDeclaration)declaration);
} else if(declaration instanceof WyilFile.MethodDeclaration) {
buildPools((WyilFile.MethodDeclaration)declaration);
}
}
private void buildPools(WyilFile.TypeDeclaration declaration) {
addStringItem(declaration.name());
addTypeItem(declaration.type());
}
private void buildPools(WyilFile.ConstantDeclaration declaration) {
addStringItem(declaration.name());
addConstantItem(declaration.constant());
}
private void buildPools(WyilFile.MethodDeclaration declaration) {
addStringItem(declaration.name());
addTypeItem(declaration.type());
}
private int addPathItem(NAME_Kind kind, Path.ID pid) {
Pair<NAME_Kind,Path.ID> p = new Pair(kind,pid);
Integer index = nameCache.get(p);
if(index == null) {
int i = namePool.size();
nameCache.put(p, i);
namePool.add(new NAME_Item(kind,addPathItem(pid)));
return i;
} else {
return index;
}
}
private int addStringItem(String string) {
Integer index = stringCache.get(string);
if(index == null) {
int i = stringPool.size();
stringCache.put(string, i);
stringPool.add(string);
return i;
} else {
return index;
}
}
private int addPathItem(Path.ID pid) {
if(pid == null) {
return -1;
}
Integer index = pathCache.get(pid);
if(index == null) {
int i = pathPool.size();
pathCache.put(pid, i);
pathPool.add(new PATH_Item(addPathItem(pid.parent()),addStringItem(pid.last())));
return i;
} else {
return index;
}
}
private int addTypeItem(Type t) {
// TODO: this could be made way more efficient.
Integer index = typeCache.get(t);
if(index == null) {
int i = typePool.size();
typeCache.put(t, i);
TYPE_Kind kind;
int[] children = null;
if(t instanceof Type.Null) {
kind = TYPE_Kind.NULL;
} else if(t instanceof Type.Bool) {
kind = TYPE_Kind.BOOL;
} else if(t instanceof Type.Byte) {
kind = TYPE_Kind.BYTE;
} else if(t instanceof Type.Char) {
kind = TYPE_Kind.CHAR;
} else if(t instanceof Type.Int) {
kind = TYPE_Kind.INT;
} else if(t instanceof Type.Real) {
kind = TYPE_Kind.RATIONAL;
} else if(t instanceof Type.Strung) {
kind = TYPE_Kind.STRING;
} else if(t instanceof Type.List) {
Type.List l = (Type.List) t;
kind = TYPE_Kind.LIST;
children = new int[1];
children[0] = addTypeItem(l.element());
} else if(t instanceof Type.Set) {
Type.Set l = (Type.Set) t;
kind = TYPE_Kind.SET;
children = new int[1];
children[0] = addTypeItem(l.element());
} else if(t instanceof Type.Map) {
Type.Map l = (Type.Map) t;
kind = TYPE_Kind.MAP;
children = new int[2];
children[0] = addTypeItem(l.key());
children[1] = addTypeItem(l.value());
} else if(t instanceof Type.Tuple) {
Type.Tuple l = (Type.Tuple) t;
kind = TYPE_Kind.TUPLE;
List<Type> elements = l.elements();
children = new int[elements.size()];
for(int k=0;k!=elements.size();++k) {
children[k] = addTypeItem(elements.get(k));
}
} else if(t instanceof Type.Record) {
Type.Record l = (Type.Record) t;
kind = TYPE_Kind.RECORD;
HashSet<String> fields = l.keys();
children = new int[fields.size()*2];
int k = 0;
for(String field : fields) {
children[k] = addTypeItem(l.field(field));
children[k+1] = addStringItem(field);
k = k + 2;
}
} else if(t instanceof Type.Function) {
kind = TYPE_Kind.FUNCTION;
// TODO:
} else if(t instanceof Type.Method) {
kind = TYPE_Kind.METHOD;
// TODO:
} else if(t instanceof Type.Reference) {
Type.Reference l = (Type.Reference) t;
kind = TYPE_Kind.REFERENCE;
children = new int[1];
children[0] = addTypeItem(l.element());
} else if(t instanceof Type.Negation) {
Type.Negation l = (Type.Negation) t;
kind = TYPE_Kind.NEGATION;
children = new int[1];
children[0] = addTypeItem(l.element());
} else if(t instanceof Type.EffectiveList) {
kind = TYPE_Kind.EFFECTIVE_LIST;
} else if(t instanceof Type.Union) {
if(t instanceof Type.EffectiveSet) {
kind = TYPE_Kind.EFFECTIVE_SET;
} else if(t instanceof Type.EffectiveMap) {
kind = TYPE_Kind.EFFECTIVE_MAP;
} else if(t instanceof Type.EffectiveTuple) {
kind = TYPE_Kind.EFFECTIVE_TUPLE;
} else if(t instanceof Type.EffectiveRecord) {
kind = TYPE_Kind.EFFECTIVE_RECORD;
} else if(t instanceof Type.EffectiveIndexible) {
kind = TYPE_Kind.EFFECTIVE_INDEXIBLE;
} else if(t instanceof Type.EffectiveCollection) {
kind = TYPE_Kind.EFFECTIVE_COLLECTION;
} else {
kind = TYPE_Kind.UNION;
}
Type.Union u = (Type.Union) t;
HashSet<Type> bounds = u.bounds();
children = new int[bounds.size()];
int k = 0;
for(Type bound : bounds) {
children[k++] = addTypeItem(bound);
}
} else {
throw new IllegalArgumentException("unknown type encountered");
}
typePool.add(new TYPE_Item(kind,children));
return i;
} else {
return index;
}
}
private int addConstantItem(Value v) {
Integer index = constantCache.get(v);
if(index == null) {
int i = constantPool.size();
constantCache.put(v, i);
CONSTANT_Kind kind;
int[] children = null;
if(v instanceof Value.Null) {
kind = CONSTANT_Kind.NULL;
} else if(v instanceof Value.Bool) {
kind = CONSTANT_Kind.BOOL;
} else if(v instanceof Value.Byte) {
kind = CONSTANT_Kind.BYTE;
} else if(v instanceof Value.Char) {
kind = CONSTANT_Kind.CHAR;
} else if(v instanceof Value.Integer) {
kind = CONSTANT_Kind.INT;
} else if(v instanceof Value.Rational) {
kind = CONSTANT_Kind.RATIONAL;
} else if(v instanceof Value.Strung) {
kind = CONSTANT_Kind.STRING;
} else if(v instanceof Value.List) {
Value.List l = (Value.List) v;
kind = CONSTANT_Kind.LIST;
children = new int[l.values.size()];
for (int k = 0; k != children.length; ++k) {
children[k] = addConstantItem(l.values.get(k));
}
} else if(v instanceof Value.Set) {
Value.Set s = (Value.Set) v;
kind = CONSTANT_Kind.SET;
children = new int[s.values.size()];
ArrayList<Value> values = new ArrayList<Value>(s.values);
for (int k = 0; k != children.length; ++k) {
children[k] = addConstantItem(values.get(k));
}
} else if(v instanceof Value.Map) {
Value.Map s = (Value.Map) v;
kind = CONSTANT_Kind.MAP;
ArrayList<Value> values = new ArrayList<Value>(s.values.keySet());
children = new int[values.size() * 2];
for (int k = 0; k != values.size(); ++k) {
Value key = values.get(k);
Value val = s.values.get(key);
children[k * 2] = addConstantItem(key);
children[(k * 2) + 1] = addConstantItem(val);
}
} else if(v instanceof Value.Tuple) {
Value.Tuple t = (Value.Tuple) v;
kind = CONSTANT_Kind.TUPLE;
children = new int[t.values.size()];
for (int k = 0; k != children.length; ++k) {
children[k] = addConstantItem(t.values.get(k));
}
} else if(v instanceof Value.Record) {
Value.Record r = (Value.Record) v;
kind = CONSTANT_Kind.RECORD;
ArrayList<String> fields = new ArrayList<String>(r.values.keySet());
children = new int[fields.size()*2];
for (int k = 0; k != fields.size(); ++k) {
String field = fields.get(k);
children[k << 1] = addStringItem(field);
children[(k << 1) + 1] = addConstantItem(r.values.get(field));
}
} else if(v instanceof Value.FunctionOrMethod){
kind = CONSTANT_Kind.FUNCTION_OR_METHOD;
// TODO
} else {
throw new IllegalArgumentException("unknown value encountered");
}
constantPool.add(new CONSTANT_Item(kind,children));
return i;
} else {
return index;
}
}
/**
* An PATH_Item represents a path item.
*
* @author David J. Pearce
*
*/
private class PATH_Item {
/**
* The index in the path pool of the parent for this item, or -1 if it
* has not parent.
*/
public final int parentIndex;
/**
* The index of this path component in the string pool
*/
public final int stringIndex;
public PATH_Item(int parentIndex, int stringIndex) {
this.parentIndex = parentIndex;
this.stringIndex = stringIndex;
}
}
private enum NAME_Kind {
PACKAGE(0),
MODULE(1),
CONSTANT(2),
TYPE(3),
FUNCTION(4),
METHOD(5);
private final int kind;
private NAME_Kind(int kind) {
this.kind = kind;
}
public int kind() {
return kind;
}
}
/**
* A NAME_Item represents a named path item, such as a package, module or
* something within a module (e.g. a function or method declaration).
*
* @author David J. Pearce
*
*/
private class NAME_Item {
/**
* The kind of name item this represents.
*/
public final NAME_Kind kind;
/**
* Index of path for this item in path pool
*/
public final int pathIndex;
public NAME_Item(NAME_Kind kind, int pathIndex) {
this.kind = kind;
this.pathIndex = pathIndex;
}
}
private enum CONSTANT_Kind {
NULL(0),
BOOL(1),
BYTE(2),
CHAR(3),
INT(4),
RATIONAL(5),
STRING(6),
LIST(7),
SET(8),
MAP(9),
TUPLE(10),
RECORD(11),
FUNCTION_OR_METHOD(12);
private final int kind;
private CONSTANT_Kind(int kind) {
this.kind = kind;
}
public int kind() {
return kind;
}
}
/**
* Represents a WYIL Constant value.
*
* @author David J. Pearce
*
*/
private class CONSTANT_Item {
public final CONSTANT_Kind kind;
public final int[] children;
public CONSTANT_Item(CONSTANT_Kind kind, int... children) {
this.kind = kind;
this.children = children;
}
}
private enum TYPE_Kind {
NULL(0),
BOOL(1),
BYTE(2),
CHAR(3),
INT(4),
RATIONAL(5),
STRING(6),
LIST(7),
SET(8),
MAP(9),
TUPLE(10),
RECORD(11),
REFERENCE(12),
FUNCTION(13),
METHOD(14),
NOMINAL(15),
NEGATION(16),
UNION(17),
EFFECTIVE_COLLECTION(18),
EFFECTIVE_INDEXIBLE(19),
EFFECTIVE_LIST(20),
EFFECTIVE_SET(21),
EFFECTIVE_MAP(22),
EFFECTIVE_TUPLE(23),
EFFECTIVE_RECORD(24);
private final int kind;
private TYPE_Kind(int kind) {
this.kind = kind;
}
public int kind() {
return kind;
}
}
/**
* A pool item represents a WYIL type. For example, a <code>int</code> type
* or <code>[int]</code> (i.e. list of int) type.
*
* @author David J. Pearce
*
*/
private class TYPE_Item {
/**
* Type kind (e.g. INT, REAL, etc)
*/
public final TYPE_Kind kind;
/**
* Indices of any children in type pool
*/
public final int[] children;
public TYPE_Item(TYPE_Kind kind, int[] children) {
this.kind = kind;
this.children = Arrays.copyOf(children, children.length);
}
}
}
| src/wyil/io/WyilFileWriter.java | package wyil.io;
import java.io.*;
import java.util.*;
import wyil.Transform;
import wybs.lang.Path;
import wyil.lang.*;
import wyil.util.Pair;
import wyjvm.io.BinaryOutputStream;
public class WyilFileWriter implements Transform {
private static final int MAJOR_VERSION = 0;
private static final int MINOR_VERSION = 1;
private BinaryOutputStream output;
private ArrayList<String> stringPool = new ArrayList<String>();
private HashMap<String,Integer> stringCache = new HashMap<String,Integer>();
private ArrayList<PATH_Item> pathPool = new ArrayList<PATH_Item>();
private HashMap<Path.ID,Integer> pathCache = new HashMap<Path.ID,Integer>();
private ArrayList<NAME_Item> namePool = new ArrayList<NAME_Item>();
private HashMap<Pair<NAME_Kind,Path.ID>,Integer> nameCache = new HashMap<Pair<NAME_Kind,Path.ID>,Integer>();
private ArrayList<CONSTANT_Item> constantPool = new ArrayList<CONSTANT_Item>();
private HashMap<Value,Integer> constantCache = new HashMap<Value,Integer>();
private ArrayList<TYPE_Item> typePool = new ArrayList<TYPE_Item>();
private HashMap<Type,Integer> typeCache = new HashMap<Type,Integer>();
@Override
public void apply(WyilFile module) throws IOException {
String filename = module.filename().replace(".whiley", ".wyasm");
output = new BinaryOutputStream(new FileOutputStream(filename));
buildPools(module);
writeHeader(module);
}
/**
* Write the header information for this WYIL file.
*
* @param module
* @throws IOException
*/
private void writeHeader(WyilFile module)
throws IOException {
// first, write magic number
output.write(0x57); // W
output.write(0x59); // Y
output.write(0x49); // I
output.write(0x4C); // L
output.write(0x46); // F
output.write(0x49); // I
output.write(0x4C); // L
output.write(0x45); // E
// second, write the file version number
output.write_uv(MAJOR_VERSION);
output.write_uv(MINOR_VERSION);
// third, write the various pool sizes
output.write_uv(stringPool.size());
output.write_uv(pathPool.size());
output.write_uv(namePool.size());
output.write_uv(constantPool.size());
output.write_uv(typePool.size());
// finally, write the number of blocks
output.write_uv(module.declarations().size());
}
private void buildPools(WyilFile module) {
stringPool.clear();
stringCache.clear();
pathPool.clear();
pathCache.clear();
namePool.clear();
nameCache.clear();
constantPool.clear();
constantCache.clear();
typePool.clear();
typeCache.clear();
addPathItem(NAME_Kind.MODULE,module.id());
for(WyilFile.Declaration d : module.declarations()) {
buildPools(d);
}
}
private void buildPools(WyilFile.Declaration declaration) {
if(declaration instanceof WyilFile.TypeDeclaration) {
buildPools((WyilFile.TypeDeclaration)declaration);
} else if(declaration instanceof WyilFile.ConstantDeclaration) {
buildPools((WyilFile.ConstantDeclaration)declaration);
} else if(declaration instanceof WyilFile.MethodDeclaration) {
buildPools((WyilFile.MethodDeclaration)declaration);
}
}
private void buildPools(WyilFile.TypeDeclaration declaration) {
addStringItem(declaration.name());
addTypeItem(declaration.type());
}
private void buildPools(WyilFile.ConstantDeclaration declaration) {
addStringItem(declaration.name());
addConstantItem(declaration.constant());
}
private void buildPools(WyilFile.MethodDeclaration declaration) {
addStringItem(declaration.name());
addTypeItem(declaration.type());
}
private int addPathItem(NAME_Kind kind, Path.ID pid) {
Pair<NAME_Kind,Path.ID> p = new Pair(kind,pid);
Integer index = nameCache.get(p);
if(index == null) {
int i = namePool.size();
nameCache.put(p, i);
namePool.add(new NAME_Item(kind,addPathItem(pid)));
return i;
} else {
return index;
}
}
private int addStringItem(String string) {
Integer index = stringCache.get(string);
if(index == null) {
int i = stringPool.size();
stringCache.put(string, i);
stringPool.add(string);
return i;
} else {
return index;
}
}
private int addPathItem(Path.ID pid) {
if(pid == null) {
return -1;
}
Integer index = pathCache.get(pid);
if(index == null) {
int i = pathPool.size();
pathCache.put(pid, i);
pathPool.add(new PATH_Item(addPathItem(pid.parent()),addStringItem(pid.last())));
return i;
} else {
return index;
}
}
private int addTypeItem(Type t) {
// TODO: this could be made way more efficient.
Integer index = typeCache.get(t);
if(index == null) {
int i = typePool.size();
typeCache.put(t, i);
TYPE_Kind kind;
int[] children = null;
if(t instanceof Type.Null) {
kind = TYPE_Kind.NULL;
} else if(t instanceof Type.Bool) {
kind = TYPE_Kind.BOOL;
} else if(t instanceof Type.Byte) {
kind = TYPE_Kind.BYTE;
} else if(t instanceof Type.Char) {
kind = TYPE_Kind.CHAR;
} else if(t instanceof Type.Int) {
kind = TYPE_Kind.INT;
} else if(t instanceof Type.Real) {
kind = TYPE_Kind.RATIONAL;
} else if(t instanceof Type.Strung) {
kind = TYPE_Kind.STRING;
} else if(t instanceof Type.List) {
Type.List l = (Type.List) t;
kind = TYPE_Kind.LIST;
children = new int[1];
children[0] = addTypeItem(l.element());
} else if(t instanceof Type.Set) {
Type.Set l = (Type.Set) t;
kind = TYPE_Kind.SET;
children = new int[1];
children[0] = addTypeItem(l.element());
} else if(t instanceof Type.Map) {
Type.Map l = (Type.Map) t;
kind = TYPE_Kind.MAP;
children = new int[2];
children[0] = addTypeItem(l.key());
children[1] = addTypeItem(l.value());
} else if(t instanceof Type.Tuple) {
Type.Tuple l = (Type.Tuple) t;
kind = TYPE_Kind.TUPLE;
List<Type> elements = l.elements();
children = new int[elements.size()];
for(int k=0;k!=elements.size();++k) {
children[k] = addTypeItem(elements.get(k));
}
} else if(t instanceof Type.Record) {
Type.Record l = (Type.Record) t;
kind = TYPE_Kind.RECORD;
HashSet<String> fields = l.keys();
children = new int[fields.size()*2];
int k = 0;
for(String field : fields) {
children[k] = addTypeItem(l.field(field));
children[k+1] = addStringItem(field);
k = k + 2;
}
} else if(t instanceof Type.FunctionOrMethod) {
kind = TYPE_Kind.FUNCTION;
} else if(t instanceof Type.Reference) {
Type.Reference l = (Type.Reference) t;
kind = TYPE_Kind.REFERENCE;
children = new int[1];
children[0] = addTypeItem(l.element());
} else if(t instanceof Type.Negation) {
Type.Negation l = (Type.Negation) t;
kind = TYPE_Kind.NEGATION;
children = new int[1];
children[0] = addTypeItem(l.element());
} else if(t instanceof Type.EffectiveList) {
} else if(t instanceof Type.EffectiveSet) {
} else if(t instanceof Type.EffectiveMap) {
} else if(t instanceof Type.EffectiveTuple) {
} else if(t instanceof Type.EffectiveRecord) {
} else if(t instanceof Type.EffectiveIndexible) {
} else if(t instanceof Type.EffectiveCollection) {
} else if(t instanceof Type.Union) {
} else {
throw new IllegalArgumentException("unknown type encountered");
}
typePool.add(new TYPE_Item(kind,children));
return i;
} else {
return index;
}
}
private int addConstantItem(Value v) {
Integer index = constantCache.get(v);
if(index == null) {
int i = constantPool.size();
constantCache.put(v, i);
CONSTANT_Kind kind;
int[] children = null;
if(v instanceof Value.Null) {
kind = CONSTANT_Kind.NULL;
} else if(v instanceof Value.Bool) {
kind = CONSTANT_Kind.BOOL;
} else if(v instanceof Value.Byte) {
kind = CONSTANT_Kind.BYTE;
} else if(v instanceof Value.Char) {
kind = CONSTANT_Kind.CHAR;
} else if(v instanceof Value.Integer) {
kind = CONSTANT_Kind.INT;
} else if(v instanceof Value.Rational) {
kind = CONSTANT_Kind.RATIONAL;
} else if(v instanceof Value.Strung) {
kind = CONSTANT_Kind.STRING;
} else if(v instanceof Value.List) {
Value.List l = (Value.List) v;
kind = CONSTANT_Kind.LIST;
children = new int[l.values.size()];
for (int k = 0; k != children.length; ++k) {
children[k] = addConstantItem(l.values.get(k));
}
} else if(v instanceof Value.Set) {
Value.Set s = (Value.Set) v;
kind = CONSTANT_Kind.SET;
children = new int[s.values.size()];
ArrayList<Value> values = new ArrayList<Value>(s.values);
for (int k = 0; k != children.length; ++k) {
children[k] = addConstantItem(values.get(k));
}
} else if(v instanceof Value.Map) {
Value.Map s = (Value.Map) v;
kind = CONSTANT_Kind.MAP;
ArrayList<Value> values = new ArrayList<Value>(s.values.keySet());
children = new int[values.size() * 2];
for (int k = 0; k != values.size(); ++k) {
Value key = values.get(k);
Value val = s.values.get(key);
children[k * 2] = addConstantItem(key);
children[(k * 2) + 1] = addConstantItem(val);
}
} else if(v instanceof Value.Tuple) {
Value.Tuple t = (Value.Tuple) v;
kind = CONSTANT_Kind.TUPLE;
children = new int[t.values.size()];
for (int k = 0; k != children.length; ++k) {
children[k] = addConstantItem(t.values.get(k));
}
} else if(v instanceof Value.Record) {
Value.Record r = (Value.Record) v;
kind = CONSTANT_Kind.RECORD;
ArrayList<String> fields = new ArrayList<String>(r.values.keySet());
children = new int[fields.size()*2];
for (int k = 0; k != fields.size(); ++k) {
String field = fields.get(k);
children[k << 1] = addStringItem(field);
children[(k << 1) + 1] = addConstantItem(r.values.get(field));
}
} else if(v instanceof Value.FunctionOrMethod){
kind = CONSTANT_Kind.FUNCTION_OR_METHOD;
// TODO
} else {
throw new IllegalArgumentException("unknown value encountered");
}
constantPool.add(new CONSTANT_Item(kind,children));
return i;
} else {
return index;
}
}
/**
* An PATH_Item represents a path item.
*
* @author David J. Pearce
*
*/
private class PATH_Item {
/**
* The index in the path pool of the parent for this item, or -1 if it
* has not parent.
*/
public final int parentIndex;
/**
* The index of this path component in the string pool
*/
public final int stringIndex;
public PATH_Item(int parentIndex, int stringIndex) {
this.parentIndex = parentIndex;
this.stringIndex = stringIndex;
}
}
private enum NAME_Kind {
PACKAGE(0),
MODULE(1),
CONSTANT(2),
TYPE(3),
FUNCTION(4),
METHOD(5);
private final int kind;
private NAME_Kind(int kind) {
this.kind = kind;
}
public int kind() {
return kind;
}
}
/**
* A NAME_Item represents a named path item, such as a package, module or
* something within a module (e.g. a function or method declaration).
*
* @author David J. Pearce
*
*/
private class NAME_Item {
/**
* The kind of name item this represents.
*/
public final NAME_Kind kind;
/**
* Index of path for this item in path pool
*/
public final int pathIndex;
public NAME_Item(NAME_Kind kind, int pathIndex) {
this.kind = kind;
this.pathIndex = pathIndex;
}
}
private enum CONSTANT_Kind {
NULL(0),
BOOL(1),
BYTE(2),
CHAR(3),
INT(4),
RATIONAL(5),
STRING(6),
LIST(7),
SET(8),
MAP(9),
TUPLE(10),
RECORD(11),
FUNCTION_OR_METHOD(12);
private final int kind;
private CONSTANT_Kind(int kind) {
this.kind = kind;
}
public int kind() {
return kind;
}
}
/**
* Represents a WYIL Constant value.
*
* @author David J. Pearce
*
*/
private class CONSTANT_Item {
public final CONSTANT_Kind kind;
public final int[] children;
public CONSTANT_Item(CONSTANT_Kind kind, int... children) {
this.kind = kind;
this.children = children;
}
}
private enum TYPE_Kind {
NULL(0),
BOOL(1),
BYTE(2),
CHAR(3),
INT(4),
RATIONAL(5),
STRING(6),
LIST(7),
SET(8),
MAP(9),
TUPLE(10),
RECORD(11),
REFERENCE(12),
FUNCTION(13),
METHOD(14),
NOMINAL(15),
NEGATION(16),
UNION(17),
EFFECTIVE_COLLECTION(18),
EFFECTIVE_INDEXIBLE(19),
EFFECTIVE_LIST(20),
EFFECTIVE_SET(21),
EFFECTIVE_MAP(22),
EFFECTIVE_TUPLE(23),
EFFECTIVE_RECORD(24);
private final int kind;
private TYPE_Kind(int kind) {
this.kind = kind;
}
public int kind() {
return kind;
}
}
/**
* A pool item represents a WYIL type. For example, a <code>int</code> type
* or <code>[int]</code> (i.e. list of int) type.
*
* @author David J. Pearce
*
*/
private class TYPE_Item {
/**
* Type kind (e.g. INT, REAL, etc)
*/
public final TYPE_Kind kind;
/**
* Indices of any children in type pool
*/
public final int[] children;
public TYPE_Item(TYPE_Kind kind, int[] children) {
this.kind = kind;
this.children = Arrays.copyOf(children, children.length);
}
}
}
| Ok, well it compiles now.
| src/wyil/io/WyilFileWriter.java | Ok, well it compiles now. | <ide><path>rc/wyil/io/WyilFileWriter.java
<ide> children[k+1] = addStringItem(field);
<ide> k = k + 2;
<ide> }
<del> } else if(t instanceof Type.FunctionOrMethod) {
<add> } else if(t instanceof Type.Function) {
<ide> kind = TYPE_Kind.FUNCTION;
<add> // TODO:
<add> } else if(t instanceof Type.Method) {
<add> kind = TYPE_Kind.METHOD;
<add> // TODO:
<ide> } else if(t instanceof Type.Reference) {
<ide> Type.Reference l = (Type.Reference) t;
<ide> kind = TYPE_Kind.REFERENCE;
<ide> children = new int[1];
<ide> children[0] = addTypeItem(l.element());
<ide> } else if(t instanceof Type.EffectiveList) {
<del>
<del> } else if(t instanceof Type.EffectiveSet) {
<del>
<del> } else if(t instanceof Type.EffectiveMap) {
<del>
<del> } else if(t instanceof Type.EffectiveTuple) {
<del>
<del> } else if(t instanceof Type.EffectiveRecord) {
<del>
<del> } else if(t instanceof Type.EffectiveIndexible) {
<del>
<del> } else if(t instanceof Type.EffectiveCollection) {
<del>
<del> } else if(t instanceof Type.Union) {
<del>
<add> kind = TYPE_Kind.EFFECTIVE_LIST;
<add> } else if(t instanceof Type.Union) {
<add> if(t instanceof Type.EffectiveSet) {
<add> kind = TYPE_Kind.EFFECTIVE_SET;
<add> } else if(t instanceof Type.EffectiveMap) {
<add> kind = TYPE_Kind.EFFECTIVE_MAP;
<add> } else if(t instanceof Type.EffectiveTuple) {
<add> kind = TYPE_Kind.EFFECTIVE_TUPLE;
<add> } else if(t instanceof Type.EffectiveRecord) {
<add> kind = TYPE_Kind.EFFECTIVE_RECORD;
<add> } else if(t instanceof Type.EffectiveIndexible) {
<add> kind = TYPE_Kind.EFFECTIVE_INDEXIBLE;
<add> } else if(t instanceof Type.EffectiveCollection) {
<add> kind = TYPE_Kind.EFFECTIVE_COLLECTION;
<add> } else {
<add> kind = TYPE_Kind.UNION;
<add> }
<add> Type.Union u = (Type.Union) t;
<add> HashSet<Type> bounds = u.bounds();
<add> children = new int[bounds.size()];
<add> int k = 0;
<add> for(Type bound : bounds) {
<add> children[k++] = addTypeItem(bound);
<add> }
<ide> } else {
<ide> throw new IllegalArgumentException("unknown type encountered");
<ide> } |
|
Java | apache-2.0 | 9d92f4efa90c20c406dcc254fefcf55838441745 | 0 | novoda/download-manager | package com.novoda.downloadmanager;
/**
* Builds instances of {@link Batch} using a fluent API.
*/
public interface BatchBuilder {
/**
* Sets {@link BatchFileBuilder} to build a {@link Batch} that will download a {@link BatchFile}
* from a given networkAddress.
*
* @param networkAddress to download file from.
* @return {@link BatchFileBuilder}.
*/
BatchFileBuilder downloadFrom(String networkAddress);
/**
* Build a new {@link Batch} instance.
*
* @return an instance of {@link Batch}.
*/
Batch build();
static BatchBuilder from(Batch batch) {
InternalBatchBuilder builder = (InternalBatchBuilder) Batch.with(batch.storageRoot(), batch.downloadBatchId(), batch.title());
for (BatchFile batchFile : batch.batchFiles()) {
builder.withFile(batchFile);
}
return builder;
}
}
| library/src/main/java/com/novoda/downloadmanager/BatchBuilder.java | package com.novoda.downloadmanager;
/**
* Builds instances of {@link Batch} using a fluent API.
*/
public interface BatchBuilder {
/**
* Sets {@link BatchFileBuilder} to build a {@link Batch} that will download a {@link BatchFile}
* from a given networkAddress.
*
* @param networkAddress to download file from.
* @return {@link BatchFileBuilder}.
*/
BatchFileBuilder downloadFrom(String networkAddress);
/**
* Build a new {@link Batch} instance.
*
* @return an instance of {@link Batch}.
*/
Batch build();
}
| Add mechanism to create a `BatchBuilder` from a given batch.
This will allow clients to add additional files to a batch outside of a singular flow before pushing to the `download-manager`.
| library/src/main/java/com/novoda/downloadmanager/BatchBuilder.java | Add mechanism to create a `BatchBuilder` from a given batch. | <ide><path>ibrary/src/main/java/com/novoda/downloadmanager/BatchBuilder.java
<ide> * @return an instance of {@link Batch}.
<ide> */
<ide> Batch build();
<add>
<add> static BatchBuilder from(Batch batch) {
<add> InternalBatchBuilder builder = (InternalBatchBuilder) Batch.with(batch.storageRoot(), batch.downloadBatchId(), batch.title());
<add> for (BatchFile batchFile : batch.batchFiles()) {
<add> builder.withFile(batchFile);
<add> }
<add> return builder;
<add> }
<ide> } |
|
JavaScript | agpl-3.0 | 79686eecec61c023f47d90e8abd581dae303dd8b | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 9ca57204-2e64-11e5-9284-b827eb9e62be | helloWorld.js | 9ca002c4-2e64-11e5-9284-b827eb9e62be | 9ca57204-2e64-11e5-9284-b827eb9e62be | helloWorld.js | 9ca57204-2e64-11e5-9284-b827eb9e62be | <ide><path>elloWorld.js
<del>9ca002c4-2e64-11e5-9284-b827eb9e62be
<add>9ca57204-2e64-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | 9d686c2a506f15c894a59a5a2a0851aaac47cc8b | 0 | Basil135/vkucyh | package ru.job4j.chess.model;
import ru.job4j.chess.exceptions.ImpossibleMoveException;
/**
* This class describes the figure King of the chess.
*
* @author Kucykh Vasily (mailto:[email protected])
* @version $Id$
* @since 24.04.2017
*/
public class King extends Figure {
/**
* constructor of this figure.
*
* @param position is the figure's position on the chess board
* @param fraction is the fraction
*/
public King(Cell position, Fraction fraction) {
super(position, fraction);
}
/**
* method describes figure's move.
*
* @param destination is cell as destination on the board
* @return array of Cells as a way from position to destination
* @throws ImpossibleMoveException if this figure can not move from position to destination
*/
@Override
Cell[] way(Cell destination) throws ImpossibleMoveException {
int conditionX = Math.abs(getPosition().getX() - destination.getX());
int conditionY = Math.abs(getPosition().getY() - destination.getY());
if (conditionX == 0 && conditionY == 0 || conditionX > 1 || conditionY > 1) {
throw new ImpossibleMoveException();
}
Cell[] result = new Cell[1];
result[0] = destination;
return result;
}
/**
* method clone figure and return new figure.
*
* @param destination is cell as position of new figure
* @return clone figure
*/
@Override
public Figure clone(Cell destination) {
return new King(destination, this.getFraction());
}
}
| chapter_002/src/main/java/ru/job4j/chess/model/King.java | package ru.job4j.chess.model;
import ru.job4j.chess.exceptions.ImpossibleMoveException;
/**
* This class describes the figure King of the chess.
*
* @author Kucykh Vasily (mailto:[email protected])
* @version $Id$
* @since 24.04.2017
*/
public class King extends Figure {
/**
* constructor of this figure.
*
* @param position is the figure's position on the chess board
* @param fraction is the fraction
*/
public King(Cell position, Fraction fraction) {
super(position, fraction);
}
/**
* method describes figure's move.
*
* @param destination is cell as destination on the board
* @return array of Cells as a way from position to destination
* @throws ImpossibleMoveException if this figure can not move from position to destination
*/
@Override
Cell[] way(Cell destination) throws ImpossibleMoveException {
int conditionX = Math.abs(position.getX() - destination.getX());
int conditionY = Math.abs(position.getY() - destination.getY());
if (conditionX == 0 && conditionY == 0 || conditionX > 1 || conditionY > 1) {
throw new ImpossibleMoveException();
}
Cell[] result = new Cell[1];
result[0] = destination;
return result;
}
/**
* method clone figure and return new figure.
*
* @param destination is cell as position of new figure
* @return clone figure
*/
@Override
public Figure clone(Cell destination) {
return new King(destination, this.fraction);
}
}
| Refactor King.java
| chapter_002/src/main/java/ru/job4j/chess/model/King.java | Refactor King.java | <ide><path>hapter_002/src/main/java/ru/job4j/chess/model/King.java
<ide> @Override
<ide> Cell[] way(Cell destination) throws ImpossibleMoveException {
<ide>
<del> int conditionX = Math.abs(position.getX() - destination.getX());
<del> int conditionY = Math.abs(position.getY() - destination.getY());
<add> int conditionX = Math.abs(getPosition().getX() - destination.getX());
<add> int conditionY = Math.abs(getPosition().getY() - destination.getY());
<ide>
<ide> if (conditionX == 0 && conditionY == 0 || conditionX > 1 || conditionY > 1) {
<ide> throw new ImpossibleMoveException();
<ide> */
<ide> @Override
<ide> public Figure clone(Cell destination) {
<del> return new King(destination, this.fraction);
<add> return new King(destination, this.getFraction());
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 670a93ee0a534a060f86221da82d1cf9ee6a2a26 | 0 | googleapis/java-spanner,googleapis/java-spanner,googleapis/java-spanner,looker-open-source/java-spanner,looker-open-source/java-spanner,looker-open-source/java-spanner | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.api.core.ApiFunction;
import com.google.api.gax.longrunning.OperationFuture;
import com.google.api.gax.longrunning.OperationSnapshot;
import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.paging.Page;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.retrying.RetryingFuture;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.cloud.Identity;
import com.google.cloud.NoCredentials;
import com.google.cloud.Policy;
import com.google.cloud.Role;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.DatabaseInfo.State;
import com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime;
import com.google.longrunning.Operation;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.spanner.admin.database.v1.CreateBackupMetadata;
import com.google.spanner.admin.database.v1.CreateBackupRequest;
import com.google.spanner.admin.database.v1.CreateDatabaseMetadata;
import com.google.spanner.admin.database.v1.CreateDatabaseRequest;
import com.google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata;
import com.google.spanner.admin.database.v1.RestoreDatabaseMetadata;
import com.google.spanner.admin.database.v1.RestoreDatabaseRequest;
import com.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Server;
import io.grpc.Status;
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.threeten.bp.Duration;
@RunWith(JUnit4.class)
public class DatabaseAdminClientTest {
private static final String PROJECT_ID = "my-project";
private static final String INSTANCE_ID = "my-instance";
private static final String DB_ID = "test-db";
private static final String BCK_ID = "test-bck";
private static final String RESTORED_ID = "restored-test-db";
private static final String TEST_PARENT = "projects/my-project/instances/my-instance";
private static final String TEST_BCK_NAME = String.format("%s/backups/test-bck", TEST_PARENT);
private static final List<String> INITIAL_STATEMENTS =
Arrays.asList("CREATE TABLE FOO", "CREATE TABLE BAR");
private static MockOperationsServiceImpl mockOperations;
private static MockDatabaseAdminServiceImpl mockDatabaseAdmin;
private static Server server;
private static InetSocketAddress address;
private Spanner spanner;
private DatabaseAdminClient client;
private OperationFuture<Database, CreateDatabaseMetadata> createDatabaseOperation;
private OperationFuture<Backup, CreateBackupMetadata> createBackupOperation;
private OperationFuture<Database, RestoreDatabaseMetadata> restoreDatabaseOperation;
@BeforeClass
public static void startStaticServer() throws Exception {
mockOperations = new MockOperationsServiceImpl();
mockDatabaseAdmin = new MockDatabaseAdminServiceImpl(mockOperations);
// This test uses a NettyServer to properly test network and timeout issues.
address = new InetSocketAddress("localhost", 0);
server =
NettyServerBuilder.forAddress(address)
.addService(mockOperations)
.addService(mockDatabaseAdmin)
.build()
.start();
}
@AfterClass
public static void stopServer() throws Exception {
server.shutdown();
server.awaitTermination();
}
@SuppressWarnings("rawtypes")
@Before
public void setUp() throws IOException {
mockDatabaseAdmin.reset();
mockOperations.reset();
SpannerOptions.Builder builder = SpannerOptions.newBuilder();
RetrySettings longRunningInitialRetrySettings =
RetrySettings.newBuilder()
.setInitialRpcTimeout(Duration.ofMillis(600L))
.setMaxRpcTimeout(Duration.ofMillis(6000L))
.setInitialRetryDelay(Duration.ofMillis(20L))
.setMaxRetryDelay(Duration.ofMillis(45L))
.setRetryDelayMultiplier(1.5)
.setRpcTimeoutMultiplier(1.5)
.setTotalTimeout(Duration.ofMinutes(48L))
.build();
builder
.getDatabaseAdminStubSettingsBuilder()
.createBackupOperationSettings()
.setInitialCallSettings(
UnaryCallSettings.<CreateBackupRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetrySettings(longRunningInitialRetrySettings)
.build());
builder
.getDatabaseAdminStubSettingsBuilder()
.createBackupOperationSettings()
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRpcTimeout(Duration.ofMillis(20L))
.setInitialRetryDelay(Duration.ofMillis(10L))
.setMaxRetryDelay(Duration.ofMillis(150L))
.setMaxRpcTimeout(Duration.ofMillis(150L))
.setMaxAttempts(10)
.setTotalTimeout(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.3)
.setRpcTimeoutMultiplier(1.3)
.build()));
builder
.getDatabaseAdminStubSettingsBuilder()
.createDatabaseOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<CreateDatabaseRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetrySettings(longRunningInitialRetrySettings)
.build());
builder
.getDatabaseAdminStubSettingsBuilder()
.createDatabaseOperationSettings()
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRpcTimeout(Duration.ofMillis(20L))
.setInitialRetryDelay(Duration.ofMillis(10L))
.setMaxRetryDelay(Duration.ofMillis(150L))
.setMaxRpcTimeout(Duration.ofMillis(150L))
.setMaxAttempts(10)
.setTotalTimeout(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.3)
.setRpcTimeoutMultiplier(1.3)
.build()));
builder
.getDatabaseAdminStubSettingsBuilder()
.restoreDatabaseOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<RestoreDatabaseRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetrySettings(longRunningInitialRetrySettings)
.build());
builder
.getDatabaseAdminStubSettingsBuilder()
.restoreDatabaseOperationSettings()
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRpcTimeout(Duration.ofMillis(20L))
.setInitialRetryDelay(Duration.ofMillis(10L))
.setMaxRetryDelay(Duration.ofMillis(150L))
.setMaxRpcTimeout(Duration.ofMillis(150L))
.setMaxAttempts(10)
.setTotalTimeout(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.3)
.setRpcTimeoutMultiplier(1.3)
.build()));
spanner =
builder
.setHost("http://localhost:" + server.getPort())
.setChannelConfigurator(
new ApiFunction<ManagedChannelBuilder, ManagedChannelBuilder>() {
@Override
public ManagedChannelBuilder apply(ManagedChannelBuilder input) {
return input.usePlaintext();
}
})
.setCredentials(NoCredentials.getInstance())
.setProjectId(PROJECT_ID)
.build()
.getService();
client = spanner.getDatabaseAdminClient();
createTestDatabase();
createTestBackup();
restoreTestBackup();
}
@After
public void tearDown() throws Exception {
mockDatabaseAdmin.reset();
mockDatabaseAdmin.removeAllExecutionTimes();
mockOperations.reset();
spanner.close();
}
@Test
public void dbAdminCreateBackup() throws InterruptedException, ExecutionException {
final String backupId = "other-backup-id";
OperationFuture<Backup, CreateBackupMetadata> op =
client.createBackup(INSTANCE_ID, backupId, DB_ID, after7Days());
Backup backup = op.get();
assertThat(backup.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/backups/%s", PROJECT_ID, INSTANCE_ID, backupId));
assertThat(client.getBackup(INSTANCE_ID, backupId)).isEqualTo(backup);
}
@Test
public void backupCreate() throws InterruptedException, ExecutionException {
final String backupId = "other-backup-id";
Backup backup =
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, backupId))
.setDatabase(DatabaseId.of(PROJECT_ID, INSTANCE_ID, DB_ID))
.setExpireTime(after7Days())
.build();
OperationFuture<Backup, CreateBackupMetadata> op = backup.create();
backup = op.get();
assertThat(backup.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/backups/%s", PROJECT_ID, INSTANCE_ID, backupId));
assertThat(client.getBackup(INSTANCE_ID, backupId)).isEqualTo(backup);
}
@Test
public void backupCreateCancel() {
final String backupId = "other-backup-id";
// Set expire time to 14 days from now.
long currentTimeInMicroSeconds =
TimeUnit.MICROSECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
long deltaTimeInMicroseconds = TimeUnit.MICROSECONDS.convert(14L, TimeUnit.DAYS);
Timestamp expireTime =
Timestamp.ofTimeMicroseconds(currentTimeInMicroSeconds + deltaTimeInMicroseconds);
Backup backup =
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, backupId))
.setDatabase(DatabaseId.of(PROJECT_ID, INSTANCE_ID, DB_ID))
.setExpireTime(expireTime)
.build();
// Start a creation of a backup.
OperationFuture<Backup, CreateBackupMetadata> op = backup.create();
try {
// Try to cancel the backup operation.
client.cancelOperation(op.getName());
// Get a polling future for the running operation. This future will regularly poll the server
// for the current status of the backup operation.
RetryingFuture<OperationSnapshot> pollingFuture = op.getPollingFuture();
// Wait for the operation to finish.
// isDone will return true if the operation has finished successfully or if it was cancelled
// or any other error occurred.
while (!pollingFuture.get().isDone()) {
Thread.sleep(TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS));
}
} catch (CancellationException e) {
// ignore, this exception may also occur if the polling future has been cancelled.
} catch (ExecutionException e) {
throw (RuntimeException) e.getCause();
} catch (InterruptedException e) {
throw SpannerExceptionFactory.propagateInterrupt(e);
} finally {
backup.delete();
}
}
@Test
public void databaseBackup() throws InterruptedException, ExecutionException {
final String backupId = "other-backup-id";
Database db = client.getDatabase(INSTANCE_ID, DB_ID);
Backup backup =
db.backup(
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, backupId))
.setExpireTime(after7Days())
.build())
.get();
assertThat(backup.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/backups/%s", PROJECT_ID, INSTANCE_ID, backupId));
assertThat(client.getBackup(INSTANCE_ID, backupId)).isEqualTo(backup);
}
@Test
public void dbAdminCreateBackupAlreadyExists() throws InterruptedException, ExecutionException {
OperationFuture<Backup, CreateBackupMetadata> op =
client.createBackup(INSTANCE_ID, BCK_ID, DB_ID, after7Days());
try {
op.get();
fail("missing expected exception");
} catch (ExecutionException e) {
assertThat(e.getCause()).isInstanceOf(SpannerException.class);
assertThat(((SpannerException) e.getCause()).getErrorCode())
.isEqualTo(ErrorCode.ALREADY_EXISTS);
}
}
@Test
public void backupCreateAlreadyExists() throws InterruptedException, ExecutionException {
Backup backup =
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID))
.setDatabase(DatabaseId.of(PROJECT_ID, INSTANCE_ID, DB_ID))
.setExpireTime(after7Days())
.build();
try {
backup.create().get();
fail("missing expected exception");
} catch (ExecutionException e) {
assertThat(e.getCause()).isInstanceOf(SpannerException.class);
assertThat(((SpannerException) e.getCause()).getErrorCode())
.isEqualTo(ErrorCode.ALREADY_EXISTS);
}
}
@Test
public void databaseBackupAlreadyExists() throws InterruptedException, ExecutionException {
Database db = client.getDatabase(INSTANCE_ID, DB_ID);
OperationFuture<Backup, CreateBackupMetadata> op =
db.backup(
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID))
.setExpireTime(after7Days())
.build());
try {
op.get();
fail("missing expected exception");
} catch (ExecutionException e) {
assertThat(e.getCause()).isInstanceOf(SpannerException.class);
assertThat(((SpannerException) e.getCause()).getErrorCode())
.isEqualTo(ErrorCode.ALREADY_EXISTS);
}
}
@Test
public void dbAdminCreateBackupDbNotFound() throws InterruptedException, ExecutionException {
final String backupId = "other-backup-id";
OperationFuture<Backup, CreateBackupMetadata> op =
client.createBackup(INSTANCE_ID, backupId, "does-not-exist", after7Days());
try {
op.get();
fail("missing expected exception");
} catch (ExecutionException e) {
assertThat(e.getCause()).isInstanceOf(SpannerException.class);
assertThat(((SpannerException) e.getCause()).getErrorCode()).isEqualTo(ErrorCode.NOT_FOUND);
}
}
@Test
public void backupCreateDbNotFound() throws InterruptedException, ExecutionException {
final String backupId = "other-backup-id";
Backup backup =
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, backupId))
.setDatabase(DatabaseId.of(PROJECT_ID, INSTANCE_ID, "does-not-exist"))
.setExpireTime(after7Days())
.build();
try {
backup.create().get();
fail("missing expected exception");
} catch (ExecutionException e) {
assertThat(e.getCause()).isInstanceOf(SpannerException.class);
assertThat(((SpannerException) e.getCause()).getErrorCode()).isEqualTo(ErrorCode.NOT_FOUND);
}
}
@Test
public void databaseBackupDbNotFound() throws InterruptedException, ExecutionException {
final String backupId = "other-backup-id";
Database db =
new Database(
DatabaseId.of(PROJECT_ID, INSTANCE_ID, "does-not-exist"), State.UNSPECIFIED, client);
OperationFuture<Backup, CreateBackupMetadata> op =
db.backup(
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, backupId))
.setExpireTime(after7Days())
.build());
try {
op.get();
fail("missing expected exception");
} catch (ExecutionException e) {
assertThat(e.getCause()).isInstanceOf(SpannerException.class);
assertThat(((SpannerException) e.getCause()).getErrorCode()).isEqualTo(ErrorCode.NOT_FOUND);
}
}
@Test
public void dbAdminDeleteBackup() {
Backup backup = client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID)).build();
assertThat(backup.exists()).isTrue();
client.deleteBackup(INSTANCE_ID, BCK_ID);
assertThat(backup.exists()).isFalse();
}
@Test
public void backupDelete() {
Backup backup = client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID)).build();
assertThat(backup.exists()).isTrue();
backup.delete();
assertThat(backup.exists()).isFalse();
}
@Test
public void dbAdminDeleteBackupNotFound() {
try {
client.deleteBackup(INSTANCE_ID, "does-not-exist");
fail("missing expected exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.NOT_FOUND);
}
}
@Test
public void backupDeleteNotFound() {
Backup backup =
client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, "does-not-exist")).build();
try {
backup.delete();
fail("missing expected exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.NOT_FOUND);
}
}
@Test
public void dbAdminGetBackup() {
Backup backup = client.getBackup(INSTANCE_ID, BCK_ID);
assertThat(backup.getId().getName()).isEqualTo(TEST_BCK_NAME);
}
@Test
public void backupReload() {
Backup backup = client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID)).build();
assertThat(backup.getState()).isEqualTo(com.google.cloud.spanner.BackupInfo.State.UNSPECIFIED);
backup.reload();
assertThat(backup.getId().getName()).isEqualTo(TEST_BCK_NAME);
}
@Test
public void dbAdminGetBackupNotFound() {
try {
client.getBackup(INSTANCE_ID, "does-not-exist");
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.NOT_FOUND);
}
}
@Test
public void backupReloadNotFound() {
Backup backup =
client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, "does-not-exist")).build();
try {
backup.reload();
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.NOT_FOUND);
}
}
@Test
public void backupExists() {
Backup backup =
client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, "does-not-exist")).build();
assertThat(backup.exists()).isFalse();
backup = client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID)).build();
assertThat(backup.exists()).isTrue();
}
@Test
public void dbClientListBackups()
throws SpannerException, InterruptedException, ExecutionException {
Backup backup = client.getBackup(INSTANCE_ID, BCK_ID);
assertThat(client.listBackups(INSTANCE_ID).iterateAll()).containsExactly(backup);
Backup backup2 = client.createBackup(INSTANCE_ID, "backup2", DB_ID, after7Days()).get();
assertThat(client.listBackups(INSTANCE_ID).iterateAll()).containsExactly(backup, backup2);
backup2.delete();
assertThat(client.listBackups(INSTANCE_ID).iterateAll()).containsExactly(backup);
}
@Test
public void instanceListBackups()
throws SpannerException, InterruptedException, ExecutionException {
Instance instance =
spanner
.getInstanceAdminClient()
.newInstanceBuilder(InstanceId.of(PROJECT_ID, INSTANCE_ID))
.build();
Backup backup = client.getBackup(INSTANCE_ID, BCK_ID);
assertThat(instance.listBackups().iterateAll()).containsExactly(backup);
Backup backup2 = client.createBackup(INSTANCE_ID, "backup2", DB_ID, after7Days()).get();
assertThat(instance.listBackups().iterateAll()).containsExactly(backup, backup2);
backup2.delete();
assertThat(instance.listBackups().iterateAll()).containsExactly(backup);
}
@Test
public void instanceListBackupsWithFilter()
throws SpannerException, InterruptedException, ExecutionException {
Instance instance =
spanner
.getInstanceAdminClient()
.newInstanceBuilder(InstanceId.of(PROJECT_ID, INSTANCE_ID))
.build();
Backup backup = client.getBackup(INSTANCE_ID, BCK_ID);
assertThat(instance.listBackups().iterateAll()).containsExactly(backup);
Backup backup2 = client.createBackup(INSTANCE_ID, "backup2", DB_ID, after7Days()).get();
// All backups.
assertThat(instance.listBackups().iterateAll()).containsExactly(backup, backup2);
// All backups with name containing 'backup2'.
String filter = "name:backup2";
mockDatabaseAdmin.addFilterMatches(filter, backup2.getId().getName());
assertThat(instance.listBackups(Options.filter(filter)).iterateAll()).containsExactly(backup2);
// All backups for a database with the name db2.
filter = String.format("database:%s", DB_ID);
mockDatabaseAdmin.addFilterMatches(filter, backup.getId().getName(), backup2.getId().getName());
assertThat(instance.listBackups(Options.filter(filter)).iterateAll())
.containsExactly(backup, backup2);
// All backups that expire before a certain time.
String ts = after14Days().toString();
filter = String.format("expire_time < \"%s\"", ts);
mockDatabaseAdmin.addFilterMatches(filter, backup.getId().getName(), backup2.getId().getName());
assertThat(instance.listBackups(Options.filter(filter)).iterateAll())
.containsExactly(backup, backup2);
// All backups with size greater than a certain number of bytes.
long minBytes = Math.min(backup.getSize(), backup2.getSize());
filter = String.format("size_bytes > %d", minBytes);
Backup backupWithLargestSize;
if (backup.getSize() == minBytes) {
backupWithLargestSize = backup2;
} else {
backupWithLargestSize = backup;
}
mockDatabaseAdmin.addFilterMatches(filter, backupWithLargestSize.getId().getName());
assertThat(instance.listBackups(Options.filter(filter)).iterateAll())
.containsExactly(backupWithLargestSize);
// All backups with a create time after a certain timestamp and that are also ready.
ts = backup2.getProto().getCreateTime().toString();
filter = String.format("create_time >= \"%s\" AND state:READY", ts.toString());
mockDatabaseAdmin.addFilterMatches(filter, backup2.getId().getName());
assertThat(instance.listBackups(Options.filter(filter)).iterateAll()).containsExactly(backup2);
}
@Test
public void dbClientUpdateBackup() {
Timestamp oldExpireTime = client.getBackup(INSTANCE_ID, BCK_ID).getExpireTime();
Timestamp newExpireTime =
Timestamp.ofTimeSecondsAndNanos(
Timestamp.now().getSeconds() + TimeUnit.SECONDS.convert(1, TimeUnit.DAYS), 0);
assertThat(oldExpireTime).isNotEqualTo(newExpireTime);
Backup backup = client.updateBackup(INSTANCE_ID, BCK_ID, newExpireTime);
assertThat(backup.getExpireTime()).isEqualTo(newExpireTime);
assertThat(client.getBackup(INSTANCE_ID, BCK_ID)).isEqualTo(backup);
}
@Test
public void backupUpdate() {
Timestamp newExpireTime =
Timestamp.ofTimeSecondsAndNanos(
Timestamp.now().getSeconds() + TimeUnit.SECONDS.convert(1, TimeUnit.DAYS), 0);
Backup backup = client.getBackup(INSTANCE_ID, BCK_ID);
assertThat(backup.getExpireTime()).isNotEqualTo(newExpireTime);
backup.toBuilder().setExpireTime(newExpireTime).build().updateExpireTime();
Backup updated = client.getBackup(INSTANCE_ID, BCK_ID);
assertThat(updated.getExpireTime()).isEqualTo(newExpireTime);
assertThat(updated).isNotEqualTo(backup);
assertThat(backup.reload()).isEqualTo(updated);
}
@Test
public void dbClientRestoreDatabase() throws InterruptedException, ExecutionException {
OperationFuture<Database, RestoreDatabaseMetadata> op =
client.restoreDatabase(INSTANCE_ID, BCK_ID, "other-instance-id", "restored-db");
Database restored = op.get();
assertThat(restored.getId().getDatabase()).isEqualTo("restored-db");
assertThat(restored.getId().getInstanceId().getInstance()).isEqualTo("other-instance-id");
}
@Test
public void backupRestoreDatabase() throws InterruptedException, ExecutionException {
Backup backup = client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID)).build();
Database restored =
backup.restore(DatabaseId.of(PROJECT_ID, "other-instance-id", "restored-db")).get();
assertThat(restored.getId().getDatabase()).isEqualTo("restored-db");
assertThat(restored.getId().getInstanceId().getInstance()).isEqualTo("other-instance-id");
}
@Test
public void dbClientListDatabaseOperations()
throws SpannerException, InterruptedException, ExecutionException {
// Note: The mock server keeps all operations until the server is reset, including operations
// that have already finished.
// The setup method creates a test database --> 1 operation.
// + restores a database --> 2 operations.
assertThat(client.listDatabaseOperations(INSTANCE_ID).iterateAll()).hasSize(3);
// Create another database which should also create another operation.
client.createDatabase(INSTANCE_ID, "other-database", Collections.<String>emptyList()).get();
assertThat(client.listDatabaseOperations(INSTANCE_ID).iterateAll()).hasSize(4);
// Restore a backup. This should create 2 database operations: One to restore the database and
// one to optimize it.
client.restoreDatabase(INSTANCE_ID, BCK_ID, INSTANCE_ID, "restored-db").get();
assertThat(client.listDatabaseOperations(INSTANCE_ID).iterateAll()).hasSize(6);
}
@Test
public void instanceListDatabaseOperations()
throws SpannerException, InterruptedException, ExecutionException {
Instance instance =
spanner
.getInstanceAdminClient()
.newInstanceBuilder(InstanceId.of(PROJECT_ID, INSTANCE_ID))
.build();
assertThat(instance.listDatabaseOperations().iterateAll()).hasSize(3);
instance.createDatabase("other-database", Collections.<String>emptyList()).get();
assertThat(instance.listDatabaseOperations().iterateAll()).hasSize(4);
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID))
.build()
.restore(DatabaseId.of(PROJECT_ID, INSTANCE_ID, "restored-db"))
.get();
assertThat(instance.listDatabaseOperations().iterateAll()).hasSize(6);
}
@Test
public void instanceListDatabaseOperationsWithMetadata() throws Exception {
Instance instance =
spanner
.getInstanceAdminClient()
.newInstanceBuilder(InstanceId.of(PROJECT_ID, INSTANCE_ID))
.build();
String filter =
"(metadata.@type:type.googleapis.com/"
+ "google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata)";
mockDatabaseAdmin.addFilterMatches(
filter, restoreDatabaseOperation.getMetadata().get().getOptimizeDatabaseOperationName());
Iterable<Operation> operations =
instance.listDatabaseOperations(Options.filter(filter)).iterateAll();
assertThat(operations).hasSize(1);
for (Operation op : operations) {
OptimizeRestoredDatabaseMetadata metadata =
op.getMetadata().unpack(OptimizeRestoredDatabaseMetadata.class);
String progress =
String.format(
"Restored database %s is optimized",
metadata.getName(), metadata.getProgress().getProgressPercent());
assertThat(progress.contains("100%"));
}
}
@Test
public void databaseListDatabaseOperations()
throws SpannerException, InterruptedException, ExecutionException {
Database database = client.getDatabase(INSTANCE_ID, DB_ID);
mockDatabaseAdmin.addFilterMatches(
"name:databases/" + DB_ID, createDatabaseOperation.getName());
assertThat(database.listDatabaseOperations().iterateAll()).hasSize(1);
// Create another database which should also create another operation, but for a different
// database.
client.createDatabase(INSTANCE_ID, "other-database", Collections.<String>emptyList()).get();
assertThat(database.listDatabaseOperations().iterateAll()).hasSize(1);
// Update the database DDL. This should create an operation for this database.
OperationFuture<Void, UpdateDatabaseDdlMetadata> op =
database.updateDdl(Arrays.asList("DROP TABLE FOO"), null);
mockDatabaseAdmin.addFilterMatches("name:databases/" + DB_ID, op.getName());
assertThat(database.listDatabaseOperations().iterateAll()).hasSize(2);
}
@Test
public void dbClientListBackupOperations()
throws SpannerException, InterruptedException, ExecutionException {
assertThat(client.listBackupOperations(INSTANCE_ID).iterateAll()).hasSize(1);
client.createBackup(INSTANCE_ID, "other-backup", DB_ID, after7Days()).get();
assertThat(client.listBackupOperations(INSTANCE_ID).iterateAll()).hasSize(2);
// Restore a backup. This creates 2 DATABASE operations: One to restore the database and
// one to optimize it.
client.restoreDatabase(INSTANCE_ID, BCK_ID, INSTANCE_ID, "restored-db").get();
assertThat(client.listBackupOperations(INSTANCE_ID).iterateAll()).hasSize(2);
}
@Test
public void instanceListBackupOperations()
throws SpannerException, InterruptedException, ExecutionException {
Instance instance =
spanner
.getInstanceAdminClient()
.newInstanceBuilder(InstanceId.of(PROJECT_ID, INSTANCE_ID))
.build();
assertThat(instance.listBackupOperations().iterateAll()).hasSize(1);
instance
.getDatabase(DB_ID)
.backup(
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, "other-backup"))
.setExpireTime(after7Days())
.build())
.get();
assertThat(instance.listBackupOperations().iterateAll()).hasSize(2);
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID))
.build()
.restore(DatabaseId.of(PROJECT_ID, INSTANCE_ID, "restored-db"))
.get();
assertThat(instance.listBackupOperations().iterateAll()).hasSize(2);
}
@Test
public void instanceListBackupOperationsWithProgress() throws InvalidProtocolBufferException {
Instance instance =
spanner
.getInstanceAdminClient()
.newInstanceBuilder(InstanceId.of(PROJECT_ID, INSTANCE_ID))
.build();
String database = String.format("%s/databases/%s", TEST_PARENT, DB_ID);
String filter =
String.format(
"(metadata.database:%s) AND "
+ "(metadata.@type:type.googleapis.com/"
+ "google.spanner.admin.database.v1.CreateBackupMetadata)",
database);
Page<Operation> operations = instance.listBackupOperations(Options.filter(filter));
for (Operation op : operations.iterateAll()) {
CreateBackupMetadata metadata = op.getMetadata().unpack(CreateBackupMetadata.class);
String progress =
String.format(
"Backup %s on database %s pending: %d%% complete",
metadata.getName(),
metadata.getDatabase(),
metadata.getProgress().getProgressPercent());
assertThat(progress.contains("100%"));
}
}
@Test
public void backupListBackupOperations()
throws SpannerException, InterruptedException, ExecutionException {
Backup backup = client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID)).build();
mockDatabaseAdmin.addFilterMatches("name:backups/" + BCK_ID, createBackupOperation.getName());
assertThat(backup.listBackupOperations().iterateAll()).hasSize(1);
client.createBackup(INSTANCE_ID, "other-backup", DB_ID, after7Days()).get();
assertThat(backup.listBackupOperations().iterateAll()).hasSize(1);
}
@Test
public void getAndSetIAMPolicy() {
Policy policy = client.getDatabaseIAMPolicy(INSTANCE_ID, DB_ID);
assertThat(policy).isEqualTo(Policy.newBuilder().build());
Policy newPolicy =
Policy.newBuilder().addIdentity(Role.editor(), Identity.user("[email protected]")).build();
Policy returnedPolicy = client.setDatabaseIAMPolicy(INSTANCE_ID, DB_ID, newPolicy);
assertThat(returnedPolicy).isEqualTo(newPolicy);
assertThat(client.getDatabaseIAMPolicy(INSTANCE_ID, DB_ID)).isEqualTo(newPolicy);
}
@Test
public void testDatabaseIAMPermissions() {
Iterable<String> permissions =
client.testDatabaseIAMPermissions(
INSTANCE_ID, DB_ID, Arrays.asList("spanner.databases.select"));
assertThat(permissions).containsExactly("spanner.databases.select");
}
private Timestamp after7Days() {
return Timestamp.ofTimeMicroseconds(
TimeUnit.MICROSECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
+ TimeUnit.MICROSECONDS.convert(7, TimeUnit.DAYS));
}
private Timestamp after14Days() {
return Timestamp.ofTimeMicroseconds(
TimeUnit.MICROSECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
+ TimeUnit.MICROSECONDS.convert(14, TimeUnit.DAYS));
}
private void createTestDatabase() {
try {
createDatabaseOperation = client.createDatabase(INSTANCE_ID, DB_ID, INITIAL_STATEMENTS);
createDatabaseOperation.get();
} catch (InterruptedException | ExecutionException e) {
throw SpannerExceptionFactory.newSpannerException(e);
}
}
private void createTestBackup() {
try {
createBackupOperation = client.createBackup(INSTANCE_ID, BCK_ID, DB_ID, after7Days());
createBackupOperation.get();
} catch (InterruptedException | ExecutionException e) {
throw SpannerExceptionFactory.newSpannerException(e);
}
}
private void restoreTestBackup() {
try {
restoreDatabaseOperation =
client.restoreDatabase(INSTANCE_ID, BCK_ID, INSTANCE_ID, RESTORED_ID);
restoreDatabaseOperation.get();
} catch (InterruptedException | ExecutionException e) {
throw SpannerExceptionFactory.newSpannerException(e);
}
}
@Test
public void retryCreateBackupSlowResponse() throws Exception {
// Throw a DEADLINE_EXCEEDED after the operation has been created. This should cause the retry
// to pick up the existing operation.
mockDatabaseAdmin.setCreateBackupResponseExecutionTime(
SimulatedExecutionTime.ofException(Status.DEADLINE_EXCEEDED.asRuntimeException()));
final String backupId = "other-backup-id";
OperationFuture<Backup, CreateBackupMetadata> op =
client.createBackup(INSTANCE_ID, backupId, DB_ID, after7Days());
Backup backup = op.get();
assertThat(backup.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/backups/%s", PROJECT_ID, INSTANCE_ID, backupId));
assertThat(client.getBackup(INSTANCE_ID, backupId)).isEqualTo(backup);
// There should be at exactly 2 requests. One from this test case and one from the setup of the
// test which also creates a test backup.
assertThat(mockDatabaseAdmin.countRequestsOfType(CreateBackupRequest.class)).isEqualTo(2);
}
@Test
public void retryCreateBackupSlowStartup() throws Exception {
mockDatabaseAdmin.setCreateBackupStartupExecutionTime(
SimulatedExecutionTime.ofException(Status.DEADLINE_EXCEEDED.asRuntimeException()));
final String backupId = "other-backup-id";
OperationFuture<Backup, CreateBackupMetadata> op =
client.createBackup(INSTANCE_ID, backupId, DB_ID, after7Days());
Backup backup = op.get();
assertThat(backup.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/backups/%s", PROJECT_ID, INSTANCE_ID, backupId));
assertThat(client.getBackup(INSTANCE_ID, backupId)).isEqualTo(backup);
assertThat(mockDatabaseAdmin.countRequestsOfType(CreateBackupRequest.class)).isAtLeast(3);
}
@Test
public void retryCreateDatabaseSlowResponse() throws Exception {
// Throw a DEADLINE_EXCEEDED after the operation has been created. This should cause the retry
// to pick up the existing operation.
mockDatabaseAdmin.setCreateDatabaseResponseExecutionTime(
SimulatedExecutionTime.ofException(Status.DEADLINE_EXCEEDED.asRuntimeException()));
final String databaseId = "other-database-id";
OperationFuture<Database, CreateDatabaseMetadata> op =
client.createDatabase(INSTANCE_ID, databaseId, Collections.<String>emptyList());
Database database = op.get();
assertThat(database.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/databases/%s", PROJECT_ID, INSTANCE_ID, databaseId));
assertThat(client.getDatabase(INSTANCE_ID, databaseId)).isEqualTo(database);
// There should be at exactly 2 requests. One from this test case and one from the setup of the
// test which also creates a test database.
assertThat(mockDatabaseAdmin.countRequestsOfType(CreateDatabaseRequest.class)).isEqualTo(2);
}
@Test
public void retryCreateDatabaseSlowStartup() throws Exception {
mockDatabaseAdmin.setCreateDatabaseStartupExecutionTime(
SimulatedExecutionTime.ofException(Status.DEADLINE_EXCEEDED.asRuntimeException()));
final String databaseId = "other-database-id";
OperationFuture<Database, CreateDatabaseMetadata> op =
client.createDatabase(INSTANCE_ID, databaseId, Collections.<String>emptyList());
Database database = op.get();
assertThat(database.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/databases/%s", PROJECT_ID, INSTANCE_ID, databaseId));
assertThat(client.getDatabase(INSTANCE_ID, databaseId)).isEqualTo(database);
assertThat(mockDatabaseAdmin.countRequestsOfType(CreateDatabaseRequest.class)).isAtLeast(3);
}
@Test
public void retryRestoreDatabaseSlowResponse() throws Exception {
// Throw a DEADLINE_EXCEEDED after the operation has been created. This should cause the retry
// to pick up the existing operation.
mockDatabaseAdmin.setRestoreDatabaseResponseExecutionTime(
SimulatedExecutionTime.ofException(Status.DEADLINE_EXCEEDED.asRuntimeException()));
final String databaseId = "other-database-id";
OperationFuture<Database, RestoreDatabaseMetadata> op =
client.restoreDatabase(INSTANCE_ID, BCK_ID, INSTANCE_ID, databaseId);
Database database = op.get();
assertThat(database.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/databases/%s", PROJECT_ID, INSTANCE_ID, databaseId));
Database retrieved = client.getDatabase(INSTANCE_ID, databaseId);
assertThat(retrieved.getCreateTime()).isEqualTo(database.getCreateTime());
// There should be exactly 2 requests. One from this test case and one from the setup of the
// test which also restores a test database.
assertThat(mockDatabaseAdmin.countRequestsOfType(RestoreDatabaseRequest.class)).isEqualTo(2);
}
@Test
public void retryRestoreDatabaseSlowStartup() throws Exception {
mockDatabaseAdmin.setRestoreDatabaseStartupExecutionTime(
SimulatedExecutionTime.ofException(Status.DEADLINE_EXCEEDED.asRuntimeException()));
final String databaseId = "other-database-id";
OperationFuture<Database, RestoreDatabaseMetadata> op =
client.restoreDatabase(INSTANCE_ID, BCK_ID, INSTANCE_ID, databaseId);
Database database = op.get();
assertThat(database.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/databases/%s", PROJECT_ID, INSTANCE_ID, databaseId));
Database retrieved = client.getDatabase(INSTANCE_ID, databaseId);
assertThat(retrieved.getCreateTime()).isEqualTo(database.getCreateTime());
assertThat(mockDatabaseAdmin.countRequestsOfType(RestoreDatabaseRequest.class)).isAtLeast(3);
}
}
| google-cloud-spanner/src/test/java/com/google/cloud/spanner/DatabaseAdminClientTest.java | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.truth.Truth.assertThat;
import com.google.api.core.ApiFunction;
import com.google.api.gax.longrunning.OperationFuture;
import com.google.api.gax.longrunning.OperationSnapshot;
import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.paging.Page;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.retrying.RetryingFuture;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.cloud.Identity;
import com.google.cloud.NoCredentials;
import com.google.cloud.Policy;
import com.google.cloud.Role;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.DatabaseInfo.State;
import com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime;
import com.google.longrunning.Operation;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.spanner.admin.database.v1.CreateBackupMetadata;
import com.google.spanner.admin.database.v1.CreateBackupRequest;
import com.google.spanner.admin.database.v1.CreateDatabaseMetadata;
import com.google.spanner.admin.database.v1.CreateDatabaseRequest;
import com.google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata;
import com.google.spanner.admin.database.v1.RestoreDatabaseMetadata;
import com.google.spanner.admin.database.v1.RestoreDatabaseRequest;
import com.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Server;
import io.grpc.Status;
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.threeten.bp.Duration;
@RunWith(JUnit4.class)
public class DatabaseAdminClientTest {
private static class SpannerExecutionExceptionMatcher extends BaseMatcher<Throwable> {
private final ErrorCode expectedCode;
private static SpannerExecutionExceptionMatcher forCode(ErrorCode code) {
return new SpannerExecutionExceptionMatcher(code);
}
private SpannerExecutionExceptionMatcher(ErrorCode code) {
this.expectedCode = checkNotNull(code);
}
@Override
public boolean matches(Object item) {
if (item instanceof ExecutionException) {
ExecutionException e = (ExecutionException) item;
if (e.getCause() instanceof SpannerException) {
SpannerException se = (SpannerException) e.getCause();
return se.getErrorCode() == expectedCode;
}
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("SpannerException[" + expectedCode + "]");
}
}
private static final String PROJECT_ID = "my-project";
private static final String INSTANCE_ID = "my-instance";
private static final String DB_ID = "test-db";
private static final String BCK_ID = "test-bck";
private static final String RESTORED_ID = "restored-test-db";
private static final String TEST_PARENT = "projects/my-project/instances/my-instance";
private static final String TEST_BCK_NAME = String.format("%s/backups/test-bck", TEST_PARENT);
private static final List<String> INITIAL_STATEMENTS =
Arrays.asList("CREATE TABLE FOO", "CREATE TABLE BAR");
private static MockOperationsServiceImpl mockOperations;
private static MockDatabaseAdminServiceImpl mockDatabaseAdmin;
private static Server server;
private static InetSocketAddress address;
private Spanner spanner;
private DatabaseAdminClient client;
@Rule public ExpectedException exception = ExpectedException.none();
private OperationFuture<Database, CreateDatabaseMetadata> createDatabaseOperation;
private OperationFuture<Backup, CreateBackupMetadata> createBackupOperation;
private OperationFuture<Database, RestoreDatabaseMetadata> restoreDatabaseOperation;
@BeforeClass
public static void startStaticServer() throws Exception {
mockOperations = new MockOperationsServiceImpl();
mockDatabaseAdmin = new MockDatabaseAdminServiceImpl(mockOperations);
// This test uses a NettyServer to properly test network and timeout issues.
address = new InetSocketAddress("localhost", 0);
server =
NettyServerBuilder.forAddress(address)
.addService(mockOperations)
.addService(mockDatabaseAdmin)
.build()
.start();
}
@AfterClass
public static void stopServer() throws Exception {
server.shutdown();
server.awaitTermination();
}
@SuppressWarnings("rawtypes")
@Before
public void setUp() throws IOException {
mockDatabaseAdmin.reset();
mockOperations.reset();
SpannerOptions.Builder builder = SpannerOptions.newBuilder();
RetrySettings longRunningInitialRetrySettings =
RetrySettings.newBuilder()
.setInitialRpcTimeout(Duration.ofMillis(60L))
.setMaxRpcTimeout(Duration.ofMillis(600L))
.setInitialRetryDelay(Duration.ofMillis(20L))
.setMaxRetryDelay(Duration.ofMillis(45L))
.setRetryDelayMultiplier(1.5)
.setRpcTimeoutMultiplier(1.5)
.setTotalTimeout(Duration.ofMinutes(48L))
.build();
builder
.getDatabaseAdminStubSettingsBuilder()
.createBackupOperationSettings()
.setInitialCallSettings(
UnaryCallSettings.<CreateBackupRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetrySettings(longRunningInitialRetrySettings)
.build());
builder
.getDatabaseAdminStubSettingsBuilder()
.createBackupOperationSettings()
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRpcTimeout(Duration.ofMillis(20L))
.setInitialRetryDelay(Duration.ofMillis(10L))
.setMaxRetryDelay(Duration.ofMillis(150L))
.setMaxRpcTimeout(Duration.ofMillis(150L))
.setMaxAttempts(10)
.setTotalTimeout(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.3)
.setRpcTimeoutMultiplier(1.3)
.build()));
builder
.getDatabaseAdminStubSettingsBuilder()
.createDatabaseOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<CreateDatabaseRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetrySettings(longRunningInitialRetrySettings)
.build());
builder
.getDatabaseAdminStubSettingsBuilder()
.createDatabaseOperationSettings()
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRpcTimeout(Duration.ofMillis(20L))
.setInitialRetryDelay(Duration.ofMillis(10L))
.setMaxRetryDelay(Duration.ofMillis(150L))
.setMaxRpcTimeout(Duration.ofMillis(150L))
.setMaxAttempts(10)
.setTotalTimeout(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.3)
.setRpcTimeoutMultiplier(1.3)
.build()));
builder
.getDatabaseAdminStubSettingsBuilder()
.restoreDatabaseOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<RestoreDatabaseRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetrySettings(longRunningInitialRetrySettings)
.build());
builder
.getDatabaseAdminStubSettingsBuilder()
.restoreDatabaseOperationSettings()
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRpcTimeout(Duration.ofMillis(20L))
.setInitialRetryDelay(Duration.ofMillis(10L))
.setMaxRetryDelay(Duration.ofMillis(150L))
.setMaxRpcTimeout(Duration.ofMillis(150L))
.setMaxAttempts(10)
.setTotalTimeout(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.3)
.setRpcTimeoutMultiplier(1.3)
.build()));
spanner =
builder
.setHost("http://localhost:" + server.getPort())
.setChannelConfigurator(
new ApiFunction<ManagedChannelBuilder, ManagedChannelBuilder>() {
@Override
public ManagedChannelBuilder apply(ManagedChannelBuilder input) {
return input.usePlaintext();
}
})
.setCredentials(NoCredentials.getInstance())
.setProjectId(PROJECT_ID)
.build()
.getService();
client = spanner.getDatabaseAdminClient();
createTestDatabase();
createTestBackup();
restoreTestBackup();
}
@After
public void tearDown() throws Exception {
mockDatabaseAdmin.reset();
mockDatabaseAdmin.removeAllExecutionTimes();
mockOperations.reset();
spanner.close();
}
@Test
public void dbAdminCreateBackup() throws InterruptedException, ExecutionException {
final String backupId = "other-backup-id";
OperationFuture<Backup, CreateBackupMetadata> op =
client.createBackup(INSTANCE_ID, backupId, DB_ID, after7Days());
Backup backup = op.get();
assertThat(backup.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/backups/%s", PROJECT_ID, INSTANCE_ID, backupId));
assertThat(client.getBackup(INSTANCE_ID, backupId)).isEqualTo(backup);
}
@Test
public void backupCreate() throws InterruptedException, ExecutionException {
final String backupId = "other-backup-id";
Backup backup =
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, backupId))
.setDatabase(DatabaseId.of(PROJECT_ID, INSTANCE_ID, DB_ID))
.setExpireTime(after7Days())
.build();
OperationFuture<Backup, CreateBackupMetadata> op = backup.create();
backup = op.get();
assertThat(backup.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/backups/%s", PROJECT_ID, INSTANCE_ID, backupId));
assertThat(client.getBackup(INSTANCE_ID, backupId)).isEqualTo(backup);
}
@Test
public void backupCreateCancel() {
final String backupId = "other-backup-id";
// Set expire time to 14 days from now.
long currentTimeInMicroSeconds =
TimeUnit.MICROSECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
long deltaTimeInMicroseconds = TimeUnit.MICROSECONDS.convert(14L, TimeUnit.DAYS);
Timestamp expireTime =
Timestamp.ofTimeMicroseconds(currentTimeInMicroSeconds + deltaTimeInMicroseconds);
Backup backup =
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, backupId))
.setDatabase(DatabaseId.of(PROJECT_ID, INSTANCE_ID, DB_ID))
.setExpireTime(expireTime)
.build();
// Start a creation of a backup.
OperationFuture<Backup, CreateBackupMetadata> op = backup.create();
try {
// Try to cancel the backup operation.
client.cancelOperation(op.getName());
// Get a polling future for the running operation. This future will regularly poll the server
// for the current status of the backup operation.
RetryingFuture<OperationSnapshot> pollingFuture = op.getPollingFuture();
// Wait for the operation to finish.
// isDone will return true if the operation has finished successfully or if it was cancelled
// or any other error occurred.
while (!pollingFuture.get().isDone()) {
Thread.sleep(TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS));
}
} catch (CancellationException e) {
// ignore, this exception may also occur if the polling future has been cancelled.
} catch (ExecutionException e) {
throw (RuntimeException) e.getCause();
} catch (InterruptedException e) {
throw SpannerExceptionFactory.propagateInterrupt(e);
} finally {
backup.delete();
}
}
@Test
public void databaseBackup() throws InterruptedException, ExecutionException {
final String backupId = "other-backup-id";
Database db = client.getDatabase(INSTANCE_ID, DB_ID);
Backup backup =
db.backup(
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, backupId))
.setExpireTime(after7Days())
.build())
.get();
assertThat(backup.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/backups/%s", PROJECT_ID, INSTANCE_ID, backupId));
assertThat(client.getBackup(INSTANCE_ID, backupId)).isEqualTo(backup);
}
@Test
public void dbAdminCreateBackupAlreadyExists() throws InterruptedException, ExecutionException {
OperationFuture<Backup, CreateBackupMetadata> op =
client.createBackup(INSTANCE_ID, BCK_ID, DB_ID, after7Days());
exception.expect(SpannerExecutionExceptionMatcher.forCode(ErrorCode.ALREADY_EXISTS));
op.get();
}
@Test
public void backupCreateAlreadyExists() throws InterruptedException, ExecutionException {
Backup backup =
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID))
.setDatabase(DatabaseId.of(PROJECT_ID, INSTANCE_ID, DB_ID))
.setExpireTime(after7Days())
.build();
OperationFuture<Backup, CreateBackupMetadata> op = backup.create();
exception.expect(SpannerExecutionExceptionMatcher.forCode(ErrorCode.ALREADY_EXISTS));
op.get();
}
@Test
public void databaseBackupAlreadyExists() throws InterruptedException, ExecutionException {
Database db = client.getDatabase(INSTANCE_ID, DB_ID);
OperationFuture<Backup, CreateBackupMetadata> op =
db.backup(
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID))
.setExpireTime(after7Days())
.build());
exception.expect(SpannerExecutionExceptionMatcher.forCode(ErrorCode.ALREADY_EXISTS));
op.get();
}
@Test
public void dbAdminCreateBackupDbNotFound() throws InterruptedException, ExecutionException {
final String backupId = "other-backup-id";
OperationFuture<Backup, CreateBackupMetadata> op =
client.createBackup(INSTANCE_ID, backupId, "does-not-exist", after7Days());
exception.expect(SpannerExecutionExceptionMatcher.forCode(ErrorCode.NOT_FOUND));
op.get();
}
@Test
public void backupCreateDbNotFound() throws InterruptedException, ExecutionException {
final String backupId = "other-backup-id";
Backup backup =
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, backupId))
.setDatabase(DatabaseId.of(PROJECT_ID, INSTANCE_ID, "does-not-exist"))
.setExpireTime(after7Days())
.build();
OperationFuture<Backup, CreateBackupMetadata> op = backup.create();
exception.expect(SpannerExecutionExceptionMatcher.forCode(ErrorCode.NOT_FOUND));
op.get();
}
@Test
public void databaseBackupDbNotFound() throws InterruptedException, ExecutionException {
final String backupId = "other-backup-id";
Database db =
new Database(
DatabaseId.of(PROJECT_ID, INSTANCE_ID, "does-not-exist"), State.UNSPECIFIED, client);
OperationFuture<Backup, CreateBackupMetadata> op =
db.backup(
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, backupId))
.setExpireTime(after7Days())
.build());
exception.expect(SpannerExecutionExceptionMatcher.forCode(ErrorCode.NOT_FOUND));
op.get();
}
@Test
public void dbAdminDeleteBackup() {
Backup backup = client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID)).build();
assertThat(backup.exists()).isTrue();
client.deleteBackup(INSTANCE_ID, BCK_ID);
assertThat(backup.exists()).isFalse();
}
@Test
public void backupDelete() {
Backup backup = client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID)).build();
assertThat(backup.exists()).isTrue();
backup.delete();
assertThat(backup.exists()).isFalse();
}
@Test
public void dbAdminDeleteBackupNotFound() {
exception.expect(SpannerMatchers.isSpannerException(ErrorCode.NOT_FOUND));
client.deleteBackup(INSTANCE_ID, "does-not-exist");
}
@Test
public void backupDeleteNotFound() {
Backup backup =
client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, "does-not-exist")).build();
exception.expect(SpannerMatchers.isSpannerException(ErrorCode.NOT_FOUND));
backup.delete();
}
@Test
public void dbAdminGetBackup() {
Backup backup = client.getBackup(INSTANCE_ID, BCK_ID);
assertThat(backup.getId().getName()).isEqualTo(TEST_BCK_NAME);
}
@Test
public void backupReload() {
Backup backup = client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID)).build();
assertThat(backup.getState()).isEqualTo(com.google.cloud.spanner.BackupInfo.State.UNSPECIFIED);
backup.reload();
assertThat(backup.getId().getName()).isEqualTo(TEST_BCK_NAME);
}
@Test
public void dbAdminGetBackupNotFound() {
exception.expect(SpannerMatchers.isSpannerException(ErrorCode.NOT_FOUND));
client.getBackup(INSTANCE_ID, "does-not-exist");
}
@Test
public void backupReloadNotFound() {
Backup backup =
client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, "does-not-exist")).build();
exception.expect(SpannerMatchers.isSpannerException(ErrorCode.NOT_FOUND));
backup.reload();
}
@Test
public void backupExists() {
Backup backup =
client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, "does-not-exist")).build();
assertThat(backup.exists()).isFalse();
backup = client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID)).build();
assertThat(backup.exists()).isTrue();
}
@Test
public void dbClientListBackups()
throws SpannerException, InterruptedException, ExecutionException {
Backup backup = client.getBackup(INSTANCE_ID, BCK_ID);
assertThat(client.listBackups(INSTANCE_ID).iterateAll()).containsExactly(backup);
Backup backup2 = client.createBackup(INSTANCE_ID, "backup2", DB_ID, after7Days()).get();
assertThat(client.listBackups(INSTANCE_ID).iterateAll()).containsExactly(backup, backup2);
backup2.delete();
assertThat(client.listBackups(INSTANCE_ID).iterateAll()).containsExactly(backup);
}
@Test
public void instanceListBackups()
throws SpannerException, InterruptedException, ExecutionException {
Instance instance =
spanner
.getInstanceAdminClient()
.newInstanceBuilder(InstanceId.of(PROJECT_ID, INSTANCE_ID))
.build();
Backup backup = client.getBackup(INSTANCE_ID, BCK_ID);
assertThat(instance.listBackups().iterateAll()).containsExactly(backup);
Backup backup2 = client.createBackup(INSTANCE_ID, "backup2", DB_ID, after7Days()).get();
assertThat(instance.listBackups().iterateAll()).containsExactly(backup, backup2);
backup2.delete();
assertThat(instance.listBackups().iterateAll()).containsExactly(backup);
}
@Test
public void instanceListBackupsWithFilter()
throws SpannerException, InterruptedException, ExecutionException {
Instance instance =
spanner
.getInstanceAdminClient()
.newInstanceBuilder(InstanceId.of(PROJECT_ID, INSTANCE_ID))
.build();
Backup backup = client.getBackup(INSTANCE_ID, BCK_ID);
assertThat(instance.listBackups().iterateAll()).containsExactly(backup);
Backup backup2 = client.createBackup(INSTANCE_ID, "backup2", DB_ID, after7Days()).get();
// All backups.
assertThat(instance.listBackups().iterateAll()).containsExactly(backup, backup2);
// All backups with name containing 'backup2'.
String filter = "name:backup2";
mockDatabaseAdmin.addFilterMatches(filter, backup2.getId().getName());
assertThat(instance.listBackups(Options.filter(filter)).iterateAll()).containsExactly(backup2);
// All backups for a database with the name db2.
filter = String.format("database:%s", DB_ID);
mockDatabaseAdmin.addFilterMatches(filter, backup.getId().getName(), backup2.getId().getName());
assertThat(instance.listBackups(Options.filter(filter)).iterateAll())
.containsExactly(backup, backup2);
// All backups that expire before a certain time.
String ts = after14Days().toString();
filter = String.format("expire_time < \"%s\"", ts);
mockDatabaseAdmin.addFilterMatches(filter, backup.getId().getName(), backup2.getId().getName());
assertThat(instance.listBackups(Options.filter(filter)).iterateAll())
.containsExactly(backup, backup2);
// All backups with size greater than a certain number of bytes.
long minBytes = Math.min(backup.getSize(), backup2.getSize());
filter = String.format("size_bytes > %d", minBytes);
Backup backupWithLargestSize;
if (backup.getSize() == minBytes) {
backupWithLargestSize = backup2;
} else {
backupWithLargestSize = backup;
}
mockDatabaseAdmin.addFilterMatches(filter, backupWithLargestSize.getId().getName());
assertThat(instance.listBackups(Options.filter(filter)).iterateAll())
.containsExactly(backupWithLargestSize);
// All backups with a create time after a certain timestamp and that are also ready.
ts = backup2.getProto().getCreateTime().toString();
filter = String.format("create_time >= \"%s\" AND state:READY", ts.toString());
mockDatabaseAdmin.addFilterMatches(filter, backup2.getId().getName());
assertThat(instance.listBackups(Options.filter(filter)).iterateAll()).containsExactly(backup2);
}
@Test
public void dbClientUpdateBackup() {
Timestamp oldExpireTime = client.getBackup(INSTANCE_ID, BCK_ID).getExpireTime();
Timestamp newExpireTime =
Timestamp.ofTimeSecondsAndNanos(
Timestamp.now().getSeconds() + TimeUnit.SECONDS.convert(1, TimeUnit.DAYS), 0);
assertThat(oldExpireTime).isNotEqualTo(newExpireTime);
Backup backup = client.updateBackup(INSTANCE_ID, BCK_ID, newExpireTime);
assertThat(backup.getExpireTime()).isEqualTo(newExpireTime);
assertThat(client.getBackup(INSTANCE_ID, BCK_ID)).isEqualTo(backup);
}
@Test
public void backupUpdate() {
Timestamp newExpireTime =
Timestamp.ofTimeSecondsAndNanos(
Timestamp.now().getSeconds() + TimeUnit.SECONDS.convert(1, TimeUnit.DAYS), 0);
Backup backup = client.getBackup(INSTANCE_ID, BCK_ID);
assertThat(backup.getExpireTime()).isNotEqualTo(newExpireTime);
backup.toBuilder().setExpireTime(newExpireTime).build().updateExpireTime();
Backup updated = client.getBackup(INSTANCE_ID, BCK_ID);
assertThat(updated.getExpireTime()).isEqualTo(newExpireTime);
assertThat(updated).isNotEqualTo(backup);
assertThat(backup.reload()).isEqualTo(updated);
}
@Test
public void dbClientRestoreDatabase() throws InterruptedException, ExecutionException {
OperationFuture<Database, RestoreDatabaseMetadata> op =
client.restoreDatabase(INSTANCE_ID, BCK_ID, "other-instance-id", "restored-db");
Database restored = op.get();
assertThat(restored.getId().getDatabase()).isEqualTo("restored-db");
assertThat(restored.getId().getInstanceId().getInstance()).isEqualTo("other-instance-id");
}
@Test
public void backupRestoreDatabase() throws InterruptedException, ExecutionException {
Backup backup = client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID)).build();
Database restored =
backup.restore(DatabaseId.of(PROJECT_ID, "other-instance-id", "restored-db")).get();
assertThat(restored.getId().getDatabase()).isEqualTo("restored-db");
assertThat(restored.getId().getInstanceId().getInstance()).isEqualTo("other-instance-id");
}
@Test
public void dbClientListDatabaseOperations()
throws SpannerException, InterruptedException, ExecutionException {
// Note: The mock server keeps all operations until the server is reset, including operations
// that have already finished.
// The setup method creates a test database --> 1 operation.
// + restores a database --> 2 operations.
assertThat(client.listDatabaseOperations(INSTANCE_ID).iterateAll()).hasSize(3);
// Create another database which should also create another operation.
client.createDatabase(INSTANCE_ID, "other-database", Collections.<String>emptyList()).get();
assertThat(client.listDatabaseOperations(INSTANCE_ID).iterateAll()).hasSize(4);
// Restore a backup. This should create 2 database operations: One to restore the database and
// one to optimize it.
client.restoreDatabase(INSTANCE_ID, BCK_ID, INSTANCE_ID, "restored-db").get();
assertThat(client.listDatabaseOperations(INSTANCE_ID).iterateAll()).hasSize(6);
}
@Test
public void instanceListDatabaseOperations()
throws SpannerException, InterruptedException, ExecutionException {
Instance instance =
spanner
.getInstanceAdminClient()
.newInstanceBuilder(InstanceId.of(PROJECT_ID, INSTANCE_ID))
.build();
assertThat(instance.listDatabaseOperations().iterateAll()).hasSize(3);
instance.createDatabase("other-database", Collections.<String>emptyList()).get();
assertThat(instance.listDatabaseOperations().iterateAll()).hasSize(4);
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID))
.build()
.restore(DatabaseId.of(PROJECT_ID, INSTANCE_ID, "restored-db"))
.get();
assertThat(instance.listDatabaseOperations().iterateAll()).hasSize(6);
}
@Test
public void instanceListDatabaseOperationsWithMetadata() throws Exception {
Instance instance =
spanner
.getInstanceAdminClient()
.newInstanceBuilder(InstanceId.of(PROJECT_ID, INSTANCE_ID))
.build();
String filter =
"(metadata.@type:type.googleapis.com/"
+ "google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata)";
mockDatabaseAdmin.addFilterMatches(
filter, restoreDatabaseOperation.getMetadata().get().getOptimizeDatabaseOperationName());
Iterable<Operation> operations =
instance.listDatabaseOperations(Options.filter(filter)).iterateAll();
assertThat(operations).hasSize(1);
for (Operation op : operations) {
OptimizeRestoredDatabaseMetadata metadata =
op.getMetadata().unpack(OptimizeRestoredDatabaseMetadata.class);
String progress =
String.format(
"Restored database %s is optimized",
metadata.getName(), metadata.getProgress().getProgressPercent());
assertThat(progress.contains("100%"));
}
}
@Test
public void databaseListDatabaseOperations()
throws SpannerException, InterruptedException, ExecutionException {
Database database = client.getDatabase(INSTANCE_ID, DB_ID);
mockDatabaseAdmin.addFilterMatches(
"name:databases/" + DB_ID, createDatabaseOperation.getName());
assertThat(database.listDatabaseOperations().iterateAll()).hasSize(1);
// Create another database which should also create another operation, but for a different
// database.
client.createDatabase(INSTANCE_ID, "other-database", Collections.<String>emptyList()).get();
assertThat(database.listDatabaseOperations().iterateAll()).hasSize(1);
// Update the database DDL. This should create an operation for this database.
OperationFuture<Void, UpdateDatabaseDdlMetadata> op =
database.updateDdl(Arrays.asList("DROP TABLE FOO"), null);
mockDatabaseAdmin.addFilterMatches("name:databases/" + DB_ID, op.getName());
assertThat(database.listDatabaseOperations().iterateAll()).hasSize(2);
}
@Test
public void dbClientListBackupOperations()
throws SpannerException, InterruptedException, ExecutionException {
assertThat(client.listBackupOperations(INSTANCE_ID).iterateAll()).hasSize(1);
client.createBackup(INSTANCE_ID, "other-backup", DB_ID, after7Days()).get();
assertThat(client.listBackupOperations(INSTANCE_ID).iterateAll()).hasSize(2);
// Restore a backup. This creates 2 DATABASE operations: One to restore the database and
// one to optimize it.
client.restoreDatabase(INSTANCE_ID, BCK_ID, INSTANCE_ID, "restored-db").get();
assertThat(client.listBackupOperations(INSTANCE_ID).iterateAll()).hasSize(2);
}
@Test
public void instanceListBackupOperations()
throws SpannerException, InterruptedException, ExecutionException {
Instance instance =
spanner
.getInstanceAdminClient()
.newInstanceBuilder(InstanceId.of(PROJECT_ID, INSTANCE_ID))
.build();
assertThat(instance.listBackupOperations().iterateAll()).hasSize(1);
instance
.getDatabase(DB_ID)
.backup(
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, "other-backup"))
.setExpireTime(after7Days())
.build())
.get();
assertThat(instance.listBackupOperations().iterateAll()).hasSize(2);
client
.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID))
.build()
.restore(DatabaseId.of(PROJECT_ID, INSTANCE_ID, "restored-db"))
.get();
assertThat(instance.listBackupOperations().iterateAll()).hasSize(2);
}
@Test
public void instanceListBackupOperationsWithProgress() throws InvalidProtocolBufferException {
Instance instance =
spanner
.getInstanceAdminClient()
.newInstanceBuilder(InstanceId.of(PROJECT_ID, INSTANCE_ID))
.build();
String database = String.format("%s/databases/%s", TEST_PARENT, DB_ID);
String filter =
String.format(
"(metadata.database:%s) AND "
+ "(metadata.@type:type.googleapis.com/"
+ "google.spanner.admin.database.v1.CreateBackupMetadata)",
database);
Page<Operation> operations = instance.listBackupOperations(Options.filter(filter));
for (Operation op : operations.iterateAll()) {
CreateBackupMetadata metadata = op.getMetadata().unpack(CreateBackupMetadata.class);
String progress =
String.format(
"Backup %s on database %s pending: %d%% complete",
metadata.getName(),
metadata.getDatabase(),
metadata.getProgress().getProgressPercent());
assertThat(progress.contains("100%"));
}
}
@Test
public void backupListBackupOperations()
throws SpannerException, InterruptedException, ExecutionException {
Backup backup = client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID)).build();
mockDatabaseAdmin.addFilterMatches("name:backups/" + BCK_ID, createBackupOperation.getName());
assertThat(backup.listBackupOperations().iterateAll()).hasSize(1);
client.createBackup(INSTANCE_ID, "other-backup", DB_ID, after7Days()).get();
assertThat(backup.listBackupOperations().iterateAll()).hasSize(1);
}
@Test
public void getAndSetIAMPolicy() {
Policy policy = client.getDatabaseIAMPolicy(INSTANCE_ID, DB_ID);
assertThat(policy).isEqualTo(Policy.newBuilder().build());
Policy newPolicy =
Policy.newBuilder().addIdentity(Role.editor(), Identity.user("[email protected]")).build();
Policy returnedPolicy = client.setDatabaseIAMPolicy(INSTANCE_ID, DB_ID, newPolicy);
assertThat(returnedPolicy).isEqualTo(newPolicy);
assertThat(client.getDatabaseIAMPolicy(INSTANCE_ID, DB_ID)).isEqualTo(newPolicy);
}
@Test
public void testDatabaseIAMPermissions() {
Iterable<String> permissions =
client.testDatabaseIAMPermissions(
INSTANCE_ID, DB_ID, Arrays.asList("spanner.databases.select"));
assertThat(permissions).containsExactly("spanner.databases.select");
}
private Timestamp after7Days() {
return Timestamp.ofTimeMicroseconds(
TimeUnit.MICROSECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
+ TimeUnit.MICROSECONDS.convert(7, TimeUnit.DAYS));
}
private Timestamp after14Days() {
return Timestamp.ofTimeMicroseconds(
TimeUnit.MICROSECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
+ TimeUnit.MICROSECONDS.convert(14, TimeUnit.DAYS));
}
private void createTestDatabase() {
try {
createDatabaseOperation = client.createDatabase(INSTANCE_ID, DB_ID, INITIAL_STATEMENTS);
createDatabaseOperation.get();
} catch (InterruptedException | ExecutionException e) {
throw SpannerExceptionFactory.newSpannerException(e);
}
}
private void createTestBackup() {
try {
createBackupOperation = client.createBackup(INSTANCE_ID, BCK_ID, DB_ID, after7Days());
createBackupOperation.get();
} catch (InterruptedException | ExecutionException e) {
throw SpannerExceptionFactory.newSpannerException(e);
}
}
private void restoreTestBackup() {
try {
restoreDatabaseOperation =
client.restoreDatabase(INSTANCE_ID, BCK_ID, INSTANCE_ID, RESTORED_ID);
restoreDatabaseOperation.get();
} catch (InterruptedException | ExecutionException e) {
throw SpannerExceptionFactory.newSpannerException(e);
}
}
@Test
public void retryCreateBackupSlowResponse() throws Exception {
// Throw a DEADLINE_EXCEEDED after the operation has been created. This should cause the retry
// to pick up the existing operation.
mockDatabaseAdmin.setCreateBackupResponseExecutionTime(
SimulatedExecutionTime.ofException(Status.DEADLINE_EXCEEDED.asRuntimeException()));
final String backupId = "other-backup-id";
OperationFuture<Backup, CreateBackupMetadata> op =
client.createBackup(INSTANCE_ID, backupId, DB_ID, after7Days());
Backup backup = op.get();
assertThat(backup.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/backups/%s", PROJECT_ID, INSTANCE_ID, backupId));
assertThat(client.getBackup(INSTANCE_ID, backupId)).isEqualTo(backup);
// There should be at exactly 2 requests. One from this test case and one from the setup of the
// test which also creates a test backup.
assertThat(mockDatabaseAdmin.countRequestsOfType(CreateBackupRequest.class)).isEqualTo(2);
}
@Test
public void retryCreateBackupSlowStartup() throws Exception {
mockDatabaseAdmin.setCreateBackupStartupExecutionTime(
SimulatedExecutionTime.ofException(Status.DEADLINE_EXCEEDED.asRuntimeException()));
final String backupId = "other-backup-id";
OperationFuture<Backup, CreateBackupMetadata> op =
client.createBackup(INSTANCE_ID, backupId, DB_ID, after7Days());
Backup backup = op.get();
assertThat(backup.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/backups/%s", PROJECT_ID, INSTANCE_ID, backupId));
assertThat(client.getBackup(INSTANCE_ID, backupId)).isEqualTo(backup);
assertThat(mockDatabaseAdmin.countRequestsOfType(CreateBackupRequest.class)).isAtLeast(3);
}
@Test
public void retryCreateDatabaseSlowResponse() throws Exception {
// Throw a DEADLINE_EXCEEDED after the operation has been created. This should cause the retry
// to pick up the existing operation.
mockDatabaseAdmin.setCreateDatabaseResponseExecutionTime(
SimulatedExecutionTime.ofException(Status.DEADLINE_EXCEEDED.asRuntimeException()));
final String databaseId = "other-database-id";
OperationFuture<Database, CreateDatabaseMetadata> op =
client.createDatabase(INSTANCE_ID, databaseId, Collections.<String>emptyList());
Database database = op.get();
assertThat(database.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/databases/%s", PROJECT_ID, INSTANCE_ID, databaseId));
assertThat(client.getDatabase(INSTANCE_ID, databaseId)).isEqualTo(database);
// There should be at exactly 2 requests. One from this test case and one from the setup of the
// test which also creates a test database.
assertThat(mockDatabaseAdmin.countRequestsOfType(CreateDatabaseRequest.class)).isEqualTo(2);
}
@Test
public void retryCreateDatabaseSlowStartup() throws Exception {
mockDatabaseAdmin.setCreateDatabaseStartupExecutionTime(
SimulatedExecutionTime.ofException(Status.DEADLINE_EXCEEDED.asRuntimeException()));
final String databaseId = "other-database-id";
OperationFuture<Database, CreateDatabaseMetadata> op =
client.createDatabase(INSTANCE_ID, databaseId, Collections.<String>emptyList());
Database database = op.get();
assertThat(database.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/databases/%s", PROJECT_ID, INSTANCE_ID, databaseId));
assertThat(client.getDatabase(INSTANCE_ID, databaseId)).isEqualTo(database);
assertThat(mockDatabaseAdmin.countRequestsOfType(CreateDatabaseRequest.class)).isAtLeast(3);
}
@Test
public void retryRestoreDatabaseSlowResponse() throws Exception {
// Throw a DEADLINE_EXCEEDED after the operation has been created. This should cause the retry
// to pick up the existing operation.
mockDatabaseAdmin.setRestoreDatabaseResponseExecutionTime(
SimulatedExecutionTime.ofException(Status.DEADLINE_EXCEEDED.asRuntimeException()));
final String databaseId = "other-database-id";
OperationFuture<Database, RestoreDatabaseMetadata> op =
client.restoreDatabase(INSTANCE_ID, BCK_ID, INSTANCE_ID, databaseId);
Database database = op.get();
assertThat(database.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/databases/%s", PROJECT_ID, INSTANCE_ID, databaseId));
Database retrieved = client.getDatabase(INSTANCE_ID, databaseId);
assertThat(retrieved.getCreateTime()).isEqualTo(database.getCreateTime());
// There should be exactly 2 requests. One from this test case and one from the setup of the
// test which also restores a test database.
assertThat(mockDatabaseAdmin.countRequestsOfType(RestoreDatabaseRequest.class)).isEqualTo(2);
}
@Test
public void retryRestoreDatabaseSlowStartup() throws Exception {
mockDatabaseAdmin.setRestoreDatabaseStartupExecutionTime(
SimulatedExecutionTime.ofException(Status.DEADLINE_EXCEEDED.asRuntimeException()));
final String databaseId = "other-database-id";
OperationFuture<Database, RestoreDatabaseMetadata> op =
client.restoreDatabase(INSTANCE_ID, BCK_ID, INSTANCE_ID, databaseId);
Database database = op.get();
assertThat(database.getId().getName())
.isEqualTo(
String.format(
"projects/%s/instances/%s/databases/%s", PROJECT_ID, INSTANCE_ID, databaseId));
Database retrieved = client.getDatabase(INSTANCE_ID, databaseId);
assertThat(retrieved.getCreateTime()).isEqualTo(database.getCreateTime());
assertThat(mockDatabaseAdmin.countRequestsOfType(RestoreDatabaseRequest.class)).isAtLeast(3);
}
}
| tests: fix flaky restoreTestDatabase failures (#205)
| google-cloud-spanner/src/test/java/com/google/cloud/spanner/DatabaseAdminClientTest.java | tests: fix flaky restoreTestDatabase failures (#205) | <ide><path>oogle-cloud-spanner/src/test/java/com/google/cloud/spanner/DatabaseAdminClientTest.java
<ide>
<ide> package com.google.cloud.spanner;
<ide>
<del>import static com.google.common.base.Preconditions.checkNotNull;
<ide> import static com.google.common.truth.Truth.assertThat;
<add>import static org.junit.Assert.fail;
<ide>
<ide> import com.google.api.core.ApiFunction;
<ide> import com.google.api.gax.longrunning.OperationFuture;
<ide> import java.util.concurrent.CancellationException;
<ide> import java.util.concurrent.ExecutionException;
<ide> import java.util.concurrent.TimeUnit;
<del>import org.hamcrest.BaseMatcher;
<del>import org.hamcrest.Description;
<ide> import org.junit.After;
<ide> import org.junit.AfterClass;
<ide> import org.junit.Before;
<ide> import org.junit.BeforeClass;
<del>import org.junit.Rule;
<ide> import org.junit.Test;
<del>import org.junit.rules.ExpectedException;
<ide> import org.junit.runner.RunWith;
<ide> import org.junit.runners.JUnit4;
<ide> import org.threeten.bp.Duration;
<ide>
<ide> @RunWith(JUnit4.class)
<ide> public class DatabaseAdminClientTest {
<del> private static class SpannerExecutionExceptionMatcher extends BaseMatcher<Throwable> {
<del> private final ErrorCode expectedCode;
<del>
<del> private static SpannerExecutionExceptionMatcher forCode(ErrorCode code) {
<del> return new SpannerExecutionExceptionMatcher(code);
<del> }
<del>
<del> private SpannerExecutionExceptionMatcher(ErrorCode code) {
<del> this.expectedCode = checkNotNull(code);
<del> }
<del>
<del> @Override
<del> public boolean matches(Object item) {
<del> if (item instanceof ExecutionException) {
<del> ExecutionException e = (ExecutionException) item;
<del> if (e.getCause() instanceof SpannerException) {
<del> SpannerException se = (SpannerException) e.getCause();
<del> return se.getErrorCode() == expectedCode;
<del> }
<del> }
<del> return false;
<del> }
<del>
<del> @Override
<del> public void describeTo(Description description) {
<del> description.appendText("SpannerException[" + expectedCode + "]");
<del> }
<del> }
<del>
<ide> private static final String PROJECT_ID = "my-project";
<ide> private static final String INSTANCE_ID = "my-instance";
<ide> private static final String DB_ID = "test-db";
<ide>
<ide> private Spanner spanner;
<ide> private DatabaseAdminClient client;
<del> @Rule public ExpectedException exception = ExpectedException.none();
<ide> private OperationFuture<Database, CreateDatabaseMetadata> createDatabaseOperation;
<ide> private OperationFuture<Backup, CreateBackupMetadata> createBackupOperation;
<ide> private OperationFuture<Database, RestoreDatabaseMetadata> restoreDatabaseOperation;
<ide> SpannerOptions.Builder builder = SpannerOptions.newBuilder();
<ide> RetrySettings longRunningInitialRetrySettings =
<ide> RetrySettings.newBuilder()
<del> .setInitialRpcTimeout(Duration.ofMillis(60L))
<del> .setMaxRpcTimeout(Duration.ofMillis(600L))
<add> .setInitialRpcTimeout(Duration.ofMillis(600L))
<add> .setMaxRpcTimeout(Duration.ofMillis(6000L))
<ide> .setInitialRetryDelay(Duration.ofMillis(20L))
<ide> .setMaxRetryDelay(Duration.ofMillis(45L))
<ide> .setRetryDelayMultiplier(1.5)
<ide> public void dbAdminCreateBackupAlreadyExists() throws InterruptedException, ExecutionException {
<ide> OperationFuture<Backup, CreateBackupMetadata> op =
<ide> client.createBackup(INSTANCE_ID, BCK_ID, DB_ID, after7Days());
<del> exception.expect(SpannerExecutionExceptionMatcher.forCode(ErrorCode.ALREADY_EXISTS));
<del> op.get();
<add> try {
<add> op.get();
<add> fail("missing expected exception");
<add> } catch (ExecutionException e) {
<add> assertThat(e.getCause()).isInstanceOf(SpannerException.class);
<add> assertThat(((SpannerException) e.getCause()).getErrorCode())
<add> .isEqualTo(ErrorCode.ALREADY_EXISTS);
<add> }
<ide> }
<ide>
<ide> @Test
<ide> .setDatabase(DatabaseId.of(PROJECT_ID, INSTANCE_ID, DB_ID))
<ide> .setExpireTime(after7Days())
<ide> .build();
<del> OperationFuture<Backup, CreateBackupMetadata> op = backup.create();
<del> exception.expect(SpannerExecutionExceptionMatcher.forCode(ErrorCode.ALREADY_EXISTS));
<del> op.get();
<add> try {
<add> backup.create().get();
<add> fail("missing expected exception");
<add> } catch (ExecutionException e) {
<add> assertThat(e.getCause()).isInstanceOf(SpannerException.class);
<add> assertThat(((SpannerException) e.getCause()).getErrorCode())
<add> .isEqualTo(ErrorCode.ALREADY_EXISTS);
<add> }
<ide> }
<ide>
<ide> @Test
<ide> .newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, BCK_ID))
<ide> .setExpireTime(after7Days())
<ide> .build());
<del> exception.expect(SpannerExecutionExceptionMatcher.forCode(ErrorCode.ALREADY_EXISTS));
<del> op.get();
<add> try {
<add> op.get();
<add> fail("missing expected exception");
<add> } catch (ExecutionException e) {
<add> assertThat(e.getCause()).isInstanceOf(SpannerException.class);
<add> assertThat(((SpannerException) e.getCause()).getErrorCode())
<add> .isEqualTo(ErrorCode.ALREADY_EXISTS);
<add> }
<ide> }
<ide>
<ide> @Test
<ide> final String backupId = "other-backup-id";
<ide> OperationFuture<Backup, CreateBackupMetadata> op =
<ide> client.createBackup(INSTANCE_ID, backupId, "does-not-exist", after7Days());
<del> exception.expect(SpannerExecutionExceptionMatcher.forCode(ErrorCode.NOT_FOUND));
<del> op.get();
<add> try {
<add> op.get();
<add> fail("missing expected exception");
<add> } catch (ExecutionException e) {
<add> assertThat(e.getCause()).isInstanceOf(SpannerException.class);
<add> assertThat(((SpannerException) e.getCause()).getErrorCode()).isEqualTo(ErrorCode.NOT_FOUND);
<add> }
<ide> }
<ide>
<ide> @Test
<ide> .setDatabase(DatabaseId.of(PROJECT_ID, INSTANCE_ID, "does-not-exist"))
<ide> .setExpireTime(after7Days())
<ide> .build();
<del> OperationFuture<Backup, CreateBackupMetadata> op = backup.create();
<del> exception.expect(SpannerExecutionExceptionMatcher.forCode(ErrorCode.NOT_FOUND));
<del> op.get();
<add> try {
<add> backup.create().get();
<add> fail("missing expected exception");
<add> } catch (ExecutionException e) {
<add> assertThat(e.getCause()).isInstanceOf(SpannerException.class);
<add> assertThat(((SpannerException) e.getCause()).getErrorCode()).isEqualTo(ErrorCode.NOT_FOUND);
<add> }
<ide> }
<ide>
<ide> @Test
<ide> .newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, backupId))
<ide> .setExpireTime(after7Days())
<ide> .build());
<del> exception.expect(SpannerExecutionExceptionMatcher.forCode(ErrorCode.NOT_FOUND));
<del> op.get();
<add> try {
<add> op.get();
<add> fail("missing expected exception");
<add> } catch (ExecutionException e) {
<add> assertThat(e.getCause()).isInstanceOf(SpannerException.class);
<add> assertThat(((SpannerException) e.getCause()).getErrorCode()).isEqualTo(ErrorCode.NOT_FOUND);
<add> }
<ide> }
<ide>
<ide> @Test
<ide>
<ide> @Test
<ide> public void dbAdminDeleteBackupNotFound() {
<del> exception.expect(SpannerMatchers.isSpannerException(ErrorCode.NOT_FOUND));
<del> client.deleteBackup(INSTANCE_ID, "does-not-exist");
<add> try {
<add> client.deleteBackup(INSTANCE_ID, "does-not-exist");
<add> fail("missing expected exception");
<add> } catch (SpannerException e) {
<add> assertThat(e.getErrorCode()).isEqualTo(ErrorCode.NOT_FOUND);
<add> }
<ide> }
<ide>
<ide> @Test
<ide> public void backupDeleteNotFound() {
<ide> Backup backup =
<ide> client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, "does-not-exist")).build();
<del> exception.expect(SpannerMatchers.isSpannerException(ErrorCode.NOT_FOUND));
<del> backup.delete();
<add> try {
<add> backup.delete();
<add> fail("missing expected exception");
<add> } catch (SpannerException e) {
<add> assertThat(e.getErrorCode()).isEqualTo(ErrorCode.NOT_FOUND);
<add> }
<ide> }
<ide>
<ide> @Test
<ide>
<ide> @Test
<ide> public void dbAdminGetBackupNotFound() {
<del> exception.expect(SpannerMatchers.isSpannerException(ErrorCode.NOT_FOUND));
<del> client.getBackup(INSTANCE_ID, "does-not-exist");
<add> try {
<add> client.getBackup(INSTANCE_ID, "does-not-exist");
<add> } catch (SpannerException e) {
<add> assertThat(e.getErrorCode()).isEqualTo(ErrorCode.NOT_FOUND);
<add> }
<ide> }
<ide>
<ide> @Test
<ide> public void backupReloadNotFound() {
<ide> Backup backup =
<ide> client.newBackupBuilder(BackupId.of(PROJECT_ID, INSTANCE_ID, "does-not-exist")).build();
<del> exception.expect(SpannerMatchers.isSpannerException(ErrorCode.NOT_FOUND));
<del> backup.reload();
<add> try {
<add> backup.reload();
<add> } catch (SpannerException e) {
<add> assertThat(e.getErrorCode()).isEqualTo(ErrorCode.NOT_FOUND);
<add> }
<ide> }
<ide>
<ide> @Test |
|
Java | apache-2.0 | 90f378c2ac5c909be5abb5454ecef059c93cb0a6 | 0 | Hultron/LifeHelper | package com.hultron.lifehelper.ui;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.hultron.lifehelper.R;
import com.hultron.lifehelper.gson.weather.Forecast;
import com.hultron.lifehelper.gson.weather.Weather;
import com.hultron.lifehelper.service.AutoUpdateService;
import com.hultron.lifehelper.uitils.HttpUtil;
import com.hultron.lifehelper.uitils.ParsingJson;
import com.hultron.lifehelper.uitils.ShareUtil;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
/**
* 天气查询
*/
public class WeatherActivity extends AppCompatActivity {
private ScrollView weatherLayout;
private TextView titleCity;
private TextView titleUpdateTime;
private TextView degreeText;
private TextView weatherInfoText;
private LinearLayout forecastLayout;
private TextView aqiText;
private TextView pm25Text;
private TextView comfortText;
private TextView carWashText;
private TextView sportText;
private ImageView bingPicImg;
public SwipeRefreshLayout swipeRefreshLayout;
public DrawerLayout drawerLayout;
private Button navButton;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 21) {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
setContentView(R.layout.activity_weather);
initView();
}
private void initView() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navButton = (Button) findViewById(R.id.nav_button);
navButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
titleCity = (TextView) findViewById(R.id.title_city);
titleUpdateTime = (TextView) findViewById(R.id.title_update_time);
degreeText = (TextView) findViewById(R.id.degree_text);
weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
forecastLayout = (LinearLayout) findViewById(R.id.forcast_layout);
aqiText = (TextView) findViewById(R.id.aqi_text);
pm25Text = (TextView) findViewById(R.id.pm25_text);
comfortText = (TextView) findViewById(R.id.comfort_text);
carWashText = (TextView) findViewById(R.id.car_wash_text);
sportText = (TextView) findViewById(R.id.sport_text);
bingPicImg = (ImageView) findViewById(R.id.bing_pic_img);
String bingPic = ShareUtil.getString(this, "bing_pic", null);
if (bingPic != null) {
Picasso.with(this).load(bingPic).into(bingPicImg);
} else {
loadBingPic();
}
String weatherString = ShareUtil.getString(this, "weather", null);
final String weatherId;
if (weatherString != null) {
//有缓存时直接解析天气数据
Weather weather = ParsingJson.handleWeatherResponse(weatherString);
if (weather != null) {
weatherId = weather.basic.weatherId;
} else {
weatherId = null;
}
showWeatherInfo(weather);
} else {
//无缓存时去服务器查询天气
weatherId = getIntent().getStringExtra("weather_id");
weatherLayout.setVisibility(View.INVISIBLE);
requestWeather(weatherId);
}
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
requestWeather(weatherId);
}
});
}
private void loadBingPic() {
String requestBingPic = "http://guolin.tech/api/bing_pic";
HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String bingPic = response.body().string();
ShareUtil.putString(WeatherActivity.this, "bing_pic", bingPic);
runOnUiThread(new Runnable() {
@Override
public void run() {
Picasso.with(WeatherActivity.this).load(bingPic).into(bingPicImg);
}
});
}
});
}
/*
* 根据天气id请求城市天气信息
* */
public void requestWeather(final String weatherId) {
String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId +
"&key=edcc301174514a5e811431c763457862";
if (weatherId == null) {
Toast.makeText(WeatherActivity.this,
"当前没有选择城市,无法查询天气,请在左侧导航菜单中选择城市",
Toast.LENGTH_LONG).show();
drawerLayout.openDrawer(GravityCompat.START);
return;
}
HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WeatherActivity.this,
"获取天气信息失败,请在左侧导航菜单中选择城市",
Toast.LENGTH_LONG).show();
swipeRefreshLayout.setRefreshing(false);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final Weather weather = ParsingJson.handleWeatherResponse(responseText);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (weather != null && "ok".equals(weather.status)) {
ShareUtil.putString(WeatherActivity.this, "weather", responseText);
showWeatherInfo(weather);
} else {
Toast.makeText(WeatherActivity.this, "获取天气信息成功",
Toast.LENGTH_SHORT).show();
}
swipeRefreshLayout.setRefreshing(false);
}
});
}
});
loadBingPic();
}
/*
* 获取并展示 Weather 实体类中的数据
* */
private void showWeatherInfo(Weather weather) {
String cityName = weather.basic.cityName;
String updateTime = weather.basic.update.updateTime.split(" ")[1];
String degree = weather.now.temperature + "°C";
String weatherInfo = weather.now.more.info;
titleCity.setText(cityName);
titleUpdateTime.setText(updateTime);
degreeText.setText(degree);
weatherInfoText.setText(weatherInfo);
forecastLayout.removeAllViews();
for (Forecast forecast : weather.forecastList) {
View view = LayoutInflater.from(this).inflate(R.layout.forcast_item,
forecastLayout, false);
TextView dateText = (TextView) view.findViewById(R.id.date_text);
TextView infoText = (TextView) view.findViewById(R.id.info_text);
TextView maxText = (TextView) view.findViewById(R.id.max_text);
TextView minText = (TextView) view.findViewById(R.id.min_text);
dateText.setText(forecast.date);
infoText.setText(forecast.more.info);
maxText.setText(forecast.temperature.max);
minText.setText(forecast.temperature.min);
forecastLayout.addView(view);
}
if (weather.aqi != null) {
aqiText.setText(weather.aqi.city.aqi);
pm25Text.setText(weather.aqi.city.pm25);
}
if (weather.suggestion != null) {
String comfort = "舒适度: " + weather.suggestion.comfort.info;
String carWash = "洗车指数: " + weather.suggestion.carWash.info;
String sport = "运动建议: " + weather.suggestion.sport.info;
comfortText.setText(comfort);
carWashText.setText(carWash);
sportText.setText(sport);
}
Intent intent = new Intent(this, AutoUpdateService.class);
startService(intent);
weatherLayout.setVisibility(View.VISIBLE);
}
}
| app/src/main/java/com/hultron/lifehelper/ui/WeatherActivity.java | package com.hultron.lifehelper.ui;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.hultron.lifehelper.R;
import com.hultron.lifehelper.gson.weather.Forecast;
import com.hultron.lifehelper.gson.weather.Weather;
import com.hultron.lifehelper.service.AutoUpdateService;
import com.hultron.lifehelper.uitils.HttpUtil;
import com.hultron.lifehelper.uitils.ParsingJson;
import com.hultron.lifehelper.uitils.ShareUtil;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
/**
* 天气查询
*/
public class WeatherActivity extends AppCompatActivity {
private ScrollView weatherLayout;
private TextView titleCity;
private TextView titleUpdateTime;
private TextView degreeText;
private TextView weatherInfoText;
private LinearLayout forecastLayout;
private TextView aqiText;
private TextView pm25Text;
private TextView comfortText;
private TextView carWashText;
private TextView sportText;
private ImageView bingPicImg;
public SwipeRefreshLayout swipeRefreshLayout;
public DrawerLayout drawerLayout;
private Button navButton;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 21) {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
setContentView(R.layout.activity_weather);
initView();
}
private void initView() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navButton = (Button) findViewById(R.id.nav_button);
navButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
titleCity = (TextView) findViewById(R.id.title_city);
titleUpdateTime = (TextView) findViewById(R.id.title_update_time);
degreeText = (TextView) findViewById(R.id.degree_text);
weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
forecastLayout = (LinearLayout) findViewById(R.id.forcast_layout);
aqiText = (TextView) findViewById(R.id.aqi_text);
pm25Text = (TextView) findViewById(R.id.pm25_text);
comfortText = (TextView) findViewById(R.id.comfort_text);
carWashText = (TextView) findViewById(R.id.car_wash_text);
sportText = (TextView) findViewById(R.id.sport_text);
bingPicImg = (ImageView) findViewById(R.id.bing_pic_img);
String bingPic = ShareUtil.getString(this, "bing_pic", null);
if (bingPic != null) {
Picasso.with(this).load(bingPic).into(bingPicImg);
} else {
loadBingPic();
}
String weatherString = ShareUtil.getString(this, "weather", null);
final String weatherId;
if (weatherString != null) {
//有缓存时直接解析天气数据
Weather weather = ParsingJson.handleWeatherResponse(weatherString);
if (weather != null) {
weatherId = weather.basic.weatherId;
} else {
weatherId = null;
}
showWeatherInfo(weather);
} else {
//无缓存时去服务器查询天气
weatherId = getIntent().getStringExtra("weather_id");
weatherLayout.setVisibility(View.INVISIBLE);
requestWeather(weatherId);
}
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
requestWeather(weatherId);
}
});
}
private void loadBingPic() {
String requestBingPic = "http://guolin.tech/api/bing_pic";
HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String bingPic = response.body().string();
ShareUtil.putString(WeatherActivity.this, "bing_pic", bingPic);
runOnUiThread(new Runnable() {
@Override
public void run() {
Picasso.with(WeatherActivity.this).load(bingPic).into(bingPicImg);
}
});
}
});
}
/*
* 根据天气id请求城市天气信息
* */
public void requestWeather(final String weatherId) {
String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId +
"&key=edcc301174514a5e811431c763457862";
HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WeatherActivity.this, "获取天气信息失败,请在左侧导航菜单中选择城市",
Toast.LENGTH_LONG).show();
swipeRefreshLayout.setRefreshing(false);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final Weather weather = ParsingJson.handleWeatherResponse(responseText);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (weather != null && "ok".equals(weather.status)) {
ShareUtil.putString(WeatherActivity.this, "weather", responseText);
showWeatherInfo(weather);
} else {
Toast.makeText(WeatherActivity.this, "获取天气信息成功",
Toast.LENGTH_SHORT).show();
}
swipeRefreshLayout.setRefreshing(false);
}
});
}
});
loadBingPic();
}
/*
* 获取并展示 Weather 实体类中的数据
* */
private void showWeatherInfo(Weather weather) {
String cityName = weather.basic.cityName;
String updateTime = weather.basic.update.updateTime.split(" ")[1];
String degree = weather.now.temperature + "°C";
String weatherInfo = weather.now.more.info;
titleCity.setText(cityName);
titleUpdateTime.setText(updateTime);
degreeText.setText(degree);
weatherInfoText.setText(weatherInfo);
forecastLayout.removeAllViews();
for (Forecast forecast : weather.forecastList) {
View view = LayoutInflater.from(this).inflate(R.layout.forcast_item,
forecastLayout, false);
TextView dateText = (TextView) view.findViewById(R.id.date_text);
TextView infoText = (TextView) view.findViewById(R.id.info_text);
TextView maxText = (TextView) view.findViewById(R.id.max_text);
TextView minText = (TextView) view.findViewById(R.id.min_text);
dateText.setText(forecast.date);
infoText.setText(forecast.more.info);
maxText.setText(forecast.temperature.max);
minText.setText(forecast.temperature.min);
forecastLayout.addView(view);
}
if (weather.aqi != null) {
aqiText.setText(weather.aqi.city.aqi);
pm25Text.setText(weather.aqi.city.pm25);
}
if (weather.suggestion != null) {
String comfort = "舒适度: " + weather.suggestion.comfort.info;
String carWash = "洗车指数: " + weather.suggestion.carWash.info;
String sport = "运动建议: " + weather.suggestion.sport.info;
comfortText.setText(comfort);
carWashText.setText(carWash);
sportText.setText(sport);
}
Intent intent = new Intent(this, AutoUpdateService.class);
startService(intent);
weatherLayout.setVisibility(View.VISIBLE);
}
}
| 优化天气查询逻辑,弹出选择城市的Toast
| app/src/main/java/com/hultron/lifehelper/ui/WeatherActivity.java | 优化天气查询逻辑,弹出选择城市的Toast | <ide><path>pp/src/main/java/com/hultron/lifehelper/ui/WeatherActivity.java
<ide> public void requestWeather(final String weatherId) {
<ide> String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId +
<ide> "&key=edcc301174514a5e811431c763457862";
<add> if (weatherId == null) {
<add> Toast.makeText(WeatherActivity.this,
<add> "当前没有选择城市,无法查询天气,请在左侧导航菜单中选择城市",
<add> Toast.LENGTH_LONG).show();
<add> drawerLayout.openDrawer(GravityCompat.START);
<add> return;
<add> }
<ide> HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
<ide> @Override
<ide> public void onFailure(Call call, IOException e) {
<ide> runOnUiThread(new Runnable() {
<ide> @Override
<ide> public void run() {
<del> Toast.makeText(WeatherActivity.this, "获取天气信息失败,请在左侧导航菜单中选择城市",
<add> Toast.makeText(WeatherActivity.this,
<add> "获取天气信息失败,请在左侧导航菜单中选择城市",
<ide> Toast.LENGTH_LONG).show();
<ide> swipeRefreshLayout.setRefreshing(false);
<ide> } |
|
JavaScript | bsd-3-clause | 4e92599d87126a2fa7220442cd9dd806c85f3b62 | 0 | ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article | (function($){
zeit.cms.declare_namespace('zeit.content.article');
zeit.cms.in_article_editor = function() {
return Boolean(jQuery('.article-editor-inner').length);
};
MochiKit.Signal.connect(window, 'cp-editor-loaded', function() {
if (! zeit.cms.in_article_editor()) {
return;
}
// Initialize module library
zeit.edit.library.create(
'article-modules', context_url + '/editable-body', 'Artikel');
// Update error messages and checkin button disabled status
MochiKit.Signal.connect(window, 'changed', function() {
var workflow_area = $('form[action$="edit.form.publish"]')[0];
MochiKit.Async.callLater(0.25, function() {
workflow_area.form.reload(); });
});
$('.editable-area > .block-inner').append('<div class="totop"><span class="totopclick">↑</span></div>');
$('.totopclick').live("click", function() {
$('#cp-content-inner').animate({scrollTop: 0}, 300);
});
});
MochiKit.Signal.connect(window, 'script-loading-finished', function() {
if (! zeit.cms.in_article_editor()) {
return;
}
zeit.edit.drop.registerHandler({
accept: ['editable-body-module'],
activated_by: 'action-editable-body-module-droppable',
url_attribute: 'cms:create-block-url',
query_arguments: function(draggable) {
return {'block_type': draggable.getAttribute('cms:block_type')};
}
});
zeit.edit.drop.registerContentHandler({
accept: ['type-image',
'type-gallery', 'type-video',
'type-infobox', 'type-portraitbox'],
activated_by: 'action-article-body-content-droppable'
});
});
(function() {
var ident = MochiKit.Signal.connect(
window, 'script-loading-finished', function() {
MochiKit.Signal.disconnect(ident);
if (! zeit.cms.in_article_editor()) {
return;
}
forEach($$('#cp-content .action-block-sorter'), function(element) {
element.body_sorter =
new zeit.edit.sortable.BlockSorter(element.id);
});
});
}());
zeit.content.article.Editable = gocept.Class.extend({
// Inline editing module
autosave_interval: 10,
editor_active_lock: new MochiKit.Async.DeferredLock(),
construct: function(context_element, place_cursor_at_end) {
var self = this;
self.block_id = MochiKit.DOM.getFirstParentByTagAndClassName(
context_element, null, 'block').id;
self.locked = false;
var d = self.editor_active_lock.acquire();
log('Waiting for lock', self.block_id);
d.addCallback(function() {
log('Lock acquired', self.block_id);
var block = $('#' + self.block_id)[0];
if (typeof block === "undefined") {
// block vanished while waiting for lock.
self.editor_active_lock.release();
log('block vanished', self.block_id);
return;
}
self.events = [];
self.edited_paragraphs = [];
self.autosave_timer = window.setInterval(
MochiKit.Base.bind(self.autosave, self),
self.autosave_interval*1000);
self.initial_paragraph = MochiKit.Selector.findChildElements(
block, ['.editable > *'])[0];
self.editable = self.merge(block);
self.block = MochiKit.DOM.getFirstParentByTagAndClassName(
self.editable, null, 'block');
log('Editable block', self.block.id);
self.editable.removeAttribute('cms:cp-module');
self.editable.contentEditable = true;
self.editable.editable = self; // make instance available for tests
self.command('styleWithCSS', false, false);
MochiKit.DOM.addElementClass(self.block, 'editing');
// This catches the blur-signal in the capturing-phase!
// In case you use the toolbar, the editing-mode won't be stopped.
self.editable.parentNode.addEventListener("blur", function(e) {
var clicked_on_block =
MochiKit.DOM.getFirstParentByTagAndClassName(
e.explicitOriginalTarget, 'div', 'block');
var is_in_block = (clicked_on_block == self.block);
log("Blur while editing:", is_in_block, self.block_id);
if (is_in_block || self.locked) {
e.stopPropagation();
} else {
self.save();
}
}, true);
self.events.push(MochiKit.Signal.connect(
self.editable, 'onkeydown', self, self.handle_keydown));
self.events.push(MochiKit.Signal.connect(
self.editable, 'onkeyup', self, self.handle_keyup));
$('.editable').bind('paste', function() {
self.handle_paste();
});
self.events.push(MochiKit.Signal.connect(
zeit.edit.editor, 'before-reload', function() {
// XXX giant hack around strange browser behaviour.
//
// Reproduction recipe for the bug: While a block is
// contentEditable, drag it around to change sorting. This
// will result in a blinking cursor being left somewhere on
// the page. In spite of investigating this at length, we
// have no idea what causes this, so far.
//
// To get rid of this stray cursor, we focus-then-blur
// something else (we scientifcally chose the
// fulltext-search input box at random). Synthesizing a
// blur on self.editable or similar has no effect, and the
// "something else" we dash off to needs to be an <input
// type="text">.
$('#fulltext').focus();
$('#fulltext').blur();
self.save(/*no_reload=*/true);
}));
self.fix_html();
$('body').trigger('update-ads');
self.place_cursor(self.initial_paragraph, place_cursor_at_end);
self.editable.focus();
self.init_linkbar();
self.init_toolbar();
self.shortcuts();
self.relocate_toolbar(true);
self.events.push(MochiKit.Signal.connect(
window, 'before-content-drag', function() {
if (!self.locked) {
self.save();
}
}));
});
d.addErrback(function(err) {zeit.cms.log_error(err); return err;});
},
place_cursor: function(element, place_cursor_at_end) {
// Place cursor to the beginnning of element
log('Placing cursor to', element.nodeName);
var range = getSelection().getRangeAt(0);
var direction;
if (place_cursor_at_end) {
direction = 'lastChild';
} else {
direction = 'firstChild';
}
var text_node = element;
while (text_node[direction] !== null) {
text_node = text_node[direction];
}
var offset = 0;
if (place_cursor_at_end &&
text_node.nodeType == text_node.TEXT_NODE) {
offset = text_node.data.length;
}
range.setStart(text_node, offset);
range.setEnd(text_node, offset);
},
is_block_editable: function(block) {
return !isNull(
MochiKit.DOM.getFirstElementByTagAndClassName(
'div', 'editable', block));
},
merge: function(block) {
var self = this;
var blocks = MochiKit.DOM.getElementsByTagAndClassName(
null, 'block', block.parentNode);
var i = blocks.indexOf(block);
var paragraphs = [];
// XXX remove code duplication
while (i > 0) {
i -= 1;
if (self.is_block_editable(blocks[i])) {
paragraphs.push(blocks[i]);
} else {
break;
}
}
paragraphs.reverse();
paragraphs.push(block);
i = blocks.indexOf(block);
while (i < blocks.length-1) {
i += 1;
if (self.is_block_editable(blocks[i])) {
paragraphs.push(blocks[i]);
} else {
break;
}
}
self.edited_paragraphs = MochiKit.Base.map(
function(element) { return element.id; },
paragraphs);
paragraphs[0].block_ids = self.edited_paragraphs;
var editable = MochiKit.DOM.getFirstElementByTagAndClassName(
null, 'editable', paragraphs[0]);
forEach(paragraphs.slice(1), function(paragraph) {
forEach(MochiKit.Selector.findChildElements(
paragraph, ['.editable > *']), function(p) {
editable.appendChild(p);
});
jQuery(paragraph).next('.landing-zone').remove();
MochiKit.DOM.removeElement(paragraph);
});
// Clear out all non element nodes
forEach(editable.childNodes, function(child) {
if (child.nodeType != child.ELEMENT_NODE) {
editable.removeChild(child);
}
});
return editable;
},
init_linkbar: function() {
var self = this;
self.link_input = self.editable.parentNode.insertBefore(
DIV({'class': 'link_input hidden'},
INPUT({type: 'text', name: 'href', value: ''}),
SELECT({name: 'target'},
OPTION({value: '_blank'}, 'Neues Fenster'),
OPTION({value: ''}, 'Gleiches Fenster')),
BUTTON({name: 'insert_link_ok',
value: 'method'}, 'Setzen'),
BUTTON({name: 'insert_link_cancel',
value: 'method'}, 'Abbrechen')),
self.editable);
self.link_input.dropable = new MochiKit.DragAndDrop.Droppable(
self.link_input, {
accept: ['content-drag-pane', 'uniqueId'],
activeclass: 'droppable-active',
hoverclass: 'hover-content',
ondrop: function(element, last_active_element, event) {
// One could consider the replace a hack.
$('input[name=href]', self.link_input).val(
element.uniqueId.replace(
'http://xml.zeit.de/',
'http://www.zeit.de/'));
}
});
self.events.push(MochiKit.Signal.connect(
self.link_input, 'onkeydown', function(event) {
if (event.key().string == 'KEY_ENTER') {
self.insert_link_ok();
event.stop();
}
}));
},
init_toolbar: function() {
var self = this;
self.toolbar = self.editable.parentNode.insertBefore(
DIV({'class': 'rte-toolbar',
'style': 'display: block; opacity: 0'}),
self.editable);
self.toolbar.innerHTML = "\
<a title='fett [Cmd/Strg+b]' rel='command' href='bold'>B</a>\
<a title='kursiv [Cmd/Strg+i]' rel='command' href='italic'>I</a>\
<a title='Zwischenüberschrift [Cmd/Strg+h]' rel='command' href='formatBlock/h3'>H3</a>\
<a title='Link [Cmd/Strg+l]' rel='method' href='insert_link'>A</a>\
<a title='Link entfernen [Cmd/Strg+u]' rel='command' href='unlink'>A</a>\
<a title='Liste' rel='command' href='insertunorderedlist'>UL</a>\
<a title='Formatierungen entfernen [Cmd/Strg+r]' rel='command' href='removeFormat'>PL</a>\
";
self.events.push(MochiKit.Signal.connect(
self.block, 'onclick',
self, self.handle_click));
MochiKit.Visual.appear(self.toolbar);
self.update_toolbar();
},
update_toolbar: function() {
var self = this;
var element = self.get_selected_container();
log('got', element.nodeName);
if (element.nodeType == element.TEXT_NODE) {
element = element.parentNode;
}
forEach(MochiKit.DOM.getElementsByTagAndClassName(
'a', null, self.toolbar), function(action) {
MochiKit.DOM.removeElementClass(action, 'active');
});
while(!isNull(element) && element != self.editable) {
log('checking', element.nodeName);
forEach(MochiKit.DOM.getElementsByTagAndClassName(
'a', null, self.toolbar), function(action) {
if (action.innerHTML == element.nodeName) {
MochiKit.DOM.addElementClass(action, 'active');
if (element.nodeName == 'H3' && action.innerHTML == 'H3') {
MochiKit.DOM.updateNodeAttributes(action, {'href': 'formatBlock/p'});
action.innerHTML = 'P';
}
if (element.nodeName != 'H3' && MochiKit.DOM.getNodeAttribute(action, 'href') == 'formatBlock/p') {
MochiKit.DOM.updateNodeAttributes(action, {'href': 'formatBlock/h3'});
action.innerHTML = 'H3';
}
}
});
element = element.parentNode;
}
},
relocate_toolbar: function(fast) {
var self = this;
var y = MochiKit.Style.getStyle(self.toolbar, 'top');
var cursor_pos = self._get_cursor_position();
if (cursor_pos && cursor_pos.y>0){
y = cursor_pos.y;
}
var move = {
duration: 0.5,
mode: 'absolute',
// By mode=absolute MochiKit means 'left' and 'top' CSS values.
// Since they refer to the next parent with a specified 'position'
// value, which is not necessarily self.block, we need to look at
// the 'left' value instead of calling getElementPosition() in
// order to retrieve the current x position (which is to be the
// target x position, i.e. we don't want any horizontal motion).
x: MochiKit.Style.getStyle(self.toolbar, 'left'),
y: y
};
if (fast) {
MochiKit.Style.setElementPosition(self.toolbar, move);
} else {
MochiKit.Visual.Move(self.toolbar, move);
}
},
_get_cursor_position: function() {
var self = this;
var pos = {x:0,y:0};
var selection = window.getSelection();
if (! selection.rangeCount) {
return null;
}
var range = selection.getRangeAt(0);
var cloned_range = range.cloneRange();
cloned_range.collapse(true);
var cloned_collapsed_rect = cloned_range.getClientRects()[0];
if (cloned_collapsed_rect) {
var offset = $(".rte-toolbar").parent().offset();
pos.y = cloned_collapsed_rect.top - offset.top;
pos.x = cloned_collapsed_rect.left;
} else if (range.startContainer.tagName == "P" &&
range.getClientRects().length==0){
var html = '<span id="_find_cursor_position"> </span>';
document.execCommand('insertHTML', false, html);
var tmp_el = $('#_find_cursor_position');
var tmp_pos = tmp_el.position();
var par = tmp_el.parent();
pos.y = tmp_pos.top;
pos.x = tmp_pos.left;
tmp_el.remove();
if (par.children().length==0){
document.execCommand('insertHTML', false,'<br type="_moz" />');
}
} else {
return null;
}
return pos;
},
handle_click: function(event) {
var self = this;
var mode, argument;
self.update_toolbar();
self.relocate_toolbar();
if (event.target().nodeName == 'A') {
mode = event.target().rel;
argument = event.target().getAttribute('href');
} else if (event.target().nodeName == 'BUTTON') {
mode = event.target().value;
argument = event.target().name;
} else {
return;
}
event.stop();
if (mode == 'command') {
event.stop();
var action = argument.split('/');
self.command(action[0], action[1]);
} else if (mode == 'method') {
var method = argument;
self[method]();
}
},
handle_keydown: function(event) {
var self = this;
var range = getSelection().getRangeAt(0);
var container = range.commonAncestorContainer;
// lastnode/firstnodee?
var direction = null;
var cursor_at_end = false;
if (event.key().string == 'KEY_ARROW_DOWN' &&
((container.nodeType == container.TEXT_NODE && // Last
container.parentNode.nextSibling === null) || // node
(container.tagName == 'P' && // Empty
container.nextSibling === null)) && // node
MochiKit.DOM.scrapeText(container).length == range.endOffset) {
direction = 'nextSibling';
} else if (
event.key().string == 'KEY_ARROW_UP' &&
((container.nodeType == container.TEXT_NODE && // First
container.parentNode.previousSibling === null) || // node
(container.tagName == 'P' && // Empty
container.previousSibling === null)) && // node
range.startOffset === 0) {
direction = 'previousSibling';
cursor_at_end = true;
} else if (
event.key().string == 'KEY_ENTER') {
setTimeout(function() {
$('body').trigger('update-ads');
}, 0);
} else if (
(event.key().string == 'KEY_BACKSPACE') ||
event.key().string == 'KEY_DELETE') {
// Don't remove empty paragraphs.
if (container.tagName == 'P' &&
container.previousSibling === null &&
MochiKit.DOM.scrapeText(container).length === 0) {
event.preventDefault();
}
setTimeout(function() {
$('body').trigger('update-ads');
}, 0);
} else if (
container.nodeType == container.TEXT_NODE &&
container.parentNode.tagName == 'DIV') {
/*
* Currently contenteditable seems to be buggy in firefox 4.
* While a new paragraph is created every time the return key has
* been pressed inside a paragraph, there will be just a textnode as
* direct child of the contenteditable, when hitting the return key
* within any other tag (e.g. h3, li...). The following workaround
* will wrap a p around every textnode, which is the direct child of
* the contenteditable.
*
* Sometimes another paragraph is added accidentally, when pressing
* the up and down keys within an empty p tag, so we have to get rid
* of the previous and next empty paragraph respectively.
*/
self.command('formatBlock', 'p');
var next_sibling = container.parentNode.nextSibling;
var prev_sibling = container.parentNode.previousSibling;
if (next_sibling != null &&
next_sibling.nodeName == 'BR') {
$(next_sibling).remove(); // Get rid of superfluous <br/>.
} else if (
next_sibling != null &&
next_sibling.nodeName == 'P') {
$(next_sibling).remove(); // Get rid of empty <p/>.
} else if (
prev_sibling != null &&
prev_sibling.nodeName == 'P') {
$(prev_sibling).remove(); // Get rid of empty <p/>.
}
}
if (direction !== null) {
var block = self.block;
var next_block = null;
while (block[direction] !== null) {
block = block[direction];
if (block.nodeType != block.ELEMENT_NODE) {
continue;
}
if (MochiKit.DOM.hasElementClass(block, 'block') &&
self.is_block_editable(block)) {
next_block = block;
break;
}
}
if (next_block !== null) {
log('Next block', next_block.id);
// Note id as save may (or probably will) replace the element
var next_block_id = next_block.id;
self.save();
new zeit.content.article.Editable(
MochiKit.DOM.getFirstElementByTagAndClassName(
'div', 'editable', $('#' + next_block_id)[0]),
cursor_at_end);
event.stop();
}
}
},
handle_keyup: function(event) {
var self = this;
self.update_toolbar();
self.relocate_toolbar();
self.fix_html();
},
handle_paste: function() {
var self = this;
// Get rid of obsolete mark-up when pasting content from third party
// software. Ensure that content is processed AFTER it has been pasted.
setTimeout(function() {
self.fix_html();
$(self.editable).children().has('style').remove();
$('a', self.editable).attr('target', '_blank');
}, 0);
},
fix_html: function() {
var self = this;
self.editable.normalize();
forEach(
MochiKit.DOM.getElementsByTagAndClassName(
null, null, self.editable),
function(element) {
element.removeAttribute('class');
element.removeAttribute('style');
// Yeah, I luv it!
if (element.nodeName == 'EM') {
zeit.content.article.html.change_tag(element, 'I');
} else if (element.nodeName == 'STRONG') {
zeit.content.article.html.change_tag(element, 'B');
}
});
},
get_text_list: function() {
var self = this;
self.fix_html();
var tree = self.editable.cloneNode(/*deep=*/true);
zeit.content.article.html.to_xml(tree);
var result = MochiKit.Base.map(function(el) {
return {factory: el.nodeName.toLowerCase(),
text: el.innerHTML};
}, tree.childNodes);
return result;
},
autosave: function() {
var self = this;
if (zeit.cms.request_lock.locked) {
log('Skipping autosave due to running other request');
return;
}
log('Autosaving', self.block_id);
zeit.cms.with_lock(function() {
var url = $('#editable-body').attr('cms:url') +
'/@@autosave_text';
var data = {paragraphs: self.edited_paragraphs,
text: self.get_text_list()};
data = MochiKit.Base.serializeJSON(data);
var d = MochiKit.Async.doXHR(url, {
method: 'POST',
sendContent: data});
d.addCallback(function(result) {
result = MochiKit.Async.evalJSONRequest(result);
self.edited_paragraphs = result['data']['new_ids'];
self.block.block_ids = self.edited_paragraphs;
});
d.addErrback(function(err) {zeit.cms.log_error(err); return err;});
});
},
save: function(no_reload) {
var self = this;
log('Saving', self.block_id);
MochiKit.DOM.addElementClass(self.block, 'busy');
window.clearInterval(self.autosave_timer);
zeit.cms.with_lock(function() {
while (self.events.length) {
MochiKit.Signal.disconnect(self.events.pop());
}
self.link_input.dropable.destroy();
log('disconnected event handlers');
var ident = MochiKit.Signal.connect(
zeit.edit.editor, 'after-reload', function() {
MochiKit.Signal.disconnect(ident);
log('Release lock', self.block_id);
self.editor_active_lock.release();
});
// until now, the editor can only be contained in an editable-body.
var url = $('#editable-body').attr('cms:url') + '/@@save_text';
var data = {paragraphs: self.edited_paragraphs,
text: self.get_text_list()};
if (no_reload) {
data = MochiKit.Base.serializeJSON(data);
MochiKit.Async.doXHR(url, {
method: 'POST',
sendContent: data});
} else {
zeit.edit._locked_makeJSONRequest(url, data);
}
});
},
get_selected_container: function() {
var container;
var range = getSelection().getRangeAt(0);
if ((range.startContainer.nodeType ==
range.startContainer.ELEMENT_NODE) &&
(range.startContainer == range.endContainer) &&
(range.startOffset + 1 == range.endOffset)) {
// There is one single element inside the range, use that.
container = range.startContainer.childNodes[range.startOffset];
} else {
container = range.commonAncestorContainer;
}
return container;
},
select_container: function(element) {
var self = this;
try {
var range = getSelection().getRangeAt(0);
range.setStartBefore(element);
range.setEndAfter(element);
} catch(e) {
if (window.console) {
console.log(e);
}
}
},
insert_link: function() {
var self = this;
if (self.locked) {
return;
}
var container = self.get_selected_container();
if (container.nodeName == 'A') {
self.insert_link_node = container;
} else {
self.insert_link_node =
MochiKit.DOM.getFirstParentByTagAndClassName(
container, 'a', null);
}
var href = '';
var target = '';
if (self.insert_link_node) {
href = self.insert_link_node.getAttribute('href') || '';
target = self.insert_link_node.getAttribute('target') || '';
} else {
self.command('createLink', '#article-editor-create-link');
self.insert_link_node = $(
'a[href="#article-editor-create-link"]', self.editable)[0];
self.insert_link_node._just_created = true;
}
$(self.insert_link_node).addClass('link-edit');
if (!self.insert_link_node._just_created) {
$('*[name=href]', self.link_input).val(href);
$('*[name=target]', self.link_input).val(target);
}
var line_height = parseInt(
$(self.insert_link_node).css('line-height').replace('px', ''));
var position = $(self.insert_link_node).position();
$(self.link_input).css('top',
(parseInt(position.top) + line_height) + 'px');
$(self.link_input).removeClass('hidden');
$('*[name=href]', self.link_input).focus();
self.locked = true;
},
insert_link_ok: function() {
var self = this;
var href = $('*[name=href]', self.link_input).val();
var target = $('*[name=target]', self.link_input).val();
self.insert_link_node.href = href;
if (target) {
self.insert_link_node.target = target;
} else {
self.insert_link_node.removeAttribute('target');
}
self.select_container(self.insert_link_node);
self._insert_link_finish();
},
insert_link_cancel: function() {
var self = this;
self.select_container(self.insert_link_node);
if (self.insert_link_node._just_created) {
while(!isNull(self.insert_link_node.firstChild)) {
self.insert_link_node.parentNode.insertBefore(
self.insert_link_node.firstChild,
self.insert_link_node);
}
$(self.insert_link_node).remove();
}
self._insert_link_finish();
},
_insert_link_finish: function() {
var self = this;
$(self.link_input).addClass('hidden');
$(self.insert_link_node).removeClass('link-edit');
self.insert_link_node._just_created = false;
self.insert_link_node = null;
self.locked = false;
self.editable.focus();
},
command: function(command, option, refocus) {
var self = this;
if (self.locked) {
return;
}
log("Executing", command, option);
try {
document.execCommand(command, false, option);
} catch(e) {
if (window.console) {
console.log(e);
}
}
if (typeof refocus === 'undefined' || refocus === true) {
self.editable.focus();
}
self.update_toolbar();
},
shortcuts: function() {
var self = this;
$("#editable-body").keydown(function(e) {
console.log(e);
if (e.ctrlKey || e.metaKey) {
if (e.which == 66) {
e.preventDefault();
self.command('bold');
} else if (e.which == 73) {
e.preventDefault();
self.command('italic');
} else if (e.which == 72) {
e.preventDefault();
self.command('formatBlock', '<h3>');
} else if (e.which == 76) {
e.preventDefault();
self['insert_link']();
} else if (e.which == 85) {
e.preventDefault();
self.command('unlink');
} else if (e.which == 82) {
e.preventDefault();
self.command('removeFormat');
} else if (e.which == 65) {
e.preventDefault();
self.selectall();
}
}
});
},
selectall: function() {
$('#editable-body .block.type-p p, #editable-body .block.type-p li, #editable-body .block.type-p h3, #editable-body .block.type-intertitle h3, #editable-body .block.type-ul li' ).each(function(index, value) {
var content = $(this).text();
if(content !='') {
var range = document.createRange();
range.selectNodeContents(this);
var sel = window.getSelection();
sel.addRange(range);
}
});
}
});
zeit.content.article.AppendParagraph = zeit.edit.LoadAndReload.extend({
construct: function(context_element) {
var self = this;
$('.create-paragraph').first().remove();
var ident = MochiKit.Signal.connect(
zeit.edit.editor, 'after-reload', function() {
MochiKit.Signal.disconnect(ident);
var new_p = $('#editable-body .block.type-p').last()[0];
new zeit.content.article.Editable(new_p.firstChild, true);
});
arguments.callee.$.construct.call(self, context_element);
}
});
}(jQuery));
| src/zeit/content/article/edit/browser/resources/editor.js | (function($){
zeit.cms.declare_namespace('zeit.content.article');
zeit.cms.in_article_editor = function() {
return Boolean(jQuery('.article-editor-inner').length);
};
MochiKit.Signal.connect(window, 'cp-editor-loaded', function() {
if (! zeit.cms.in_article_editor()) {
return;
}
// Initialize module library
zeit.edit.library.create(
'article-modules', context_url + '/editable-body', 'Artikel');
// Update error messages and checkin button disabled status
MochiKit.Signal.connect(window, 'changed', function() {
var workflow_area = $('form[action$="edit.form.publish"]')[0];
MochiKit.Async.callLater(0.25, function() {
workflow_area.form.reload(); });
});
$('.editable-area > .block-inner').append('<div class="totop"><span class="totopclick">↑</span></div>');
$('.totopclick').live("click", function() {
$('#cp-content-inner').animate({scrollTop: 0}, 300);
});
});
MochiKit.Signal.connect(window, 'script-loading-finished', function() {
if (! zeit.cms.in_article_editor()) {
return;
}
zeit.edit.drop.registerHandler({
accept: ['editable-body-module'],
activated_by: 'action-editable-body-module-droppable',
url_attribute: 'cms:create-block-url',
query_arguments: function(draggable) {
return {'block_type': draggable.getAttribute('cms:block_type')};
}
});
zeit.edit.drop.registerContentHandler({
accept: ['type-image',
'type-gallery', 'type-video',
'type-infobox', 'type-portraitbox'],
activated_by: 'action-article-body-content-droppable'
});
});
(function() {
var ident = MochiKit.Signal.connect(
window, 'script-loading-finished', function() {
MochiKit.Signal.disconnect(ident);
if (! zeit.cms.in_article_editor()) {
return;
}
forEach($$('#cp-content .action-block-sorter'), function(element) {
element.body_sorter =
new zeit.edit.sortable.BlockSorter(element.id);
});
});
}());
zeit.content.article.Editable = gocept.Class.extend({
// Inline editing module
autosave_interval: 10,
editor_active_lock: new MochiKit.Async.DeferredLock(),
construct: function(context_element, place_cursor_at_end) {
var self = this;
self.block_id = MochiKit.DOM.getFirstParentByTagAndClassName(
context_element, null, 'block').id;
self.locked = false;
var d = self.editor_active_lock.acquire();
log('Waiting for lock', self.block_id);
d.addCallback(function() {
log('Lock acquired', self.block_id);
var block = $('#' + self.block_id)[0];
if (typeof block === "undefined") {
// block vanished while waiting for lock.
self.editor_active_lock.release();
log('block vanished', self.block_id);
return;
}
self.events = [];
self.edited_paragraphs = [];
self.autosave_timer = window.setInterval(
MochiKit.Base.bind(self.autosave, self),
self.autosave_interval*1000);
self.initial_paragraph = MochiKit.Selector.findChildElements(
block, ['.editable > *'])[0];
self.editable = self.merge(block);
self.block = MochiKit.DOM.getFirstParentByTagAndClassName(
self.editable, null, 'block');
log('Editable block', self.block.id);
self.editable.removeAttribute('cms:cp-module');
self.editable.contentEditable = true;
self.editable.editable = self; // make instance available for tests
self.command('styleWithCSS', false, false);
MochiKit.DOM.addElementClass(self.block, 'editing');
// This catches the blur-signal in the capturing-phase!
// In case you use the toolbar, the editing-mode won't be stopped.
self.editable.parentNode.addEventListener("blur", function(e) {
var clicked_on_block =
MochiKit.DOM.getFirstParentByTagAndClassName(
e.explicitOriginalTarget, 'div', 'block');
var is_in_block = (clicked_on_block == self.block);
log("Blur while editing:", is_in_block, self.block_id);
if (is_in_block || self.locked) {
e.stopPropagation();
} else {
self.save();
}
}, true);
self.events.push(MochiKit.Signal.connect(
self.editable, 'onkeydown', self, self.handle_keydown));
self.events.push(MochiKit.Signal.connect(
self.editable, 'onkeyup', self, self.handle_keyup));
$('.editable').bind('paste', function() {
self.handle_paste();
});
self.events.push(MochiKit.Signal.connect(
zeit.edit.editor, 'before-reload', function() {
// XXX giant hack around strange browser behaviour.
//
// Reproduction recipe for the bug: While a block is
// contentEditable, drag it around to change sorting. This
// will result in a blinking cursor being left somewhere on
// the page. In spite of investigating this at length, we
// have no idea what causes this, so far.
//
// To get rid of this stray cursor, we focus-then-blur
// something else (we scientifcally chose the
// fulltext-search input box at random). Synthesizing a
// blur on self.editable or similar has no effect, and the
// "something else" we dash off to needs to be an <input
// type="text">.
$('#fulltext').focus();
$('#fulltext').blur();
self.save(/*no_reload=*/true);
}));
self.fix_html();
$('body').trigger('update-ads');
self.place_cursor(self.initial_paragraph, place_cursor_at_end);
self.editable.focus();
self.init_linkbar();
self.init_toolbar();
self.shortcuts();
self.relocate_toolbar(true);
self.events.push(MochiKit.Signal.connect(
window, 'before-content-drag', function() {
if (!self.locked) {
self.save();
}
}));
});
d.addErrback(function(err) {zeit.cms.log_error(err); return err;});
},
place_cursor: function(element, place_cursor_at_end) {
// Place cursor to the beginnning of element
log('Placing cursor to', element.nodeName);
var range = getSelection().getRangeAt(0);
var direction;
if (place_cursor_at_end) {
direction = 'lastChild';
} else {
direction = 'firstChild';
}
var text_node = element;
while (text_node[direction] !== null) {
text_node = text_node[direction];
}
var offset = 0;
if (place_cursor_at_end &&
text_node.nodeType == text_node.TEXT_NODE) {
offset = text_node.data.length;
}
range.setStart(text_node, offset);
range.setEnd(text_node, offset);
},
is_block_editable: function(block) {
return !isNull(
MochiKit.DOM.getFirstElementByTagAndClassName(
'div', 'editable', block));
},
merge: function(block) {
var self = this;
var blocks = MochiKit.DOM.getElementsByTagAndClassName(
null, 'block', block.parentNode);
var i = blocks.indexOf(block);
var paragraphs = [];
// XXX remove code duplication
while (i > 0) {
i -= 1;
if (self.is_block_editable(blocks[i])) {
paragraphs.push(blocks[i]);
} else {
break;
}
}
paragraphs.reverse();
paragraphs.push(block);
i = blocks.indexOf(block);
while (i < blocks.length-1) {
i += 1;
if (self.is_block_editable(blocks[i])) {
paragraphs.push(blocks[i]);
} else {
break;
}
}
self.edited_paragraphs = MochiKit.Base.map(
function(element) { return element.id; },
paragraphs);
paragraphs[0].block_ids = self.edited_paragraphs;
var editable = MochiKit.DOM.getFirstElementByTagAndClassName(
null, 'editable', paragraphs[0]);
forEach(paragraphs.slice(1), function(paragraph) {
forEach(MochiKit.Selector.findChildElements(
paragraph, ['.editable > *']), function(p) {
editable.appendChild(p);
});
jQuery(paragraph).next('.landing-zone').remove();
MochiKit.DOM.removeElement(paragraph);
});
// Clear out all non element nodes
forEach(editable.childNodes, function(child) {
if (child.nodeType != child.ELEMENT_NODE) {
editable.removeChild(child);
}
});
return editable;
},
init_linkbar: function() {
var self = this;
self.link_input = self.editable.parentNode.insertBefore(
DIV({'class': 'link_input hidden'},
INPUT({type: 'text', name: 'href', value: ''}),
SELECT({name: 'target'},
OPTION({value: '_blank'}, 'Neues Fenster'),
OPTION({value: ''}, 'Gleiches Fenster')),
BUTTON({name: 'insert_link_ok',
value: 'method'}, 'Setzen'),
BUTTON({name: 'insert_link_cancel',
value: 'method'}, 'Abbrechen')),
self.editable);
self.link_input.dropable = new MochiKit.DragAndDrop.Droppable(
self.link_input, {
accept: ['content-drag-pane', 'uniqueId'],
activeclass: 'droppable-active',
hoverclass: 'hover-content',
ondrop: function(element, last_active_element, event) {
// One could consider the replace a hack.
$('input[name=href]', self.link_input).val(
element.uniqueId.replace(
'http://xml.zeit.de/',
'http://www.zeit.de/'));
}
});
self.events.push(MochiKit.Signal.connect(
self.link_input, 'onkeydown', function(event) {
if (event.key().string == 'KEY_ENTER') {
self.insert_link_ok();
event.stop();
}
}));
},
init_toolbar: function() {
var self = this;
self.toolbar = self.editable.parentNode.insertBefore(
DIV({'class': 'rte-toolbar',
'style': 'display: block; opacity: 0'}),
self.editable);
self.toolbar.innerHTML = "\
<a title='fett [Cmd/Strg+b]' rel='command' href='bold'>B</a>\
<a title='kursiv [Cmd/Strg+i]' rel='command' href='italic'>I</a>\
<a title='Zwischenüberschrift [Cmd/Strg+h]' rel='command' href='formatBlock/h3'>H3</a>\
<a title='Link [Cmd/Strg+l]' rel='method' href='insert_link'>A</a>\
<a title='Link entfernen [Cmd/Strg+u]' rel='command' href='unlink'>A</a>\
<a title='Liste' rel='command' href='insertunorderedlist'>UL</a>\
<a title='Formatierungen entfernen [Cmd/Strg+r]' rel='command' href='removeFormat'>PL</a>\
";
self.events.push(MochiKit.Signal.connect(
self.block, 'onclick',
self, self.handle_click));
MochiKit.Visual.appear(self.toolbar);
self.update_toolbar();
},
update_toolbar: function() {
var self = this;
var element = self.get_selected_container();
log('got', element.nodeName);
if (element.nodeType == element.TEXT_NODE) {
element = element.parentNode;
}
forEach(MochiKit.DOM.getElementsByTagAndClassName(
'a', null, self.toolbar), function(action) {
MochiKit.DOM.removeElementClass(action, 'active');
});
while(!isNull(element) && element != self.editable) {
log('checking', element.nodeName);
forEach(MochiKit.DOM.getElementsByTagAndClassName(
'a', null, self.toolbar), function(action) {
if (action.innerHTML == element.nodeName) {
MochiKit.DOM.addElementClass(action, 'active');
if (element.nodeName == 'H3' && action.innerHTML == 'H3') {
MochiKit.DOM.updateNodeAttributes(action, {'href': 'formatBlock/p'});
action.innerHTML = 'P';
}
if (element.nodeName != 'H3' && MochiKit.DOM.getNodeAttribute(action, 'href') == 'formatBlock/p') {
MochiKit.DOM.updateNodeAttributes(action, {'href': 'formatBlock/h3'});
action.innerHTML = 'H3';
}
}
});
element = element.parentNode;
}
},
relocate_toolbar: function(fast) {
var self = this;
var y = MochiKit.Style.getStyle(self.toolbar, 'top');
var cursor_pos = self._get_cursor_position();
if (cursor_pos && cursor_pos.y>0){
y = cursor_pos.y;
}
var move = {
duration: 0.5,
mode: 'absolute',
// By mode=absolute MochiKit means 'left' and 'top' CSS values.
// Since they refer to the next parent with a specified 'position'
// value, which is not necessarily self.block, we need to look at
// the 'left' value instead of calling getElementPosition() in
// order to retrieve the current x position (which is to be the
// target x position, i.e. we don't want any horizontal motion).
x: MochiKit.Style.getStyle(self.toolbar, 'left'),
y: y
};
if (fast) {
MochiKit.Style.setElementPosition(self.toolbar, move);
} else {
MochiKit.Visual.Move(self.toolbar, move);
}
},
_get_cursor_position: function() {
var self = this;
var pos = {x:0,y:0};
var selection = window.getSelection();
if (! selection.rangeCount) {
return null;
}
var range = selection.getRangeAt(0);
var cloned_range = range.cloneRange();
cloned_range.collapse(true);
var cloned_collapsed_rect = cloned_range.getClientRects()[0];
if (cloned_collapsed_rect) {
var offset = $(".rte-toolbar").parent().offset();
pos.y = cloned_collapsed_rect.top - offset.top;
pos.x = cloned_collapsed_rect.left;
} else if (range.startContainer.tagName == "P" &&
range.getClientRects().length==0){
var html = '<span id="_find_cursor_position"> </span>';
document.execCommand('insertHTML', false, html);
var tmp_el = $('#_find_cursor_position');
var tmp_pos = tmp_el.position();
var par = tmp_el.parent();
pos.y = tmp_pos.top;
pos.x = tmp_pos.left;
tmp_el.remove();
if (par.children().length==0){
document.execCommand('insertHTML', false,'<br type="_moz" />');
}
} else {
return null;
}
return pos;
},
handle_click: function(event) {
var self = this;
var mode, argument;
self.update_toolbar();
self.relocate_toolbar();
if (event.target().nodeName == 'A') {
mode = event.target().rel;
argument = event.target().getAttribute('href');
} else if (event.target().nodeName == 'BUTTON') {
mode = event.target().value;
argument = event.target().name;
} else {
return;
}
event.stop();
if (mode == 'command') {
event.stop();
var action = argument.split('/');
self.command(action[0], action[1]);
} else if (mode == 'method') {
var method = argument;
self[method]();
}
},
handle_keydown: function(event) {
var self = this;
var range = getSelection().getRangeAt(0);
var container = range.commonAncestorContainer;
// lastnode/firstnodee?
var direction = null;
var cursor_at_end = false;
if (event.key().string == 'KEY_ARROW_DOWN' &&
((container.nodeType == container.TEXT_NODE && // Last
container.parentNode.nextSibling === null) || // node
(container.tagName == 'P' && // Empty
container.nextSibling === null)) && // node
MochiKit.DOM.scrapeText(container).length == range.endOffset) {
direction = 'nextSibling';
} else if (
event.key().string == 'KEY_ARROW_UP' &&
((container.nodeType == container.TEXT_NODE && // First
container.parentNode.previousSibling === null) || // node
(container.tagName == 'P' && // Empty
container.previousSibling === null)) && // node
range.startOffset === 0) {
direction = 'previousSibling';
cursor_at_end = true;
} else if (
event.key().string == 'KEY_ENTER') {
setTimeout(function() {
$('body').trigger('update-ads');
}, 0);
} else if (
(event.key().string == 'KEY_BACKSPACE') ||
event.key().string == 'KEY_DELETE') {
// Don't remove empty paragraphs.
if (container.tagName == 'P' &&
container.previousSibling === null &&
MochiKit.DOM.scrapeText(container).length === 0) {
event.preventDefault();
}
setTimeout(function() {
$('body').trigger('update-ads');
}, 0);
} else if (
container.nodeType == container.TEXT_NODE &&
container.parentNode.tagName == 'DIV') {
/*
* Currently contenteditable seems to be buggy in firefox 4.
* While a new paragraph is created every time the return key has
* been pressed inside a paragraph, there will be just a textnode as
* direct child of the contenteditable, when hitting the return key
* within any other tag (e.g. h3, li...). The following workaround
* will wrap a p around every textnode, which is the direct child of
* the contenteditable.
*
* Sometimes another paragraph is added accidentally, when pressing
* the up and down keys within an empty p tag, so we have to get rid
* of the previous and next empty paragraph respectively.
*/
self.command('formatBlock', 'p');
var next_sibling = container.parentNode.nextSibling;
var prev_sibling = container.parentNode.previousSibling;
if (next_sibling != null &&
next_sibling.nodeName == 'BR') {
$(next_sibling).remove(); // Get rid of superfluous <br/>.
} else if (
next_sibling != null &&
next_sibling.nodeName == 'P') {
$(next_sibling).remove(); // Get rid of empty <p/>.
} else if (
prev_sibling != null &&
prev_sibling.nodeName == 'P') {
$(prev_sibling).remove(); // Get rid of empty <p/>.
}
}
if (direction !== null) {
var block = self.block;
var next_block = null;
while (block[direction] !== null) {
block = block[direction];
if (block.nodeType != block.ELEMENT_NODE) {
continue;
}
if (MochiKit.DOM.hasElementClass(block, 'block') &&
self.is_block_editable(block)) {
next_block = block;
break;
}
}
if (next_block !== null) {
log('Next block', next_block.id);
// Note id as save may (or probably will) replace the element
var next_block_id = next_block.id;
self.save();
new zeit.content.article.Editable(
MochiKit.DOM.getFirstElementByTagAndClassName(
'div', 'editable', $('#' + next_block_id)[0]),
cursor_at_end);
event.stop();
}
}
},
handle_keyup: function(event) {
var self = this;
self.update_toolbar();
self.relocate_toolbar();
self.fix_html();
},
handle_paste: function() {
var self = this;
// Get rid of obsolete mark-up when pasting content from third party
// software. Ensure that content is processed AFTER it has been pasted.
setTimeout(function() {
self.fix_html();
$(self.editable).children().has('style').remove();
$('a', self.editable).attr('target', '_blank');
}, 0);
},
fix_html: function() {
var self = this;
self.editable.normalize();
forEach(
MochiKit.DOM.getElementsByTagAndClassName(
null, null, self.editable),
function(element) {
element.removeAttribute('class');
element.removeAttribute('style');
// Yeah, I luv it!
if (element.nodeName == 'EM') {
zeit.content.article.html.change_tag(element, 'I');
} else if (element.nodeName == 'STRONG') {
zeit.content.article.html.change_tag(element, 'B');
}
});
},
get_text_list: function() {
var self = this;
self.fix_html();
var tree = self.editable.cloneNode(/*deep=*/true);
zeit.content.article.html.to_xml(tree);
var result = MochiKit.Base.map(function(el) {
return {factory: el.nodeName.toLowerCase(),
text: el.innerHTML};
}, tree.childNodes);
return result;
},
autosave: function() {
var self = this;
if (zeit.cms.request_lock.locked) {
log('Skipping autosave due to running other request');
return;
}
log('Autosaving', self.block_id);
zeit.cms.with_lock(function() {
var url = $('#editable-body').attr('cms:url') +
'/@@autosave_text';
var data = {paragraphs: self.edited_paragraphs,
text: self.get_text_list()};
data = MochiKit.Base.serializeJSON(data);
var d = MochiKit.Async.doXHR(url, {
method: 'POST',
sendContent: data});
d.addCallback(function(result) {
result = MochiKit.Async.evalJSONRequest(result);
self.edited_paragraphs = result['data']['new_ids'];
self.block.block_ids = self.edited_paragraphs;
});
d.addErrback(function(err) {zeit.cms.log_error(err); return err;});
});
},
save: function(no_reload) {
var self = this;
log('Saving', self.block_id);
MochiKit.DOM.addElementClass(self.block, 'busy');
window.clearInterval(self.autosave_timer);
zeit.cms.with_lock(function() {
while (self.events.length) {
MochiKit.Signal.disconnect(self.events.pop());
}
self.link_input.dropable.destroy();
log('disconnected event handlers');
var ident = MochiKit.Signal.connect(
zeit.edit.editor, 'after-reload', function() {
MochiKit.Signal.disconnect(ident);
log('Release lock', self.block_id);
self.editor_active_lock.release();
});
// until now, the editor can only be contained in an editable-body.
var url = $('#editable-body').attr('cms:url') + '/@@save_text';
var data = {paragraphs: self.edited_paragraphs,
text: self.get_text_list()};
if (no_reload) {
data = MochiKit.Base.serializeJSON(data);
MochiKit.Async.doXHR(url, {
method: 'POST',
sendContent: data});
} else {
zeit.edit._locked_makeJSONRequest(url, data);
}
});
},
get_selected_container: function() {
var container;
var range = getSelection().getRangeAt(0);
if ((range.startContainer.nodeType ==
range.startContainer.ELEMENT_NODE) &&
(range.startContainer == range.endContainer) &&
(range.startOffset + 1 == range.endOffset)) {
// There is one single element inside the range, use that.
container = range.startContainer.childNodes[range.startOffset];
} else {
container = range.commonAncestorContainer;
}
return container;
},
select_container: function(element) {
var self = this;
try {
var range = getSelection().getRangeAt(0);
range.setStartBefore(element);
range.setEndAfter(element);
} catch(e) {
if (window.console) {
console.log(e);
}
}
},
insert_link: function() {
var self = this;
if (self.locked) {
return;
}
var container = self.get_selected_container();
if (container.nodeName == 'A') {
self.insert_link_node = container;
} else {
self.insert_link_node =
MochiKit.DOM.getFirstParentByTagAndClassName(
container, 'a', null);
}
var href = '';
var target = '';
if (self.insert_link_node) {
href = self.insert_link_node.getAttribute('href') || '';
target = self.insert_link_node.getAttribute('target') || '';
} else {
self.command('createLink', '#article-editor-create-link');
self.insert_link_node = $(
'a[href="#article-editor-create-link"]', self.editable)[0];
self.insert_link_node._just_created = true;
}
$(self.insert_link_node).addClass('link-edit');
if (!self.insert_link_node._just_created) {
$('*[name=href]', self.link_input).val(href);
$('*[name=target]', self.link_input).val(target);
}
var line_height = parseInt(
$(self.insert_link_node).css('line-height').replace('px', ''));
var position = $(self.insert_link_node).position();
$(self.link_input).css('top',
(parseInt(position.top) + line_height) + 'px');
$(self.link_input).removeClass('hidden');
$('*[name=href]', self.link_input).focus();
self.locked = true;
},
insert_link_ok: function() {
var self = this;
var href = $('*[name=href]', self.link_input).val();
var target = $('*[name=target]', self.link_input).val();
self.insert_link_node.href = href;
if (target) {
self.insert_link_node.target = target;
} else {
self.insert_link_node.removeAttribute('target');
}
self.select_container(self.insert_link_node);
self._insert_link_finish();
},
insert_link_cancel: function() {
var self = this;
self.select_container(self.insert_link_node);
if (self.insert_link_node._just_created) {
while(!isNull(self.insert_link_node.firstChild)) {
self.insert_link_node.parentNode.insertBefore(
self.insert_link_node.firstChild,
self.insert_link_node);
}
$(self.insert_link_node).remove();
}
self._insert_link_finish();
},
_insert_link_finish: function() {
var self = this;
$(self.link_input).addClass('hidden');
$(self.insert_link_node).removeClass('link-edit');
self.insert_link_node._just_created = false;
self.insert_link_node = null;
self.locked = false;
self.editable.focus();
},
command: function(command, option, refocus) {
var self = this;
if (self.locked) {
return;
}
log("Executing", command, option);
try {
document.execCommand(command, false, option);
} catch(e) {
if (window.console) {
console.log(e);
}
}
if (typeof refocus === 'undefined' || refocus === true) {
self.editable.focus();
}
self.update_toolbar();
},
shortcuts: function() {
var self = this;
$("#editable-body").keydown(function(e) {
console.log(e);
if (e.ctrlKey || e.metaKey) {
if (e.which == 66) {
e.preventDefault();
self.command('bold');
} else if (e.which == 73) {
e.preventDefault();
self.command('italic');
} else if (e.which == 72) {
e.preventDefault();
self.command('formatBlock', '<h3>');
} else if (e.which == 76) {
e.preventDefault();
self['insert_link']();
} else if (e.which == 85) {
e.preventDefault();
self.command('unlink');
} else if (e.which == 82) {
e.preventDefault();
self.command('removeFormat');
}
}
});
}
});
zeit.content.article.AppendParagraph = zeit.edit.LoadAndReload.extend({
construct: function(context_element) {
var self = this;
$('.create-paragraph').first().remove();
var ident = MochiKit.Signal.connect(
zeit.edit.editor, 'after-reload', function() {
MochiKit.Signal.disconnect(ident);
var new_p = $('#editable-body .block.type-p').last()[0];
new zeit.content.article.Editable(new_p.firstChild, true);
});
arguments.callee.$.construct.call(self, context_element);
}
});
}(jQuery));
| Re #12152: Cmd+All
| src/zeit/content/article/edit/browser/resources/editor.js | Re #12152: Cmd+All | <ide><path>rc/zeit/content/article/edit/browser/resources/editor.js
<ide> } else if (e.which == 82) {
<ide> e.preventDefault();
<ide> self.command('removeFormat');
<del> }
<del> }
<add> } else if (e.which == 65) {
<add> e.preventDefault();
<add> self.selectall();
<add> }
<add> }
<add> });
<add> },
<add>
<add> selectall: function() {
<add> $('#editable-body .block.type-p p, #editable-body .block.type-p li, #editable-body .block.type-p h3, #editable-body .block.type-intertitle h3, #editable-body .block.type-ul li' ).each(function(index, value) {
<add> var content = $(this).text();
<add> if(content !='') {
<add> var range = document.createRange();
<add> range.selectNodeContents(this);
<add> var sel = window.getSelection();
<add> sel.addRange(range);
<add> }
<ide> });
<ide> }
<add>
<ide> });
<ide>
<ide> |
|
Java | agpl-3.0 | 42f7c591ef5d2f9424989b629139924d7025b3a4 | 0 | AAccount/dt_call_aclient,AAccount/dt_call_aclient,AAccount/dt_call_aclient,AAccount/dt_call_aclient,AAccount/dt_call_aclient,AAccount/dt_call_aclient | package dt.call.aclient.Voip;
/**
* Created by Daniel on 12/22/19.
*
*/
import android.content.Context;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.SocketTimeoutException;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.LinkedBlockingQueue;
import dt.call.aclient.CallState;
import dt.call.aclient.Const;
import dt.call.aclient.Utils;
import dt.call.aclient.Vars;
import dt.call.aclient.background.CmdListener;
import dt.call.aclient.codec.Opus;
import dt.call.aclient.pool.DatagramPacketPool;
import dt.call.aclient.sodium.SodiumUtils;
public class Voice
{
private static final String tag = "Voip.Voice";
private static final int OORANGE_LIMIT = 100;
private static final int WAVBUFFERSIZE = Opus.getWavFrameSize();
private static final int HEADERS = 52;
private static final int SAMPLES = Opus.getSampleRate();
private static final int S16 = AudioFormat.ENCODING_PCM_16BIT;
private static final int STREAMCALL = AudioManager.STREAM_VOICE_CALL;
private int garbage=0, txData=0, rxData=0, rxSeq=0, txSeq=0, skipped=0, oorange=0;
private boolean micMute = false;
private Thread playbackThread = null, recordThread = null;
private Timer timer = new Timer();
private AudioManager audioManager;
//reconnect udp variables
private boolean reconnectionAttempted = false;
private long lastReceivedTimestamp = 0;
private final Object rxtsLock = new Object();
private int reconenctTries = 0;
private final Object stopLock = new Object();
private boolean stopRequested = false;
private static Voice instance = null;
public static Voice getInstance()
{
if(instance == null)
{
instance = new Voice();
}
return instance;
}
private Voice()
{
audioManager = (AudioManager) Vars.applicationContext.getSystemService(Context.AUDIO_SERVICE);
}
public void start()
{
TimerTask counterTask = new TimerTask()
{
@Override
public void run()
{
if(Vars.state == CallState.INCALL)
{
synchronized(rxtsLock)
{
final long A_SECOND = 1000L; //usual delay between receives is ~60.2milliseconds
final long now = System.currentTimeMillis();
final long btw = now - lastReceivedTimestamp;
if((lastReceivedTimestamp > 0) && (btw > A_SECOND) && (Vars.mediaUdp != null))
{
Utils.logcat(Const.LOGD, tag, "delay since last received more than 1s: " + btw);
Vars.mediaUdp.close();
}
}
}
}
};
timer.schedule(counterTask, 0, 1000);
//now that the call is ACTUALLY starting put android into communications mode
//communications mode will prevent the ringtone from playing
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(false);
//initialize the opus library before creating the threads so it will be ready when the threads start
Opus.init();
startMediaEncodeThread();
startMediaDecodeThread();
}
public void stop()
{
if(playbackThread != null)
{
playbackThread.interrupt();
}
playbackThread = null;
if(recordThread != null)
{
recordThread.interrupt();
}
recordThread = null;
audioManager.setMode(AudioManager.MODE_NORMAL);
//overwrite the voice sodium symmetric key memory contents
SodiumUtils.applyFiller(Vars.voiceSymmetricKey);
if(Vars.mediaUdp != null && !Vars.mediaUdp.isClosed())
{
Vars.mediaUdp.close();
Vars.mediaUdp = null;
}
garbage=0; txData=0; rxData=0; rxSeq=0; txSeq=0; skipped=0; oorange=0;
micMute = false;
stopRequested = false;
}
private void startMediaEncodeThread()
{
recordThread = new Thread(new Runnable()
{
private static final String tag = "EncodingThread";
private final int STEREO = AudioFormat.CHANNEL_IN_STEREO;
private final int MIC = MediaRecorder.AudioSource.DEFAULT;
private final LinkedBlockingQueue<DatagramPacket> sendQ = new LinkedBlockingQueue<>();
private DatagramPacketPool packetPool = new DatagramPacketPool(Vars.callServer, Vars.mediaPort);
private final Thread networkThread = new Thread(new Runnable()
{
private static final String tag = "EncodeNetwork";
@Override
public void run()
{
Utils.logcat(Const.LOGD, tag, "encoder network thread started");
while(Vars.state == CallState.INCALL)
{
DatagramPacket packet = null;
try
{
packet = sendQ.take();
Vars.mediaUdp.send(packet);
}
catch(IOException e) //this will happen at the end of a call, no need to reconnect.
{
Utils.dumpException(tag, e);
if(!reconnectUDP())
{
stopOnError();
return;
}
sendQ.clear(); //don't bother with the stored voice data
}
catch(InterruptedException e)
{
break;
}
finally
{
packetPool.returnDatagramPacket(packet);
}
}
Utils.logcat(Const.LOGD, tag, "encoder network thread stopped");
}
});
@Override
public void run()
{
Utils.logcat(Const.LOGD, tag, "MediaCodec encoder thread has started");
AudioRecord wavRecorder = new AudioRecord(MIC, SAMPLES, STEREO, S16, WAVBUFFERSIZE);
wavRecorder.startRecording();
//my dying i9300 on CM12.1 sometimes can't get the audio record on its first try
int recorderRetries = 5;
while(wavRecorder.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING && recorderRetries > 0)
{
wavRecorder.stop();
wavRecorder.release();
wavRecorder = new AudioRecord(MIC, SAMPLES, STEREO, S16, WAVBUFFERSIZE);
wavRecorder.startRecording();
Utils.logcat(Const.LOGW, tag, "audiorecord failed to initialized. retried");
recorderRetries--;
}
if(recorderRetries == 0)
{
Utils.logcat(Const.LOGE, tag, "couldn't get the microphone from the cell phone. hanging up");
stopOnError();
return;
}
networkThread.setName("Media_Encoder_Network");
networkThread.start();
final byte[] packetBuffer = new byte[Const.SIZE_MAX_UDP];
final short[] wavbuffer = new short[WAVBUFFERSIZE];
final byte[] encodedbuffer = new byte[WAVBUFFERSIZE];
while (Vars.state == CallState.INCALL)
{
Arrays.fill(wavbuffer, (short)0);
int totalRead = 0, dataRead;
while (totalRead < WAVBUFFERSIZE)
{
dataRead = wavRecorder.read(wavbuffer, totalRead, WAVBUFFERSIZE - totalRead);
totalRead = totalRead + dataRead;
}
if(micMute)
{
//if muting, erase the recorded audio
//need to record during mute because a cell phone can generate zeros faster than real time talking
// so you can't just skip the recording and send placeholder zeros in a loop
Arrays.fill(wavbuffer, (short)0);
}
Arrays.fill(encodedbuffer, (byte)0);
final int encodeLength = Opus.encode(wavbuffer, encodedbuffer);
if(encodeLength < 1)
{
Utils.logcat(Const.LOGE, tag, Opus.getError(encodeLength));
continue;
}
Arrays.fill(packetBuffer, (byte)0);
final byte[] txSeqDisassembled = Utils.disassembleInt(txSeq);
System.arraycopy(txSeqDisassembled, 0, packetBuffer, 0, Const.SIZEOF_INT);
txSeq++;
System.arraycopy(encodedbuffer, 0 , packetBuffer, Const.SIZEOF_INT, encodeLength);
final DatagramPacket packet = packetPool.getDatagramPacket();
final byte[] packetBufferEncrypted = packet.getData();
final int packetBufferEncryptedLength = SodiumUtils.symmetricEncrypt(packetBuffer, Const.SIZEOF_INT+encodeLength, Vars.voiceSymmetricKey, packetBufferEncrypted);
if(packetBufferEncryptedLength == 0)
{
Utils.logcat(Const.LOGE, tag, "voice symmetric encryption failed");
}
else
{
packet.setLength(packetBufferEncryptedLength);
try
{
sendQ.put(packet);
}
catch(InterruptedException e)
{
break;
}
txData = txData + packetBufferEncryptedLength + HEADERS;
}
}
SodiumUtils.applyFiller(packetBuffer);
SodiumUtils.applyFiller(encodedbuffer);
SodiumUtils.applyFiller(wavbuffer);
Opus.closeOpus();
wavRecorder.stop();
wavRecorder.release();
networkThread.interrupt();
Utils.logcat(Const.LOGD, tag, "MediaCodec encoder thread has stopped");
}
});
recordThread.setName("Media_Encoder");
recordThread.start();
}
private void startMediaDecodeThread()
{
playbackThread = new Thread(new Runnable()
{
private static final String tag = "DecodingThread";
private static final int STEREO = AudioFormat.CHANNEL_OUT_STEREO;
private final LinkedBlockingQueue<DatagramPacket> receiveQ = new LinkedBlockingQueue<>();
private DatagramPacketPool packetPool = new DatagramPacketPool();
private final Thread networkThread = new Thread(new Runnable()
{
private static final String tag = "DecodeNetwork";
@Override
public void run()
{
Utils.logcat(Const.LOGD, tag, "decoder network thread started");
while(Vars.state == CallState.INCALL)
{
DatagramPacket received;
try
{
received = packetPool.getDatagramPacket();
Vars.mediaUdp.receive(received);
long now = System.currentTimeMillis();
synchronized (rxtsLock)
{
lastReceivedTimestamp = now;
}
receiveQ.put(received);
}
catch(SocketTimeoutException e)
{//to prevent this thread from hanging forever, there is now a udp read timeout during calls
Utils.dumpException(tag, e);
}
catch(InterruptedException | NullPointerException e)
{
//can get a null pointer if the connection dies, media decoder dies, but this network thread is still alive
break;
}
catch(IOException e) //this will happen at the end of a call, no need to reconnect.
{
Utils.dumpException(tag, e);
if(!reconnectUDP())
{
stopOnError();
break;
}
receiveQ.clear(); //don't bother with the stored voice data
}
}
Utils.logcat(Const.LOGD, tag, "decoder network thread stopped");
}
});
@Override
public void run()
{
Utils.logcat(Const.LOGD, tag, "MediaCodec decoder thread has started");
final AudioTrack wavPlayer = new AudioTrack(STREAMCALL, SAMPLES, STEREO, S16, WAVBUFFERSIZE, AudioTrack.MODE_STREAM);
wavPlayer.play();
networkThread.setName("Media_Decoder_Network");
networkThread.start();
final byte[] encbuffer = new byte[WAVBUFFERSIZE];
final short[] wavbuffer = new short[WAVBUFFERSIZE];
final byte[] packetDecrypted = new byte[Const.SIZE_MAX_UDP];
while(Vars.state == CallState.INCALL)
{
try
{
//read encrypted opus
Arrays.fill(packetDecrypted, (byte)0);
final DatagramPacket received = receiveQ.take();
//decrypt
rxData = rxData + received.getLength() + HEADERS;
final int packetDecLength = SodiumUtils.symmetricDecrypt(received.getData(), received.getLength(), Vars.voiceSymmetricKey, packetDecrypted); //contents [seq#|opus chunk]
packetPool.returnDatagramPacket(received);
if(packetDecLength == 0)//contents [seq#|opus chunk]
{
Utils.logcat(Const.LOGD, tag, "Invalid decryption");
garbage++;
continue;
}
final byte[] sequenceBytes = new byte[Const.SIZEOF_INT];
System.arraycopy(packetDecrypted, 0, sequenceBytes, 0, Const.SIZEOF_INT);
final int sequence = Utils.reassembleInt(sequenceBytes);
if(sequence <= rxSeq)
{
skipped++;
continue;
}
//out of range receive sequences have happened before. still unexplained. log it as a stat
if(Math.abs(sequence - rxSeq) > OORANGE_LIMIT)
{
oorange++;
}
else
{
rxSeq = sequence;
}
//extract the opus chunk
Arrays.fill(encbuffer, (byte)0);
final int encodedLength = packetDecLength - Const.SIZEOF_INT;
System.arraycopy(packetDecrypted, Const.SIZEOF_INT, encbuffer, 0, encodedLength);
//decode opus chunk
Arrays.fill(wavbuffer, (short)0);
final int frames = Opus.decode(encbuffer, encodedLength, wavbuffer);
if(frames < 1)
{
Utils.logcat(Const.LOGE, tag, Opus.getError(frames));
continue;
}
wavPlayer.write(wavbuffer, 0, WAVBUFFERSIZE);
}
catch(Exception i)
{
Utils.dumpException(tag, i);
}
}
SodiumUtils.applyFiller(packetDecrypted);
SodiumUtils.applyFiller(encbuffer);
SodiumUtils.applyFiller(wavbuffer);
wavPlayer.pause();
wavPlayer.flush();
wavPlayer.stop();
wavPlayer.release();
Opus.closeOpus();
networkThread.interrupt();
Utils.logcat(Const.LOGD, tag, "MediaCodec decoder thread has stopped, state:" + Vars.state);
}
});
playbackThread.setName("Media_Decoder");
playbackThread.start();
}
private synchronized boolean reconnectUDP()
{
if(Vars.state == CallState.INCALL)
{
final int MAX_UDP_RECONNECTS = 10;
if(reconenctTries > MAX_UDP_RECONNECTS)
{
return false;
}
reconenctTries ++;
if(reconnectionAttempted)
{
reconnectionAttempted = false;
return true;
}
else
{
boolean reconnected = CmdListener.registerVoiceUDP();
reconnectionAttempted = true;
return reconnected;
}
}
return false;
}
public void toggleMic()
{
micMute = !micMute;
final Intent micChange = new Intent(Const.BROADCAST_CALL);
micChange.putExtra(Const.BROADCAST_CALL_MIC, Boolean.toString(micMute));
Vars.applicationContext.sendBroadcast(micChange);
}
private void stopOnError()
{
synchronized(stopLock)
{
if(!stopRequested)
{
stopRequested = true;
final Intent micChange = new Intent(Const.BROADCAST_CALL);
micChange.putExtra(Const.BROADCAST_CALL_RESP, Const.BROADCAST_CALL_END);
Vars.applicationContext.sendBroadcast(micChange);
}
}
stop();
}
public int getGarbage()
{
return garbage;
}
public int getTxData()
{
return txData;
}
public int getRxData()
{
return rxData;
}
public int getRxSeq()
{
return rxSeq;
}
public int getTxSeq()
{
return txSeq;
}
public int getSkipped()
{
return skipped;
}
public int getOorange()
{
return oorange;
}
}
| aclient/src/main/java/dt/call/aclient/Voip/Voice.java | package dt.call.aclient.Voip;
/**
* Created by Daniel on 12/22/19.
*
*/
import android.content.Context;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.SocketTimeoutException;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.LinkedBlockingQueue;
import dt.call.aclient.CallState;
import dt.call.aclient.Const;
import dt.call.aclient.R;
import dt.call.aclient.Utils;
import dt.call.aclient.Vars;
import dt.call.aclient.background.CmdListener;
import dt.call.aclient.codec.Opus;
import dt.call.aclient.pool.DatagramPacketPool;
import dt.call.aclient.sodium.SodiumUtils;
public class Voice
{
private static final String tag = "Voip.Voice";
private static final int OORANGE_LIMIT = 100;
private static final int WAVBUFFERSIZE = Opus.getWavFrameSize();
private static final int HEADERS = 52;
private static final int SAMPLES = Opus.getSampleRate();
private static final int S16 = AudioFormat.ENCODING_PCM_16BIT;
private static final int STREAMCALL = AudioManager.STREAM_VOICE_CALL;
private int garbage=0, txData=0, rxData=0, rxSeq=0, txSeq=0, skipped=0, oorange=0;
private boolean micMute = false;
private Thread playbackThread = null, recordThread = null;
private Timer timer = new Timer();
private AudioManager audioManager;
//reconnect udp variables
private boolean reconnectionAttempted = false;
private long lastReceivedTimestamp = System.currentTimeMillis();
private final Object rxtsLock = new Object();
private int reconenctTries = 0;
private final Object stopLock = new Object();
private boolean stopRequested = false;
private static Voice instance = null;
public static Voice getInstance()
{
if(instance == null)
{
instance = new Voice();
}
return instance;
}
private Voice()
{
audioManager = (AudioManager) Vars.applicationContext.getSystemService(Context.AUDIO_SERVICE);
}
public void start()
{
TimerTask counterTask = new TimerTask()
{
@Override
public void run()
{
if(Vars.state == CallState.INCALL)
{
synchronized(rxtsLock)
{
final long A_SECOND = 1000L; //usual delay between receives is ~60.2milliseconds
final long now = System.currentTimeMillis();
final long btw = now - lastReceivedTimestamp;
if(btw > A_SECOND && Vars.mediaUdp != null)
{
Utils.logcat(Const.LOGD, tag, "delay since last received more than 1s: " + btw);
Vars.mediaUdp.close();
}
}
}
}
};
timer.schedule(counterTask, 0, 1000);
//now that the call is ACTUALLY starting put android into communications mode
//communications mode will prevent the ringtone from playing
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(false);
//initialize the opus library before creating the threads so it will be ready when the threads start
Opus.init();
startMediaEncodeThread();
startMediaDecodeThread();
}
public void stop()
{
if(playbackThread != null)
{
playbackThread.interrupt();
}
playbackThread = null;
if(recordThread != null)
{
recordThread.interrupt();
}
recordThread = null;
audioManager.setMode(AudioManager.MODE_NORMAL);
//overwrite the voice sodium symmetric key memory contents
SodiumUtils.applyFiller(Vars.voiceSymmetricKey);
if(Vars.mediaUdp != null && !Vars.mediaUdp.isClosed())
{
Vars.mediaUdp.close();
Vars.mediaUdp = null;
}
garbage=0; txData=0; rxData=0; rxSeq=0; txSeq=0; skipped=0; oorange=0;
micMute = false;
stopRequested = false;
}
private void startMediaEncodeThread()
{
recordThread = new Thread(new Runnable()
{
private static final String tag = "EncodingThread";
private final int STEREO = AudioFormat.CHANNEL_IN_STEREO;
private final int MIC = MediaRecorder.AudioSource.DEFAULT;
private final LinkedBlockingQueue<DatagramPacket> sendQ = new LinkedBlockingQueue<>();
private DatagramPacketPool packetPool = new DatagramPacketPool(Vars.callServer, Vars.mediaPort);
private final Thread internalNetworkThread = new Thread(new Runnable()
{
private static final String tag = "EncodeNetwork";
@Override
public void run()
{
while(Vars.state == CallState.INCALL)
{
DatagramPacket packet = null;
try
{
packet = sendQ.take();
Vars.mediaUdp.send(packet);
}
catch(IOException e) //this will happen at the end of a call, no need to reconnect.
{
Utils.dumpException(tag, e);
if(!reconnectUDP())
{
stopOnError();
return;
}
sendQ.clear(); //don't bother with the stored voice data
}
catch(InterruptedException e)
{
break;
}
finally
{
packetPool.returnDatagramPacket(packet);
}
}
Utils.logcat(Const.LOGD, tag, "encoder network thread stopped");
}
});
@Override
public void run()
{
Utils.logcat(Const.LOGD, tag, "MediaCodec encoder thread has started");
AudioRecord wavRecorder = new AudioRecord(MIC, SAMPLES, STEREO, S16, WAVBUFFERSIZE);
wavRecorder.startRecording();
//my dying i9300 on CM12.1 sometimes can't get the audio record on its first try
int recorderRetries = 5;
while(wavRecorder.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING && recorderRetries > 0)
{
wavRecorder.stop();
wavRecorder.release();
wavRecorder = new AudioRecord(MIC, SAMPLES, STEREO, S16, WAVBUFFERSIZE);
wavRecorder.startRecording();
Utils.logcat(Const.LOGW, tag, "audiorecord failed to initialized. retried");
recorderRetries--;
}
if(recorderRetries == 0)
{
Utils.logcat(Const.LOGE, tag, "couldn't get the microphone from the cell phone. hanging up");
stopOnError();
return;
}
internalNetworkThread.setName("Media_Encoder_Network");
internalNetworkThread.start();
final byte[] packetBuffer = new byte[Const.SIZE_MAX_UDP];
final short[] wavbuffer = new short[WAVBUFFERSIZE];
final byte[] encodedbuffer = new byte[WAVBUFFERSIZE];
while (Vars.state == CallState.INCALL)
{
Arrays.fill(wavbuffer, (short)0);
int totalRead = 0, dataRead;
while (totalRead < WAVBUFFERSIZE)
{
dataRead = wavRecorder.read(wavbuffer, totalRead, WAVBUFFERSIZE - totalRead);
totalRead = totalRead + dataRead;
}
if(micMute)
{
//if muting, erase the recorded audio
//need to record during mute because a cell phone can generate zeros faster than real time talking
// so you can't just skip the recording and send placeholder zeros in a loop
Arrays.fill(wavbuffer, (short)0);
}
Arrays.fill(encodedbuffer, (byte)0);
final int encodeLength = Opus.encode(wavbuffer, encodedbuffer);
if(encodeLength < 1)
{
Utils.logcat(Const.LOGE, tag, Opus.getError(encodeLength));
continue;
}
Arrays.fill(packetBuffer, (byte)0);
final byte[] txSeqDisassembled = Utils.disassembleInt(txSeq);
System.arraycopy(txSeqDisassembled, 0, packetBuffer, 0, Const.SIZEOF_INT);
txSeq++;
System.arraycopy(encodedbuffer, 0 , packetBuffer, Const.SIZEOF_INT, encodeLength);
final DatagramPacket packet = packetPool.getDatagramPacket();
final byte[] packetBufferEncrypted = packet.getData();
final int packetBufferEncryptedLength = SodiumUtils.symmetricEncrypt(packetBuffer, Const.SIZEOF_INT+encodeLength, Vars.voiceSymmetricKey, packetBufferEncrypted);
if(packetBufferEncryptedLength == 0)
{
Utils.logcat(Const.LOGE, tag, "voice symmetric encryption failed");
}
else
{
packet.setLength(packetBufferEncryptedLength);
try
{
sendQ.put(packet);
}
catch(InterruptedException e)
{
Utils.dumpException(tag, e);
}
txData = txData + packetBufferEncryptedLength + HEADERS;
}
}
SodiumUtils.applyFiller(packetBuffer);
SodiumUtils.applyFiller(encodedbuffer);
SodiumUtils.applyFiller(wavbuffer);
Opus.closeOpus();
wavRecorder.stop();
wavRecorder.release();
internalNetworkThread.interrupt();
Utils.logcat(Const.LOGD, tag, "MediaCodec encoder thread has stopped");
}
});
recordThread.setName("Media_Encoder");
recordThread.start();
}
private void startMediaDecodeThread()
{
playbackThread = new Thread(new Runnable()
{
private static final String tag = "DecodingThread";
private static final int STEREO = AudioFormat.CHANNEL_OUT_STEREO;
private final LinkedBlockingQueue<DatagramPacket> receiveQ = new LinkedBlockingQueue<>();
private DatagramPacketPool packetPool = new DatagramPacketPool();
private final Thread networkThread = new Thread(new Runnable()
{
private static final String tag = "DecodeNetwork";
@Override
public void run()
{
while(Vars.state == CallState.INCALL)
{
DatagramPacket received;
try
{
received = packetPool.getDatagramPacket();
Vars.mediaUdp.receive(received);
long now = System.currentTimeMillis();
synchronized (rxtsLock)
{
lastReceivedTimestamp = now;
}
receiveQ.put(received);
}
catch(SocketTimeoutException e)
{//to prevent this thread from hanging forever, there is now a udp read timeout during calls
Utils.dumpException(tag, e);
}
catch(InterruptedException | NullPointerException e)
{
//can get a null pointer if the connection dies, media decoder dies, but this network thread is still alive
break;
}
catch(IOException e) //this will happen at the end of a call, no need to reconnect.
{
Utils.dumpException(tag, e);
if(!reconnectUDP())
{
stopOnError();
return;
}
receiveQ.clear(); //don't bother with the stored voice data
}
}
Utils.logcat(Const.LOGD, tag, "decoder network thread stopped");
}
});
@Override
public void run()
{
Utils.logcat(Const.LOGD, tag, "MediaCodec decoder thread has started");
final AudioTrack wavPlayer = new AudioTrack(STREAMCALL, SAMPLES, STEREO, S16, WAVBUFFERSIZE, AudioTrack.MODE_STREAM);
wavPlayer.play();
networkThread.setName("Media_Decoder_Network");
networkThread.start();
final byte[] encbuffer = new byte[WAVBUFFERSIZE];
final short[] wavbuffer = new short[WAVBUFFERSIZE];
final byte[] packetDecrypted = new byte[Const.SIZE_MAX_UDP];
while(Vars.state == CallState.INCALL)
{
try
{
//read encrypted opus
Arrays.fill(packetDecrypted, (byte)0);
final DatagramPacket received = receiveQ.take();
//decrypt
rxData = rxData + received.getLength() + HEADERS;
final int packetDecLength = SodiumUtils.symmetricDecrypt(received.getData(), received.getLength(), Vars.voiceSymmetricKey, packetDecrypted); //contents [seq#|opus chunk]
packetPool.returnDatagramPacket(received);
if(packetDecLength == 0)//contents [seq#|opus chunk]
{
Utils.logcat(Const.LOGD, tag, "Invalid decryption");
garbage++;
continue;
}
final byte[] sequenceBytes = new byte[Const.SIZEOF_INT];
System.arraycopy(packetDecrypted, 0, sequenceBytes, 0, Const.SIZEOF_INT);
final int sequence = Utils.reassembleInt(sequenceBytes);
if(sequence <= rxSeq)
{
skipped++;
continue;
}
//out of range receive sequences have happened before. still unexplained. log it as a stat
if(Math.abs(sequence - rxSeq) > OORANGE_LIMIT)
{
oorange++;
}
else
{
rxSeq = sequence;
}
//extract the opus chunk
Arrays.fill(encbuffer, (byte)0);
final int encodedLength = packetDecLength - Const.SIZEOF_INT;
System.arraycopy(packetDecrypted, Const.SIZEOF_INT, encbuffer, 0, encodedLength);
//decode opus chunk
Arrays.fill(wavbuffer, (short)0);
final int frames = Opus.decode(encbuffer, encodedLength, wavbuffer);
if(frames < 1)
{
Utils.logcat(Const.LOGE, tag, Opus.getError(frames));
continue;
}
wavPlayer.write(wavbuffer, 0, WAVBUFFERSIZE);
}
catch(Exception i)
{
Utils.dumpException(tag, i);
}
}
SodiumUtils.applyFiller(packetDecrypted);
SodiumUtils.applyFiller(encbuffer);
SodiumUtils.applyFiller(wavbuffer);
wavPlayer.pause();
wavPlayer.flush();
wavPlayer.stop();
wavPlayer.release();
Opus.closeOpus();
networkThread.interrupt();
Utils.logcat(Const.LOGD, tag, "MediaCodec decoder thread has stopped, state:" + Vars.state);
}
});
playbackThread.setName("Media_Decoder");
playbackThread.start();
}
private synchronized boolean reconnectUDP()
{
if(Vars.state == CallState.INCALL)
{
final int MAX_UDP_RECONNECTS = 10;
if(reconenctTries > MAX_UDP_RECONNECTS)
{
return false;
}
reconenctTries ++;
if(reconnectionAttempted)
{
reconnectionAttempted = false;
return true;
}
else
{
boolean reconnected = CmdListener.registerVoiceUDP();
reconnectionAttempted = true;
return reconnected;
}
}
return false;
}
public void toggleMic()
{
micMute = !micMute;
final Intent micChange = new Intent(Const.BROADCAST_CALL);
micChange.putExtra(Const.BROADCAST_CALL_MIC, Boolean.toString(micMute));
Vars.applicationContext.sendBroadcast(micChange);
}
private void stopOnError()
{
synchronized(stopLock)
{
if(!stopRequested)
{
stopRequested = true;
final Intent micChange = new Intent(Const.BROADCAST_CALL);
micChange.putExtra(Const.BROADCAST_CALL_RESP, Const.BROADCAST_CALL_END);
Vars.applicationContext.sendBroadcast(micChange);
}
}
stop();
}
public int getGarbage()
{
return garbage;
}
public int getTxData()
{
return txData;
}
public int getRxData()
{
return rxData;
}
public int getRxSeq()
{
return rxSeq;
}
public int getTxSeq()
{
return txSeq;
}
public int getSkipped()
{
return skipped;
}
public int getOorange()
{
return oorange;
}
}
| Minor changes for voip core voice after seeing the refactor in action.
| aclient/src/main/java/dt/call/aclient/Voip/Voice.java | Minor changes for voip core voice after seeing the refactor in action. | <ide><path>client/src/main/java/dt/call/aclient/Voip/Voice.java
<ide> import android.media.MediaRecorder;
<ide>
<ide> import java.io.IOException;
<del>import java.io.InputStream;
<ide> import java.net.DatagramPacket;
<ide> import java.net.SocketTimeoutException;
<ide> import java.util.Arrays;
<ide>
<ide> import dt.call.aclient.CallState;
<ide> import dt.call.aclient.Const;
<del>import dt.call.aclient.R;
<ide> import dt.call.aclient.Utils;
<ide> import dt.call.aclient.Vars;
<ide> import dt.call.aclient.background.CmdListener;
<ide>
<ide> //reconnect udp variables
<ide> private boolean reconnectionAttempted = false;
<del> private long lastReceivedTimestamp = System.currentTimeMillis();
<add> private long lastReceivedTimestamp = 0;
<ide> private final Object rxtsLock = new Object();
<ide> private int reconenctTries = 0;
<ide>
<ide> final long A_SECOND = 1000L; //usual delay between receives is ~60.2milliseconds
<ide> final long now = System.currentTimeMillis();
<ide> final long btw = now - lastReceivedTimestamp;
<del> if(btw > A_SECOND && Vars.mediaUdp != null)
<add> if((lastReceivedTimestamp > 0) && (btw > A_SECOND) && (Vars.mediaUdp != null))
<ide> {
<ide> Utils.logcat(Const.LOGD, tag, "delay since last received more than 1s: " + btw);
<ide> Vars.mediaUdp.close();
<ide> private final LinkedBlockingQueue<DatagramPacket> sendQ = new LinkedBlockingQueue<>();
<ide> private DatagramPacketPool packetPool = new DatagramPacketPool(Vars.callServer, Vars.mediaPort);
<ide>
<del> private final Thread internalNetworkThread = new Thread(new Runnable()
<add> private final Thread networkThread = new Thread(new Runnable()
<ide> {
<ide> private static final String tag = "EncodeNetwork";
<ide>
<ide> @Override
<ide> public void run()
<ide> {
<add> Utils.logcat(Const.LOGD, tag, "encoder network thread started");
<ide> while(Vars.state == CallState.INCALL)
<ide> {
<ide> DatagramPacket packet = null;
<ide> return;
<ide> }
<ide>
<del> internalNetworkThread.setName("Media_Encoder_Network");
<del> internalNetworkThread.start();
<add> networkThread.setName("Media_Encoder_Network");
<add> networkThread.start();
<ide>
<ide> final byte[] packetBuffer = new byte[Const.SIZE_MAX_UDP];
<ide> final short[] wavbuffer = new short[WAVBUFFERSIZE];
<ide> }
<ide> catch(InterruptedException e)
<ide> {
<del> Utils.dumpException(tag, e);
<add> break;
<ide> }
<ide> txData = txData + packetBufferEncryptedLength + HEADERS;
<ide> }
<ide> Opus.closeOpus();
<ide> wavRecorder.stop();
<ide> wavRecorder.release();
<del> internalNetworkThread.interrupt();
<add> networkThread.interrupt();
<ide> Utils.logcat(Const.LOGD, tag, "MediaCodec encoder thread has stopped");
<ide> }
<ide> });
<ide> @Override
<ide> public void run()
<ide> {
<add> Utils.logcat(Const.LOGD, tag, "decoder network thread started");
<ide> while(Vars.state == CallState.INCALL)
<ide> {
<ide> DatagramPacket received;
<ide> if(!reconnectUDP())
<ide> {
<ide> stopOnError();
<del> return;
<add> break;
<ide> }
<ide> receiveQ.clear(); //don't bother with the stored voice data
<ide> } |
|
Java | apache-2.0 | 8e3a2ea75b03f09e2299e1eefe6bb54c937325e5 | 0 | wildfly-security/wildfly-elytron,wildfly-security/wildfly-elytron | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.wildfly.security.auth.client;
import static org.wildfly.common.math.HashMath.multiHashUnordered;
import java.util.Objects;
import javax.security.auth.callback.CallbackHandler;
import org.wildfly.security.auth.client.AuthenticationConfiguration.HandlesCallbacks;
/**
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
class SetCallbackHandlerAuthenticationConfiguration extends AuthenticationConfiguration implements HandlesCallbacks {
private final CallbackHandler callbackHandler;
SetCallbackHandlerAuthenticationConfiguration(final AuthenticationConfiguration parent, final CallbackHandler callbackHandler) {
super(parent.without(HandlesCallbacks.class));
this.callbackHandler = callbackHandler;
}
AuthenticationConfiguration reparent(final AuthenticationConfiguration newParent) {
return new SetCallbackHandlerAuthenticationConfiguration(newParent, callbackHandler);
}
CallbackHandler getCallbackHandler() {
return callbackHandler;
}
@Override
boolean saslSupportedByConfiguration(String mechanismName) {
return true;
}
boolean halfEqual(final AuthenticationConfiguration other) {
return Objects.equals(callbackHandler, other.getCallbackHandler()) && parentHalfEqual(other);
}
int calcHashCode() {
return multiHashUnordered(parentHashCode(), 1487, Objects.hashCode(callbackHandler));
}
@Override
StringBuilder asString(StringBuilder sb) {
return parentAsString(sb).append("CallbackHandler,");
}
}
| src/main/java/org/wildfly/security/auth/client/SetCallbackHandlerAuthenticationConfiguration.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.wildfly.security.auth.client;
import static org.wildfly.common.math.HashMath.multiHashUnordered;
import java.io.IOException;
import java.util.Objects;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.wildfly.security.auth.client.AuthenticationConfiguration.HandlesCallbacks;
/**
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
class SetCallbackHandlerAuthenticationConfiguration extends AuthenticationConfiguration implements HandlesCallbacks {
private final CallbackHandler callbackHandler;
SetCallbackHandlerAuthenticationConfiguration(final AuthenticationConfiguration parent, final CallbackHandler callbackHandler) {
super(parent.without(HandlesCallbacks.class));
this.callbackHandler = callbackHandler;
}
void handleCallbacks(final AuthenticationConfiguration config, final Callback[] callbacks) throws IOException, UnsupportedCallbackException {
callbackHandler.handle(callbacks);
}
AuthenticationConfiguration reparent(final AuthenticationConfiguration newParent) {
return new SetCallbackHandlerAuthenticationConfiguration(newParent, callbackHandler);
}
CallbackHandler getCallbackHandler() {
return callbackHandler;
}
@Override
boolean saslSupportedByConfiguration(String mechanismName) {
return true;
}
boolean halfEqual(final AuthenticationConfiguration other) {
return Objects.equals(callbackHandler, other.getCallbackHandler()) && parentHalfEqual(other);
}
int calcHashCode() {
return multiHashUnordered(parentHashCode(), 1487, Objects.hashCode(callbackHandler));
}
@Override
StringBuilder asString(StringBuilder sb) {
return parentAsString(sb).append("CallbackHandler,");
}
}
| Unused method
| src/main/java/org/wildfly/security/auth/client/SetCallbackHandlerAuthenticationConfiguration.java | Unused method | <ide><path>rc/main/java/org/wildfly/security/auth/client/SetCallbackHandlerAuthenticationConfiguration.java
<ide>
<ide> import static org.wildfly.common.math.HashMath.multiHashUnordered;
<ide>
<del>import java.io.IOException;
<ide> import java.util.Objects;
<ide>
<del>import javax.security.auth.callback.Callback;
<ide> import javax.security.auth.callback.CallbackHandler;
<del>import javax.security.auth.callback.UnsupportedCallbackException;
<ide>
<ide> import org.wildfly.security.auth.client.AuthenticationConfiguration.HandlesCallbacks;
<ide>
<ide> SetCallbackHandlerAuthenticationConfiguration(final AuthenticationConfiguration parent, final CallbackHandler callbackHandler) {
<ide> super(parent.without(HandlesCallbacks.class));
<ide> this.callbackHandler = callbackHandler;
<del> }
<del>
<del> void handleCallbacks(final AuthenticationConfiguration config, final Callback[] callbacks) throws IOException, UnsupportedCallbackException {
<del> callbackHandler.handle(callbacks);
<ide> }
<ide>
<ide> AuthenticationConfiguration reparent(final AuthenticationConfiguration newParent) { |
|
JavaScript | mit | 8473caaf19e7995daa8b75141075a04f984cd647 | 0 | NCI-Agency/anet,NCI-Agency/anet,NCI-Agency/anet,NCI-Agency/anet,NCI-Agency/anet | import API, { Settings } from "api";
import AdvancedMultiSelect from "components/advancedSelectWidget/AdvancedMultiSelect";
import AppContext from "components/AppContext";
import LinkTo from "components/LinkTo";
import Messages from "components/Messages";
import RemoveButton from "components/RemoveButton";
import { Form, Formik } from "formik";
import { Person, Position } from "models";
import PropTypes from "prop-types";
import React, { Component } from "react";
import { Button, Col, Grid, Modal, Row, Table } from "react-bootstrap";
import POSITIONS_ICON from "resources/positions.png";
const PositionTable = ({associatedPositions, onDelete}) => (
<Table striped condensed hover responsive>
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Organization</th>
<th />
</tr>
</thead>
<tbody>
{Position.map(associatedPositions, relPos => {
const person = new Person(relPos.person)
return (
<tr key={relPos.uuid}>
<td><LinkTo person={person} isLink={false} /></td>
<td><LinkTo person={relPos} isLink={false} /></td>
<td><LinkTo organization={relPos.organization} isLink={false} /></td>
<td>
<RemoveButton
title="Unassign person"
handleOnClick={() => onDelete(relPos)}
/>
</td>
</tr>
)
})}
</tbody>
</Table>
)
)
class BaseEditAssociatedPositionsModal extends Component {
static propTypes = {
position: PropTypes.object.isRequired,
showModal: PropTypes.bool,
onCancel: PropTypes.func.isRequired,
onSuccess: PropTypes.func.isRequired,
currentUser: PropTypes.instanceOf(Person)
}
constructor(props) {
super(props)
this.state = {
error: null
}
}
render() {
const { position, currentUser } = this.props
const assignedRole =
position.type === Position.TYPE.PRINCIPAL
? Settings.fields.advisor.person.name
: Settings.fields.principal.person.name
const positionSearchQuery = {
status: Position.STATUS.ACTIVE,
matchPersonName: true
}
if (position.type === Position.TYPE.PRINCIPAL) {
positionSearchQuery.type = [
Position.TYPE.ADVISOR,
Position.TYPE.SUPER_USER,
Position.TYPE.ADMINISTRATOR
]
if (currentUser.isAdmin() === false) {
// Super Users can only assign a position in their organization!
positionSearchQuery.organizationUuid =
currentUser.position.organization.uuid
positionSearchQuery.includeChildrenOrgs = true
}
} else {
positionSearchQuery.type = [Position.TYPE.PRINCIPAL]
}
const positionsFilters = {
allAdvisorPositions: {
label: "All",
searchQuery: true,
queryVars: positionSearchQuery
}
}
return (
<Formik
enableReinitialize
onSubmit={this.onSubmit}
initialValues={position}
>
{({ setFieldValue, values, submitForm }) => {
return (
<Modal show={this.props.showModal} onHide={this.close}>
<Modal.Header closeButton>
<Modal.Title>Modify assigned {assignedRole}</Modal.Title>
</Modal.Header>
<Modal.Body>
<Messages error={this.state.error} />
<Form className="form-horizontal" method="post">
<Grid fluid>
<Row>
<Col md={12}>
<AdvancedMultiSelect
fieldName="associatedPositions"
fieldLabel={null}
placeholder={`Search for a ${assignedRole} position...`}
value={values.associatedPositions}
renderSelected={
<PositionTable
associatedPositions={values.associatedPositions}
/>
}
overlayColumns={["", "Person", "Position"]}
overlayRenderRow={this.renderPositionOverlayRow}
filterDefs={positionsFilters}
onChange={value =>
setFieldValue("associatedPositions", value)
}
objectType={Position}
fields="uuid, name, code, type, person { uuid, name, rank, role }, organization { uuid, shortName, longName, identificationCode }"
addon={POSITIONS_ICON}
vertical
/>
</Col>
</Row>
</Grid>
</Form>
</Modal.Body>
<Modal.Footer>
<Button className="pull-left" onClick={this.close}>
Cancel
</Button>
<Button onClick={submitForm} bsStyle={"primary"}>
Save
</Button>
</Modal.Footer>
</Modal>
)
}}
</Formik>
)
}
close = () => {
// Reset state before closing (cancel)
this.setState({
error: null
})
this.props.onCancel()
}
onSubmit = (values, form) => {
return this.save(values, form)
.then(response => this.props.onSuccess())
.catch(error => {
this.setState({ error }, () => {
form.setSubmitting(false)
})
})
}
save = (values, form) => {
const position = new Position(this.props.position)
position.associatedPositions = values.associatedPositions
delete position.previousPeople
delete position.person // prevent any changes to person.
const graphql = "updateAssociatedPosition(position: $position)"
const variables = { position: position }
const variableDef = "($position: PositionInput!)"
return API.mutation(graphql, variables, variableDef)
}
renderPositionOverlayRow = item => {
return (
<React.Fragment key={item.uuid}>
<td>
<LinkTo person={item.person} isLink={false} />
</td>
<td>
<LinkTo position={item} isLink={false} />
</td>
</React.Fragment>
)
}
}
const EditAssociatedPositionsModal = props => (
<AppContext.Consumer>
{context => (
<BaseEditAssociatedPositionsModal
currentUser={context.currentUser}
{...props}
/>
)}
</AppContext.Consumer>
)
export default EditAssociatedPositionsModal
| client/src/components/EditAssociatedPositionsModal.js | import API, { Settings } from "api"
import AppContext from "components/AppContext"
import Messages from "components/Messages"
import MultiSelector from "components/MultiSelector"
import { Form, Formik } from "formik"
import { Person, Position } from "models"
import PropTypes from "prop-types"
import React, { Component } from "react"
import { Button, Modal, Table } from "react-bootstrap"
import REMOVE_ICON from "resources/delete.png"
import POSITIONS_ICON from "resources/positions.png"
const PositionTable = props => (
<Table striped condensed hover responsive>
<thead>
<tr>
<th />
<th>Name</th>
<th>Position</th>
<th>Organization</th>
<th />
</tr>
</thead>
<tbody>
{Position.map(props.associatedPositions, relPos => {
const person = new Person(relPos.person)
return (
<tr key={relPos.uuid}>
<td>
{person && (
<img
src={person.iconUrl()}
alt={person.humanNameOfRole()}
height={20}
className="person-icon"
/>
)}
</td>
<td>{person && person.name}</td>
<td>{relPos.name}</td>
<td>{relPos.organization && relPos.organization.shortName}</td>
<td onClick={() => props.onDelete(relPos)}>
<span style={{ cursor: "pointer" }}>
<img src={REMOVE_ICON} height={14} alt="Unassign person" />
</span>
</td>
</tr>
)
})}
</tbody>
</Table>
)
class BaseEditAssociatedPositionsModal extends Component {
static propTypes = {
position: PropTypes.object.isRequired,
showModal: PropTypes.bool,
onCancel: PropTypes.func.isRequired,
onSuccess: PropTypes.func.isRequired,
currentUser: PropTypes.instanceOf(Person)
}
constructor(props) {
super(props)
this.state = {
error: null
}
}
render() {
const { position, currentUser } = this.props
const assignedRole =
position.type === Position.TYPE.PRINCIPAL
? Settings.fields.advisor.person.name
: Settings.fields.principal.person.name
const positionSearchQuery = {
status: Position.STATUS.ACTIVE,
matchPersonName: true
}
if (position.type === Position.TYPE.PRINCIPAL) {
positionSearchQuery.type = [
Position.TYPE.ADVISOR,
Position.TYPE.SUPER_USER,
Position.TYPE.ADMINISTRATOR
]
if (currentUser.isAdmin() === false) {
// Super Users can only assign a position in their organization!
positionSearchQuery.organizationUuid =
currentUser.position.organization.uuid
positionSearchQuery.includeChildrenOrgs = true
}
} else {
positionSearchQuery.type = [Position.TYPE.PRINCIPAL]
}
return (
<Formik
enableReinitialize
onSubmit={this.onSubmit}
initialValues={position}
>
{({ setFieldValue, values, submitForm }) => {
return (
<Modal show={this.props.showModal} onHide={this.close}>
<Modal.Header closeButton>
<Modal.Title>Modify assigned {assignedRole}</Modal.Title>
</Modal.Header>
<Modal.Body>
<Messages error={this.state.error} />
<Form className="form-horizontal" method="post">
<MultiSelector
items={values.associatedPositions}
objectType={Position}
queryParams={positionSearchQuery}
addFieldName="associatedPositions"
addFieldLabel={null}
addon={POSITIONS_ICON}
renderExtraCol={false}
placeholder={`Start typing to search for a ${assignedRole} position...`}
fields="uuid, name, code, type, person { uuid, name, rank, role }, organization { uuid, shortName, longName, identificationCode }"
template={pos => {
const components = []
pos.person && components.push(pos.person.name)
pos.name && components.push(pos.name)
pos.code && components.push(pos.code)
return <span>{components.join(" - ")}</span>
}}
renderSelected={
<PositionTable
associatedPositions={values.associatedPositions}
/>
}
onChange={value =>
setFieldValue("associatedPositions", value)
}
/>
</Form>
</Modal.Body>
<Modal.Footer>
<Button className="pull-left" onClick={this.close}>
Cancel
</Button>
<Button onClick={submitForm} bsStyle={"primary"}>
Save
</Button>
</Modal.Footer>
</Modal>
)
}}
</Formik>
)
}
close = () => {
// Reset state before closing (cancel)
this.setState({
error: null
})
this.props.onCancel()
}
onSubmit = (values, form) => {
return this.save(values, form)
.then(response => this.props.onSuccess())
.catch(error => {
this.setState({ error }, () => {
form.setSubmitting(false)
})
})
}
save = (values, form) => {
const position = new Position(this.props.position)
position.associatedPositions = values.associatedPositions
delete position.previousPeople
delete position.person // prevent any changes to person.
const graphql = "updateAssociatedPosition(position: $position)"
const variables = { position: position }
const variableDef = "($position: PositionInput!)"
return API.mutation(graphql, variables, variableDef)
}
}
const EditAssociatedPositionsModal = props => (
<AppContext.Consumer>
{context => (
<BaseEditAssociatedPositionsModal
currentUser={context.currentUser}
{...props}
/>
)}
</AppContext.Consumer>
)
export default EditAssociatedPositionsModal
| NCI-Agency/anet#1326: Use AdvancedMultiSelect for edit associated positions
| client/src/components/EditAssociatedPositionsModal.js | NCI-Agency/anet#1326: Use AdvancedMultiSelect for edit associated positions | <ide><path>lient/src/components/EditAssociatedPositionsModal.js
<del>import API, { Settings } from "api"
<del>import AppContext from "components/AppContext"
<del>import Messages from "components/Messages"
<del>import MultiSelector from "components/MultiSelector"
<del>import { Form, Formik } from "formik"
<del>import { Person, Position } from "models"
<del>import PropTypes from "prop-types"
<del>import React, { Component } from "react"
<del>import { Button, Modal, Table } from "react-bootstrap"
<del>import REMOVE_ICON from "resources/delete.png"
<del>import POSITIONS_ICON from "resources/positions.png"
<del>
<del>const PositionTable = props => (
<del> <Table striped condensed hover responsive>
<del> <thead>
<del> <tr>
<del> <th />
<del> <th>Name</th>
<del> <th>Position</th>
<del> <th>Organization</th>
<del> <th />
<del> </tr>
<del> </thead>
<del> <tbody>
<del> {Position.map(props.associatedPositions, relPos => {
<del> const person = new Person(relPos.person)
<del> return (
<del> <tr key={relPos.uuid}>
<del> <td>
<del> {person && (
<del> <img
<del> src={person.iconUrl()}
<del> alt={person.humanNameOfRole()}
<del> height={20}
<del> className="person-icon"
<add>import API, { Settings } from "api";
<add>import AdvancedMultiSelect from "components/advancedSelectWidget/AdvancedMultiSelect";
<add>import AppContext from "components/AppContext";
<add>import LinkTo from "components/LinkTo";
<add>import Messages from "components/Messages";
<add>import RemoveButton from "components/RemoveButton";
<add>import { Form, Formik } from "formik";
<add>import { Person, Position } from "models";
<add>import PropTypes from "prop-types";
<add>import React, { Component } from "react";
<add>import { Button, Col, Grid, Modal, Row, Table } from "react-bootstrap";
<add>import POSITIONS_ICON from "resources/positions.png";
<add>
<add>const PositionTable = ({associatedPositions, onDelete}) => (
<add> <Table striped condensed hover responsive>
<add> <thead>
<add> <tr>
<add> <th>Name</th>
<add> <th>Position</th>
<add> <th>Organization</th>
<add> <th />
<add> </tr>
<add> </thead>
<add> <tbody>
<add> {Position.map(associatedPositions, relPos => {
<add> const person = new Person(relPos.person)
<add> return (
<add> <tr key={relPos.uuid}>
<add> <td><LinkTo person={person} isLink={false} /></td>
<add> <td><LinkTo person={relPos} isLink={false} /></td>
<add> <td><LinkTo organization={relPos.organization} isLink={false} /></td>
<add> <td>
<add> <RemoveButton
<add> title="Unassign person"
<add> handleOnClick={() => onDelete(relPos)}
<ide> />
<del> )}
<del> </td>
<del>
<del> <td>{person && person.name}</td>
<del> <td>{relPos.name}</td>
<del> <td>{relPos.organization && relPos.organization.shortName}</td>
<del>
<del> <td onClick={() => props.onDelete(relPos)}>
<del> <span style={{ cursor: "pointer" }}>
<del> <img src={REMOVE_ICON} height={14} alt="Unassign person" />
<del> </span>
<del> </td>
<del> </tr>
<del> )
<del> })}
<del> </tbody>
<del> </Table>
<add> </td>
<add> </tr>
<add> )
<add> })}
<add> </tbody>
<add> </Table>
<add> )
<ide> )
<ide>
<ide> class BaseEditAssociatedPositionsModal extends Component {
<ide> }
<ide> } else {
<ide> positionSearchQuery.type = [Position.TYPE.PRINCIPAL]
<add> }
<add> const positionsFilters = {
<add> allAdvisorPositions: {
<add> label: "All",
<add> searchQuery: true,
<add> queryVars: positionSearchQuery
<add> }
<ide> }
<ide>
<ide> return (
<ide> <Modal.Body>
<ide> <Messages error={this.state.error} />
<ide> <Form className="form-horizontal" method="post">
<del> <MultiSelector
<del> items={values.associatedPositions}
<del> objectType={Position}
<del> queryParams={positionSearchQuery}
<del> addFieldName="associatedPositions"
<del> addFieldLabel={null}
<del> addon={POSITIONS_ICON}
<del> renderExtraCol={false}
<del> placeholder={`Start typing to search for a ${assignedRole} position...`}
<del> fields="uuid, name, code, type, person { uuid, name, rank, role }, organization { uuid, shortName, longName, identificationCode }"
<del> template={pos => {
<del> const components = []
<del> pos.person && components.push(pos.person.name)
<del> pos.name && components.push(pos.name)
<del> pos.code && components.push(pos.code)
<del> return <span>{components.join(" - ")}</span>
<del> }}
<del> renderSelected={
<del> <PositionTable
<del> associatedPositions={values.associatedPositions}
<del> />
<del> }
<del> onChange={value =>
<del> setFieldValue("associatedPositions", value)
<del> }
<del> />
<add> <Grid fluid>
<add> <Row>
<add> <Col md={12}>
<add> <AdvancedMultiSelect
<add> fieldName="associatedPositions"
<add> fieldLabel={null}
<add> placeholder={`Search for a ${assignedRole} position...`}
<add> value={values.associatedPositions}
<add> renderSelected={
<add> <PositionTable
<add> associatedPositions={values.associatedPositions}
<add> />
<add> }
<add> overlayColumns={["", "Person", "Position"]}
<add> overlayRenderRow={this.renderPositionOverlayRow}
<add> filterDefs={positionsFilters}
<add> onChange={value =>
<add> setFieldValue("associatedPositions", value)
<add> }
<add> objectType={Position}
<add> fields="uuid, name, code, type, person { uuid, name, rank, role }, organization { uuid, shortName, longName, identificationCode }"
<add> addon={POSITIONS_ICON}
<add> vertical
<add> />
<add> </Col>
<add> </Row>
<add> </Grid>
<ide> </Form>
<ide> </Modal.Body>
<ide> <Modal.Footer>
<ide> const variableDef = "($position: PositionInput!)"
<ide> return API.mutation(graphql, variables, variableDef)
<ide> }
<add>
<add> renderPositionOverlayRow = item => {
<add> return (
<add> <React.Fragment key={item.uuid}>
<add> <td>
<add> <LinkTo person={item.person} isLink={false} />
<add> </td>
<add> <td>
<add> <LinkTo position={item} isLink={false} />
<add> </td>
<add> </React.Fragment>
<add> )
<add> }
<ide> }
<ide>
<ide> const EditAssociatedPositionsModal = props => ( |
|
Java | apache-2.0 | 917dba8dff10ab282e18c29c9323a8ac57c6fed8 | 0 | CS-SI/Stavor,CS-SI/Stavor,CS-SI/Stavor | package cs.si.stavor.fragments;
import cs.si.stavor.R;
import cs.si.stavor.MainActivity;
import cs.si.stavor.StavorApplication;
import cs.si.stavor.app.Parameters;
import cs.si.stavor.database.MissionReaderContract;
import cs.si.stavor.database.ReaderDbHelper;
import cs.si.stavor.database.SerializationUtil;
import cs.si.stavor.database.MissionReaderContract.MissionEntry;
import cs.si.stavor.dialogs.CopyMissionDialogFragment;
import cs.si.stavor.dialogs.DeleteMissionDialogFragment;
import cs.si.stavor.mission.Mission;
import cs.si.stavor.mission.MissionAndId;
import cs.si.stavor.simulator.Simulator;
import cs.si.stavor.simulator.SimulatorStatus;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Fragment;
import android.content.Loader;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Paint;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import com.commonsware.cwac.loaderex.SQLiteCursorLoader;
/**
* Fragment to show all the simulator configurations
* @author Xavier Gibert
*
*/
public final class SimulatorFragment extends Fragment implements LoaderCallbacks<Cursor> {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
* @param simulation
* @param sim_config
*/
public static SimulatorFragment newInstance(int sectionNumber) {
SimulatorFragment fragment = new SimulatorFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public SimulatorFragment() {
}
public Simulator simulator;
Switch switch_remote;
ViewSwitcher sim_container;
SharedPreferences sharedPref;
Button button_connect;
AutoCompleteTextView host_view;
EditText port_view;
ListView missionsList;
CheckBox checkSSL;
@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled", "NewApi" })
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sim, container,
false);
((MainActivity)getActivity()).showTutorialSimulator();
sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
simulator = ((MainActivity)getActivity()).getSimulator();
//Load missions in list
missionsList = (ListView) rootView.findViewById(R.id.listView1);
missionsList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if(arg1!=null){
activeMissionId = Integer.parseInt(((TextView)arg1.findViewById(R.id.textViewMissionId)).getText().toString());
activeMissionName=((TextView)arg1.findViewById(R.id.textViewMission)).getText().toString();
markActiveMission();
}else{
activeMissionId=-1;
activeMissionName="";
}
}
});
missionsList.setOnScrollListener(new OnScrollListener(){
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
updateListSelection();
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
//if(scrollState == 0){//Stop scroll
updateListSelection();
//}
}
});
adapter = new SimpleCursorAdapter(
this.getActivity().getApplicationContext(),
R.layout.mission_list_item, null,
new String[] {"_id", "name", "description"},
new int[] {R.id.textViewMissionId, R.id.textViewMission, R.id.textViewMissionDescription}, 0 );
missionsList.setAdapter(adapter);
registerForContextMenu(missionsList);
getLoaderManager().initLoader(R.id.listView1, null, this);
//Switch local/remote
switch_remote = (Switch) rootView.findViewById(R.id.switch1);
sim_container = (ViewSwitcher) rootView.findViewById(R.id.sim_content);
loadCorrectSimulatorScreen(rootView);
switch_remote.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
sharedPref.edit().putBoolean(buttonView.getContext().getString(R.string.pref_key_sim_global_remote), isChecked).commit();
loadCorrectSimulatorScreen(buttonView);
}
});
host_view = (AutoCompleteTextView) rootView.findViewById(R.id.autoCompleteTextViewHost);
port_view = (EditText) rootView.findViewById(R.id.editTextPort);
checkSSL = (CheckBox) rootView.findViewById(R.id.checkBoxSSL);
String host = sharedPref.getString(getString(R.string.pref_key_sim_remote_host), Parameters.Simulator.Remote.default_host);
String port = sharedPref.getString(getString(R.string.pref_key_sim_remote_port), Parameters.Simulator.Remote.default_port);
Boolean ssl = sharedPref.getBoolean(getString(R.string.pref_key_sim_remote_ssl), Parameters.Simulator.Remote.default_ssl);
host_view.setText(host);
port_view.setText(port);
checkSSL.setChecked(ssl);
checkSSL.setEnabled(Parameters.App.pro_version);
if(!Parameters.App.pro_version){
checkSSL.setText(checkSSL.getText()+" "+getString(R.string.pro_only));
checkSSL.setChecked(false);
}
button_connect = (Button) rootView.findViewById(R.id.buttonConnect);
simulator.setButtonConnect(button_connect);
simulator.setSwitchView(switch_remote);
button_connect.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(simulator.getSimulatorStatus().equals(SimulatorStatus.Connected)){
//int tmp_sel = last_mission_selection;
simulator.disconnect();
//selectMissionInList(tmp_sel);
updateListSelection();
}else{
boolean remote = sharedPref.getBoolean(v.getContext().getString(R.string.pref_key_sim_global_remote), false);
if(remote){
sharedPref.edit().putString(v.getContext().getString(
R.string.pref_key_sim_remote_host),
host_view.getText().toString()
).commit();
sharedPref.edit().putString(v.getContext().getString(
R.string.pref_key_sim_remote_port),
port_view.getText().toString()
).commit();
sharedPref.edit().putBoolean(v.getContext().getString(
R.string.pref_key_sim_remote_ssl),
checkSSL.isChecked()
).commit();
simulator.connect();
}else{
//Set mission
MissionAndId mis = getMission(activeMissionId);
if(mis!=null){
simulator.setSelectedMission(mis.mission, mis.id);
simulator.connect();
}else{
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_cannot_deserialize_selected_mission), Toast.LENGTH_LONG).show();
}
}
}
}
});
//Delete
Button button_delete = (Button)rootView.findViewById(R.id.buttonMissionDelete);
button_delete.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
//if(simulator.getSimulatorStatus().equals(SimulatorStatus.Connected)){
//Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_stop_simulator_first), Toast.LENGTH_LONG).show();
//}else{
if(activeMissionId==-1){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_select_first_a_mission), Toast.LENGTH_LONG).show();
}else if (activeMissionId<=Parameters.Simulator.amount_mission_examples ){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_mission_not_removable), Toast.LENGTH_LONG).show();
}else{
showDeleteMissionDialog(activeMissionId, activeMissionName);
}
//}
}
});
//New
Button button_new = (Button)rootView.findViewById(R.id.buttonMissionNew);
button_new.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
//if(simulator.getSimulatorStatus().equals(SimulatorStatus.Connected)){
//Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_stop_simulator_first), Toast.LENGTH_LONG).show();
//}else{
((MainActivity)getActivity()).showMissionCreator();
//}
}
});
//Edit
Button button_edit = (Button)rootView.findViewById(R.id.buttonMissionEdit);
button_edit.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
//if(simulator.getSimulatorStatus().equals(SimulatorStatus.Connected)){
//Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_stop_simulator_first), Toast.LENGTH_LONG).show();
//}else{
if(activeMissionId==-1){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_select_first_a_mission), Toast.LENGTH_LONG).show();
}else if (activeMissionId<=Parameters.Simulator.amount_mission_examples){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_mission_not_editable), Toast.LENGTH_LONG).show();
}else{
MissionAndId mis = getMission(activeMissionId);
if(mis!=null){
((MainActivity)getActivity()).showMissionEditor(mis);
}else{
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_cannot_deserialize_selected_mission), Toast.LENGTH_LONG).show();
}
}
//}
}
});
return rootView;
}
/**
* Returns the selected Mission from the database
* @return
*/
private MissionAndId getMission(int id){
String[] projection = {
MissionEntry._ID,
MissionEntry.COLUMN_NAME_CLASS
};
Cursor c = ((StavorApplication)((MainActivity)getActivity()).getApplication()).db
.query(
MissionEntry.TABLE_NAME, // The table to query
projection, // The columns to return
MissionEntry._ID+" = ?", // The columns for the WHERE clause
new String[]{Integer.toString(id)}, // The values for the WHERE clause
"", // don't group the rows
"", // don't filter by row groups
null // The sort order
);
if (c != null && c.getCount() > 0) {
c.moveToFirst();
int idIndex = c.getColumnIndex(MissionEntry._ID);
int nameIndex = c.getColumnIndex(MissionEntry.COLUMN_NAME_CLASS);
//this.itemId = cursor.getLong(idIndex);
byte[] mission_serie = c.getBlob(nameIndex);
int mission_id = c.getInt(idIndex);
Mission mis = SerializationUtil.deserialize(mission_serie);
return new MissionAndId(mis, mission_id);
}else{
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_cannot_find_selected_mission_in_db), Toast.LENGTH_LONG).show();
return null;
}
}
/**
* Shows the delete mission confirmation dialog
* @param id Mission id
* @param name Mission name
*/
public void showDeleteMissionDialog(int id, String name) {
DialogFragment newFragment = DeleteMissionDialogFragment.newInstance(id, name);
newFragment.setCancelable(true);
newFragment.show(getFragmentManager(), "delete");
}
/**
* Shows the copy mission confirmation dialog
* @param id Mission id
* @param name Mission name
*/
public void showCopyMissionDialog(int id, String name, Mission mis) {
DialogFragment newFragment = CopyMissionDialogFragment.newInstance(id, name, mis);
newFragment.setCancelable(true);
newFragment.show(getFragmentManager(), "copy");
}
/**
* load local or remote simulator view
* @param view
*/
private void loadCorrectSimulatorScreen(View view) {
simulator.updateConnectButtonText();
boolean remote = sharedPref.getBoolean(view.getContext().getString(R.string.pref_key_sim_global_remote), false);
switch_remote.setChecked(remote);
if(remote){
// Remote
sim_container.setDisplayedChild(1);
}else{
// Local
sim_container.setDisplayedChild(0);
missionsList.post(new Runnable() {
@Override
public void run() {
if(isAdded()){
boolean remote = sharedPref.getBoolean(getString(R.string.pref_key_sim_global_remote), false);
if(!remote){
selectFirstMissionInList();
}
}
}
});
}
}
/**
* Change the text color of the missions in list that is selected
*/
private void markActiveMission() {
if(missionsList!=null){
for(int i = 0; i < missionsList.getChildCount(); i++){
LinearLayout lay = (LinearLayout)missionsList.getChildAt(i);
TextView text_id = (TextView)lay.findViewById(R.id.textViewMissionId);
TextView text_name = (TextView)lay.findViewById(R.id.textViewMission);
if(simulator.getSelectedMissionid()==Integer.parseInt(text_id.getText().toString())){
text_name.setTextColor(getResources().getColor(R.color.selected_mission));
text_name.setPaintFlags(text_name.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
}else{
text_name.setTextColor(getResources().getColor(R.color.white));
text_name.setPaintFlags(text_name.getPaintFlags() & (~Paint.UNDERLINE_TEXT_FLAG));
}
}
}
}
private void selectFirstMissionInList(){
try{
missionsList.setItemChecked(0, true);
missionsList.setSelection(0);
Cursor curs = (Cursor)missionsList.getItemAtPosition(0);
if(curs!=null){
activeMissionId = curs.getInt(curs.getColumnIndex(MissionReaderContract.MissionEntry._ID));
activeMissionName = curs.getString(curs.getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_NAME));
markActiveMission();
}
}catch(Exception e){
e.printStackTrace();
}
}
private void selectMissionByKey(int key){
if(key!=-1){
boolean found = false;
for(int j = 0; j<adapter.getCount(); j++){
adapter.getCursor().moveToPosition(j);
int mis_key = adapter.getCursor().getInt(
adapter.getCursor().getColumnIndex(
MissionReaderContract.MissionEntry._ID));
if(mis_key == key){
found=true;
missionsList.setItemChecked(j, true);
missionsList.setSelection(j);
Cursor curs = (Cursor)missionsList.getItemAtPosition(j);
activeMissionId = curs.getInt(curs.getColumnIndex(MissionReaderContract.MissionEntry._ID));
activeMissionName = curs.getString(curs.getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_NAME));
markActiveMission();
}
}
if(!found){
selectFirstMissionInList();
}
}else{
selectFirstMissionInList();
}
}
private void updateListSelection(){
markActiveMission();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt(
ARG_SECTION_NUMBER));
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
ReaderDbHelper db_help = ((StavorApplication)((MainActivity)getActivity()).getApplication()).db_help;
String sql="SELECT _ID, name, description FROM "+MissionEntry.TABLE_NAME+" ORDER BY name COLLATE NOCASE ASC;";
String[] params = null;
SQLiteCursorLoader loader = new SQLiteCursorLoader(
getActivity().getApplicationContext(),
db_help,
sql,
params);
return loader;
}
SimpleCursorAdapter adapter;
int activeMissionId = -1;
String activeMissionName = "";
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
((StavorApplication)((MainActivity)getActivity()).getApplication()).loader=(SQLiteCursorLoader)loader;
adapter.changeCursor(cursor);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
missionsList.post(new Runnable() {
@Override
public void run() {
boolean remote = sharedPref.getBoolean(getString(R.string.pref_key_sim_global_remote), false);
if(!remote){
selectMissionByKey(activeMissionId);
}
}
});
}
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
adapter.changeCursor(null);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId()==R.id.listView1) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
missionsList.setItemChecked(info.position, true);
missionsList.setSelection(info.position);
Cursor curs = (Cursor)missionsList.getItemAtPosition(info.position);
activeMissionId = curs.getInt(curs.getColumnIndex(MissionReaderContract.MissionEntry._ID));
activeMissionName = curs.getString(curs.getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_NAME));
markActiveMission();
if(adapter!=null && adapter.getCursor()!=null){
adapter.getCursor().moveToPosition(info.position);
String header = adapter.getCursor().getString(
adapter.getCursor().getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_NAME));
menu.setHeaderTitle(header);
}
String[] menuItems = getResources().getStringArray(R.array.missions_menu);
for (int i = 0; i<menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int menuItemIndex = item.getItemId();
//String[] menuItems = getResources().getStringArray(R.array.missions_menu);
//String menuItemName = menuItems[menuItemIndex];
int listItemKey = -1;
try{
if(adapter!=null && adapter.getCursor()!=null){
adapter.getCursor().moveToPosition(info.position);
listItemKey = adapter.getCursor().getInt(
adapter.getCursor().getColumnIndex(MissionReaderContract.MissionEntry._ID));
String listItemName = adapter.getCursor().getString(
adapter.getCursor().getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_NAME));
if(menuItemIndex==0){
if(listItemKey==-1){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_select_first_a_mission), Toast.LENGTH_LONG).show();
}else if (listItemKey==0 ||listItemKey==1 ||listItemKey==2 || listItemKey==3 ){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_mission_not_removable), Toast.LENGTH_LONG).show();
}else{
showDeleteMissionDialog(listItemKey, listItemName);
}
}else if(menuItemIndex==1){
showCopyMissionDialog(listItemKey, listItemName, getMission(listItemKey).mission);
}else if(menuItemIndex==2){
if(listItemKey==-1){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_select_first_a_mission), Toast.LENGTH_LONG).show();
}else if (listItemKey==0 ||listItemKey==1 ||listItemKey==2 ||listItemKey==3){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_mission_not_editable), Toast.LENGTH_LONG).show();
}else{
MissionAndId mis = getMission(listItemKey);
if(mis!=null){
((MainActivity)getActivity()).showMissionEditor(mis);
}else{
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_cannot_deserialize_selected_mission), Toast.LENGTH_LONG).show();
}
}
}
}
}catch(Exception e){
}
return true;
}
}
| src/cs/si/stavor/fragments/SimulatorFragment.java | package cs.si.stavor.fragments;
import cs.si.stavor.R;
import cs.si.stavor.MainActivity;
import cs.si.stavor.StavorApplication;
import cs.si.stavor.app.Parameters;
import cs.si.stavor.database.MissionReaderContract;
import cs.si.stavor.database.ReaderDbHelper;
import cs.si.stavor.database.SerializationUtil;
import cs.si.stavor.database.MissionReaderContract.MissionEntry;
import cs.si.stavor.dialogs.CopyMissionDialogFragment;
import cs.si.stavor.dialogs.DeleteMissionDialogFragment;
import cs.si.stavor.mission.Mission;
import cs.si.stavor.mission.MissionAndId;
import cs.si.stavor.simulator.Simulator;
import cs.si.stavor.simulator.SimulatorStatus;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Fragment;
import android.content.Loader;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Paint;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import com.commonsware.cwac.loaderex.SQLiteCursorLoader;
/**
* Fragment to show all the simulator configurations
* @author Xavier Gibert
*
*/
public final class SimulatorFragment extends Fragment implements LoaderCallbacks<Cursor> {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
* @param simulation
* @param sim_config
*/
public static SimulatorFragment newInstance(int sectionNumber) {
SimulatorFragment fragment = new SimulatorFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public SimulatorFragment() {
}
public Simulator simulator;
Switch switch_remote;
ViewSwitcher sim_container;
SharedPreferences sharedPref;
Button button_connect;
AutoCompleteTextView host_view;
EditText port_view;
ListView missionsList;
CheckBox checkSSL;
@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled", "NewApi" })
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sim, container,
false);
((MainActivity)getActivity()).showTutorialSimulator();
sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
simulator = ((MainActivity)getActivity()).getSimulator();
//Load missions in list
missionsList = (ListView) rootView.findViewById(R.id.listView1);
missionsList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if(arg1!=null){
activeMissionId = Integer.parseInt(((TextView)arg1.findViewById(R.id.textViewMissionId)).getText().toString());
activeMissionName=((TextView)arg1.findViewById(R.id.textViewMission)).getText().toString();
markActiveMission();
}else{
activeMissionId=-1;
activeMissionName="";
}
}
});
missionsList.setOnScrollListener(new OnScrollListener(){
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
updateListSelection();
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
//if(scrollState == 0){//Stop scroll
updateListSelection();
//}
}
});
adapter = new SimpleCursorAdapter(
this.getActivity().getApplicationContext(),
R.layout.mission_list_item, null,
new String[] {"_id", "name", "description"},
new int[] {R.id.textViewMissionId, R.id.textViewMission, R.id.textViewMissionDescription}, 0 );
missionsList.setAdapter(adapter);
registerForContextMenu(missionsList);
getLoaderManager().initLoader(R.id.listView1, null, this);
//Switch local/remote
switch_remote = (Switch) rootView.findViewById(R.id.switch1);
sim_container = (ViewSwitcher) rootView.findViewById(R.id.sim_content);
loadCorrectSimulatorScreen(rootView);
switch_remote.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
sharedPref.edit().putBoolean(buttonView.getContext().getString(R.string.pref_key_sim_global_remote), isChecked).commit();
loadCorrectSimulatorScreen(buttonView);
}
});
host_view = (AutoCompleteTextView) rootView.findViewById(R.id.autoCompleteTextViewHost);
port_view = (EditText) rootView.findViewById(R.id.editTextPort);
checkSSL = (CheckBox) rootView.findViewById(R.id.checkBoxSSL);
String host = sharedPref.getString(getString(R.string.pref_key_sim_remote_host), Parameters.Simulator.Remote.default_host);
String port = sharedPref.getString(getString(R.string.pref_key_sim_remote_port), Parameters.Simulator.Remote.default_port);
Boolean ssl = sharedPref.getBoolean(getString(R.string.pref_key_sim_remote_ssl), Parameters.Simulator.Remote.default_ssl);
host_view.setText(host);
port_view.setText(port);
checkSSL.setChecked(ssl);
checkSSL.setEnabled(Parameters.App.pro_version);
if(!Parameters.App.pro_version)
checkSSL.setText(checkSSL.getText()+" "+getString(R.string.pro_only));
button_connect = (Button) rootView.findViewById(R.id.buttonConnect);
simulator.setButtonConnect(button_connect);
simulator.setSwitchView(switch_remote);
button_connect.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(simulator.getSimulatorStatus().equals(SimulatorStatus.Connected)){
//int tmp_sel = last_mission_selection;
simulator.disconnect();
//selectMissionInList(tmp_sel);
updateListSelection();
}else{
boolean remote = sharedPref.getBoolean(v.getContext().getString(R.string.pref_key_sim_global_remote), false);
if(remote){
sharedPref.edit().putString(v.getContext().getString(
R.string.pref_key_sim_remote_host),
host_view.getText().toString()
).commit();
sharedPref.edit().putString(v.getContext().getString(
R.string.pref_key_sim_remote_port),
port_view.getText().toString()
).commit();
sharedPref.edit().putBoolean(v.getContext().getString(
R.string.pref_key_sim_remote_ssl),
checkSSL.isChecked()
).commit();
simulator.connect();
}else{
//Set mission
MissionAndId mis = getMission(activeMissionId);
if(mis!=null){
simulator.setSelectedMission(mis.mission, mis.id);
simulator.connect();
}else{
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_cannot_deserialize_selected_mission), Toast.LENGTH_LONG).show();
}
}
}
}
});
//Delete
Button button_delete = (Button)rootView.findViewById(R.id.buttonMissionDelete);
button_delete.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
//if(simulator.getSimulatorStatus().equals(SimulatorStatus.Connected)){
//Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_stop_simulator_first), Toast.LENGTH_LONG).show();
//}else{
if(activeMissionId==-1){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_select_first_a_mission), Toast.LENGTH_LONG).show();
}else if (activeMissionId<=Parameters.Simulator.amount_mission_examples ){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_mission_not_removable), Toast.LENGTH_LONG).show();
}else{
showDeleteMissionDialog(activeMissionId, activeMissionName);
}
//}
}
});
//New
Button button_new = (Button)rootView.findViewById(R.id.buttonMissionNew);
button_new.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
//if(simulator.getSimulatorStatus().equals(SimulatorStatus.Connected)){
//Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_stop_simulator_first), Toast.LENGTH_LONG).show();
//}else{
((MainActivity)getActivity()).showMissionCreator();
//}
}
});
//Edit
Button button_edit = (Button)rootView.findViewById(R.id.buttonMissionEdit);
button_edit.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
//if(simulator.getSimulatorStatus().equals(SimulatorStatus.Connected)){
//Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_stop_simulator_first), Toast.LENGTH_LONG).show();
//}else{
if(activeMissionId==-1){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_select_first_a_mission), Toast.LENGTH_LONG).show();
}else if (activeMissionId<=Parameters.Simulator.amount_mission_examples){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_mission_not_editable), Toast.LENGTH_LONG).show();
}else{
MissionAndId mis = getMission(activeMissionId);
if(mis!=null){
((MainActivity)getActivity()).showMissionEditor(mis);
}else{
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_cannot_deserialize_selected_mission), Toast.LENGTH_LONG).show();
}
}
//}
}
});
return rootView;
}
/**
* Returns the selected Mission from the database
* @return
*/
private MissionAndId getMission(int id){
String[] projection = {
MissionEntry._ID,
MissionEntry.COLUMN_NAME_CLASS
};
Cursor c = ((StavorApplication)((MainActivity)getActivity()).getApplication()).db
.query(
MissionEntry.TABLE_NAME, // The table to query
projection, // The columns to return
MissionEntry._ID+" = ?", // The columns for the WHERE clause
new String[]{Integer.toString(id)}, // The values for the WHERE clause
"", // don't group the rows
"", // don't filter by row groups
null // The sort order
);
if (c != null && c.getCount() > 0) {
c.moveToFirst();
int idIndex = c.getColumnIndex(MissionEntry._ID);
int nameIndex = c.getColumnIndex(MissionEntry.COLUMN_NAME_CLASS);
//this.itemId = cursor.getLong(idIndex);
byte[] mission_serie = c.getBlob(nameIndex);
int mission_id = c.getInt(idIndex);
Mission mis = SerializationUtil.deserialize(mission_serie);
return new MissionAndId(mis, mission_id);
}else{
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_cannot_find_selected_mission_in_db), Toast.LENGTH_LONG).show();
return null;
}
}
/**
* Shows the delete mission confirmation dialog
* @param id Mission id
* @param name Mission name
*/
public void showDeleteMissionDialog(int id, String name) {
DialogFragment newFragment = DeleteMissionDialogFragment.newInstance(id, name);
newFragment.setCancelable(true);
newFragment.show(getFragmentManager(), "delete");
}
/**
* Shows the copy mission confirmation dialog
* @param id Mission id
* @param name Mission name
*/
public void showCopyMissionDialog(int id, String name, Mission mis) {
DialogFragment newFragment = CopyMissionDialogFragment.newInstance(id, name, mis);
newFragment.setCancelable(true);
newFragment.show(getFragmentManager(), "copy");
}
/**
* load local or remote simulator view
* @param view
*/
private void loadCorrectSimulatorScreen(View view) {
simulator.updateConnectButtonText();
boolean remote = sharedPref.getBoolean(view.getContext().getString(R.string.pref_key_sim_global_remote), false);
switch_remote.setChecked(remote);
if(remote){
// Remote
sim_container.setDisplayedChild(1);
}else{
// Local
sim_container.setDisplayedChild(0);
missionsList.post(new Runnable() {
@Override
public void run() {
if(isAdded()){
boolean remote = sharedPref.getBoolean(getString(R.string.pref_key_sim_global_remote), false);
if(!remote){
selectFirstMissionInList();
}
}
}
});
}
}
/**
* Change the text color of the missions in list that is selected
*/
private void markActiveMission() {
if(missionsList!=null){
for(int i = 0; i < missionsList.getChildCount(); i++){
LinearLayout lay = (LinearLayout)missionsList.getChildAt(i);
TextView text_id = (TextView)lay.findViewById(R.id.textViewMissionId);
TextView text_name = (TextView)lay.findViewById(R.id.textViewMission);
if(simulator.getSelectedMissionid()==Integer.parseInt(text_id.getText().toString())){
text_name.setTextColor(getResources().getColor(R.color.selected_mission));
text_name.setPaintFlags(text_name.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
}else{
text_name.setTextColor(getResources().getColor(R.color.white));
text_name.setPaintFlags(text_name.getPaintFlags() & (~Paint.UNDERLINE_TEXT_FLAG));
}
}
}
}
private void selectFirstMissionInList(){
try{
missionsList.setItemChecked(0, true);
missionsList.setSelection(0);
Cursor curs = (Cursor)missionsList.getItemAtPosition(0);
if(curs!=null){
activeMissionId = curs.getInt(curs.getColumnIndex(MissionReaderContract.MissionEntry._ID));
activeMissionName = curs.getString(curs.getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_NAME));
markActiveMission();
}
}catch(Exception e){
e.printStackTrace();
}
}
private void selectMissionByKey(int key){
if(key!=-1){
boolean found = false;
for(int j = 0; j<adapter.getCount(); j++){
adapter.getCursor().moveToPosition(j);
int mis_key = adapter.getCursor().getInt(
adapter.getCursor().getColumnIndex(
MissionReaderContract.MissionEntry._ID));
if(mis_key == key){
found=true;
missionsList.setItemChecked(j, true);
missionsList.setSelection(j);
Cursor curs = (Cursor)missionsList.getItemAtPosition(j);
activeMissionId = curs.getInt(curs.getColumnIndex(MissionReaderContract.MissionEntry._ID));
activeMissionName = curs.getString(curs.getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_NAME));
markActiveMission();
}
}
if(!found){
selectFirstMissionInList();
}
}else{
selectFirstMissionInList();
}
}
private void updateListSelection(){
markActiveMission();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt(
ARG_SECTION_NUMBER));
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
ReaderDbHelper db_help = ((StavorApplication)((MainActivity)getActivity()).getApplication()).db_help;
String sql="SELECT _ID, name, description FROM "+MissionEntry.TABLE_NAME+" ORDER BY name COLLATE NOCASE ASC;";
String[] params = null;
SQLiteCursorLoader loader = new SQLiteCursorLoader(
getActivity().getApplicationContext(),
db_help,
sql,
params);
return loader;
}
SimpleCursorAdapter adapter;
int activeMissionId = -1;
String activeMissionName = "";
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
((StavorApplication)((MainActivity)getActivity()).getApplication()).loader=(SQLiteCursorLoader)loader;
adapter.changeCursor(cursor);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
missionsList.post(new Runnable() {
@Override
public void run() {
boolean remote = sharedPref.getBoolean(getString(R.string.pref_key_sim_global_remote), false);
if(!remote){
selectMissionByKey(activeMissionId);
}
}
});
}
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
adapter.changeCursor(null);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId()==R.id.listView1) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
missionsList.setItemChecked(info.position, true);
missionsList.setSelection(info.position);
Cursor curs = (Cursor)missionsList.getItemAtPosition(info.position);
activeMissionId = curs.getInt(curs.getColumnIndex(MissionReaderContract.MissionEntry._ID));
activeMissionName = curs.getString(curs.getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_NAME));
markActiveMission();
if(adapter!=null && adapter.getCursor()!=null){
adapter.getCursor().moveToPosition(info.position);
String header = adapter.getCursor().getString(
adapter.getCursor().getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_NAME));
menu.setHeaderTitle(header);
}
String[] menuItems = getResources().getStringArray(R.array.missions_menu);
for (int i = 0; i<menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int menuItemIndex = item.getItemId();
//String[] menuItems = getResources().getStringArray(R.array.missions_menu);
//String menuItemName = menuItems[menuItemIndex];
int listItemKey = -1;
try{
if(adapter!=null && adapter.getCursor()!=null){
adapter.getCursor().moveToPosition(info.position);
listItemKey = adapter.getCursor().getInt(
adapter.getCursor().getColumnIndex(MissionReaderContract.MissionEntry._ID));
String listItemName = adapter.getCursor().getString(
adapter.getCursor().getColumnIndex(MissionReaderContract.MissionEntry.COLUMN_NAME_NAME));
if(menuItemIndex==0){
if(listItemKey==-1){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_select_first_a_mission), Toast.LENGTH_LONG).show();
}else if (listItemKey==0 ||listItemKey==1 ||listItemKey==2 || listItemKey==3 ){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_mission_not_removable), Toast.LENGTH_LONG).show();
}else{
showDeleteMissionDialog(listItemKey, listItemName);
}
}else if(menuItemIndex==1){
showCopyMissionDialog(listItemKey, listItemName, getMission(listItemKey).mission);
}else if(menuItemIndex==2){
if(listItemKey==-1){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_select_first_a_mission), Toast.LENGTH_LONG).show();
}else if (listItemKey==0 ||listItemKey==1 ||listItemKey==2 ||listItemKey==3){
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_mission_not_editable), Toast.LENGTH_LONG).show();
}else{
MissionAndId mis = getMission(listItemKey);
if(mis!=null){
((MainActivity)getActivity()).showMissionEditor(mis);
}else{
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.sim_local_cannot_deserialize_selected_mission), Toast.LENGTH_LONG).show();
}
}
}
}
}catch(Exception e){
}
return true;
}
}
| block correctly non PRO versions | src/cs/si/stavor/fragments/SimulatorFragment.java | block correctly non PRO versions | <ide><path>rc/cs/si/stavor/fragments/SimulatorFragment.java
<ide> port_view.setText(port);
<ide> checkSSL.setChecked(ssl);
<ide> checkSSL.setEnabled(Parameters.App.pro_version);
<del> if(!Parameters.App.pro_version)
<add> if(!Parameters.App.pro_version){
<ide> checkSSL.setText(checkSSL.getText()+" "+getString(R.string.pro_only));
<add> checkSSL.setChecked(false);
<add> }
<ide>
<ide> button_connect = (Button) rootView.findViewById(R.id.buttonConnect);
<ide> simulator.setButtonConnect(button_connect); |
|
Java | apache-2.0 | 43e4f58d6b6bb31e2f5842875e6e8dae50ddf355 | 0 | alien4cloud/alien4cloud,OresteVisari/alien4cloud,san-tak/alien4cloud,broly-git/alien4cloud,alien4cloud/alien4cloud,OresteVisari/alien4cloud,san-tak/alien4cloud,OresteVisari/alien4cloud,san-tak/alien4cloud,alien4cloud/alien4cloud,broly-git/alien4cloud,san-tak/alien4cloud,broly-git/alien4cloud,alien4cloud/alien4cloud,broly-git/alien4cloud,OresteVisari/alien4cloud | package alien4cloud.topology.validation;
import alien4cloud.component.CSARRepositorySearchService;
import alien4cloud.model.components.AbstractPropertyValue;
import alien4cloud.model.components.ComplexPropertyValue;
import alien4cloud.model.components.FunctionPropertyValue;
import alien4cloud.model.components.IndexedCapabilityType;
import alien4cloud.model.components.IndexedNodeType;
import alien4cloud.model.components.IndexedRelationshipType;
import alien4cloud.model.components.ListPropertyValue;
import alien4cloud.model.components.PropertyDefinition;
import alien4cloud.model.components.ScalarPropertyValue;
import alien4cloud.model.topology.Capability;
import alien4cloud.model.topology.NodeTemplate;
import alien4cloud.model.topology.RelationshipTemplate;
import alien4cloud.model.topology.Topology;
import alien4cloud.paas.exception.NotSupportedException;
import alien4cloud.paas.function.FunctionEvaluator;
import alien4cloud.topology.task.PropertiesTask;
import alien4cloud.topology.task.ScalableTask;
import alien4cloud.topology.task.TaskCode;
import alien4cloud.topology.task.TaskLevel;
import alien4cloud.tosca.normative.NormativeComputeConstants;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.common.collect.Lists;
import org.springframework.stereotype.Component;
import static alien4cloud.utils.AlienUtils.safe;
/**
* Performs validation of the properties
*/
@Component
@Slf4j
public class TopologyPropertiesValidationService {
@Resource
private CSARRepositorySearchService csarRepoSearchService;
/**
* Validate that the properties values in the topology are matching the property definitions (required & constraints).
* Skips properties defined as get_input
*
* @param topology The actual topology to validate.
* @return A list tasks to be done to make this topology valid.
*/
public List<PropertiesTask> validateStaticProperties(Topology topology) {
return validateProperties(topology, true);
}
/**
* Validate that the All properties (including dynamic properties (get_input )) values in the topology are matching the property definitions (required &
* constraints).
*
* @param topology The actual topology to validate.
* @return A list tasks to be done to make this topology valid.
*/
public List<PropertiesTask> validateAllProperties(Topology topology) {
return validateProperties(topology, false);
}
/**
* Validate properties.
*
* @param topology
* @param skipInputProperties whether to skip input properties validation or not. This is in case inputs are not yet processed
* @return
*/
private List<PropertiesTask> validateProperties(Topology topology, boolean skipInputProperties) {
List<PropertiesTask> toReturnTaskList = Lists.newArrayList();
Map<String, NodeTemplate> nodeTemplates = topology.getNodeTemplates();
// create task by nodetemplate
for (Map.Entry<String, NodeTemplate> nodeTempEntry : nodeTemplates.entrySet()) {
NodeTemplate nodeTemplate = nodeTempEntry.getValue();
IndexedNodeType relatedIndexedNodeType = csarRepoSearchService.getRequiredElementInDependencies(IndexedNodeType.class, nodeTemplate.getType(),
topology.getDependencies());
// do pass if abstract node
if (relatedIndexedNodeType.isAbstract()) {
continue;
}
// Define a task regarding properties
PropertiesTask task = new PropertiesTask();
task.setNodeTemplateName(nodeTempEntry.getKey());
task.setComponent(relatedIndexedNodeType);
task.setCode(TaskCode.PROPERTIES);
task.setProperties(Maps.<TaskLevel, List<String>> newHashMap());
// Check the properties of node template
if (MapUtils.isNotEmpty(nodeTemplate.getProperties())) {
addRequiredPropertyIdToTaskProperties(null, nodeTemplate.getProperties(), relatedIndexedNodeType.getProperties(), task, skipInputProperties);
}
// Check relationships PD
for (Map.Entry<String, RelationshipTemplate> relationshipEntry : safe(nodeTemplate.getRelationships()).entrySet()) {
RelationshipTemplate relationship = relationshipEntry.getValue();
if (relationship.getProperties() == null || relationship.getProperties().isEmpty()) {
continue;
}
addRequiredPropertyIdToTaskProperties("relationships[" + relationshipEntry.getKey() + "]", relationship.getProperties(),
getRelationshipPropertyDefinition(topology, nodeTemplate), task, skipInputProperties);
}
for (Map.Entry<String, Capability> capabilityEntry : safe(nodeTemplate.getCapabilities()).entrySet()) {
Capability capability = capabilityEntry.getValue();
if (capability.getProperties() == null || capability.getProperties().isEmpty()) {
continue;
}
addRequiredPropertyIdToTaskProperties("capabilities[" + capabilityEntry.getKey() + "]", capability.getProperties(),
getCapabilitiesPropertyDefinition(topology, nodeTemplate), task, skipInputProperties);
if (capability.getType().equals(NormativeComputeConstants.SCALABLE_CAPABILITY_TYPE)) {
Map<String, AbstractPropertyValue> scalableProperties = capability.getProperties();
verifyScalableProperties(scalableProperties, toReturnTaskList, nodeTempEntry.getKey(), skipInputProperties);
}
}
if (MapUtils.isNotEmpty(task.getProperties())) {
toReturnTaskList.add(task);
}
}
return toReturnTaskList.isEmpty() ? null : toReturnTaskList;
}
private Map<String, PropertyDefinition> getCapabilitiesPropertyDefinition(Topology topology, NodeTemplate nodeTemplate) {
Map<String, PropertyDefinition> relatedProperties = Maps.newTreeMap();
for (Map.Entry<String, Capability> capabilityEntry : nodeTemplate.getCapabilities().entrySet()) {
IndexedCapabilityType indexedCapabilityType = csarRepoSearchService.getRequiredElementInDependencies(IndexedCapabilityType.class,
capabilityEntry.getValue().getType(), topology.getDependencies());
if (indexedCapabilityType.getProperties() != null && !indexedCapabilityType.getProperties().isEmpty()) {
relatedProperties.putAll(indexedCapabilityType.getProperties());
}
}
return relatedProperties;
}
private Map<String, PropertyDefinition> getRelationshipPropertyDefinition(Topology topology, NodeTemplate nodeTemplate) {
Map<String, PropertyDefinition> relatedProperties = Maps.newTreeMap();
for (Map.Entry<String, RelationshipTemplate> relationshipTemplateEntry : nodeTemplate.getRelationships().entrySet()) {
IndexedRelationshipType indexedRelationshipType = csarRepoSearchService.getRequiredElementInDependencies(IndexedRelationshipType.class,
relationshipTemplateEntry.getValue().getType(), topology.getDependencies());
if (indexedRelationshipType.getProperties() != null && !indexedRelationshipType.getProperties().isEmpty()) {
relatedProperties.putAll(indexedRelationshipType.getProperties());
}
}
return relatedProperties;
}
private void verifyScalableProperties(Map<String, AbstractPropertyValue> scalableProperties, List<PropertiesTask> toReturnTaskList, String nodeTemplateId,
boolean skipInputProperties) {
Set<String> missingProperties = Sets.newHashSet();
Set<String> errorProperties = Sets.newHashSet();
if (skipInputProperties) {
for (Entry<String, AbstractPropertyValue> entry : scalableProperties.entrySet()) {
if (entry.getValue() instanceof FunctionPropertyValue) {
return;
}
}
}
if (MapUtils.isEmpty(scalableProperties)) {
missingProperties.addAll(Lists.newArrayList(NormativeComputeConstants.SCALABLE_MIN_INSTANCES, NormativeComputeConstants.SCALABLE_MAX_INSTANCES,
NormativeComputeConstants.SCALABLE_DEFAULT_INSTANCES));
} else {
int min = verifyScalableProperty(scalableProperties, NormativeComputeConstants.SCALABLE_MIN_INSTANCES, missingProperties, errorProperties);
int max = verifyScalableProperty(scalableProperties, NormativeComputeConstants.SCALABLE_MAX_INSTANCES, missingProperties, errorProperties);
int init = verifyScalableProperty(scalableProperties, NormativeComputeConstants.SCALABLE_DEFAULT_INSTANCES, missingProperties, errorProperties);
if (min > 0 && max > 0 && init > 0) {
if (min > init || min > max) {
errorProperties.add(NormativeComputeConstants.SCALABLE_MIN_INSTANCES);
}
if (init > max || init < min) {
errorProperties.add(NormativeComputeConstants.SCALABLE_DEFAULT_INSTANCES);
}
if (max < min || max < init) {
errorProperties.add(NormativeComputeConstants.SCALABLE_MAX_INSTANCES);
}
}
}
if (!missingProperties.isEmpty()) {
ScalableTask scalableTask = new ScalableTask(nodeTemplateId);
scalableTask.getProperties().put(TaskLevel.REQUIRED, Lists.newArrayList(missingProperties));
toReturnTaskList.add(scalableTask);
}
if (!errorProperties.isEmpty()) {
ScalableTask scalableTask = new ScalableTask(nodeTemplateId);
scalableTask.getProperties().put(TaskLevel.ERROR, Lists.newArrayList(errorProperties));
toReturnTaskList.add(scalableTask);
}
}
private int verifyScalableProperty(Map<String, AbstractPropertyValue> scalableProperties, String propertyToVerify, Set<String> missingProperties,
Set<String> errorProperties) {
String rawValue = null;
try {
rawValue = FunctionEvaluator.getScalarValue(scalableProperties.get(propertyToVerify));
} catch (NotSupportedException e1) {
// the value is a function (get_input normally), this means the input is not yet filled.
}
if (StringUtils.isEmpty(rawValue)) {
missingProperties.add(propertyToVerify);
return -1;
}
int value;
try {
value = Integer.parseInt(rawValue);
} catch (Exception e) {
errorProperties.add(propertyToVerify);
return -1;
}
if (value <= 0) {
errorProperties.add(propertyToVerify);
return -1;
}
return value;
}
private void addRequiredPropertyError(PropertiesTask task, String propertyName) {
if (!task.getProperties().containsKey(TaskLevel.REQUIRED)) {
task.getProperties().put(TaskLevel.REQUIRED, Lists.<String> newArrayList());
}
task.getProperties().get(TaskLevel.REQUIRED).add(propertyName);
}
private void addRequiredPropertyIdToTaskProperties(String prefix, Map<String, AbstractPropertyValue> properties,
Map<String, PropertyDefinition> relatedProperties, PropertiesTask task, boolean skipInputProperties) {
for (Map.Entry<String, AbstractPropertyValue> propertyEntry : properties.entrySet()) {
PropertyDefinition propertyDef = relatedProperties.get(propertyEntry.getKey());
String propertyErrorKey = prefix == null ? propertyEntry.getKey() : prefix + "." + propertyEntry.getKey();
AbstractPropertyValue value = propertyEntry.getValue();
if (propertyDef != null && propertyDef.isRequired()) {
if (value == null) {
addRequiredPropertyError(task, propertyErrorKey);
} else if (value instanceof ScalarPropertyValue) {
String propertyValue = ((ScalarPropertyValue) value).getValue();
if (StringUtils.isBlank(propertyValue)) {
addRequiredPropertyError(task, propertyErrorKey);
}
} else if (value instanceof ComplexPropertyValue) {
Map<String, Object> mapValue = ((ComplexPropertyValue) value).getValue();
if (MapUtils.isEmpty(mapValue)) {
addRequiredPropertyError(task, propertyErrorKey);
}
} else if (value instanceof ListPropertyValue) {
List<Object> listValue = ((ListPropertyValue) value).getValue();
if (listValue.isEmpty()) {
addRequiredPropertyError(task, propertyErrorKey);
}
} else if (skipInputProperties) {
// this is a get_input funtion.
// get_input Will be validated later on
continue;
} else {
addRequiredPropertyError(task, propertyErrorKey);
}
}
}
}
} | alien4cloud-core/src/main/java/alien4cloud/topology/validation/TopologyPropertiesValidationService.java | package alien4cloud.topology.validation;
import alien4cloud.component.CSARRepositorySearchService;
import alien4cloud.model.components.AbstractPropertyValue;
import alien4cloud.model.components.ComplexPropertyValue;
import alien4cloud.model.components.FunctionPropertyValue;
import alien4cloud.model.components.IndexedCapabilityType;
import alien4cloud.model.components.IndexedNodeType;
import alien4cloud.model.components.IndexedRelationshipType;
import alien4cloud.model.components.ListPropertyValue;
import alien4cloud.model.components.PropertyDefinition;
import alien4cloud.model.components.ScalarPropertyValue;
import alien4cloud.model.topology.Capability;
import alien4cloud.model.topology.NodeTemplate;
import alien4cloud.model.topology.RelationshipTemplate;
import alien4cloud.model.topology.Topology;
import alien4cloud.paas.exception.NotSupportedException;
import alien4cloud.paas.function.FunctionEvaluator;
import alien4cloud.topology.task.PropertiesTask;
import alien4cloud.topology.task.ScalableTask;
import alien4cloud.topology.task.TaskCode;
import alien4cloud.topology.task.TaskLevel;
import alien4cloud.tosca.normative.NormativeComputeConstants;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.common.collect.Lists;
import org.springframework.stereotype.Component;
/**
* Performs validation of the properties
*/
@Component
@Slf4j
public class TopologyPropertiesValidationService {
@Resource
private CSARRepositorySearchService csarRepoSearchService;
/**
* Validate that the properties values in the topology are matching the property definitions (required & constraints).
* Skips properties defined as get_input
*
* @param topology The actual topology to validate.
* @return A list tasks to be done to make this topology valid.
*/
public List<PropertiesTask> validateStaticProperties(Topology topology) {
return validateProperties(topology, true);
}
/**
* Validate that the All properties (including dynamic properties (get_input )) values in the topology are matching the property definitions (required &
* constraints).
*
* @param topology The actual topology to validate.
* @return A list tasks to be done to make this topology valid.
*/
public List<PropertiesTask> validateAllProperties(Topology topology) {
return validateProperties(topology, false);
}
/**
* Validate properties.
*
* @param topology
* @param skipInputProperties whether to skip input properties validation or not. This is in case inputs are not yet processed
* @return
*/
private List<PropertiesTask> validateProperties(Topology topology, boolean skipInputProperties) {
List<PropertiesTask> toReturnTaskList = Lists.newArrayList();
Map<String, NodeTemplate> nodeTemplates = topology.getNodeTemplates();
// create task by nodetemplate
for (Map.Entry<String, NodeTemplate> nodeTempEntry : nodeTemplates.entrySet()) {
NodeTemplate nodeTemplate = nodeTempEntry.getValue();
IndexedNodeType relatedIndexedNodeType = csarRepoSearchService.getRequiredElementInDependencies(IndexedNodeType.class, nodeTemplate.getType(),
topology.getDependencies());
// do pass if abstract node
if (relatedIndexedNodeType.isAbstract()) {
continue;
}
// Define a task regarding properties
PropertiesTask task = new PropertiesTask();
task.setNodeTemplateName(nodeTempEntry.getKey());
task.setComponent(relatedIndexedNodeType);
task.setCode(TaskCode.PROPERTIES);
task.setProperties(Maps.<TaskLevel, List<String>> newHashMap());
// Check the properties of node template
if (MapUtils.isNotEmpty(nodeTemplate.getProperties())) {
addRequiredPropertyIdToTaskProperties(nodeTemplate.getProperties(), relatedIndexedNodeType.getProperties(), task, skipInputProperties);
}
// Check relationships PD
if (MapUtils.isNotEmpty(nodeTemplate.getRelationships())) {
Collection<RelationshipTemplate> relationships = nodeTemplate.getRelationships().values();
for (RelationshipTemplate relationship : relationships) {
if (relationship.getProperties() == null || relationship.getProperties().isEmpty()) {
continue;
}
addRequiredPropertyIdToTaskProperties(relationship.getProperties(), getRelationshipPropertyDefinition(topology, nodeTemplate), task,
skipInputProperties);
}
}
// Check capabilities PD
if (MapUtils.isNotEmpty(nodeTemplate.getCapabilities())) {
Collection<Capability> capabilities = nodeTemplate.getCapabilities().values();
for (Capability capability : capabilities) {
if (capability.getProperties() == null || capability.getProperties().isEmpty()) {
continue;
}
addRequiredPropertyIdToTaskProperties(capability.getProperties(), getCapabilitiesPropertyDefinition(topology, nodeTemplate), task,
skipInputProperties);
if (capability.getType().equals(NormativeComputeConstants.SCALABLE_CAPABILITY_TYPE)) {
Map<String, AbstractPropertyValue> scalableProperties = capability.getProperties();
verifyScalableProperties(scalableProperties, toReturnTaskList, nodeTempEntry.getKey(), skipInputProperties);
}
}
}
if (MapUtils.isNotEmpty(task.getProperties())) {
toReturnTaskList.add(task);
}
}
return toReturnTaskList.isEmpty() ? null : toReturnTaskList;
}
private Map<String, PropertyDefinition> getCapabilitiesPropertyDefinition(Topology topology, NodeTemplate nodeTemplate) {
Map<String, PropertyDefinition> relatedProperties = Maps.newTreeMap();
for (Map.Entry<String, Capability> capabilityEntry : nodeTemplate.getCapabilities().entrySet()) {
IndexedCapabilityType indexedCapabilityType = csarRepoSearchService.getRequiredElementInDependencies(IndexedCapabilityType.class,
capabilityEntry.getValue().getType(), topology.getDependencies());
if (indexedCapabilityType.getProperties() != null && !indexedCapabilityType.getProperties().isEmpty()) {
relatedProperties.putAll(indexedCapabilityType.getProperties());
}
}
return relatedProperties;
}
private Map<String, PropertyDefinition> getRelationshipPropertyDefinition(Topology topology, NodeTemplate nodeTemplate) {
Map<String, PropertyDefinition> relatedProperties = Maps.newTreeMap();
for (Map.Entry<String, RelationshipTemplate> relationshipTemplateEntry : nodeTemplate.getRelationships().entrySet()) {
IndexedRelationshipType indexedRelationshipType = csarRepoSearchService.getRequiredElementInDependencies(IndexedRelationshipType.class,
relationshipTemplateEntry.getValue().getType(), topology.getDependencies());
if (indexedRelationshipType.getProperties() != null && !indexedRelationshipType.getProperties().isEmpty()) {
relatedProperties.putAll(indexedRelationshipType.getProperties());
}
}
return relatedProperties;
}
private void verifyScalableProperties(Map<String, AbstractPropertyValue> scalableProperties, List<PropertiesTask> toReturnTaskList, String nodeTemplateId,
boolean skipInputProperties) {
Set<String> missingProperties = Sets.newHashSet();
Set<String> errorProperties = Sets.newHashSet();
if (skipInputProperties) {
for (Entry<String, AbstractPropertyValue> entry : scalableProperties.entrySet()) {
if (entry.getValue() instanceof FunctionPropertyValue) {
return;
}
}
}
if (MapUtils.isEmpty(scalableProperties)) {
missingProperties.addAll(Lists.newArrayList(NormativeComputeConstants.SCALABLE_MIN_INSTANCES, NormativeComputeConstants.SCALABLE_MAX_INSTANCES,
NormativeComputeConstants.SCALABLE_DEFAULT_INSTANCES));
} else {
int min = verifyScalableProperty(scalableProperties, NormativeComputeConstants.SCALABLE_MIN_INSTANCES, missingProperties, errorProperties);
int max = verifyScalableProperty(scalableProperties, NormativeComputeConstants.SCALABLE_MAX_INSTANCES, missingProperties, errorProperties);
int init = verifyScalableProperty(scalableProperties, NormativeComputeConstants.SCALABLE_DEFAULT_INSTANCES, missingProperties, errorProperties);
if (min > 0 && max > 0 && init > 0) {
if (min > init || min > max) {
errorProperties.add(NormativeComputeConstants.SCALABLE_MIN_INSTANCES);
}
if (init > max || init < min) {
errorProperties.add(NormativeComputeConstants.SCALABLE_DEFAULT_INSTANCES);
}
if (max < min || max < init) {
errorProperties.add(NormativeComputeConstants.SCALABLE_MAX_INSTANCES);
}
}
}
if (!missingProperties.isEmpty()) {
ScalableTask scalableTask = new ScalableTask(nodeTemplateId);
scalableTask.getProperties().put(TaskLevel.REQUIRED, Lists.newArrayList(missingProperties));
toReturnTaskList.add(scalableTask);
}
if (!errorProperties.isEmpty()) {
ScalableTask scalableTask = new ScalableTask(nodeTemplateId);
scalableTask.getProperties().put(TaskLevel.ERROR, Lists.newArrayList(errorProperties));
toReturnTaskList.add(scalableTask);
}
}
private int verifyScalableProperty(Map<String, AbstractPropertyValue> scalableProperties, String propertyToVerify, Set<String> missingProperties,
Set<String> errorProperties) {
String rawValue = null;
try {
rawValue = FunctionEvaluator.getScalarValue(scalableProperties.get(propertyToVerify));
} catch (NotSupportedException e1) {
// the value is a function (get_input normally), this means the input is not yet filled.
}
if (StringUtils.isEmpty(rawValue)) {
missingProperties.add(propertyToVerify);
return -1;
}
int value;
try {
value = Integer.parseInt(rawValue);
} catch (Exception e) {
errorProperties.add(propertyToVerify);
return -1;
}
if (value <= 0) {
errorProperties.add(propertyToVerify);
return -1;
}
return value;
}
private void addRequiredPropertyError(PropertiesTask task, String propertyName) {
if (!task.getProperties().containsKey(TaskLevel.REQUIRED)) {
task.getProperties().put(TaskLevel.REQUIRED, Lists.<String> newArrayList());
}
task.getProperties().get(TaskLevel.REQUIRED).add(propertyName);
}
private void addRequiredPropertyIdToTaskProperties(Map<String, AbstractPropertyValue> properties, Map<String, PropertyDefinition> relatedProperties,
PropertiesTask task, boolean skipInputProperties) {
for (Map.Entry<String, AbstractPropertyValue> propertyEntry : properties.entrySet()) {
PropertyDefinition propertyDef = relatedProperties.get(propertyEntry.getKey());
AbstractPropertyValue value = propertyEntry.getValue();
if (propertyDef != null && propertyDef.isRequired()) {
if (value == null) {
addRequiredPropertyError(task, propertyEntry.getKey());
} else if (value instanceof ScalarPropertyValue) {
String propertyValue = ((ScalarPropertyValue) value).getValue();
if (StringUtils.isBlank(propertyValue)) {
addRequiredPropertyError(task, propertyEntry.getKey());
}
} else if (value instanceof ComplexPropertyValue) {
Map<String, Object> mapValue = ((ComplexPropertyValue) value).getValue();
if (MapUtils.isEmpty(mapValue)) {
addRequiredPropertyError(task, propertyEntry.getKey());
}
} else if (value instanceof ListPropertyValue) {
List<Object> listValue = ((ListPropertyValue) value).getValue();
if (listValue.isEmpty()) {
addRequiredPropertyError(task, propertyEntry.getKey());
}
} else if (skipInputProperties) {
// this is a get_input funtion.
// get_input Will be validated later on
continue;
} else {
addRequiredPropertyError(task, propertyEntry.getKey());
}
}
}
}
} | Add capability/requirement prefix in property validation result to avoid name collisions.
| alien4cloud-core/src/main/java/alien4cloud/topology/validation/TopologyPropertiesValidationService.java | Add capability/requirement prefix in property validation result to avoid name collisions. | <ide><path>lien4cloud-core/src/main/java/alien4cloud/topology/validation/TopologyPropertiesValidationService.java
<ide> import org.elasticsearch.common.collect.Lists;
<ide> import org.springframework.stereotype.Component;
<ide>
<add>import static alien4cloud.utils.AlienUtils.safe;
<add>
<ide> /**
<ide> * Performs validation of the properties
<ide> */
<ide>
<ide> // Check the properties of node template
<ide> if (MapUtils.isNotEmpty(nodeTemplate.getProperties())) {
<del> addRequiredPropertyIdToTaskProperties(nodeTemplate.getProperties(), relatedIndexedNodeType.getProperties(), task, skipInputProperties);
<add> addRequiredPropertyIdToTaskProperties(null, nodeTemplate.getProperties(), relatedIndexedNodeType.getProperties(), task, skipInputProperties);
<ide> }
<ide>
<ide> // Check relationships PD
<del> if (MapUtils.isNotEmpty(nodeTemplate.getRelationships())) {
<del> Collection<RelationshipTemplate> relationships = nodeTemplate.getRelationships().values();
<del> for (RelationshipTemplate relationship : relationships) {
<del> if (relationship.getProperties() == null || relationship.getProperties().isEmpty()) {
<del> continue;
<del> }
<del> addRequiredPropertyIdToTaskProperties(relationship.getProperties(), getRelationshipPropertyDefinition(topology, nodeTemplate), task,
<del> skipInputProperties);
<del> }
<del> }
<del>
<del> // Check capabilities PD
<del> if (MapUtils.isNotEmpty(nodeTemplate.getCapabilities())) {
<del> Collection<Capability> capabilities = nodeTemplate.getCapabilities().values();
<del> for (Capability capability : capabilities) {
<del> if (capability.getProperties() == null || capability.getProperties().isEmpty()) {
<del> continue;
<del> }
<del> addRequiredPropertyIdToTaskProperties(capability.getProperties(), getCapabilitiesPropertyDefinition(topology, nodeTemplate), task,
<del> skipInputProperties);
<del> if (capability.getType().equals(NormativeComputeConstants.SCALABLE_CAPABILITY_TYPE)) {
<del> Map<String, AbstractPropertyValue> scalableProperties = capability.getProperties();
<del> verifyScalableProperties(scalableProperties, toReturnTaskList, nodeTempEntry.getKey(), skipInputProperties);
<del> }
<add> for (Map.Entry<String, RelationshipTemplate> relationshipEntry : safe(nodeTemplate.getRelationships()).entrySet()) {
<add> RelationshipTemplate relationship = relationshipEntry.getValue();
<add> if (relationship.getProperties() == null || relationship.getProperties().isEmpty()) {
<add> continue;
<add> }
<add> addRequiredPropertyIdToTaskProperties("relationships[" + relationshipEntry.getKey() + "]", relationship.getProperties(),
<add> getRelationshipPropertyDefinition(topology, nodeTemplate), task, skipInputProperties);
<add> }
<add> for (Map.Entry<String, Capability> capabilityEntry : safe(nodeTemplate.getCapabilities()).entrySet()) {
<add> Capability capability = capabilityEntry.getValue();
<add> if (capability.getProperties() == null || capability.getProperties().isEmpty()) {
<add> continue;
<add> }
<add> addRequiredPropertyIdToTaskProperties("capabilities[" + capabilityEntry.getKey() + "]", capability.getProperties(),
<add> getCapabilitiesPropertyDefinition(topology, nodeTemplate), task, skipInputProperties);
<add> if (capability.getType().equals(NormativeComputeConstants.SCALABLE_CAPABILITY_TYPE)) {
<add> Map<String, AbstractPropertyValue> scalableProperties = capability.getProperties();
<add> verifyScalableProperties(scalableProperties, toReturnTaskList, nodeTempEntry.getKey(), skipInputProperties);
<ide> }
<ide> }
<ide>
<ide> task.getProperties().get(TaskLevel.REQUIRED).add(propertyName);
<ide> }
<ide>
<del> private void addRequiredPropertyIdToTaskProperties(Map<String, AbstractPropertyValue> properties, Map<String, PropertyDefinition> relatedProperties,
<del> PropertiesTask task, boolean skipInputProperties) {
<add> private void addRequiredPropertyIdToTaskProperties(String prefix, Map<String, AbstractPropertyValue> properties,
<add> Map<String, PropertyDefinition> relatedProperties, PropertiesTask task, boolean skipInputProperties) {
<ide> for (Map.Entry<String, AbstractPropertyValue> propertyEntry : properties.entrySet()) {
<ide> PropertyDefinition propertyDef = relatedProperties.get(propertyEntry.getKey());
<add> String propertyErrorKey = prefix == null ? propertyEntry.getKey() : prefix + "." + propertyEntry.getKey();
<ide> AbstractPropertyValue value = propertyEntry.getValue();
<ide> if (propertyDef != null && propertyDef.isRequired()) {
<ide> if (value == null) {
<del> addRequiredPropertyError(task, propertyEntry.getKey());
<add> addRequiredPropertyError(task, propertyErrorKey);
<ide> } else if (value instanceof ScalarPropertyValue) {
<ide> String propertyValue = ((ScalarPropertyValue) value).getValue();
<ide> if (StringUtils.isBlank(propertyValue)) {
<del> addRequiredPropertyError(task, propertyEntry.getKey());
<add> addRequiredPropertyError(task, propertyErrorKey);
<ide> }
<ide> } else if (value instanceof ComplexPropertyValue) {
<ide> Map<String, Object> mapValue = ((ComplexPropertyValue) value).getValue();
<ide> if (MapUtils.isEmpty(mapValue)) {
<del> addRequiredPropertyError(task, propertyEntry.getKey());
<add> addRequiredPropertyError(task, propertyErrorKey);
<ide> }
<ide> } else if (value instanceof ListPropertyValue) {
<ide> List<Object> listValue = ((ListPropertyValue) value).getValue();
<ide> if (listValue.isEmpty()) {
<del> addRequiredPropertyError(task, propertyEntry.getKey());
<add> addRequiredPropertyError(task, propertyErrorKey);
<ide> }
<ide> } else if (skipInputProperties) {
<ide> // this is a get_input funtion.
<ide> // get_input Will be validated later on
<ide> continue;
<ide> } else {
<del> addRequiredPropertyError(task, propertyEntry.getKey());
<add> addRequiredPropertyError(task, propertyErrorKey);
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | e3be84e96ba116fde0b761dda98d12424054b9ac | 0 | greg-dove/flex-falcon,adufilie/flex-falcon,greg-dove/flex-falcon,adufilie/flex-falcon,greg-dove/flex-falcon,greg-dove/flex-falcon,adufilie/flex-falcon,adufilie/flex-falcon | /*
*
* 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.flex.compiler.internal.driver.js.goog;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.flex.compiler.clients.JSConfiguration;
import org.apache.flex.compiler.clients.MXMLJSC;
import org.apache.flex.compiler.config.ConfigurationValue;
import org.apache.flex.compiler.exceptions.ConfigurationException;
import org.apache.flex.compiler.internal.config.annotations.Config;
import org.apache.flex.compiler.internal.config.annotations.FlexOnly;
import org.apache.flex.compiler.internal.config.annotations.InfiniteArguments;
import org.apache.flex.compiler.internal.config.annotations.Mapping;
/**
* The {@link JSGoogConfiguration} class holds all compiler arguments needed for
* compiling ActionScript to JavaScript the 'goog' way.
* <p>
* Specific flags are implemented here for the configuration to be loaded by the
* configure() method of {@link MXMLJSC}.
* <p>
* This class inherits all compiler arguments from the MXMLC compiler.
*
* @author Erik de Bruin
*/
public class JSGoogConfiguration extends JSConfiguration
{
public JSGoogConfiguration()
{
}
//
// 'closure-lib'
//
private String closureLib = "";
public String getClosureLib()
{
try
{
if (closureLib.equals(""))
{
closureLib = getAbsolutePathFromPathRelativeToMXMLC(
"../../js/lib/google/closure-library");
}
}
catch (Exception e) { /* better to try and fail... */ }
return closureLib;
}
@Config
@Mapping("closure-lib")
public void setClosureLib(ConfigurationValue cv, String value)
throws ConfigurationException
{
if (value != null)
closureLib = value;
}
//
// Override 'compiler.binding-value-change-event-type'
//
private String bindingValueChangeEventType = "valueChange";
@Override
public String getBindingValueChangeEventType()
{
return bindingValueChangeEventType;
}
@Override
@Config(advanced = true)
public void setCompilerBindingValueChangeEventType(ConfigurationValue cv, String b)
{
bindingValueChangeEventType = b;
}
//
// Override 'compiler.mxml.children-as-data'
//
private Boolean childrenAsData = true;
@Override
public Boolean getCompilerMxmlChildrenAsData()
{
return childrenAsData;
}
@Override
@Config
@Mapping({"compiler", "mxml", "children-as-data"})
@FlexOnly
public void setCompilerMxmlChildrenAsData(ConfigurationValue cv, Boolean asData) throws ConfigurationException
{
childrenAsData = asData;
}
//
// 'marmotinni'
//
private String marmotinni;
public String getMarmotinni()
{
return marmotinni;
}
@Config
@Mapping("marmotinni")
public void setMarmotinni(ConfigurationValue cv, String value)
throws ConfigurationException
{
marmotinni = value;
}
//
// 'sdk-js-lib'
//
private List<String> sdkJSLib = new ArrayList<String>();
public List<String> getSDKJSLib()
{
if (sdkJSLib.size() == 0)
{
try
{
String path = getAbsolutePathFromPathRelativeToMXMLC(
"../../frameworks/js/FlexJS/src");
sdkJSLib.add(path);
}
catch (Exception e) { /* better to try and fail... */ }
}
return sdkJSLib;
}
@Config(allowMultiple = true)
@Mapping("sdk-js-lib")
@InfiniteArguments
public void setSDKJSLib(ConfigurationValue cv, List<String> value)
throws ConfigurationException
{
sdkJSLib.addAll(value);
}
//
// 'external-js-lib'
//
private List<String> externalJSLib = new ArrayList<String>();
public List<String> getExternalJSLib()
{
return externalJSLib;
}
@Config(allowMultiple = true)
@Mapping("external-js-lib")
@InfiniteArguments
public void setExternalJSLib(ConfigurationValue cv, List<String> value)
throws ConfigurationException
{
externalJSLib.addAll(value);
}
//
// 'strict-publish'
//
private boolean strictPublish = true;
public boolean getStrictPublish()
{
return strictPublish;
}
@Config
@Mapping("strict-publish")
public void setStrictPublish(ConfigurationValue cv, boolean value)
throws ConfigurationException
{
strictPublish = value;
}
private String getAbsolutePathFromPathRelativeToMXMLC(String relativePath)
throws IOException
{
String mxmlcURL = MXMLJSC.class.getProtectionDomain().getCodeSource()
.getLocation().getPath();
File mxmlc = new File(URLDecoder.decode(mxmlcURL, "utf-8"));
return new File(mxmlc.getParent() + File.separator + relativePath)
.getCanonicalPath();
}
}
| compiler.jx/src/org/apache/flex/compiler/internal/driver/js/goog/JSGoogConfiguration.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.flex.compiler.internal.driver.js.goog;
import java.util.ArrayList;
import java.util.List;
import org.apache.flex.compiler.clients.JSConfiguration;
import org.apache.flex.compiler.clients.MXMLJSC;
import org.apache.flex.compiler.config.ConfigurationValue;
import org.apache.flex.compiler.exceptions.ConfigurationException;
import org.apache.flex.compiler.internal.config.annotations.Config;
import org.apache.flex.compiler.internal.config.annotations.FlexOnly;
import org.apache.flex.compiler.internal.config.annotations.InfiniteArguments;
import org.apache.flex.compiler.internal.config.annotations.Mapping;
/**
* The {@link JSGoogConfiguration} class holds all compiler arguments needed for
* compiling ActionScript to JavaScript the 'goog' way.
* <p>
* Specific flags are implemented here for the configuration to be loaded by the
* configure() method of {@link MXMLJSC}.
* <p>
* This class inherits all compiler arguments from the MXMLC compiler.
*
* @author Erik de Bruin
*/
public class JSGoogConfiguration extends JSConfiguration
{
public JSGoogConfiguration()
{
}
//
// 'closure-lib'
//
private String closureLib = "";
public String getClosureLib()
{
if (closureLib.equals(""))
closureLib = "./js/lib/google/closure-library";
return closureLib;
}
@Config
@Mapping("closure-lib")
public void setClosureLib(ConfigurationValue cv, String value)
throws ConfigurationException
{
if (value != null)
closureLib = value;
}
//
// Override 'compiler.binding-value-change-event-type'
//
private String bindingValueChangeEventType = "valueChange";
@Override
public String getBindingValueChangeEventType()
{
return bindingValueChangeEventType;
}
@Override
@Config(advanced = true)
public void setCompilerBindingValueChangeEventType(ConfigurationValue cv, String b)
{
bindingValueChangeEventType = b;
}
//
// Override 'compiler.mxml.children-as-data'
//
private Boolean childrenAsData = true;
@Override
public Boolean getCompilerMxmlChildrenAsData()
{
return childrenAsData;
}
@Override
@Config
@Mapping({"compiler", "mxml", "children-as-data"})
@FlexOnly
public void setCompilerMxmlChildrenAsData(ConfigurationValue cv, Boolean asData) throws ConfigurationException
{
childrenAsData = asData;
}
//
// 'marmotinni'
//
private String marmotinni;
public String getMarmotinni()
{
return marmotinni;
}
@Config
@Mapping("marmotinni")
public void setMarmotinni(ConfigurationValue cv, String value)
throws ConfigurationException
{
marmotinni = value;
}
//
// 'sdk-js-lib'
//
private List<String> sdkJSLib = new ArrayList<String>();
public List<String> getSDKJSLib()
{
if (sdkJSLib.size() == 0)
sdkJSLib.add("./frameworks/js/FlexJS/src");
return sdkJSLib;
}
@Config(allowMultiple = true)
@Mapping("sdk-js-lib")
@InfiniteArguments
public void setSDKJSLib(ConfigurationValue cv, List<String> value)
throws ConfigurationException
{
sdkJSLib.addAll(value);
}
//
// 'external-js-lib'
//
private List<String> externalJSLib = new ArrayList<String>();
public List<String> getExternalJSLib()
{
return externalJSLib;
}
@Config(allowMultiple = true)
@Mapping("external-js-lib")
@InfiniteArguments
public void setExternalJSLib(ConfigurationValue cv, List<String> value)
throws ConfigurationException
{
externalJSLib.addAll(value);
}
//
// 'strict-publish'
//
private boolean strictPublish = true;
public boolean getStrictPublish()
{
return strictPublish;
}
@Config
@Mapping("strict-publish")
public void setStrictPublish(ConfigurationValue cv, boolean value)
throws ConfigurationException
{
strictPublish = value;
}
}
| Added some relative path resolution in order to make the defaults work when the compiler is not launched from the root of the SDK directory.
Signed-off-by: Erik de Bruin <[email protected]>
| compiler.jx/src/org/apache/flex/compiler/internal/driver/js/goog/JSGoogConfiguration.java | Added some relative path resolution in order to make the defaults work when the compiler is not launched from the root of the SDK directory. | <ide><path>ompiler.jx/src/org/apache/flex/compiler/internal/driver/js/goog/JSGoogConfiguration.java
<ide>
<ide> package org.apache.flex.compiler.internal.driver.js.goog;
<ide>
<add>import java.io.File;
<add>import java.io.IOException;
<add>import java.net.URLDecoder;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<ide>
<ide> public String getClosureLib()
<ide> {
<del> if (closureLib.equals(""))
<del> closureLib = "./js/lib/google/closure-library";
<add> try
<add> {
<add> if (closureLib.equals(""))
<add> {
<add> closureLib = getAbsolutePathFromPathRelativeToMXMLC(
<add> "../../js/lib/google/closure-library");
<add> }
<add> }
<add> catch (Exception e) { /* better to try and fail... */ }
<ide>
<ide> return closureLib;
<ide> }
<ide> public List<String> getSDKJSLib()
<ide> {
<ide> if (sdkJSLib.size() == 0)
<del> sdkJSLib.add("./frameworks/js/FlexJS/src");
<add> {
<add> try
<add> {
<add> String path = getAbsolutePathFromPathRelativeToMXMLC(
<add> "../../frameworks/js/FlexJS/src");
<add>
<add> sdkJSLib.add(path);
<add> }
<add> catch (Exception e) { /* better to try and fail... */ }
<add> }
<ide>
<ide> return sdkJSLib;
<ide> }
<ide> strictPublish = value;
<ide> }
<ide>
<add> private String getAbsolutePathFromPathRelativeToMXMLC(String relativePath)
<add> throws IOException
<add> {
<add> String mxmlcURL = MXMLJSC.class.getProtectionDomain().getCodeSource()
<add> .getLocation().getPath();
<add>
<add> File mxmlc = new File(URLDecoder.decode(mxmlcURL, "utf-8"));
<add>
<add> return new File(mxmlc.getParent() + File.separator + relativePath)
<add> .getCanonicalPath();
<add> }
<add>
<ide> } |
|
Java | apache-2.0 | 86252f3eb83c7d65f4beb6d06ac92cd1c62c8e2a | 0 | pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus | /*
*
* Copyright 2007-2008 University Of Southern California
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package edu.isi.pegasus.planner.client;
import edu.isi.pegasus.planner.catalog.SiteCatalog;
import edu.isi.pegasus.planner.catalog.site.impl.OSGMM;
import edu.isi.pegasus.planner.catalog.site.SiteCatalogException;
import edu.isi.pegasus.planner.catalog.site.SiteFactory;
import edu.isi.pegasus.planner.catalog.site.SiteFactoryException;
import edu.isi.pegasus.planner.catalog.site.classes.SiteCatalogEntry;
import edu.isi.pegasus.planner.catalog.site.classes.SiteStore;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.common.logging.LogManagerFactory;
import edu.isi.pegasus.planner.common.PegasusProperties;
import edu.isi.pegasus.common.util.Version;
import gnu.getopt.Getopt;
import gnu.getopt.LongOpt;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
/**
* The client that replaces the perl based pegasus-get-sites.
* It generates a Site Catalog by querying VORS.
*
* @author Atul Kumar
* @author Karan Vahi
* @version $Revision$
*/
public class PegasusGetSites extends Executable{
private String mVO ="";
private String mGrid ="";
private String mSource="";
private SiteCatalog mCatalog = null;
private String mSCFile = null;
private String mPropertiesFilename;
/**
* The default constructor.
*/
public PegasusGetSites(){
super();
}
/**
* Initialize the PegasusGetSites object
* @param opts the command line argument passed to the PegasusGetSites
*/
public void intialize(String [] opts){
super.initialize(opts);
mLogMsg = new String();
mVersion = Version.instance().toString();
}
/**
* The main program
*
* @param args
*/
public static void main( String[] args ){
PegasusGetSites me = new PegasusGetSites();
int result = 0;
double starttime = new Date().getTime();
double execTime = -1;
try{
me.initialize(args);
me.executeCommand( );
}
catch ( RuntimeException rte ) {
//catch all runtime exceptions including our own that
//are thrown that may have chained causes
me.log( convertException(rte),
LogManager.FATAL_MESSAGE_LEVEL );
rte.printStackTrace();
result = 1;
}
catch ( Exception e ) {
//unaccounted for exceptions
me.log(e.getMessage(),
LogManager.FATAL_MESSAGE_LEVEL );
result = 3;
} finally {
double endtime = new Date().getTime();
execTime = (endtime - starttime)/1000;
}
// warn about non zero exit code
if ( result != 0 ) {
me.log("Non-zero exit-code " + result,
LogManager.WARNING_MESSAGE_LEVEL );
}
else{
//log the time taken to execute
me.log("Time taken to execute is " + execTime + " seconds",
LogManager.INFO_MESSAGE_LEVEL);
}
me.mLogger.logEventCompletion();
System.exit( result );
}
/**
* An empty implementation.
*/
public void loadProperties() {
}
/**
* Prints out the long help.
*/
public void printLongVersion() {
StringBuffer text = new StringBuffer();
text.append( "\n" ).append( "$Id$ ").
append( "\n" ).append( getGVDSVersion() ).
append( "\n" ).append( "Usage : pegasus-get-sites --source <source> --grid <grid> --vo <vo> --sc <filename> --properties <properties file>" ).
append( "\n" ).append( "[--conf <path to property file>] [-v] [-h]" ).
append( "\n" ).
append( "\n Mandatory Options " ).
append( "\n --source the source to query for information. Valid sources are OSGMM|MYOSG|VORS" ).
append( "\n" ).
append( "\n Other Options " ).
append( "\n -g |--grid the grid for which to generate the site catalog ").
append( "\n -o |--vo the virtual organization to which the user belongs " ).
append( "\n -s |--sc the path to the created site catalog file" ).
append( "\n -p |--properties the properties file to be created" ).
append( "\n -c |--conf path to property file").
append( "\n -v |--verbose increases the verbosity of messages about what is going on" ).
append( "\n -V |--version displays the version of the Pegasus Workflow Management System" ).
append( "\n -h |--help generates this help." );
System.out.println( text.toString() );
}
/**
* The short help version.
*/
public void printShortVersion() {
StringBuffer text = new StringBuffer();
text.append( "\n" ).append( "$Id$ ").
append( "\n" ).append( getGVDSVersion() ).
append( "\n" ).append( "Usage : pegasus-get-sites -source <site> -g <grid> -o <vo> -s <filename> -p <filename>" ).
append( "\n" ).append( "[-c <path to property file>] [-v] [-h]" );
System.out.println( text.toString() );
}
/**
* Executs the command on the basis of the command line options passed.
*
* @param args
*/
public void executeCommand() {
parseCommandLineArguments(getCommandLineOptions());
PegasusProperties p = PegasusProperties.nonSingletonInstance();
p.setProperty( "pegasus.catalog.site", mSource );
if(mSCFile == null){
//no sc path is passed using command line
//sc path is not set in the properties file go to default
File f = new File(p.getPegasusHome(), "var/sites.xml");
mSCFile = f.getAbsolutePath();
}
//pass on the VO and Grid information as properties
//to site catalog back end.
if(mVO != null){
p.setProperty( getPropertyKey( mSource, "vo" ), mVO );
}
if(mGrid != null){
p.setProperty( getPropertyKey( mSource, "grid" ), mGrid );
}
try{
mCatalog = SiteFactory.loadInstance( p);
}
catch ( SiteFactoryException e ){
System.out.println( e.convertException() );
System.exit( 2 );
}
SiteStore store = new SiteStore();
/* load all sites in site catalog */
try{
List s = new ArrayList(1);
s.add( "*" );
mCatalog.load( s );
List toLoad = new ArrayList( mCatalog.list() );
toLoad.add( "local" );
//load into SiteStore from the catalog.
int num = 0;
for( Iterator<String> it = toLoad.iterator(); it.hasNext(); ){
SiteCatalogEntry se = mCatalog.lookup( it.next() );
if( se != null ){
store.addEntry( se );
num++;
}
}
mLogger.log( "Loaded " + num + " sites ", LogManager.INFO_MESSAGE_LEVEL );
//write DAX to file
FileWriter scFw = new FileWriter( mSCFile );
mLogger.log( "Writing out site catalog to " + new File( mSCFile ).getAbsolutePath() ,
LogManager.CONSOLE_MESSAGE_LEVEL );
store.toXML( scFw, "" );
scFw.close();
//generate the SRM properties file only if
//interfacing with OSGMM.
if( mCatalog instanceof OSGMM ){
Properties properties = ((OSGMM)mCatalog).generateSRMProperties();
mLogger.log( "Number of SRM Properties retrieved " + properties.entrySet().size() ,
LogManager.CONSOLE_MESSAGE_LEVEL );
mLogger.log( properties.toString(),
LogManager.DEBUG_MESSAGE_LEVEL );
File file = ( mPropertiesFilename == null )?
//default one in the working directory
//create a temporary file in directory
File.createTempFile( "pegasus.", ".properties", new File( "." ) ):
new File( mPropertiesFilename );
OutputStream os = new FileOutputStream( file );
mLogger.log( "Writing out properties to " + file.getAbsolutePath() ,
LogManager.CONSOLE_MESSAGE_LEVEL );
properties.store( os, "Pegasus SRM Properties" );
os.close();
}
}
catch ( SiteCatalogException e ){
e.printStackTrace();
}
catch( IOException ioe ){
ioe.printStackTrace();
}
}
/**
* Returns the full name of the property key with the appropriate prefix
*
* @param source the source i.e type of site catalog
* @param key the basename of the key
*
* @return the property key.
*/
protected String getPropertyKey( String source, String key ){
//"pegasus.catalog.site.vors.grid"
String lSource = source.toLowerCase();
StringBuffer property = new StringBuffer();
property.append( "pegasus.catalog.site" ).append( "." ).
append( lSource ).append( "." ).
append( key );
return property.toString();
}
/**
* Sets up the logging options for this class. Looking at the properties
* file, sets up the appropriate writers for output and stderr.
*/
protected void setupLogging(){
//setup the logger for the default streams.
mLogger = LogManagerFactory.loadSingletonInstance( mProps );
mLogger.logEventStart( "event.pegasus.pegasus-get-sites", "pegasus.version", mVersion );
}
/**
* Parses the command line arguments using GetOpt and sets the class
* member variables.
*
* @param args the arguments passed by the user at command line.
*
*
*/
public void parseCommandLineArguments(String[] args){
LongOpt[] longOptions = generateValidOptions();
Getopt g = new Getopt("pegasus-get-sites", args, "1:g:o:s:p:c:hvV", longOptions, false);
g.setOpterr(false);
int option = 0;
int level = 0;
while ( (option = g.getopt()) != -1) {
//System.out.println("Option tag " + (char)option);
switch (option) {
case '1': //--source
mSource = g.getOptarg();
break;
case 'g': //--grid
mGrid = g.getOptarg();
break;
case 'o': //--vo
mVO = g.getOptarg();
break;
case 's': //--sc
mSCFile = g.getOptarg();
break;
case 'p': //--properties
mPropertiesFilename = g.getOptarg();
break;
case 'c': // conf
//do nothing
break;
case 'v': //--verbose
level++;
break;
case 'V'://--version
mLogger.log(getGVDSVersion(),LogManager.INFO_MESSAGE_LEVEL);
System.exit(0);
case 'h'://--help
printLongVersion();
System.exit( 0 );
break;
default: //same as help
printShortVersion();
for( int i =0 ; i < args.length ; i++ )
System.out.println( args[i] );
throw new RuntimeException("Incorrect option or option usage " +
(char)g.getOptopt());
}
}
if(level >0){
mLogger.setLevel( level );
}
else{
mLogger.setLevel(LogManager.WARNING_MESSAGE_LEVEL);
}
if(mSource == null || mSource.isEmpty()){
mLogger.log("Please provide the source to query for information",LogManager.ERROR_MESSAGE_LEVEL);
this.printShortVersion();
System.exit(1);
}
}
/**
* Generates valid LongOpts.
*
* @return LongOpt[]
*/
public LongOpt[] generateValidOptions() {
LongOpt[] longopts = new LongOpt[9];
longopts[0] = new LongOpt( "source", LongOpt.REQUIRED_ARGUMENT, null, '1' );
longopts[1] = new LongOpt( "grid", LongOpt.REQUIRED_ARGUMENT, null, 'g' );
longopts[2] = new LongOpt( "vo", LongOpt.REQUIRED_ARGUMENT, null, 'o' );
longopts[3] = new LongOpt( "sc", LongOpt.REQUIRED_ARGUMENT, null, 's' );
longopts[4] = new LongOpt( "version", LongOpt.NO_ARGUMENT, null, 'V' );
longopts[5] = new LongOpt( "verbose", LongOpt.NO_ARGUMENT, null, 'v' );
longopts[6] = new LongOpt( "help", LongOpt.NO_ARGUMENT, null, 'h' );
longopts[7] = new LongOpt( "properties", LongOpt.REQUIRED_ARGUMENT, null, 'p' );
longopts[8] = new LongOpt( "conf", LongOpt.REQUIRED_ARGUMENT, null, 'c' );
return longopts;
}
}
| src/edu/isi/pegasus/planner/client/PegasusGetSites.java | /*
*
* Copyright 2007-2008 University Of Southern California
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package edu.isi.pegasus.planner.client;
import edu.isi.pegasus.planner.catalog.SiteCatalog;
import edu.isi.pegasus.planner.catalog.site.impl.OSGMM;
import edu.isi.pegasus.planner.catalog.site.SiteCatalogException;
import edu.isi.pegasus.planner.catalog.site.SiteFactory;
import edu.isi.pegasus.planner.catalog.site.SiteFactoryException;
import edu.isi.pegasus.planner.catalog.site.classes.SiteCatalogEntry;
import edu.isi.pegasus.planner.catalog.site.classes.SiteStore;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.common.logging.LogManagerFactory;
import edu.isi.pegasus.planner.common.PegasusProperties;
import edu.isi.pegasus.common.util.Version;
import gnu.getopt.Getopt;
import gnu.getopt.LongOpt;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
/**
* The client that replaces the perl based pegasus-get-sites.
* It generates a Site Catalog by querying VORS.
*
* @author Atul Kumar
* @author Karan Vahi
* @version $Revision$
*/
public class PegasusGetSites extends Executable{
private String mVO ="";
private String mGrid ="";
private String mSource="";
private SiteCatalog mCatalog = null;
private String mSCFile = null;
private String mPropertiesFilename;
/**
* The default constructor.
*/
public PegasusGetSites(){
super();
mLogMsg = new String();
mVersion = Version.instance().toString();
}
/**
* The main program
*
* @param args
*/
public static void main( String[] args ){
PegasusGetSites me = new PegasusGetSites();
int result = 0;
double starttime = new Date().getTime();
double execTime = -1;
try{
me.executeCommand( args );
}
catch ( RuntimeException rte ) {
//catch all runtime exceptions including our own that
//are thrown that may have chained causes
me.log( convertException(rte),
LogManager.FATAL_MESSAGE_LEVEL );
rte.printStackTrace();
result = 1;
}
catch ( Exception e ) {
//unaccounted for exceptions
me.log(e.getMessage(),
LogManager.FATAL_MESSAGE_LEVEL );
result = 3;
} finally {
double endtime = new Date().getTime();
execTime = (endtime - starttime)/1000;
}
// warn about non zero exit code
if ( result != 0 ) {
me.log("Non-zero exit-code " + result,
LogManager.WARNING_MESSAGE_LEVEL );
}
else{
//log the time taken to execute
me.log("Time taken to execute is " + execTime + " seconds",
LogManager.INFO_MESSAGE_LEVEL);
}
me.mLogger.logEventCompletion();
System.exit( result );
}
/**
* An empty implementation.
*/
public void loadProperties() {
}
/**
* Prints out the long help.
*/
public void printLongVersion() {
StringBuffer text = new StringBuffer();
text.append( "\n" ).append( "$Id$ ").
append( "\n" ).append( getGVDSVersion() ).
append( "\n" ).append( "Usage : pegasus-get-sites --source <source> --grid <grid> --vo <vo> --sc <filename> --properties <properties file>" ).
append( "\n" ).append( "[-v] [-h]" ).
append( "\n" ).
append( "\n Mandatory Options " ).
append( "\n --source the source to query for information. Valid sources are OSGMM|MYOSG|VORS" ).
append( "\n" ).
append( "\n Other Options " ).
append( "\n -g |--grid the grid for which to generate the site catalog ").
append( "\n -o |--vo the virtual organization to which the user belongs " ).
append( "\n -s |--sc the path to the created site catalog file" ).
append( "\n -p |--properties the properties file to be created" ).
append( "\n -v |--verbose increases the verbosity of messages about what is going on" ).
append( "\n -V |--version displays the version of the Pegasus Workflow Management System" ).
append( "\n -h |--help generates this help." );
System.out.println( text.toString() );
}
/**
* The short help version.
*/
public void printShortVersion() {
StringBuffer text = new StringBuffer();
text.append( "\n" ).append( "$Id$ ").
append( "\n" ).append( getGVDSVersion() ).
append( "\n" ).append( "Usage : pegasus-get-sites -source <site> -g <grid> -o <vo> -s <filename> -p <filename>" ).
append( "\n" ).append( "[-v] [-h]" );
System.out.println( text.toString() );
}
/**
* Executs the command on the basis of the command line options passed.
*
* @param args
*/
public void executeCommand(String[] args) {
parseCommandLineArguments(args);
PegasusProperties p = PegasusProperties.nonSingletonInstance();
p.setProperty( "pegasus.catalog.site", mSource );
if(mSCFile == null){
//no sc path is passed using command line
//sc path is not set in the properties file go to default
File f = new File(p.getPegasusHome(), "var/sites.xml");
mSCFile = f.getAbsolutePath();
}
//pass on the VO and Grid information as properties
//to site catalog back end.
if(mVO != null){
p.setProperty( getPropertyKey( mSource, "vo" ), mVO );
}
if(mGrid != null){
p.setProperty( getPropertyKey( mSource, "grid" ), mGrid );
}
try{
mCatalog = SiteFactory.loadInstance( p);
}
catch ( SiteFactoryException e ){
System.out.println( e.convertException() );
System.exit( 2 );
}
SiteStore store = new SiteStore();
/* load all sites in site catalog */
try{
List s = new ArrayList(1);
s.add( "*" );
mCatalog.load( s );
List toLoad = new ArrayList( mCatalog.list() );
toLoad.add( "local" );
//load into SiteStore from the catalog.
int num = 0;
for( Iterator<String> it = toLoad.iterator(); it.hasNext(); ){
SiteCatalogEntry se = mCatalog.lookup( it.next() );
if( se != null ){
store.addEntry( se );
num++;
}
}
mLogger.log( "Loaded " + num + " sites ", LogManager.INFO_MESSAGE_LEVEL );
//write DAX to file
FileWriter scFw = new FileWriter( mSCFile );
mLogger.log( "Writing out site catalog to " + new File( mSCFile ).getAbsolutePath() ,
LogManager.CONSOLE_MESSAGE_LEVEL );
store.toXML( scFw, "" );
scFw.close();
//generate the SRM properties file only if
//interfacing with OSGMM.
if( mCatalog instanceof OSGMM ){
Properties properties = ((OSGMM)mCatalog).generateSRMProperties();
mLogger.log( "Number of SRM Properties retrieved " + properties.entrySet().size() ,
LogManager.CONSOLE_MESSAGE_LEVEL );
mLogger.log( properties.toString(),
LogManager.DEBUG_MESSAGE_LEVEL );
File file = ( mPropertiesFilename == null )?
//default one in the working directory
//create a temporary file in directory
File.createTempFile( "pegasus.", ".properties", new File( "." ) ):
new File( mPropertiesFilename );
OutputStream os = new FileOutputStream( file );
mLogger.log( "Writing out properties to " + file.getAbsolutePath() ,
LogManager.CONSOLE_MESSAGE_LEVEL );
properties.store( os, "Pegasus SRM Properties" );
os.close();
}
}
catch ( SiteCatalogException e ){
e.printStackTrace();
}
catch( IOException ioe ){
ioe.printStackTrace();
}
}
/**
* Returns the full name of the property key with the appropriate prefix
*
* @param source the source i.e type of site catalog
* @param key the basename of the key
*
* @return the property key.
*/
protected String getPropertyKey( String source, String key ){
//"pegasus.catalog.site.vors.grid"
String lSource = source.toLowerCase();
StringBuffer property = new StringBuffer();
property.append( "pegasus.catalog.site" ).append( "." ).
append( lSource ).append( "." ).
append( key );
return property.toString();
}
/**
* Sets up the logging options for this class. Looking at the properties
* file, sets up the appropriate writers for output and stderr.
*/
protected void setupLogging(){
//setup the logger for the default streams.
mLogger = LogManagerFactory.loadSingletonInstance( mProps );
mLogger.logEventStart( "event.pegasus.pegasus-get-sites", "pegasus.version", mVersion );
}
/**
* Parses the command line arguments using GetOpt and sets the class
* member variables.
*
* @param args the arguments passed by the user at command line.
*
*
*/
public void parseCommandLineArguments(String[] args){
LongOpt[] longOptions = generateValidOptions();
Getopt g = new Getopt("pegasus-get-sites", args, "1:g:o:s:p:hvV", longOptions, false);
g.setOpterr(false);
int option = 0;
int level = 0;
while ( (option = g.getopt()) != -1) {
//System.out.println("Option tag " + (char)option);
switch (option) {
case '1': //--source
mSource = g.getOptarg();
break;
case 'g': //--grid
mGrid = g.getOptarg();
break;
case 'o': //--vo
mVO = g.getOptarg();
break;
case 's': //--sc
mSCFile = g.getOptarg();
break;
case 'p': //--properties
mPropertiesFilename = g.getOptarg();
break;
case 'v': //--verbose
level++;
break;
case 'V'://--version
mLogger.log(getGVDSVersion(),LogManager.INFO_MESSAGE_LEVEL);
System.exit(0);
case 'h'://--help
printLongVersion();
System.exit( 0 );
break;
default: //same as help
printShortVersion();
for( int i =0 ; i < args.length ; i++ )
System.out.println( args[i] );
throw new RuntimeException("Incorrect option or option usage " +
option);
}
}
if(level >0){
mLogger.setLevel( level );
}
else{
mLogger.setLevel(LogManager.WARNING_MESSAGE_LEVEL);
}
if(mSource == null || mSource.isEmpty()){
mLogger.log("Please provide the source to query for information",LogManager.ERROR_MESSAGE_LEVEL);
this.printShortVersion();
System.exit(1);
}
}
/**
* Generates valid LongOpts.
*
* @return LongOpt[]
*/
public LongOpt[] generateValidOptions() {
LongOpt[] longopts = new LongOpt[8];
longopts[0] = new LongOpt( "source", LongOpt.REQUIRED_ARGUMENT, null, '1' );
longopts[1] = new LongOpt( "grid", LongOpt.REQUIRED_ARGUMENT, null, 'g' );
longopts[2] = new LongOpt( "vo", LongOpt.REQUIRED_ARGUMENT, null, 'o' );
longopts[3] = new LongOpt( "sc", LongOpt.REQUIRED_ARGUMENT, null, 's' );
longopts[4] = new LongOpt( "version", LongOpt.NO_ARGUMENT, null, 'V' );
longopts[5] = new LongOpt( "verbose", LongOpt.NO_ARGUMENT, null, 'v' );
longopts[6] = new LongOpt( "help", LongOpt.NO_ARGUMENT, null, 'h' );
longopts[7] = new LongOpt( "properties", LongOpt.REQUIRED_ARGUMENT, null, 'p' );
return longopts;
}
}
| Related to JIRA PM-334
Adding --conf option.
| src/edu/isi/pegasus/planner/client/PegasusGetSites.java | Related to JIRA PM-334 | <ide><path>rc/edu/isi/pegasus/planner/client/PegasusGetSites.java
<ide> */
<ide> public PegasusGetSites(){
<ide> super();
<del> mLogMsg = new String();
<del> mVersion = Version.instance().toString();
<add> }
<add>
<add> /**
<add> * Initialize the PegasusGetSites object
<add> * @param opts the command line argument passed to the PegasusGetSites
<add> */
<add>
<add> public void intialize(String [] opts){
<add> super.initialize(opts);
<add> mLogMsg = new String();
<add> mVersion = Version.instance().toString();
<ide> }
<ide>
<ide> /**
<ide> double execTime = -1;
<ide>
<ide> try{
<del> me.executeCommand( args );
<add> me.initialize(args);
<add> me.executeCommand( );
<ide> }
<ide> catch ( RuntimeException rte ) {
<ide> //catch all runtime exceptions including our own that
<ide> text.append( "\n" ).append( "$Id$ ").
<ide> append( "\n" ).append( getGVDSVersion() ).
<ide> append( "\n" ).append( "Usage : pegasus-get-sites --source <source> --grid <grid> --vo <vo> --sc <filename> --properties <properties file>" ).
<del> append( "\n" ).append( "[-v] [-h]" ).
<add> append( "\n" ).append( "[--conf <path to property file>] [-v] [-h]" ).
<ide> append( "\n" ).
<ide> append( "\n Mandatory Options " ).
<ide> append( "\n --source the source to query for information. Valid sources are OSGMM|MYOSG|VORS" ).
<ide> append( "\n -o |--vo the virtual organization to which the user belongs " ).
<ide> append( "\n -s |--sc the path to the created site catalog file" ).
<ide> append( "\n -p |--properties the properties file to be created" ).
<add> append( "\n -c |--conf path to property file").
<ide> append( "\n -v |--verbose increases the verbosity of messages about what is going on" ).
<ide> append( "\n -V |--version displays the version of the Pegasus Workflow Management System" ).
<ide> append( "\n -h |--help generates this help." );
<ide> text.append( "\n" ).append( "$Id$ ").
<ide> append( "\n" ).append( getGVDSVersion() ).
<ide> append( "\n" ).append( "Usage : pegasus-get-sites -source <site> -g <grid> -o <vo> -s <filename> -p <filename>" ).
<del> append( "\n" ).append( "[-v] [-h]" );
<add> append( "\n" ).append( "[-c <path to property file>] [-v] [-h]" );
<ide>
<ide> System.out.println( text.toString() );
<ide> }
<ide> *
<ide> * @param args
<ide> */
<del> public void executeCommand(String[] args) {
<del> parseCommandLineArguments(args);
<add> public void executeCommand() {
<add> parseCommandLineArguments(getCommandLineOptions());
<ide> PegasusProperties p = PegasusProperties.nonSingletonInstance();
<ide>
<ide> p.setProperty( "pegasus.catalog.site", mSource );
<ide> public void parseCommandLineArguments(String[] args){
<ide> LongOpt[] longOptions = generateValidOptions();
<ide>
<del> Getopt g = new Getopt("pegasus-get-sites", args, "1:g:o:s:p:hvV", longOptions, false);
<add> Getopt g = new Getopt("pegasus-get-sites", args, "1:g:o:s:p:c:hvV", longOptions, false);
<ide> g.setOpterr(false);
<ide>
<ide> int option = 0;
<ide> case 'p': //--properties
<ide> mPropertiesFilename = g.getOptarg();
<ide> break;
<add>
<add> case 'c': // conf
<add> //do nothing
<add> break;
<ide>
<ide> case 'v': //--verbose
<ide> level++;
<ide> for( int i =0 ; i < args.length ; i++ )
<ide> System.out.println( args[i] );
<ide> throw new RuntimeException("Incorrect option or option usage " +
<del> option);
<add> (char)g.getOptopt());
<ide> }
<ide> }
<ide>
<ide> * @return LongOpt[]
<ide> */
<ide> public LongOpt[] generateValidOptions() {
<del> LongOpt[] longopts = new LongOpt[8];
<add> LongOpt[] longopts = new LongOpt[9];
<ide>
<ide> longopts[0] = new LongOpt( "source", LongOpt.REQUIRED_ARGUMENT, null, '1' );
<ide> longopts[1] = new LongOpt( "grid", LongOpt.REQUIRED_ARGUMENT, null, 'g' );
<ide> longopts[5] = new LongOpt( "verbose", LongOpt.NO_ARGUMENT, null, 'v' );
<ide> longopts[6] = new LongOpt( "help", LongOpt.NO_ARGUMENT, null, 'h' );
<ide> longopts[7] = new LongOpt( "properties", LongOpt.REQUIRED_ARGUMENT, null, 'p' );
<add> longopts[8] = new LongOpt( "conf", LongOpt.REQUIRED_ARGUMENT, null, 'c' );
<ide>
<ide> return longopts;
<ide> } |
|
JavaScript | mit | 6e4793180e199e30aa79105125f272296891028a | 0 | sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import Realm from 'realm';
import { createRecord } from '../utilities';
/**
* A batch of items.
*
* @property {string} id
* @property {Item} item
* @property {number} packSize
* @property {number} numberOfPacks
* @property {Date} expiryDate
* @property {string} batch
* @property {number} costPrice
* @property {number} sellPrice
* @property {Name} supplier
* @property {Name} donor
* @property {List.<TransactionBatch>} transactionBatches
*/
export class ItemBatch extends Realm.Object {
get isVaccine() {
return this.item?.isVaccine ?? false;
}
get hasBreached() {
return this.location?.hasBreached ?? false;
}
get breaches() {
return this.locationMovements?.reduce((acc, { breaches }) => [...acc, ...breaches], []) ?? [];
}
get currentVvmStatus() {
return this.vaccineVialMonitorStatusLogs.sorted('timestamp', true)[0];
}
get vvmStatusName() {
return this.currentVvmStatus?.description ?? '';
}
get otherPartyName() {
return this.supplier?.name || '';
}
/**
* Get the total number of items in this batch.
*
* @returns {number}
*/
get totalQuantity() {
return this.numberOfPacks * this.packSize;
}
/**
* Get the date this batch was added, equivalent to the confirm date
* of the earliest transaction batch this batch is associated with.
* @return {Date}
*/
get addedDate() {
return (
this.transactionBatches
.filtered('transaction.type == $0 && transaction.status != $1', 'supplier_invoice', 'new')
.sorted('transaction.confirmDate', false)[0]?.transaction?.confirmDate ?? new Date()
);
}
/**
* Get the id of the item this batch is associated with.
*
* @return {string}
*/
get itemId() {
return this.item ? this.item.id : '';
}
/**
* Get the name of the item this batch is associated with.
*
* @return {string}
*/
get itemName() {
return this.item ? this.item.name : '';
}
get itemCode() {
return this?.item?.code ?? '';
}
/**
* Set the total number of items in this batch.
*
* @param {number} quantity The total number of items in this batch, expressed as
* the product of the number of packs associated with the
* batch and the number of items contained in each pack.
*/
set totalQuantity(quantity) {
if (quantity < 0) {
throw new Error('Cannot set a negative item batch quantity');
}
this.numberOfPacks = this.packSize ? quantity / this.packSize : 0;
}
/**
* Add a transaction batch to be associated with this batch.
*
* @param {TransactionBatch} transactionBatch
*/
addTransactionBatch(transactionBatch) {
this.transactionBatches.push(transactionBatch);
}
/**
* Add a transaction batch to be associated with this batch, if not
* already added.
*
* @param {TransactionBatch} transactionBatch
*/
addTransactionBatchIfUnique(transactionBatch) {
if (this.transactionBatches.filtered('id == $0', transactionBatch.id).length > 0) return;
this.addTransactionBatch(transactionBatch);
}
/**
* Get string representation of batch.
*
* @return {string}
*/
toString() {
return `${this.itemName} - Batch ${this.batch}`;
}
/**
* @param {VaccineVialMonitorStatus} newVvmStatus
* @return {Bool} Indicator whether the new vvm status should be applied to this batch.
*/
shouldApplyVvmStatus(newVvmStatus = {}) {
return newVvmStatus?.id === this.currentVvmStatus?.id;
}
/**
* @param {Location} newLocation
* @return {Bool} Indicator whether the new location should be applied to this batch.
*/
shouldApplyLocation(newLocation = {}) {
return newLocation?.id === this.location?.id;
}
applyLocation(database, newLocation) {
this.location = newLocation;
return createRecord(database, 'LocationMovement', this, newLocation);
}
applyVvmStatus(database, newVvmStatus) {
return createRecord(database, 'VaccineVialMonitorStatusLog', this, newVvmStatus);
}
}
ItemBatch.schema = {
name: 'ItemBatch',
primaryKey: 'id',
properties: {
id: 'string',
item: { type: 'Item', optional: true },
packSize: { type: 'double', default: 1 },
numberOfPacks: { type: 'double', default: 0 },
expiryDate: { type: 'date', optional: true },
batch: { type: 'string', default: '' },
costPrice: { type: 'double', default: 0 },
sellPrice: { type: 'double', default: 0 },
supplier: { type: 'Name', optional: true },
donor: { type: 'Name', optional: true },
transactionBatches: { type: 'list', objectType: 'TransactionBatch' },
location: { type: 'Location', optional: true },
locationMovements: {
type: 'linkingObjects',
objectType: 'LocationMovement',
property: 'itemBatch',
},
doses: { type: 'double', default: 0 },
vaccineVialMonitorStatusLogs: {
type: 'linkingObjects',
objectType: 'VaccineVialMonitorStatusLog',
property: 'itemBatch',
},
},
};
export default ItemBatch;
| src/database/DataTypes/ItemBatch.js | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import Realm from 'realm';
import { createRecord } from '../utilities';
/**
* A batch of items.
*
* @property {string} id
* @property {Item} item
* @property {number} packSize
* @property {number} numberOfPacks
* @property {Date} expiryDate
* @property {string} batch
* @property {number} costPrice
* @property {number} sellPrice
* @property {Name} supplier
* @property {Name} donor
* @property {List.<TransactionBatch>} transactionBatches
*/
export class ItemBatch extends Realm.Object {
get isVaccine() {
return this.item?.isVaccine ?? false;
}
get hasBreached() {
return this.location?.hasBreached() ?? false;
}
get breaches() {
return this.locationMovements?.reduce((acc, { breaches }) => [...acc, ...breaches], []) ?? [];
}
get currentVvmStatus() {
return this.vaccineVialMonitorStatusLogs.sorted('timestamp', true)[0];
}
get vvmStatusName() {
return this.currentVvmStatus?.description ?? '';
}
get otherPartyName() {
return this.supplier?.name || '';
}
/**
* Get the total number of items in this batch.
*
* @returns {number}
*/
get totalQuantity() {
return this.numberOfPacks * this.packSize;
}
/**
* Get the date this batch was added, equivalent to the confirm date
* of the earliest transaction batch this batch is associated with.
* @return {Date}
*/
get addedDate() {
return (
this.transactionBatches
.filtered('transaction.type == $0 && transaction.status != $1', 'supplier_invoice', 'new')
.sorted('transaction.confirmDate', false)[0]?.transaction?.confirmDate ?? new Date()
);
}
/**
* Get the id of the item this batch is associated with.
*
* @return {string}
*/
get itemId() {
return this.item ? this.item.id : '';
}
/**
* Get the name of the item this batch is associated with.
*
* @return {string}
*/
get itemName() {
return this.item ? this.item.name : '';
}
get itemCode() {
return this?.item?.code ?? '';
}
/**
* Set the total number of items in this batch.
*
* @param {number} quantity The total number of items in this batch, expressed as
* the product of the number of packs associated with the
* batch and the number of items contained in each pack.
*/
set totalQuantity(quantity) {
if (quantity < 0) {
throw new Error('Cannot set a negative item batch quantity');
}
this.numberOfPacks = this.packSize ? quantity / this.packSize : 0;
}
/**
* Add a transaction batch to be associated with this batch.
*
* @param {TransactionBatch} transactionBatch
*/
addTransactionBatch(transactionBatch) {
this.transactionBatches.push(transactionBatch);
}
/**
* Add a transaction batch to be associated with this batch, if not
* already added.
*
* @param {TransactionBatch} transactionBatch
*/
addTransactionBatchIfUnique(transactionBatch) {
if (this.transactionBatches.filtered('id == $0', transactionBatch.id).length > 0) return;
this.addTransactionBatch(transactionBatch);
}
/**
* Get string representation of batch.
*
* @return {string}
*/
toString() {
return `${this.itemName} - Batch ${this.batch}`;
}
/**
* @param {VaccineVialMonitorStatus} newVvmStatus
* @return {Bool} Indicator whether the new vvm status should be applied to this batch.
*/
shouldApplyVvmStatus(newVvmStatus = {}) {
return newVvmStatus?.id === this.currentVvmStatus?.id;
}
/**
* @param {Location} newLocation
* @return {Bool} Indicator whether the new location should be applied to this batch.
*/
shouldApplyLocation(newLocation = {}) {
return newLocation?.id === this.location?.id;
}
applyLocation(database, newLocation) {
this.location = newLocation;
return createRecord(database, 'LocationMovement', this, newLocation);
}
applyVvmStatus(database, newVvmStatus) {
return createRecord(database, 'VaccineVialMonitorStatusLog', this, newVvmStatus);
}
}
ItemBatch.schema = {
name: 'ItemBatch',
primaryKey: 'id',
properties: {
id: 'string',
item: { type: 'Item', optional: true },
packSize: { type: 'double', default: 1 },
numberOfPacks: { type: 'double', default: 0 },
expiryDate: { type: 'date', optional: true },
batch: { type: 'string', default: '' },
costPrice: { type: 'double', default: 0 },
sellPrice: { type: 'double', default: 0 },
supplier: { type: 'Name', optional: true },
donor: { type: 'Name', optional: true },
transactionBatches: { type: 'list', objectType: 'TransactionBatch' },
location: { type: 'Location', optional: true },
locationMovements: {
type: 'linkingObjects',
objectType: 'LocationMovement',
property: 'itemBatch',
},
doses: { type: 'double', default: 0 },
vaccineVialMonitorStatusLogs: {
type: 'linkingObjects',
objectType: 'VaccineVialMonitorStatusLog',
property: 'itemBatch',
},
},
};
export default ItemBatch;
| Add itemBatch syntax typo
| src/database/DataTypes/ItemBatch.js | Add itemBatch syntax typo | <ide><path>rc/database/DataTypes/ItemBatch.js
<ide> }
<ide>
<ide> get hasBreached() {
<del> return this.location?.hasBreached() ?? false;
<add> return this.location?.hasBreached ?? false;
<ide> }
<ide>
<ide> get breaches() { |
|
Java | apache-2.0 | 61357a198d723b6953576dac50272ada15ef6a06 | 0 | abhishek4747/Tejas-git,abhishek4747/Tejas-git,abhishek4747/Tejas-git,abhishek4747/Tejas-git,abhishek4747/Tejas-git,abhishek4747/Tejas-git | package pipeline;
import generic.GenericCircularQueue;
import generic.GlobalClock;
import generic.Instruction;
import generic.Operand;
import generic.Statistics;
import java.lang.reflect.Array;
import main.ArchitecturalComponent;
import main.Main;
import config.XMLParser;
public class PipelineTests {
static String configFileName;
static GenericCircularQueue<Instruction> inputToPipeline;
static final int INSTRUCTION_THRESHOLD = 2000;
public static void setUpBeforeClass(String configFile) {
// Parse the command line arguments
XMLParser.parse(configFile);
// initialize object pools
Main.initializeObjectPools();
// initialize cores, memory, tokenBus
ArchitecturalComponent.createChip();
inputToPipeline = new GenericCircularQueue<Instruction>(
Instruction.class, INSTRUCTION_THRESHOLD);
GenericCircularQueue<Instruction>[] toBeSet = (GenericCircularQueue<Instruction>[]) Array
.newInstance(GenericCircularQueue.class, 1);
toBeSet[0] = inputToPipeline;
ArchitecturalComponent.getCore(0).getPipelineInterface()
.setInputToPipeline(toBeSet);
ArchitecturalComponent.getCore(0).currentThreads = 1;
ArchitecturalComponent.getCore(0).getExecEngine()
.setExecutionBegun(true);
// Initialize the statistics
Statistics.initStatistics();
}
/*
* simulates a sequence of intALU instructions that have no data
* dependencies
*/
public static void minimumDataDependencies() {
// generate instruction sequence
Instruction newInst;
int temp = 1;
for (int i = 0; i < 100; i++) {
temp++;
if (temp % 16 == 0) {
temp++;
}
newInst = Instruction.getIntALUInstruction(
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(temp % 16));
newInst.setCISCProgramCounter(i);
inputToPipeline.enqueue(newInst);
}
inputToPipeline.enqueue(Instruction.getInvalidInstruction());
// simulate pipeline
while (ArchitecturalComponent.getCores()[0].getPipelineInterface()
.isExecutionComplete() == false) {
ArchitecturalComponent.getCores()[0].getPipelineInterface()
.oneCycleOperation();
GlobalClock.incrementClock();
}
}
/*
* simulates a sequence of intALU instructions, with (i+1)th instruction
* dependent on ith
*/
public static void maximumDataDependencies() {
// generate instruction sequence
Instruction newInst;
for (int i = 0; i < 100; i++) {
newInst = Instruction.getIntALUInstruction(
Operand.getIntegerRegister(i % 16),
Operand.getIntegerRegister(i % 16),
Operand.getIntegerRegister((i + 1) % 16));
inputToPipeline.enqueue(newInst);
}
inputToPipeline.enqueue(Instruction.getInvalidInstruction());
// simulate pipeline
while (ArchitecturalComponent.getCores()[0].getPipelineInterface()
.isExecutionComplete() == false) {
ArchitecturalComponent.getCores()[0].getPipelineInterface()
.oneCycleOperation();
GlobalClock.incrementClock();
}
}
/*
* simulates a sequence of floatDiv instructions, with no data dependencies
*/
public static void structuralHazards() {
// generate instruction sequence
Instruction newInst;
int temp = 1;
for (int i = 0; i < 100; i++) {
temp++;
if (temp % 16 == 0) {
temp++;
}
newInst = Instruction.getFloatingPointDivision(
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(temp % 16));
inputToPipeline.enqueue(newInst);
}
inputToPipeline.enqueue(Instruction.getInvalidInstruction());
// simulate pipeline
while (ArchitecturalComponent.getCores()[0].getPipelineInterface()
.isExecutionComplete() == false) {
ArchitecturalComponent.getCores()[0].getPipelineInterface()
.oneCycleOperation();
GlobalClock.incrementClock();
}
}
/*
* simulates a sequence of floatDiv instructions, all operating on R0, and
* writing to R0
*/
public static void renameTest() {
// generate instruction sequence
Instruction newInst;
for (int i = 0; i < 100; i++) {
newInst = Instruction.getFloatingPointDivision(
Operand.getFloatRegister(0), Operand.getFloatRegister(0),
Operand.getFloatRegister(0));
inputToPipeline.enqueue(newInst);
}
inputToPipeline.enqueue(Instruction.getInvalidInstruction());
// simulate pipeline
while (ArchitecturalComponent.getCores()[0].getPipelineInterface()
.isExecutionComplete() == false) {
ArchitecturalComponent.getCores()[0].getPipelineInterface()
.oneCycleOperation();
GlobalClock.incrementClock();
}
}
public static void loadStoreTest() {
Instruction inst;
for (int i = 0; i < 100; i++) {
inst = Instruction
.getStoreInstruction(
Operand.getMemoryOperand(
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(1)),
Operand.getFloatRegister(0));
inputToPipeline.enqueue(inst);
inst = Instruction
.getLoadInstruction(
Operand.getMemoryOperand(
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(1)),
Operand.getFloatRegister(0));
inputToPipeline.enqueue(inst);
}
inputToPipeline.enqueue(Instruction.getInvalidInstruction());
// simulate pipeline
while (ArchitecturalComponent.getCores()[0].getPipelineInterface()
.isExecutionComplete() == false) {
ArchitecturalComponent.getCores()[0].getPipelineInterface()
.oneCycleOperation();
GlobalClock.incrementClock();
}
}
public static void loadTest() {
Instruction inst;
for (int i = 0; i < 100; i++) {
inst = Instruction
.getLoadInstruction(
Operand.getMemoryOperand(
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(1)),
Operand.getFloatRegister(0));
inst.setCISCProgramCounter(i);
inputToPipeline.enqueue(inst);
}
inputToPipeline.enqueue(Instruction.getInvalidInstruction());
// simulate pipeline
while (ArchitecturalComponent.getCores()[0].getPipelineInterface()
.isExecutionComplete() == false) {
ArchitecturalComponent.getCores()[0].getPipelineInterface()
.oneCycleOperation();
GlobalClock.incrementClock();
}
}
public static void storeTest() {
Instruction inst;
for (int i = 0; i < 100; i++) {
inst = Instruction
.getStoreInstruction(
Operand.getMemoryOperand(
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(1)),
Operand.getFloatRegister(0));
inputToPipeline.enqueue(inst);
}
inputToPipeline.enqueue(Instruction.getInvalidInstruction());
// simulate pipeline
while (ArchitecturalComponent.getCores()[0].getPipelineInterface()
.isExecutionComplete() == false) {
ArchitecturalComponent.getCores()[0].getPipelineInterface()
.oneCycleOperation();
GlobalClock.incrementClock();
}
}
public static void main(String[] arguments) {
String configFile = arguments[0];
int testType = Integer.parseInt(arguments[1]);
setUpBeforeClass(configFile);
switch (testType) {
case 0:
minimumDataDependencies();
break;
case 1:
maximumDataDependencies();
break;
case 2:
structuralHazards();
break;
case 3:
renameTest();
break;
case 4:
loadTest();
break;
case 5:
storeTest();
break;
case 6:
loadStoreTest();
break;
default:
misc.Error.showErrorAndExit("unknown test type");
}
System.out.println("Tests completed!!");
}
}
| src/simulator/pipeline/PipelineTests.java | package pipeline;
import generic.GenericCircularQueue;
import generic.GlobalClock;
import generic.Instruction;
import generic.Operand;
import generic.Statistics;
import java.lang.reflect.Array;
import main.ArchitecturalComponent;
import main.Main;
import config.XMLParser;
public class PipelineTests {
static String configFileName;
static GenericCircularQueue<Instruction> inputToPipeline;
static final int INSTRUCTION_THRESHOLD = 2000;
public static void setUpBeforeClass(String configFile) {
// Parse the command line arguments
XMLParser.parse(configFile);
// initialize object pools
Main.initializeObjectPools();
// initialize cores, memory, tokenBus
ArchitecturalComponent.createChip();
inputToPipeline = new GenericCircularQueue<Instruction>(
Instruction.class, INSTRUCTION_THRESHOLD);
GenericCircularQueue<Instruction>[] toBeSet = (GenericCircularQueue<Instruction>[]) Array
.newInstance(GenericCircularQueue.class, 1);
toBeSet[0] = inputToPipeline;
ArchitecturalComponent.getCore(0).getPipelineInterface()
.setInputToPipeline(toBeSet);
ArchitecturalComponent.getCore(0).currentThreads = 1;
ArchitecturalComponent.getCore(0).getExecEngine()
.setExecutionBegun(true);
// Initialize the statistics
Statistics.initStatistics();
}
/*
* simulates a sequence of intALU instructions that have no data
* dependencies
*/
public static void minimumDataDependencies() {
// generate instruction sequence
Instruction newInst;
int temp = 1;
for (int i = 0; i < 100; i++) {
temp++;
if (temp % 16 == 0) {
temp++;
}
newInst = Instruction.getIntALUInstruction(
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(temp % 16));
newInst.setCISCProgramCounter(i);
inputToPipeline.enqueue(newInst);
}
inputToPipeline.enqueue(Instruction.getInvalidInstruction());
// simulate pipeline
while (ArchitecturalComponent.getCores()[0].getPipelineInterface()
.isExecutionComplete() == false) {
ArchitecturalComponent.getCores()[0].getPipelineInterface()
.oneCycleOperation();
GlobalClock.incrementClock();
}
}
/*
* simulates a sequence of intALU instructions, with (i+1)th instruction
* dependent on ith
*/
public static void maximumDataDependencies() {
// generate instruction sequence
Instruction newInst;
for (int i = 0; i < 100; i++) {
newInst = Instruction.getIntALUInstruction(
Operand.getIntegerRegister(i % 16),
Operand.getIntegerRegister(i % 16),
Operand.getIntegerRegister((i + 1) % 16));
inputToPipeline.enqueue(newInst);
}
inputToPipeline.enqueue(Instruction.getInvalidInstruction());
// simulate pipeline
while (ArchitecturalComponent.getCores()[0].getPipelineInterface()
.isExecutionComplete() == false) {
ArchitecturalComponent.getCores()[0].getPipelineInterface()
.oneCycleOperation();
GlobalClock.incrementClock();
}
}
/*
* simulates a sequence of floatDiv instructions, with no data dependencies
*/
public static void structuralHazards() {
// generate instruction sequence
Instruction newInst;
int temp = 1;
for (int i = 0; i < 100; i++) {
temp++;
if (temp % 16 == 0) {
temp++;
}
newInst = Instruction.getFloatingPointDivision(
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(temp % 16));
inputToPipeline.enqueue(newInst);
}
inputToPipeline.enqueue(Instruction.getInvalidInstruction());
// simulate pipeline
while (ArchitecturalComponent.getCores()[0].getPipelineInterface()
.isExecutionComplete() == false) {
ArchitecturalComponent.getCores()[0].getPipelineInterface()
.oneCycleOperation();
GlobalClock.incrementClock();
}
}
/*
* simulates a sequence of floatDiv instructions, all operating on R0, and
* writing to R0
*/
public static void renameTest() {
// generate instruction sequence
Instruction newInst;
for (int i = 0; i < 100; i++) {
newInst = Instruction.getFloatingPointDivision(
Operand.getFloatRegister(0), Operand.getFloatRegister(0),
Operand.getFloatRegister(0));
inputToPipeline.enqueue(newInst);
}
inputToPipeline.enqueue(Instruction.getInvalidInstruction());
// simulate pipeline
while (ArchitecturalComponent.getCores()[0].getPipelineInterface()
.isExecutionComplete() == false) {
ArchitecturalComponent.getCores()[0].getPipelineInterface()
.oneCycleOperation();
GlobalClock.incrementClock();
}
}
public static void loadStoreTest() {
Instruction inst;
for (int i = 0; i < 100; i++) {
inst = Instruction
.getStoreInstruction(
Operand.getMemoryOperand(
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(1)),
Operand.getFloatRegister(0));
inputToPipeline.enqueue(inst);
inst = Instruction
.getLoadInstruction(
Operand.getMemoryOperand(
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(1)),
Operand.getFloatRegister(0));
inputToPipeline.enqueue(inst);
}
inputToPipeline.enqueue(Instruction.getInvalidInstruction());
// simulate pipeline
while (ArchitecturalComponent.getCores()[0].getPipelineInterface()
.isExecutionComplete() == false) {
ArchitecturalComponent.getCores()[0].getPipelineInterface()
.oneCycleOperation();
GlobalClock.incrementClock();
}
}
public static void loadTest() {
Instruction inst;
for (int i = 0; i < 100; i++) {
inst = Instruction
.getLoadInstruction(
Operand.getMemoryOperand(
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(1)),
Operand.getFloatRegister(0));
inputToPipeline.enqueue(inst);
}
inputToPipeline.enqueue(Instruction.getInvalidInstruction());
// simulate pipeline
while (ArchitecturalComponent.getCores()[0].getPipelineInterface()
.isExecutionComplete() == false) {
ArchitecturalComponent.getCores()[0].getPipelineInterface()
.oneCycleOperation();
GlobalClock.incrementClock();
}
}
public static void storeTest() {
Instruction inst;
for (int i = 0; i < 100; i++) {
inst = Instruction
.getStoreInstruction(
Operand.getMemoryOperand(
Operand.getIntegerRegister(0),
Operand.getIntegerRegister(1)),
Operand.getFloatRegister(0));
inputToPipeline.enqueue(inst);
}
inputToPipeline.enqueue(Instruction.getInvalidInstruction());
// simulate pipeline
while (ArchitecturalComponent.getCores()[0].getPipelineInterface()
.isExecutionComplete() == false) {
ArchitecturalComponent.getCores()[0].getPipelineInterface()
.oneCycleOperation();
GlobalClock.incrementClock();
}
}
public static void main(String[] arguments) {
String configFile = arguments[0];
int testType = Integer.parseInt(arguments[1]);
setUpBeforeClass(configFile);
switch (testType) {
case 0:
minimumDataDependencies();
break;
case 1:
maximumDataDependencies();
break;
case 2:
structuralHazards();
break;
case 3:
renameTest();
break;
case 4:
loadTest();
break;
case 5:
storeTest();
break;
case 6:
loadStoreTest();
break;
default:
misc.Error.showErrorAndExit("unknown test type");
}
System.out.println("Tests completed!!");
}
}
| set IP
| src/simulator/pipeline/PipelineTests.java | set IP | <ide><path>rc/simulator/pipeline/PipelineTests.java
<ide> Operand.getIntegerRegister(0),
<ide> Operand.getIntegerRegister(1)),
<ide> Operand.getFloatRegister(0));
<add> inst.setCISCProgramCounter(i);
<ide> inputToPipeline.enqueue(inst);
<ide> }
<ide> |
|
Java | apache-2.0 | ccd23e71f2ee03be0c5346e8337b0d2ba4a778f3 | 0 | mikeb01/Aeron,mikeb01/Aeron,mikeb01/Aeron,mikeb01/Aeron | /*
* Copyright 2014-2021 Real Logic Limited.
*
* 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
*
* https://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 io.aeron.agent;
import io.aeron.Counter;
import io.aeron.archive.Archive;
import io.aeron.archive.ArchiveThreadingMode;
import io.aeron.archive.client.AeronArchive;
import io.aeron.cluster.*;
import io.aeron.cluster.service.*;
import io.aeron.driver.MediaDriver.Context;
import io.aeron.driver.ThreadingMode;
import io.aeron.test.Tests;
import org.agrona.CloseHelper;
import org.agrona.IoUtil;
import org.agrona.MutableDirectBuffer;
import org.agrona.concurrent.*;
import org.junit.jupiter.api.*;
import java.io.File;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import static io.aeron.agent.ClusterEventCode.*;
import static io.aeron.agent.ClusterEventLogger.toEventCodeId;
import static io.aeron.agent.CommonEventEncoder.LOG_HEADER_LENGTH;
import static io.aeron.agent.EventConfiguration.EVENT_READER_FRAME_LIMIT;
import static io.aeron.agent.EventConfiguration.EVENT_RING_BUFFER;
import static java.util.Collections.synchronizedSet;
import static java.util.stream.Collectors.toSet;
import static org.agrona.BitUtil.SIZE_OF_INT;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
public class ClusterLoggingAgentTest
{
private static final Set<Integer> LOGGED_EVENTS = synchronizedSet(new HashSet<>());
private static final AtomicInteger CLUSTER_EVENTS_LOGGED = new AtomicInteger();
private File testDir;
private ClusteredMediaDriver clusteredMediaDriver;
private ClusteredServiceContainer container;
@AfterEach
public void after()
{
CloseHelper.closeAll(clusteredMediaDriver.consensusModule(), container, clusteredMediaDriver);
AgentTests.afterAgent();
if (testDir != null && testDir.exists())
{
IoUtil.delete(testDir, false);
}
}
@Test
@Timeout(20)
public void logAll()
{
testClusterEventsLogging("all", EnumSet.of(ROLE_CHANGE, STATE_CHANGE, ELECTION_STATE_CHANGE));
}
@Test
@Timeout(20)
public void logRoleChange()
{
testClusterEventsLogging(ROLE_CHANGE.name(), EnumSet.of(ROLE_CHANGE));
}
@Test
@Timeout(20)
public void logStateChange()
{
testClusterEventsLogging(STATE_CHANGE.name(), EnumSet.of(STATE_CHANGE));
}
@Test
@Timeout(20)
public void logElectionStateChange()
{
testClusterEventsLogging(ELECTION_STATE_CHANGE.name(), EnumSet.of(ELECTION_STATE_CHANGE));
}
private void testClusterEventsLogging(
final String enabledEvents, final EnumSet<ClusterEventCode> expectedEvents)
{
before(enabledEvents);
final Context mediaDriverCtx = new Context()
.errorHandler(Tests::onError)
.dirDeleteOnStart(true)
.threadingMode(ThreadingMode.SHARED);
final AeronArchive.Context aeronArchiveContext = new AeronArchive.Context()
.controlRequestChannel("aeron:ipc?term-length=64k")
.controlRequestStreamId(AeronArchive.Configuration.localControlStreamId())
.controlResponseChannel("aeron:ipc?term-length=64k")
.controlResponseStreamId(AeronArchive.Configuration.localControlStreamId() + 1)
.controlResponseStreamId(101);
final Archive.Context archiveCtx = new Archive.Context()
.errorHandler(Tests::onError)
.archiveDir(new File(testDir, "archive"))
.deleteArchiveOnStart(true)
.recordingEventsEnabled(false)
.threadingMode(ArchiveThreadingMode.SHARED);
final ConsensusModule.Context consensusModuleCtx = new ConsensusModule.Context()
.errorHandler(Tests::onError)
.clusterDir(new File(testDir, "consensus-module"))
.archiveContext(aeronArchiveContext.clone())
.clusterMemberId(0)
.clusterMembers("0,localhost:20110,localhost:20220,localhost:20330,localhost:20440,localhost:8010")
.logChannel("aeron:udp?term-length=256k|control-mode=manual|control=localhost:20550");
final ClusteredService clusteredService = mock(ClusteredService.class);
final ClusteredServiceContainer.Context clusteredServiceCtx = new ClusteredServiceContainer.Context()
.errorHandler(Tests::onError)
.archiveContext(aeronArchiveContext.clone())
.clusterDir(new File(testDir, "service"))
.clusteredService(clusteredService);
clusteredMediaDriver = ClusteredMediaDriver.launch(mediaDriverCtx, archiveCtx, consensusModuleCtx);
container = ClusteredServiceContainer.launch(clusteredServiceCtx);
final int numberOfExpectedEvents = expectedEvents.size();
Tests.await(() -> numberOfExpectedEvents == CLUSTER_EVENTS_LOGGED.get());
final Counter state = clusteredMediaDriver.consensusModule().context().electionStateCounter();
while (ElectionState.CLOSED != ElectionState.get(state))
{
Tests.sleep(1);
}
final Set<Integer> expected = expectedEvents
.stream()
.map(ClusterEventLogger::toEventCodeId)
.collect(toSet());
assertTrue(LOGGED_EVENTS.containsAll(expected));
}
private void before(final String enabledEvents)
{
System.setProperty(EventLogAgent.READER_CLASSNAME_PROP_NAME, StubEventLogReaderAgent.class.getName());
System.setProperty(EventConfiguration.ENABLED_CLUSTER_EVENT_CODES_PROP_NAME, enabledEvents);
AgentTests.beforeAgent();
LOGGED_EVENTS.clear();
CLUSTER_EVENTS_LOGGED.set(0);
testDir = new File(IoUtil.tmpDirName(), "cluster-test");
if (testDir.exists())
{
IoUtil.delete(testDir, false);
}
}
static final class StubEventLogReaderAgent implements Agent, MessageHandler
{
public String roleName()
{
return "event-log-reader";
}
public int doWork()
{
return EVENT_RING_BUFFER.read(this, EVENT_READER_FRAME_LIMIT);
}
public void onMessage(final int msgTypeId, final MutableDirectBuffer buffer, final int index, final int length)
{
LOGGED_EVENTS.add(msgTypeId);
final int offset = LOG_HEADER_LENGTH + index + SIZE_OF_INT;
if (toEventCodeId(ROLE_CHANGE) == msgTypeId)
{
final String roleChange = buffer.getStringAscii(offset);
if (roleChange.contains("LEADER"))
{
CLUSTER_EVENTS_LOGGED.getAndIncrement();
}
}
else if (toEventCodeId(STATE_CHANGE) == msgTypeId)
{
final String stateChange = buffer.getStringAscii(offset);
if (stateChange.contains("ACTIVE"))
{
CLUSTER_EVENTS_LOGGED.getAndIncrement();
}
}
else if (toEventCodeId(ELECTION_STATE_CHANGE) == msgTypeId)
{
final String stateChange = buffer.getStringAscii(offset);
if (stateChange.contains("CLOSED"))
{
CLUSTER_EVENTS_LOGGED.getAndIncrement();
}
}
}
}
}
| aeron-agent/src/test/java/io/aeron/agent/ClusterLoggingAgentTest.java | /*
* Copyright 2014-2021 Real Logic Limited.
*
* 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
*
* https://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 io.aeron.agent;
import io.aeron.Counter;
import io.aeron.archive.Archive;
import io.aeron.archive.ArchiveThreadingMode;
import io.aeron.archive.client.AeronArchive;
import io.aeron.cluster.*;
import io.aeron.cluster.service.*;
import io.aeron.driver.MediaDriver.Context;
import io.aeron.driver.ThreadingMode;
import io.aeron.test.Tests;
import org.agrona.CloseHelper;
import org.agrona.IoUtil;
import org.agrona.MutableDirectBuffer;
import org.agrona.concurrent.*;
import org.junit.jupiter.api.*;
import java.io.File;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import static io.aeron.agent.ClusterEventCode.*;
import static io.aeron.agent.ClusterEventLogger.toEventCodeId;
import static io.aeron.agent.CommonEventEncoder.LOG_HEADER_LENGTH;
import static io.aeron.agent.EventConfiguration.EVENT_READER_FRAME_LIMIT;
import static io.aeron.agent.EventConfiguration.EVENT_RING_BUFFER;
import static java.util.Collections.synchronizedSet;
import static java.util.stream.Collectors.toSet;
import static org.agrona.BitUtil.SIZE_OF_INT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
public class ClusterLoggingAgentTest
{
private static final Set<Integer> LOGGED_EVENTS = synchronizedSet(new HashSet<>());
private static final AtomicInteger CLUSTER_EVENTS_LOGGED = new AtomicInteger();
private File testDir;
private ClusteredMediaDriver clusteredMediaDriver;
private ClusteredServiceContainer container;
@AfterEach
public void after()
{
CloseHelper.closeAll(clusteredMediaDriver.consensusModule(), container, clusteredMediaDriver);
AgentTests.afterAgent();
if (testDir != null && testDir.exists())
{
IoUtil.delete(testDir, false);
}
}
@Test
@Timeout(20)
public void logAll()
{
testClusterEventsLogging("all", EnumSet.of(ROLE_CHANGE, STATE_CHANGE, ELECTION_STATE_CHANGE));
}
@Test
@Timeout(20)
public void logRoleChange()
{
testClusterEventsLogging(ROLE_CHANGE.name(), EnumSet.of(ROLE_CHANGE));
}
@Test
@Timeout(20)
public void logStateChange()
{
testClusterEventsLogging(STATE_CHANGE.name(), EnumSet.of(STATE_CHANGE));
}
@Test
@Timeout(20)
public void logElectionStateChange()
{
testClusterEventsLogging(ELECTION_STATE_CHANGE.name(), EnumSet.of(ELECTION_STATE_CHANGE));
}
private void testClusterEventsLogging(
final String enabledEvents, final EnumSet<ClusterEventCode> expectedEvents)
{
before(enabledEvents);
final Context mediaDriverCtx = new Context()
.errorHandler(Tests::onError)
.dirDeleteOnStart(true)
.threadingMode(ThreadingMode.SHARED);
final AeronArchive.Context aeronArchiveContext = new AeronArchive.Context()
.controlRequestChannel("aeron:ipc?term-length=64k")
.controlRequestStreamId(AeronArchive.Configuration.localControlStreamId())
.controlResponseChannel("aeron:ipc?term-length=64k")
.controlResponseStreamId(AeronArchive.Configuration.localControlStreamId() + 1)
.controlResponseStreamId(101);
final Archive.Context archiveCtx = new Archive.Context()
.errorHandler(Tests::onError)
.archiveDir(new File(testDir, "archive"))
.deleteArchiveOnStart(true)
.recordingEventsEnabled(false)
.threadingMode(ArchiveThreadingMode.SHARED);
final ConsensusModule.Context consensusModuleCtx = new ConsensusModule.Context()
.errorHandler(Tests::onError)
.clusterDir(new File(testDir, "consensus-module"))
.archiveContext(aeronArchiveContext.clone())
.clusterMemberId(0)
.clusterMembers("0,localhost:20110,localhost:20220,localhost:20330,localhost:20440,localhost:8010")
.logChannel("aeron:udp?term-length=256k|control-mode=manual|control=localhost:20550");
final ClusteredService clusteredService = mock(ClusteredService.class);
final ClusteredServiceContainer.Context clusteredServiceCtx = new ClusteredServiceContainer.Context()
.errorHandler(Tests::onError)
.archiveContext(aeronArchiveContext.clone())
.clusterDir(new File(testDir, "service"))
.clusteredService(clusteredService);
clusteredMediaDriver = ClusteredMediaDriver.launch(mediaDriverCtx, archiveCtx, consensusModuleCtx);
container = ClusteredServiceContainer.launch(clusteredServiceCtx);
final int numberOfExpectedEvents = expectedEvents.size();
Tests.await(() -> numberOfExpectedEvents == CLUSTER_EVENTS_LOGGED.get());
final Counter state = clusteredMediaDriver.consensusModule().context().electionStateCounter();
while (ElectionState.CLOSED != ElectionState.get(state))
{
Tests.sleep(1);
}
final Set<Integer> expected = expectedEvents
.stream()
.map(ClusterEventLogger::toEventCodeId)
.collect(toSet());
assertEquals(expected, LOGGED_EVENTS);
}
private void before(final String enabledEvents)
{
System.setProperty(EventLogAgent.READER_CLASSNAME_PROP_NAME, StubEventLogReaderAgent.class.getName());
System.setProperty(EventConfiguration.ENABLED_CLUSTER_EVENT_CODES_PROP_NAME, enabledEvents);
AgentTests.beforeAgent();
LOGGED_EVENTS.clear();
CLUSTER_EVENTS_LOGGED.set(0);
testDir = new File(IoUtil.tmpDirName(), "cluster-test");
if (testDir.exists())
{
IoUtil.delete(testDir, false);
}
}
static final class StubEventLogReaderAgent implements Agent, MessageHandler
{
public String roleName()
{
return "event-log-reader";
}
public int doWork()
{
return EVENT_RING_BUFFER.read(this, EVENT_READER_FRAME_LIMIT);
}
public void onMessage(final int msgTypeId, final MutableDirectBuffer buffer, final int index, final int length)
{
LOGGED_EVENTS.add(msgTypeId);
final int offset = LOG_HEADER_LENGTH + index + SIZE_OF_INT;
if (toEventCodeId(ROLE_CHANGE) == msgTypeId)
{
final String roleChange = buffer.getStringAscii(offset);
if (roleChange.contains("LEADER"))
{
CLUSTER_EVENTS_LOGGED.getAndIncrement();
}
}
else if (toEventCodeId(STATE_CHANGE) == msgTypeId)
{
final String stateChange = buffer.getStringAscii(offset);
if (stateChange.contains("ACTIVE"))
{
CLUSTER_EVENTS_LOGGED.getAndIncrement();
}
}
else if (toEventCodeId(ELECTION_STATE_CHANGE) == msgTypeId)
{
final String stateChange = buffer.getStringAscii(offset);
if (stateChange.contains("CLOSED"))
{
CLUSTER_EVENTS_LOGGED.getAndIncrement();
}
}
}
}
}
| [Java] Do a containsAll check rather than equals for set of expected logging events.
| aeron-agent/src/test/java/io/aeron/agent/ClusterLoggingAgentTest.java | [Java] Do a containsAll check rather than equals for set of expected logging events. | <ide><path>eron-agent/src/test/java/io/aeron/agent/ClusterLoggingAgentTest.java
<ide> import static java.util.Collections.synchronizedSet;
<ide> import static java.util.stream.Collectors.toSet;
<ide> import static org.agrona.BitUtil.SIZE_OF_INT;
<del>import static org.junit.jupiter.api.Assertions.assertEquals;
<add>import static org.junit.jupiter.api.Assertions.assertTrue;
<ide> import static org.mockito.Mockito.mock;
<ide>
<ide> public class ClusterLoggingAgentTest
<ide> .map(ClusterEventLogger::toEventCodeId)
<ide> .collect(toSet());
<ide>
<del> assertEquals(expected, LOGGED_EVENTS);
<add> assertTrue(LOGGED_EVENTS.containsAll(expected));
<ide> }
<ide>
<ide> private void before(final String enabledEvents) |
|
Java | apache-2.0 | 492be19f16979ec0de7ebdce195b39e8c4172e05 | 0 | HPSoftware/ppm-octane-connector,HPSoftware/ppm-octane-connector | package com.ppm.integration.agilesdk.connector.octane;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.wink.client.ClientRuntimeException;
import com.hp.ppm.tm.model.TimeSheet;
import com.ppm.integration.agilesdk.ValueSet;
import com.ppm.integration.agilesdk.connector.octane.client.ClientPublicAPI;
import com.ppm.integration.agilesdk.connector.octane.client.OctaneClientException;
import com.ppm.integration.agilesdk.connector.octane.client.OctaneClientHelper;
import com.ppm.integration.agilesdk.connector.octane.client.OctaneConnectivityExceptionHandler;
import com.ppm.integration.agilesdk.connector.octane.model.SharedSpace;
import com.ppm.integration.agilesdk.connector.octane.model.TimesheetItem;
import com.ppm.integration.agilesdk.connector.octane.model.WorkSpace;
import com.ppm.integration.agilesdk.provider.Providers;
import com.ppm.integration.agilesdk.tm.AuthenticationInfo;
import com.ppm.integration.agilesdk.tm.ExternalWorkItem;
import com.ppm.integration.agilesdk.tm.ExternalWorkItemEffortBreakdown;
import com.ppm.integration.agilesdk.tm.TimeSheetIntegration;
import com.ppm.integration.agilesdk.tm.TimeSheetIntegrationContext;
import com.ppm.integration.agilesdk.tm.TimeSheetLineAgileEntityInfo;
import com.ppm.integration.agilesdk.ui.Field;
import com.ppm.integration.agilesdk.ui.LineBreaker;
import com.ppm.integration.agilesdk.ui.Link;
import com.ppm.integration.agilesdk.ui.SelectList;
public class OctaneTimeSheetIntegration extends TimeSheetIntegration {
private final Logger logger = Logger.getLogger(this.getClass());
static final String SEP = ">";
protected synchronized String convertDate(Date date) {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.format(date);
} catch (Exception e) {
logger.error(e.getMessage());
}
return "";
}
@Override public List<Field> getMappingConfigurationFields(ValueSet paramValueSet) {
return Arrays.asList(new Field[] {
new Link("auth", "AUTHENTICATION_LINK", "defaultValue", "true", true, "javascript:void(0);",
"openSSOLink()"),
new LineBreaker(),
new SelectList(OctaneConstants.TS_GROUP_BY,"TS_GROUP_BY",OctaneConstants.TS_GROUP_BY_RELEASE,true)
.addLevel(OctaneConstants.TS_GROUP_BY, "TS_GROUP_BY")
.addOption(new SelectList.Option(OctaneConstants.TS_GROUP_BY_WORKSPACE,"TS_GROUP_BY_WORKSPACE"))
.addOption(new SelectList.Option(OctaneConstants.TS_GROUP_BY_RELEASE,"TS_GROUP_BY_RELEASE"))
.addOption(new SelectList.Option(OctaneConstants.TS_GROUP_BY_BACKLOG_ITEM,"TS_GROUP_BY_BACKLOG_ITEM"))
});
}
@Override public List<ExternalWorkItem> getExternalWorkItems(TimeSheetIntegrationContext context,
final ValueSet values)
{
List<ExternalWorkItem> items = null;
try {
items = getExternalWorkItemsByTasks(context, values);
} catch (ParseException e) {
logger.error(e.getMessage());
}
return items;
}
@Override
public String getSSOurl(ValueSet values) {
ClientPublicAPI clientP = OctaneClientHelper.setupClientPublicAPI(values);
return clientP.getSSOURL();
}
@Override
public AuthenticationInfo getAuthenticationInfo(ValueSet values, String identifier) {
ClientPublicAPI clientP = OctaneClientHelper.setupClientPublicAPI(values);
AuthenticationInfo userInfo = clientP.getSSOAuthentication(identifier);
return userInfo;
}
public List<ExternalWorkItem> getExternalWorkItemsByTasks(TimeSheetIntegrationContext context,
final ValueSet values) throws ParseException
{
final List<ExternalWorkItem> timesheetLines = Collections.synchronizedList(new LinkedList<ExternalWorkItem>());
try {
TimeSheet currentTimeSheet = context.currentTimeSheet();
final String startDate = convertDate(currentTimeSheet.getPeriodStartDate().toGregorianCalendar().getTime());
final String endDate = convertDate(currentTimeSheet.getPeriodEndDate().toGregorianCalendar().getTime());
ClientPublicAPI clientP = OctaneClientHelper.setupClientPublicAPI(values);
String identifier = values.get(OctaneConstants.SSO_IDENTIFIER);
if (identifier == null) {
throw new OctaneClientException("OCTANE_APP", "LOSE_AUTHORIZE_IDENTIFIER");
}
AuthenticationInfo userInfo = clientP.getSSOAuthentication(identifier);
if (userInfo == null) {
throw new OctaneClientException("OCTANE_APP", "FAIL_TO_RETRIEVE_USER_INFO");
}
String clientId = values.get(OctaneConstants.APP_CLIENT_ID);
String clientSecret = values.get(OctaneConstants.APP_CLIENT_SECRET);
String groupBy = values.get(OctaneConstants.TS_GROUP_BY);
if (clientP.getAccessTokenWithFormFormat(clientId, clientSecret)) {
List<SharedSpace> shareSpaces = clientP.getSharedSpaces();
for (SharedSpace shareSpace : shareSpaces) {
List<WorkSpace> workspaces = clientP.getWorkSpaces(Integer.parseInt(shareSpace.id));
for (WorkSpace workSpace : workspaces) {
List<TimesheetItem> timeSheets = clientP.getTimeSheetData(Integer.parseInt(shareSpace.id),
userInfo.getLoginName(), startDate.toString(), endDate.toString(),
Integer.parseInt(workSpace.id));
if (timeSheets == null || timeSheets.isEmpty()) {
continue;
}
if (OctaneConstants.TS_GROUP_BY_WORKSPACE.equals(groupBy)) {
// Group by workspace - We aggregate all items into one line for the current workspace
timesheetLines.add(new OctaneExternalWorkItem(workSpace.name,
timeSheets, startDate, endDate, workSpace.id, null, null));
} else if (OctaneConstants.TS_GROUP_BY_BACKLOG_ITEM.equals(groupBy)) {
// Group by Backlog items - One item = one line
for (TimesheetItem item : timeSheets) {
timesheetLines.add(new OctaneExternalWorkItem(workSpace.name + SEP + item.getEntityName(),
Arrays.asList(new TimesheetItem[] {item}), startDate, endDate, workSpace.id, item.getReleaseId() == 0 ? null : String.valueOf(item.getReleaseId()), String.valueOf(item.getEntityId())));
}
} else {
// group by Releases
Map<Integer, List<TimesheetItem>> releaseTimesheet = new HashMap<Integer, List<TimesheetItem>>();
Map<Integer, String> releaseIdName = new HashMap<>();
for (TimesheetItem timeItem : timeSheets) {
if (!releaseTimesheet.containsKey(timeItem.getReleaseId())) {
releaseTimesheet.put(timeItem.getReleaseId(), new ArrayList<TimesheetItem>());
}
releaseTimesheet.get(timeItem.getReleaseId()).add(timeItem);
releaseIdName.put(timeItem.getReleaseId(), timeItem.getReleaseName());
}
for (Map.Entry<Integer, List<TimesheetItem>> entry : releaseTimesheet.entrySet()) {
int releaseIdInt = entry.getKey();
String releaseId = null;
String releaseName = null;
if (releaseIdInt == 0) {
releaseId = null;
releaseName = Providers.getLocalizationProvider(OctaneIntegrationConnector.class).getConnectorText("TS_NO_RELEASE_LABEL");
} else {
releaseId = String.valueOf(releaseIdInt);
releaseName = releaseIdName.get(releaseIdInt);
}
ArrayList<TimesheetItem> oneReleaseTimeItems = (ArrayList<TimesheetItem>)entry.getValue();
timesheetLines.add(new OctaneExternalWorkItem(workSpace.name + SEP + releaseName,
oneReleaseTimeItems, startDate, endDate, workSpace.id, releaseId, null));
}
}
}
}
}
} catch (ClientRuntimeException | OctaneClientException e) {
logger.error("", e);
new OctaneConnectivityExceptionHandler()
.uncaughtException(Thread.currentThread(), e, OctaneTimeSheetIntegration.class);
} catch (RuntimeException e) {
logger.error("", e);
new OctaneConnectivityExceptionHandler()
.uncaughtException(Thread.currentThread(), e, OctaneTimeSheetIntegration.class);
}
return timesheetLines;
}
private class OctaneExternalWorkItem extends ExternalWorkItem {
String workspaceId;
String releaseId;
String backlogItemId;
String timesheetLineName;
double totalEffort = 0;
String errorMessage = null;
Date startDate;
Date finishDate;
Hashtable<String, Long> effortList = new Hashtable<>();
public OctaneExternalWorkItem(String timesheetLineName, List<TimesheetItem> timeSheets,
String startDate, String finishDate, String workspaceId, String releaseId, String backlogItemId)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
this.timesheetLineName = timesheetLineName;
this.workspaceId = workspaceId;
this.releaseId = releaseId;
this.backlogItemId = backlogItemId;
try {
this.startDate = sdf.parse(startDate);
this.finishDate = sdf.parse(finishDate);
} catch (ParseException e) {
}
for (TimesheetItem timeSheet : timeSheets) {
totalEffort += timeSheet.getInvested();
Long effort = effortList.get(timeSheet.getDate());
if (effort == null)
effort = 0L;
effortList.put(timeSheet.getDate(), timeSheet.getInvested() + effort);
}
}
@Override public String getName() {
return this.timesheetLineName;
}
@Override
public Double getTotalEffort() {
return totalEffort;
}
@Override
public TimeSheetLineAgileEntityInfo getLineAgileEntityInfo() {
TimeSheetLineAgileEntityInfo lineInfo = new TimeSheetLineAgileEntityInfo(workspaceId);
lineInfo.setBacklogItemId(this.backlogItemId);
lineInfo.setReleaseId(this.releaseId);
return lineInfo;
}
@Override
public ExternalWorkItemEffortBreakdown getEffortBreakDown() {
ExternalWorkItemEffortBreakdown effortBreakdown = new ExternalWorkItemEffortBreakdown();
int numOfWorkDays = getDaysDiffNumber(startDate, finishDate);
if (numOfWorkDays > 0) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(startDate);
for(int i = 0; i < numOfWorkDays; i++) {
Long effort = effortList.get(convertDate(calendar.getTime()));
if(effort == null) effort = 0L;
effortBreakdown.addEffort(calendar.getTime(), effort.doubleValue());
// move to next day
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
}
return effortBreakdown;
}
@Override
public String getErrorMessage() {
return errorMessage;
}
}
private int getDaysDiffNumber(Date startDate, Date endDate) {
Calendar start = new GregorianCalendar();
start.setTime(startDate);
Calendar end = new GregorianCalendar();
end.setTime(endDate);
//move to last millisecond
end.set(Calendar.HOUR_OF_DAY, 23);
end.set(Calendar.MINUTE, 59);
end.set(Calendar.SECOND, 59);
end.set(Calendar.MILLISECOND, 999);
Calendar dayDiff = Calendar.getInstance();
dayDiff.setTime(startDate);
int diffNumber = 0;
while (dayDiff.before(end)) {
diffNumber++;
dayDiff.add(Calendar.DAY_OF_MONTH, 1);
}
return diffNumber;
}
}
| src/com/ppm/integration/agilesdk/connector/octane/OctaneTimeSheetIntegration.java | package com.ppm.integration.agilesdk.connector.octane;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.wink.client.ClientRuntimeException;
import com.hp.ppm.tm.model.TimeSheet;
import com.ppm.integration.agilesdk.ValueSet;
import com.ppm.integration.agilesdk.connector.octane.client.ClientPublicAPI;
import com.ppm.integration.agilesdk.connector.octane.client.OctaneClientException;
import com.ppm.integration.agilesdk.connector.octane.client.OctaneClientHelper;
import com.ppm.integration.agilesdk.connector.octane.client.OctaneConnectivityExceptionHandler;
import com.ppm.integration.agilesdk.connector.octane.model.SharedSpace;
import com.ppm.integration.agilesdk.connector.octane.model.TimesheetItem;
import com.ppm.integration.agilesdk.connector.octane.model.WorkSpace;
import com.ppm.integration.agilesdk.provider.Providers;
import com.ppm.integration.agilesdk.tm.AuthenticationInfo;
import com.ppm.integration.agilesdk.tm.ExternalWorkItem;
import com.ppm.integration.agilesdk.tm.ExternalWorkItemEffortBreakdown;
import com.ppm.integration.agilesdk.tm.TimeSheetIntegration;
import com.ppm.integration.agilesdk.tm.TimeSheetIntegrationContext;
import com.ppm.integration.agilesdk.tm.TimeSheetLineAgileEntityInfo;
import com.ppm.integration.agilesdk.ui.Field;
import com.ppm.integration.agilesdk.ui.LineBreaker;
import com.ppm.integration.agilesdk.ui.Link;
import com.ppm.integration.agilesdk.ui.SelectList;
public class OctaneTimeSheetIntegration extends TimeSheetIntegration {
private final Logger logger = Logger.getLogger(this.getClass());
static final String SEP = ">";
protected synchronized String convertDate(Date date) {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.format(date);
} catch (Exception e) {
logger.error(e.getMessage());
}
return "";
}
@Override public List<Field> getMappingConfigurationFields(ValueSet paramValueSet) {
return Arrays.asList(new Field[] {
new Link("auth", "AUTHENTICATION_LINK", "defaultValue", "true", true, "javascript:void(0);",
"openSSOLink()"),
new LineBreaker(),
new SelectList(OctaneConstants.TS_GROUP_BY,"TS_GROUP_BY",OctaneConstants.TS_GROUP_BY_RELEASE,true)
.addLevel(OctaneConstants.TS_GROUP_BY, "TS_GROUP_BY")
.addOption(new SelectList.Option(OctaneConstants.TS_GROUP_BY_WORKSPACE,"TS_GROUP_BY_WORKSPACE"))
.addOption(new SelectList.Option(OctaneConstants.TS_GROUP_BY_RELEASE,"TS_GROUP_BY_RELEASE"))
.addOption(new SelectList.Option(OctaneConstants.TS_GROUP_BY_BACKLOG_ITEM,"TS_GROUP_BY_BACKLOG_ITEM"))
});
}
@Override public List<ExternalWorkItem> getExternalWorkItems(TimeSheetIntegrationContext context,
final ValueSet values)
{
List<ExternalWorkItem> items = null;
try {
items = getExternalWorkItemsByTasks(context, values);
} catch (ParseException e) {
logger.error(e.getMessage());
}
return items;
}
@Override
public String getSSOurl(ValueSet values) {
ClientPublicAPI clientP = OctaneClientHelper.setupClientPublicAPI(values);
return clientP.getSSOURL();
}
@Override
public AuthenticationInfo getAuthenticationInfo(ValueSet values, String identifier) {
ClientPublicAPI clientP = OctaneClientHelper.setupClientPublicAPI(values);
AuthenticationInfo userInfo = clientP.getSSOAuthentication(identifier);
return userInfo;
}
public List<ExternalWorkItem> getExternalWorkItemsByTasks(TimeSheetIntegrationContext context,
final ValueSet values) throws ParseException
{
final List<ExternalWorkItem> timesheetLines = Collections.synchronizedList(new LinkedList<ExternalWorkItem>());
try {
TimeSheet currentTimeSheet = context.currentTimeSheet();
final String startDate = convertDate(currentTimeSheet.getPeriodStartDate().toGregorianCalendar().getTime());
final String endDate = convertDate(currentTimeSheet.getPeriodEndDate().toGregorianCalendar().getTime());
ClientPublicAPI clientP = OctaneClientHelper.setupClientPublicAPI(values);
String identifier = values.get(OctaneConstants.SSO_IDENTIFIER);
if (identifier == null) {
throw new OctaneClientException("OCTANE_APP", "LOSE_AUTHORIZE_IDENTIFIER");
}
AuthenticationInfo userInfo = clientP.getSSOAuthentication(identifier);
if (userInfo == null) {
throw new OctaneClientException("OCTANE_APP", "FAIL_TO_RETRIEVE_USER_INFO");
}
String clientId = values.get(OctaneConstants.APP_CLIENT_ID);
String clientSecret = values.get(OctaneConstants.APP_CLIENT_SECRET);
String groupBy = values.get(OctaneConstants.TS_GROUP_BY);
if (clientP.getAccessTokenWithFormFormat(clientId, clientSecret)) {
List<SharedSpace> shareSpaces = clientP.getSharedSpaces();
for (SharedSpace shareSpace : shareSpaces) {
List<WorkSpace> workspacesAll = new ArrayList<WorkSpace>();
List<WorkSpace> workspaces = clientP.getWorkSpaces(Integer.parseInt(shareSpace.id));
workspacesAll.addAll(workspaces);
for (WorkSpace workSpace : workspacesAll) {
List<TimesheetItem> timeSheets = clientP.getTimeSheetData(Integer.parseInt(shareSpace.id),
userInfo.getLoginName(), startDate.toString(), endDate.toString(),
Integer.parseInt(workSpace.id));
if (timeSheets == null || timeSheets.isEmpty()) {
continue;
}
if (OctaneConstants.TS_GROUP_BY_WORKSPACE.equals(groupBy)) {
// Group by workspace - We aggregate all items into one line for the current workspace
timesheetLines.add(new OctaneExternalWorkItem(workSpace.name,
timeSheets, startDate, endDate, workSpace.id, null, null));
} else if (OctaneConstants.TS_GROUP_BY_BACKLOG_ITEM.equals(groupBy)) {
// Group by Backlog items - One item = one line
for (TimesheetItem item : timeSheets) {
timesheetLines.add(new OctaneExternalWorkItem(workSpace.name + SEP + item.getEntityName(),
Arrays.asList(new TimesheetItem[] {item}), startDate, endDate, workSpace.id, item.getReleaseId() == 0 ? null : String.valueOf(item.getReleaseId()), String.valueOf(item.getEntityId())));
}
} else {
// group by Releases
Map<Integer, List<TimesheetItem>> releaseTimesheet = new HashMap<Integer, List<TimesheetItem>>();
Map<Integer, String> releaseIdName = new HashMap<>();
for (TimesheetItem timeItem : timeSheets) {
if (!releaseTimesheet.containsKey(timeItem.getReleaseId())) {
releaseTimesheet.put(timeItem.getReleaseId(), new ArrayList<TimesheetItem>());
}
releaseTimesheet.get(timeItem.getReleaseId()).add(timeItem);
releaseIdName.put(timeItem.getReleaseId(), timeItem.getReleaseName());
}
for (Map.Entry<Integer, List<TimesheetItem>> entry : releaseTimesheet.entrySet()) {
int releaseIdInt = entry.getKey();
String releaseId = null;
String releaseName = null;
if (releaseIdInt == 0) {
releaseId = null;
releaseName = Providers.getLocalizationProvider(OctaneIntegrationConnector.class).getConnectorText("TS_NO_RELEASE_LABEL");
} else {
releaseId = String.valueOf(releaseIdInt);
releaseName = releaseIdName.get(releaseIdInt);
}
ArrayList<TimesheetItem> oneReleaseTimeItems = (ArrayList<TimesheetItem>)entry.getValue();
timesheetLines.add(new OctaneExternalWorkItem(workSpace.name + SEP + releaseName,
oneReleaseTimeItems, startDate, endDate, workSpace.id, releaseId, null));
}
}
}
}
}
} catch (ClientRuntimeException | OctaneClientException e) {
logger.error("", e);
new OctaneConnectivityExceptionHandler()
.uncaughtException(Thread.currentThread(), e, OctaneTimeSheetIntegration.class);
} catch (RuntimeException e) {
logger.error("", e);
new OctaneConnectivityExceptionHandler()
.uncaughtException(Thread.currentThread(), e, OctaneTimeSheetIntegration.class);
}
return timesheetLines;
}
private class OctaneExternalWorkItem extends ExternalWorkItem {
String workspaceId;
String releaseId;
String backlogItemId;
String timesheetLineName;
double totalEffort = 0;
String errorMessage = null;
Date startDate;
Date finishDate;
Hashtable<String, Long> effortList = new Hashtable<>();
public OctaneExternalWorkItem(String timesheetLineName, List<TimesheetItem> timeSheets,
String startDate, String finishDate, String workspaceId, String releaseId, String backlogItemId)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
this.timesheetLineName = timesheetLineName;
this.workspaceId = workspaceId;
this.releaseId = releaseId;
this.backlogItemId = backlogItemId;
try {
this.startDate = sdf.parse(startDate);
this.finishDate = sdf.parse(finishDate);
} catch (ParseException e) {
}
for (TimesheetItem timeSheet : timeSheets) {
totalEffort += timeSheet.getInvested();
Long effort = effortList.get(timeSheet.getDate());
if (effort == null)
effort = 0L;
effortList.put(timeSheet.getDate(), timeSheet.getInvested() + effort);
}
}
@Override public String getName() {
return this.timesheetLineName;
}
@Override
public Double getTotalEffort() {
return totalEffort;
}
@Override
public TimeSheetLineAgileEntityInfo getLineAgileEntityInfo() {
TimeSheetLineAgileEntityInfo lineInfo = new TimeSheetLineAgileEntityInfo(workspaceId);
lineInfo.setBacklogItemId(this.backlogItemId);
lineInfo.setReleaseId(this.releaseId);
return lineInfo;
}
@Override
public ExternalWorkItemEffortBreakdown getEffortBreakDown() {
ExternalWorkItemEffortBreakdown effortBreakdown = new ExternalWorkItemEffortBreakdown();
int numOfWorkDays = getDaysDiffNumber(startDate, finishDate);
if (numOfWorkDays > 0) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(startDate);
for(int i = 0; i < numOfWorkDays; i++) {
Long effort = effortList.get(convertDate(calendar.getTime()));
if(effort == null) effort = 0L;
effortBreakdown.addEffort(calendar.getTime(), effort.doubleValue());
// move to next day
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
}
return effortBreakdown;
}
@Override
public String getErrorMessage() {
return errorMessage;
}
}
private int getDaysDiffNumber(Date startDate, Date endDate) {
Calendar start = new GregorianCalendar();
start.setTime(startDate);
Calendar end = new GregorianCalendar();
end.setTime(endDate);
//move to last millisecond
end.set(Calendar.HOUR_OF_DAY, 23);
end.set(Calendar.MINUTE, 59);
end.set(Calendar.SECOND, 59);
end.set(Calendar.MILLISECOND, 999);
Calendar dayDiff = Calendar.getInstance();
dayDiff.setTime(startDate);
int diffNumber = 0;
while (dayDiff.before(end)) {
diffNumber++;
dayDiff.add(Calendar.DAY_OF_MONTH, 1);
}
return diffNumber;
}
}
| defect#fix multi share space
| src/com/ppm/integration/agilesdk/connector/octane/OctaneTimeSheetIntegration.java | defect#fix multi share space | <ide><path>rc/com/ppm/integration/agilesdk/connector/octane/OctaneTimeSheetIntegration.java
<ide> if (clientP.getAccessTokenWithFormFormat(clientId, clientSecret)) {
<ide> List<SharedSpace> shareSpaces = clientP.getSharedSpaces();
<ide> for (SharedSpace shareSpace : shareSpaces) {
<del> List<WorkSpace> workspacesAll = new ArrayList<WorkSpace>();
<ide> List<WorkSpace> workspaces = clientP.getWorkSpaces(Integer.parseInt(shareSpace.id));
<del> workspacesAll.addAll(workspaces);
<del> for (WorkSpace workSpace : workspacesAll) {
<add> for (WorkSpace workSpace : workspaces) {
<ide> List<TimesheetItem> timeSheets = clientP.getTimeSheetData(Integer.parseInt(shareSpace.id),
<ide> userInfo.getLoginName(), startDate.toString(), endDate.toString(),
<ide> Integer.parseInt(workSpace.id)); |
|
Java | agpl-3.0 | 979cd6d93e7960bf0dd627d52950f197aaac905b | 0 | kkronenb/kfs,bhutchinson/kfs,ua-eas/kfs,kkronenb/kfs,kkronenb/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,kuali/kfs,smith750/kfs,kuali/kfs,bhutchinson/kfs,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,kuali/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,kuali/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,kkronenb/kfs,UniversityOfHawaii/kfs,smith750/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,smith750/kfs,ua-eas/kfs,ua-eas/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,bhutchinson/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs | /*
* Copyright (c) 2004, 2005 The National Association of College and University Business Officers,
* Cornell University, Trustees of Indiana University, Michigan State University Board of Trustees,
* Trustees of San Joaquin Delta College, University of Hawai'i, The Arizona Board of Regents on
* behalf of the University of Arizona, and the r*smart group.
*
* Licensed under the Educational Community License Version 1.0 (the "License"); By obtaining,
* using and/or copying this Original Work, you agree that you have read, understand, and will
* comply with the terms and conditions of the Educational Community License.
*
* You may obtain a copy of the License at:
*
* http://kualiproject.org/license.html
*
* 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.kuali.module.kra.service;
import java.util.Iterator;
import java.util.List;
import org.kuali.core.util.KualiDecimal;
import org.kuali.core.util.SpringServiceLocator;
import org.kuali.module.cg.bo.Agency;
import org.kuali.module.kra.bo.AgencyExtension;
import org.kuali.module.kra.bo.Budget;
import org.kuali.module.kra.bo.BudgetModular;
import org.kuali.module.kra.bo.BudgetModularPeriod;
import org.kuali.module.kra.bo.BudgetNonpersonnelTest;
import org.kuali.module.kra.bo.BudgetPeriod;
import org.kuali.module.kra.bo.BudgetPeriodTest;
import org.kuali.module.kra.bo.UserAppointmentTaskPeriod;
import org.kuali.test.KualiTestBaseWithSpring;
/**
* This class tests service methods in BudgetModularService.
* @author Kuali Research Administration Team ([email protected])
*/
public class BudgetModularServiceTest extends KualiTestBaseWithSpring {
private BudgetModularService budgetModularService;
private BudgetNonpersonnelService budgetNonpersonnelService;
private List nonpersonnelCategories;
/**
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
budgetModularService = SpringServiceLocator.getBudgetModularService();
budgetNonpersonnelService = SpringServiceLocator.getBudgetNonpersonnelService();
nonpersonnelCategories = budgetNonpersonnelService.getAllNonpersonnelCategories();
}
protected Budget setupBudget() {
Budget budget = new Budget();
Agency agency = new Agency();
agency.setAgencyExtension(new AgencyExtension());
agency.getAgencyExtension().setAgencyModularIndicator(true);
agency.getAgencyExtension().setBudgetModularIncrementAmount(new Integer(25000));
agency.getAgencyExtension().setBudgetPeriodMaximumAmount(new Integer(250000));
budget.setPeriods(BudgetPeriodTest.createBudgetPeriods(2));
budget.setBudgetAgency(agency);
return budget;
}
public void testGenerateModularBudget() {
KualiDecimal zeroValue = new KualiDecimal(0);
// Case 1: Budget with no costs
Budget budget = setupBudget();
budgetModularService.generateModularBudget(budget, nonpersonnelCategories);
BudgetModular modularBudget = (BudgetModular) budget.getModularBudget();
assertEquals(modularBudget.getIncrements().size(), 10);
assertEquals(modularBudget.getBudgetModularDirectCostAmount(), zeroValue);
assertEquals(modularBudget.getTotalActualDirectCostAmount(), zeroValue);
assertEquals(modularBudget.getTotalAdjustedModularDirectCostAmount(), zeroValue);
assertEquals(modularBudget.getTotalConsortiumAmount(), zeroValue);
assertEquals(modularBudget.getTotalDirectCostAmount(), zeroValue);
assertEquals(modularBudget.getTotalModularDirectCostAmount(), zeroValue);
for (Iterator iter = modularBudget.getBudgetModularPeriods().iterator(); iter.hasNext();) {
BudgetModularPeriod modularPeriod = (BudgetModularPeriod) iter.next();
assertEquals(modularPeriod.getActualDirectCostAmount(), zeroValue);
assertEquals(modularPeriod.getConsortiumAmount(), zeroValue);
assertEquals(modularPeriod.getTotalPeriodDirectCostAmount(), zeroValue);
assertEquals(modularPeriod.getBudgetAdjustedModularDirectCostAmount(), new Integer(0));
}
// Case 2: Budget with personnel, nonpersonnel, consortium costs
budget = setupBudget();
String [] categories = {"CO", "CO", "FL"};
String [] subCategories = {"C1", "C1", "F5"};
budget.setNonpersonnelItems(BudgetNonpersonnelTest.createBudgetNonpersonnel(categories, subCategories));
for (Iterator iter = budget.getPeriods().iterator(); iter.hasNext();) {
BudgetPeriod currentPeriod = (BudgetPeriod) iter.next();
UserAppointmentTaskPeriod taskPeriod = new UserAppointmentTaskPeriod();
taskPeriod.setBudgetPeriodSequenceNumber(currentPeriod.getBudgetPeriodSequenceNumber());
taskPeriod.setAgencyRequestTotalAmount(new Integer(35000));
taskPeriod.setAgencyFringeBenefitTotalAmount(new Integer(13000));
budget.getAllUserAppointmentTaskPeriods().add(taskPeriod);
UserAppointmentTaskPeriod taskPeriod2 = new UserAppointmentTaskPeriod();
taskPeriod2.setBudgetPeriodSequenceNumber(currentPeriod.getBudgetPeriodSequenceNumber());
taskPeriod2.setAgencyRequestTotalAmount(new Integer(43000));
taskPeriod2.setAgencyFringeBenefitTotalAmount(new Integer(11500));
budget.getAllUserAppointmentTaskPeriods().add(taskPeriod2);
}
budgetModularService.generateModularBudget(budget, nonpersonnelCategories);
//assertEquals(budget.getModularBudget().getTotalModularDirectCostAmount(), new KualiDecimal(250000));
// Case 3: Budget with costs > # of periods * period maximum
// List nonpersonnelList = new ArrayList();
// BudgetNonpersonnel budgetNonpersonnel = new BudgetNonpersonnel();
// budgetNonpersonnel.setAgencyRequestAmount(new Long(35000));
}
public void testResetModularBudget() {
assertTrue(true);
}
public void testAgencySupportsModular() {
// Case 1: Agency is null.
assertFalse(budgetModularService.agencySupportsModular(null));
// Case 2: Supports modular is true.
Agency agency = new Agency();
AgencyExtension agencyExtension = new AgencyExtension();
agencyExtension.setAgencyModularIndicator(true);
agency.setAgencyExtension(agencyExtension);
assertTrue(budgetModularService.agencySupportsModular(agency));
// Case 3: Supports modular is false.
agency.getAgencyExtension().setAgencyModularIndicator(false);
assertFalse(budgetModularService.agencySupportsModular(agency));
// Case 5: Agency extension and reports to agency both null.
agency.setAgencyExtension(null);
assertFalse(budgetModularService.agencySupportsModular(agency));
}
// public void testGenerateAgencyModularIncrements() {
// BudgetModular modularBudget = new BudgetModular();
// modularBudget.setTotalActualDirectCostAmount(new KualiDecimal(120000));
// modularBudget.setBudgetPeriodMaximumAmount(new Integer(250000));
// modularBudget.setBudgetModularIncrementAmount(new Integer(25000));
// List result = budgetModularService.generateAgencyModularIncrements(modularBudget);
// assertTrue(result.size() == 10);
// assertTrue(((String) result.get(9)).equals("25000"));
// assertTrue(((String) result.get(0)).equals("250000"));
// assertTrue(((String) result.get(5)).equals("125000"));
// }
//
// public void testDetermineModularDirectCost() {
// BudgetModular modularBudget = new BudgetModular();
// modularBudget.setTotalActualDirectCostAmount(new KualiDecimal(120000));
// modularBudget.setBudgetPeriodMaximumAmount(new Integer(250000));
// modularBudget.setBudgetModularIncrementAmount(new Integer(25000));
// KualiDecimal result = budgetModularService.determineModularDirectCost(2, modularBudget);
// assertTrue(result.equals(new KualiDecimal(75000)));
// }
//
// public void testCalculateTotalModularDirectCostAmount() {
// List modularPeriodList = new ArrayList();
//
// KualiDecimal result = budgetModularService.calculateTotalModularDirectCostAmount(new KualiDecimal(120000), modularPeriodList);
// assertTrue(result.equals(new KualiDecimal(0)));
//
// BudgetModularPeriod modularPeriod1 = new BudgetModularPeriod();
// modularPeriodList.add(modularPeriod1);
//
// BudgetModularPeriod modularPeriod2 = new BudgetModularPeriod();
// modularPeriodList.add(modularPeriod2);
//
// result = budgetModularService.calculateTotalModularDirectCostAmount(new KualiDecimal(120000), modularPeriodList);
// assertTrue(result.equals(new KualiDecimal(240000)));
// }
//
// public void testCalculateTotalAdjustedModularDirectCostAmount() {
// List modularPeriodList = new ArrayList();
//
// KualiDecimal result = budgetModularService.calculateTotalAdjustedModularDirectCostAmount(modularPeriodList);
// assertTrue(result.equals(new KualiDecimal(0)));
//
// BudgetModularPeriod modularPeriod1 = new BudgetModularPeriod();
// modularPeriod1.setBudgetAdjustedModularDirectCostAmount(new Integer(30000));
// modularPeriodList.add(modularPeriod1);
//
// BudgetModularPeriod modularPeriod2 = new BudgetModularPeriod();
// modularPeriod2.setBudgetAdjustedModularDirectCostAmount(new Integer(20000));
// modularPeriodList.add(modularPeriod2);
//
// result = budgetModularService.calculateTotalAdjustedModularDirectCostAmount(modularPeriodList);
// assertTrue(result.equals(new KualiDecimal(50000)));
// }
//
// public void testSumKualiDecimalAmountAcrossPeriods() {
// List modularPeriodList = new ArrayList();
//
// KualiDecimal result = budgetModularService.sumKualiDecimalAmountAcrossPeriods(modularPeriodList, "actualDirectCostAmount");
// assertTrue(result.equals(new KualiDecimal(0)));
//
// BudgetModularPeriod modularPeriod1 = new BudgetModularPeriod();
// modularPeriod1.setActualDirectCostAmount(new KualiDecimal(30000));
// modularPeriodList.add(modularPeriod1);
//
// BudgetModularPeriod modularPeriod2 = new BudgetModularPeriod();
// modularPeriod2.setActualDirectCostAmount(new KualiDecimal(20000));
// modularPeriodList.add(modularPeriod2);
//
// result = budgetModularService.sumKualiDecimalAmountAcrossPeriods(modularPeriodList, "actualDirectCostAmount");
// assertTrue(result.equals(new KualiDecimal(50000)));
// }
}
| test/unit/src/org/kuali/kfs/module/cg/document/service/BudgetModularServiceTest.java | /*
* Copyright (c) 2004, 2005 The National Association of College and University Business Officers,
* Cornell University, Trustees of Indiana University, Michigan State University Board of Trustees,
* Trustees of San Joaquin Delta College, University of Hawai'i, The Arizona Board of Regents on
* behalf of the University of Arizona, and the r*smart group.
*
* Licensed under the Educational Community License Version 1.0 (the "License"); By obtaining,
* using and/or copying this Original Work, you agree that you have read, understand, and will
* comply with the terms and conditions of the Educational Community License.
*
* You may obtain a copy of the License at:
*
* http://kualiproject.org/license.html
*
* 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.kuali.module.kra.service;
import java.util.ArrayList;
import java.util.List;
import org.kuali.core.util.SpringServiceLocator;
import org.kuali.module.kra.bo.Budget;
import org.kuali.module.kra.bo.BudgetNonpersonnel;
import org.kuali.test.KualiTestBaseWithSpring;
/**
* This class tests service methods in BudgetModularService.
* @author Kuali Research Administration Team ([email protected])
*/
public class BudgetModularServiceTest extends KualiTestBaseWithSpring {
private BudgetModularService budgetModularService;
private BudgetNonpersonnelService budgetNonpersonnelService;
private Budget budget;
private List nonpersonnelCategories;
/**
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
budgetModularService = SpringServiceLocator.getBudgetModularService();
budgetNonpersonnelService = SpringServiceLocator.getBudgetNonpersonnelService();
budget = setupBudget();
nonpersonnelCategories = budgetNonpersonnelService.getAllNonpersonnelCategories();
}
protected Budget setupBudget() {
Budget budget = new Budget();
return budget;
}
public void testGenerateModularBudget() {
List nonpersonnelList = new ArrayList();
BudgetNonpersonnel budgetNonpersonnel = new BudgetNonpersonnel();
budgetNonpersonnel.setAgencyRequestAmount(new Long(35000));
//budgetModularService.generateModularBudget(budget, nonpersonnelCategories);
}
// public void testGenerateAgencyModularIncrements() {
// BudgetModular modularBudget = new BudgetModular();
// modularBudget.setTotalActualDirectCostAmount(new KualiDecimal(120000));
// modularBudget.setBudgetPeriodMaximumAmount(new Integer(250000));
// modularBudget.setBudgetModularIncrementAmount(new Integer(25000));
// List result = budgetModularService.generateAgencyModularIncrements(modularBudget);
// assertTrue(result.size() == 10);
// assertTrue(((String) result.get(9)).equals("25000"));
// assertTrue(((String) result.get(0)).equals("250000"));
// assertTrue(((String) result.get(5)).equals("125000"));
// }
//
// public void testDetermineModularDirectCost() {
// BudgetModular modularBudget = new BudgetModular();
// modularBudget.setTotalActualDirectCostAmount(new KualiDecimal(120000));
// modularBudget.setBudgetPeriodMaximumAmount(new Integer(250000));
// modularBudget.setBudgetModularIncrementAmount(new Integer(25000));
// KualiDecimal result = budgetModularService.determineModularDirectCost(2, modularBudget);
// assertTrue(result.equals(new KualiDecimal(75000)));
// }
//
// public void testCalculateTotalModularDirectCostAmount() {
// List modularPeriodList = new ArrayList();
//
// KualiDecimal result = budgetModularService.calculateTotalModularDirectCostAmount(new KualiDecimal(120000), modularPeriodList);
// assertTrue(result.equals(new KualiDecimal(0)));
//
// BudgetModularPeriod modularPeriod1 = new BudgetModularPeriod();
// modularPeriodList.add(modularPeriod1);
//
// BudgetModularPeriod modularPeriod2 = new BudgetModularPeriod();
// modularPeriodList.add(modularPeriod2);
//
// result = budgetModularService.calculateTotalModularDirectCostAmount(new KualiDecimal(120000), modularPeriodList);
// assertTrue(result.equals(new KualiDecimal(240000)));
// }
//
// public void testCalculateTotalAdjustedModularDirectCostAmount() {
// List modularPeriodList = new ArrayList();
//
// KualiDecimal result = budgetModularService.calculateTotalAdjustedModularDirectCostAmount(modularPeriodList);
// assertTrue(result.equals(new KualiDecimal(0)));
//
// BudgetModularPeriod modularPeriod1 = new BudgetModularPeriod();
// modularPeriod1.setBudgetAdjustedModularDirectCostAmount(new Integer(30000));
// modularPeriodList.add(modularPeriod1);
//
// BudgetModularPeriod modularPeriod2 = new BudgetModularPeriod();
// modularPeriod2.setBudgetAdjustedModularDirectCostAmount(new Integer(20000));
// modularPeriodList.add(modularPeriod2);
//
// result = budgetModularService.calculateTotalAdjustedModularDirectCostAmount(modularPeriodList);
// assertTrue(result.equals(new KualiDecimal(50000)));
// }
//
// public void testSumKualiDecimalAmountAcrossPeriods() {
// List modularPeriodList = new ArrayList();
//
// KualiDecimal result = budgetModularService.sumKualiDecimalAmountAcrossPeriods(modularPeriodList, "actualDirectCostAmount");
// assertTrue(result.equals(new KualiDecimal(0)));
//
// BudgetModularPeriod modularPeriod1 = new BudgetModularPeriod();
// modularPeriod1.setActualDirectCostAmount(new KualiDecimal(30000));
// modularPeriodList.add(modularPeriod1);
//
// BudgetModularPeriod modularPeriod2 = new BudgetModularPeriod();
// modularPeriod2.setActualDirectCostAmount(new KualiDecimal(20000));
// modularPeriodList.add(modularPeriod2);
//
// result = budgetModularService.sumKualiDecimalAmountAcrossPeriods(modularPeriodList, "actualDirectCostAmount");
// assertTrue(result.equals(new KualiDecimal(50000)));
// }
}
| adding unit tests
| test/unit/src/org/kuali/kfs/module/cg/document/service/BudgetModularServiceTest.java | adding unit tests | <ide><path>est/unit/src/org/kuali/kfs/module/cg/document/service/BudgetModularServiceTest.java
<ide> */
<ide> package org.kuali.module.kra.service;
<ide>
<del>import java.util.ArrayList;
<add>import java.util.Iterator;
<ide> import java.util.List;
<ide>
<add>import org.kuali.core.util.KualiDecimal;
<ide> import org.kuali.core.util.SpringServiceLocator;
<add>import org.kuali.module.cg.bo.Agency;
<add>import org.kuali.module.kra.bo.AgencyExtension;
<ide> import org.kuali.module.kra.bo.Budget;
<del>import org.kuali.module.kra.bo.BudgetNonpersonnel;
<add>import org.kuali.module.kra.bo.BudgetModular;
<add>import org.kuali.module.kra.bo.BudgetModularPeriod;
<add>import org.kuali.module.kra.bo.BudgetNonpersonnelTest;
<add>import org.kuali.module.kra.bo.BudgetPeriod;
<add>import org.kuali.module.kra.bo.BudgetPeriodTest;
<add>import org.kuali.module.kra.bo.UserAppointmentTaskPeriod;
<ide> import org.kuali.test.KualiTestBaseWithSpring;
<ide>
<ide> /**
<ide> private BudgetModularService budgetModularService;
<ide> private BudgetNonpersonnelService budgetNonpersonnelService;
<ide>
<del> private Budget budget;
<ide> private List nonpersonnelCategories;
<ide>
<ide> /**
<ide> super.setUp();
<ide> budgetModularService = SpringServiceLocator.getBudgetModularService();
<ide> budgetNonpersonnelService = SpringServiceLocator.getBudgetNonpersonnelService();
<del> budget = setupBudget();
<ide> nonpersonnelCategories = budgetNonpersonnelService.getAllNonpersonnelCategories();
<ide> }
<ide>
<ide> protected Budget setupBudget() {
<ide> Budget budget = new Budget();
<add>
<add> Agency agency = new Agency();
<add> agency.setAgencyExtension(new AgencyExtension());
<add> agency.getAgencyExtension().setAgencyModularIndicator(true);
<add> agency.getAgencyExtension().setBudgetModularIncrementAmount(new Integer(25000));
<add> agency.getAgencyExtension().setBudgetPeriodMaximumAmount(new Integer(250000));
<add>
<add> budget.setPeriods(BudgetPeriodTest.createBudgetPeriods(2));
<add>
<add> budget.setBudgetAgency(agency);
<ide> return budget;
<ide> }
<ide>
<ide>
<ide> public void testGenerateModularBudget() {
<del> List nonpersonnelList = new ArrayList();
<del> BudgetNonpersonnel budgetNonpersonnel = new BudgetNonpersonnel();
<del> budgetNonpersonnel.setAgencyRequestAmount(new Long(35000));
<del> //budgetModularService.generateModularBudget(budget, nonpersonnelCategories);
<add> KualiDecimal zeroValue = new KualiDecimal(0);
<add>
<add> // Case 1: Budget with no costs
<add> Budget budget = setupBudget();
<add> budgetModularService.generateModularBudget(budget, nonpersonnelCategories);
<add> BudgetModular modularBudget = (BudgetModular) budget.getModularBudget();
<add>
<add> assertEquals(modularBudget.getIncrements().size(), 10);
<add> assertEquals(modularBudget.getBudgetModularDirectCostAmount(), zeroValue);
<add> assertEquals(modularBudget.getTotalActualDirectCostAmount(), zeroValue);
<add> assertEquals(modularBudget.getTotalAdjustedModularDirectCostAmount(), zeroValue);
<add> assertEquals(modularBudget.getTotalConsortiumAmount(), zeroValue);
<add> assertEquals(modularBudget.getTotalDirectCostAmount(), zeroValue);
<add> assertEquals(modularBudget.getTotalModularDirectCostAmount(), zeroValue);
<add>
<add> for (Iterator iter = modularBudget.getBudgetModularPeriods().iterator(); iter.hasNext();) {
<add> BudgetModularPeriod modularPeriod = (BudgetModularPeriod) iter.next();
<add> assertEquals(modularPeriod.getActualDirectCostAmount(), zeroValue);
<add> assertEquals(modularPeriod.getConsortiumAmount(), zeroValue);
<add> assertEquals(modularPeriod.getTotalPeriodDirectCostAmount(), zeroValue);
<add> assertEquals(modularPeriod.getBudgetAdjustedModularDirectCostAmount(), new Integer(0));
<add> }
<add>
<add> // Case 2: Budget with personnel, nonpersonnel, consortium costs
<add> budget = setupBudget();
<add>
<add> String [] categories = {"CO", "CO", "FL"};
<add> String [] subCategories = {"C1", "C1", "F5"};
<add> budget.setNonpersonnelItems(BudgetNonpersonnelTest.createBudgetNonpersonnel(categories, subCategories));
<add>
<add> for (Iterator iter = budget.getPeriods().iterator(); iter.hasNext();) {
<add> BudgetPeriod currentPeriod = (BudgetPeriod) iter.next();
<add>
<add> UserAppointmentTaskPeriod taskPeriod = new UserAppointmentTaskPeriod();
<add> taskPeriod.setBudgetPeriodSequenceNumber(currentPeriod.getBudgetPeriodSequenceNumber());
<add> taskPeriod.setAgencyRequestTotalAmount(new Integer(35000));
<add> taskPeriod.setAgencyFringeBenefitTotalAmount(new Integer(13000));
<add> budget.getAllUserAppointmentTaskPeriods().add(taskPeriod);
<add>
<add> UserAppointmentTaskPeriod taskPeriod2 = new UserAppointmentTaskPeriod();
<add> taskPeriod2.setBudgetPeriodSequenceNumber(currentPeriod.getBudgetPeriodSequenceNumber());
<add> taskPeriod2.setAgencyRequestTotalAmount(new Integer(43000));
<add> taskPeriod2.setAgencyFringeBenefitTotalAmount(new Integer(11500));
<add> budget.getAllUserAppointmentTaskPeriods().add(taskPeriod2);
<add> }
<add>
<add> budgetModularService.generateModularBudget(budget, nonpersonnelCategories);
<add>
<add> //assertEquals(budget.getModularBudget().getTotalModularDirectCostAmount(), new KualiDecimal(250000));
<add>
<add> // Case 3: Budget with costs > # of periods * period maximum
<add>
<add>
<add>// List nonpersonnelList = new ArrayList();
<add>// BudgetNonpersonnel budgetNonpersonnel = new BudgetNonpersonnel();
<add>// budgetNonpersonnel.setAgencyRequestAmount(new Long(35000));
<add>
<add>
<add>
<add>
<add>
<add>
<add>
<add> }
<add>
<add> public void testResetModularBudget() {
<add> assertTrue(true);
<add> }
<add>
<add> public void testAgencySupportsModular() {
<add>
<add> // Case 1: Agency is null.
<add> assertFalse(budgetModularService.agencySupportsModular(null));
<add>
<add> // Case 2: Supports modular is true.
<add> Agency agency = new Agency();
<add> AgencyExtension agencyExtension = new AgencyExtension();
<add> agencyExtension.setAgencyModularIndicator(true);
<add> agency.setAgencyExtension(agencyExtension);
<add> assertTrue(budgetModularService.agencySupportsModular(agency));
<add>
<add> // Case 3: Supports modular is false.
<add> agency.getAgencyExtension().setAgencyModularIndicator(false);
<add> assertFalse(budgetModularService.agencySupportsModular(agency));
<add>
<add> // Case 5: Agency extension and reports to agency both null.
<add> agency.setAgencyExtension(null);
<add> assertFalse(budgetModularService.agencySupportsModular(agency));
<ide> }
<ide>
<ide> |
|
Java | agpl-3.0 | 4a11bfd7fc568ff8e97ad26629cc81457d7fd328 | 0 | torakiki/sejda | /*
* This file is part of the Sejda source code
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sejda.cli.model;
import com.lexicalscope.jewel.cli.CommandLineInterface;
import com.lexicalscope.jewel.cli.Option;
@CommandLineInterface(application = TaskCliArguments.EXECUTABLE_NAME + " nup")
public interface NupTaskCliArguments
extends CliArgumentsWithPdfAndDirectoryOutput,
CliArgumentsWithPrefixableOutput, MultiplePdfSourceTaskCliArguments {
@Option(shortName = "n", description = "number of pages per sheet. Only powers of 2 currently supported (2, 4, 8, 16, 32, etc). Defaults to 2. (Ex --n 4) (optional)", defaultValue = "4")
Integer getN();
@Option(shortName = "x", description = "vertical page ordering in sheets, top-down and then left-right. Default is horizontal ordering (left-right and then top-down) (optional)")
boolean isVerticalOrdering();
@Option(shortName = "s", description = "preserve original page size, scaling down the collated pages. Default is false (nup 2 of A4 will produce A3, nup 4 of A4 will produce A2 etc) (optional)")
boolean isPreservePageSize();
}
| sejda-console/src/main/java/org/sejda/cli/model/NupTaskCliArguments.java | /*
* This file is part of the Sejda source code
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sejda.cli.model;
import com.lexicalscope.jewel.cli.CommandLineInterface;
import com.lexicalscope.jewel.cli.Option;
@CommandLineInterface(application = TaskCliArguments.EXECUTABLE_NAME + " nup")
public interface NupTaskCliArguments
extends CliArgumentsWithPdfAndDirectoryOutput,
CliArgumentsWithPrefixableOutput, MultiplePdfSourceTaskCliArguments {
@Option(shortName = "n", description = "number of pages per sheet. Only powers of 2 currently supported (2, 4, 8, 16, 32, etc). Defaults to 2. (Ex --n 4) (optional)", defaultValue = "4")
Integer getN();
@Option(shortName = "x", description = "vertical page ordering in sheets, top-down and then left-right. Default is horizontal ordering (left-right and then top-down) (optional)")
boolean isVerticalOrdering();
@Option(shortName = "p", description = "preserve original page size, scaling down the collated pages. Default is false (nup 2 of A4 will produce A3, nup 4 of A4 will produce A2 etc) (optional)")
boolean isPreservePageSize();
}
| ref #243 Fixes short name collision
| sejda-console/src/main/java/org/sejda/cli/model/NupTaskCliArguments.java | ref #243 Fixes short name collision | <ide><path>ejda-console/src/main/java/org/sejda/cli/model/NupTaskCliArguments.java
<ide> @Option(shortName = "x", description = "vertical page ordering in sheets, top-down and then left-right. Default is horizontal ordering (left-right and then top-down) (optional)")
<ide> boolean isVerticalOrdering();
<ide>
<del> @Option(shortName = "p", description = "preserve original page size, scaling down the collated pages. Default is false (nup 2 of A4 will produce A3, nup 4 of A4 will produce A2 etc) (optional)")
<add> @Option(shortName = "s", description = "preserve original page size, scaling down the collated pages. Default is false (nup 2 of A4 will produce A3, nup 4 of A4 will produce A2 etc) (optional)")
<ide> boolean isPreservePageSize();
<ide> } |
|
Java | apache-2.0 | error: pathspec 'OOD/oodocp/src/main/java/ru/revdaalex/oodocp/EngineeringCalc.java' did not match any file(s) known to git
| 26bda2fe4247371d3236031983f6912736d2d911 | 1 | revdaalex/learn_java | package ru.revdaalex.oodocp;
import ru.revdaalex.oodocp.interfaces.IO;
/**
* EngineeringCalc class.
* Created by revdaalex on 21.06.2016.
*/
public class EngineeringCalc extends InteractCalc {
/**
* Variable calculator.
*/
private Calculator calculator;
/**
* Variable calculatorMenu.
*/
private EngineerCalcMenu engineerCalcMenu;
/**
* Variable menuValidator.
*/
private MenuValidator menuValidator;
/**
* Variable validator.
*/
private Validator validator;
/**
* Variable io.
*/
private IO io;
/**
* Variable user choice.
*/
private int uc;
/**
* Variable degree.
*/
private double degree;
/**
* Variable rad.
*/
private double rad;
/**
* Variable result.
*/
private String result = "Результат:";
/**
* Main constructor.
* @param calculator calculator.
* @param io io.
*/
public EngineeringCalc(Calculator calculator, IO io) {
super(calculator, io);
this.io = io;
this.calculator = calculator;
this.engineerCalcMenu = new EngineerCalcMenu(io);
this.menuValidator = new MenuValidator(io);
this.validator = new Validator(io);
}
/**
* Override method start from parent class.
*/
@Override
public void start() {
boolean notExit = true;
while(notExit){
engineerCalcMenu.showMenu();
uc = userChoice();
switch (uc){
case 1: add();break;
case 2: sub();break;
case 3: mult();break;
case 4: div();break;
case 5: calcResult();break;
case 6: clear();break;
case 7: notExit = false;break;
case 8: engineerCalc(); break;
}
}
}
/**
* Validate user choice in menu.
* @return int user choice.
*/
private int userChoice(){
return menuValidator.validEngineerMenu();
}
/**
* Method engineer calculator.
*/
private void engineerCalc() {
degree = validator.getDouble("Введите градусы угла");
rad = degreeInRad(degree, Math.PI);
engineerCalcMenu.showEngineerOperator();
uc = menuValidator.validEngineerOperation();
switch (uc) {
case 1:
calculator.sinus(rad);
this.io.println(String.format("%s %s", result, calculator.getResult()));break;
case 2:
calculator.cosine(rad);
this.io.println(String.format("%s %s", result, calculator.getResult()));
break;
case 3:
calculator.tangent(rad);
this.io.println(String.format("%s %s", result, calculator.getResult()));break;
}
}
/**
* Method degree in radian.
* @param degree degree.
* @param pi pi.
* @return
*/
private double degreeInRad(double degree, double pi) {
rad = (degree * pi) / 180;
return rad;
}
}
| OOD/oodocp/src/main/java/ru/revdaalex/oodocp/EngineeringCalc.java | add EngineeringCalc.java
| OOD/oodocp/src/main/java/ru/revdaalex/oodocp/EngineeringCalc.java | add EngineeringCalc.java | <ide><path>OD/oodocp/src/main/java/ru/revdaalex/oodocp/EngineeringCalc.java
<add>package ru.revdaalex.oodocp;
<add>
<add>import ru.revdaalex.oodocp.interfaces.IO;
<add>
<add>/**
<add> * EngineeringCalc class.
<add> * Created by revdaalex on 21.06.2016.
<add> */
<add>public class EngineeringCalc extends InteractCalc {
<add> /**
<add> * Variable calculator.
<add> */
<add> private Calculator calculator;
<add> /**
<add> * Variable calculatorMenu.
<add> */
<add> private EngineerCalcMenu engineerCalcMenu;
<add> /**
<add> * Variable menuValidator.
<add> */
<add> private MenuValidator menuValidator;
<add> /**
<add> * Variable validator.
<add> */
<add> private Validator validator;
<add> /**
<add> * Variable io.
<add> */
<add> private IO io;
<add> /**
<add> * Variable user choice.
<add> */
<add> private int uc;
<add> /**
<add> * Variable degree.
<add> */
<add> private double degree;
<add> /**
<add> * Variable rad.
<add> */
<add> private double rad;
<add> /**
<add> * Variable result.
<add> */
<add> private String result = "Результат:";
<add> /**
<add> * Main constructor.
<add> * @param calculator calculator.
<add> * @param io io.
<add> */
<add> public EngineeringCalc(Calculator calculator, IO io) {
<add> super(calculator, io);
<add> this.io = io;
<add> this.calculator = calculator;
<add> this.engineerCalcMenu = new EngineerCalcMenu(io);
<add> this.menuValidator = new MenuValidator(io);
<add> this.validator = new Validator(io);
<add> }
<add>
<add> /**
<add> * Override method start from parent class.
<add> */
<add> @Override
<add> public void start() {
<add> boolean notExit = true;
<add> while(notExit){
<add> engineerCalcMenu.showMenu();
<add> uc = userChoice();
<add> switch (uc){
<add> case 1: add();break;
<add>
<add> case 2: sub();break;
<add>
<add> case 3: mult();break;
<add>
<add> case 4: div();break;
<add>
<add> case 5: calcResult();break;
<add>
<add> case 6: clear();break;
<add>
<add> case 7: notExit = false;break;
<add>
<add> case 8: engineerCalc(); break;
<add> }
<add> }
<add> }
<add>
<add> /**
<add> * Validate user choice in menu.
<add> * @return int user choice.
<add> */
<add> private int userChoice(){
<add> return menuValidator.validEngineerMenu();
<add> }
<add>
<add> /**
<add> * Method engineer calculator.
<add> */
<add> private void engineerCalc() {
<add> degree = validator.getDouble("Введите градусы угла");
<add> rad = degreeInRad(degree, Math.PI);
<add> engineerCalcMenu.showEngineerOperator();
<add> uc = menuValidator.validEngineerOperation();
<add> switch (uc) {
<add> case 1:
<add> calculator.sinus(rad);
<add> this.io.println(String.format("%s %s", result, calculator.getResult()));break;
<add>
<add> case 2:
<add> calculator.cosine(rad);
<add> this.io.println(String.format("%s %s", result, calculator.getResult()));
<add> break;
<add>
<add> case 3:
<add> calculator.tangent(rad);
<add> this.io.println(String.format("%s %s", result, calculator.getResult()));break;
<add> }
<add> }
<add>
<add> /**
<add> * Method degree in radian.
<add> * @param degree degree.
<add> * @param pi pi.
<add> * @return
<add> */
<add> private double degreeInRad(double degree, double pi) {
<add> rad = (degree * pi) / 180;
<add> return rad;
<add> }
<add>} |
|
Java | apache-2.0 | 6b6125b3f6650aa642f54ac5c3708f337d01e72b | 0 | vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.subscription.impl;
import com.yahoo.config.ConfigInstance;
import com.yahoo.config.subscription.ConfigSet;
import com.yahoo.config.subscription.ConfigSource;
import com.yahoo.config.subscription.ConfigSubscriber;
import com.yahoo.vespa.config.ConfigKey;
import java.lang.reflect.Constructor;
/**
* Subscription on a programmatically built set of configs
* @author vegardh
* @since 5.1
*/
public class ConfigSetSubscription<T extends ConfigInstance> extends ConfigSubscription<T> {
private final ConfigSet set;
private final ConfigKey<T> subKey;
ConfigSetSubscription(ConfigKey<T> key,
ConfigSubscriber subscriber, ConfigSource cset) {
super(key, subscriber);
if (!(cset instanceof ConfigSet)) throw new IllegalArgumentException("Source is not a ConfigSet: "+cset);
this.set=(ConfigSet) cset;
subKey = new ConfigKey<T>(configClass, key.getConfigId());
if (!set.contains(subKey)) {
throw new IllegalArgumentException("The given ConfigSet "+set+" does not contain a config for "+subKey);
}
setGeneration(0L);
}
@Override
public boolean nextConfig(long timeout) {
long end = System.currentTimeMillis() + timeout;
do {
ConfigInstance myInstance = getNewInstance();
ConfigState<T> configState = getConfigState();
// User forced reload
if (checkReloaded()) {
setConfigIfChanged((T)myInstance);
return true;
}
if (!myInstance.equals(configState.getConfig())) {
setConfigIfChangedIncGen((T)myInstance);
return true;
}
sleep();
} while (System.currentTimeMillis() < end);
return false;
}
private void sleep() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException("nextConfig aborted", e);
}
}
@Override
public boolean subscribe(long timeout) {
return true;
}
public ConfigInstance getNewInstance() {
try {
ConfigInstance.Builder builder = set.get(subKey);
Constructor<?> constructor = builder.getClass().getDeclaringClass().getConstructor(builder.getClass());
return (ConfigInstance) constructor.newInstance(builder);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
| config/src/main/java/com/yahoo/config/subscription/impl/ConfigSetSubscription.java | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.subscription.impl;
import com.yahoo.config.ConfigInstance;
import com.yahoo.config.subscription.ConfigSet;
import com.yahoo.config.subscription.ConfigSource;
import com.yahoo.config.subscription.ConfigSubscriber;
import com.yahoo.vespa.config.ConfigKey;
import java.lang.reflect.Constructor;
/**
* Subscription on a programmatically built set of configs
* @author vegardh
* @since 5.1
*/
public class ConfigSetSubscription<T extends ConfigInstance> extends ConfigSubscription<T> {
private final ConfigSet set;
private final ConfigKey<T> subKey;
ConfigSetSubscription(ConfigKey<T> key,
ConfigSubscriber subscriber, ConfigSource cset) {
super(key, subscriber);
if (!(cset instanceof ConfigSet)) throw new IllegalArgumentException("Source is not a ConfigSet: "+cset);
this.set=(ConfigSet) cset;
subKey = new ConfigKey<T>(configClass, key.getConfigId());
if (!set.contains(subKey)) {
throw new IllegalArgumentException("The given ConfigSet "+set+" does not contain a config for "+subKey);
}
setGeneration(0L);
}
@Override
public boolean nextConfig(long timeout) {
long end = System.currentTimeMillis() + timeout;
do {
ConfigInstance myInstance = getNewInstance();
ConfigState<T> configState = getConfigState();
// User forced reload
if (checkReloaded()) {
updateInstance(myInstance);
return true;
}
if (!myInstance.equals(configState.getConfig())) {
updateInstance(myInstance);
return true;
}
sleep();
} while (System.currentTimeMillis() < end);
return false;
}
private void sleep() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException("nextConfig aborted", e);
}
}
@SuppressWarnings("unchecked")
private void updateInstance(ConfigInstance myInstance) {
setConfigIfChangedIncGen((T)myInstance);
}
@Override
public boolean subscribe(long timeout) {
return true;
}
public ConfigInstance getNewInstance() {
try {
ConfigInstance.Builder builder = set.get(subKey);
Constructor<?> constructor = builder.getClass().getDeclaringClass().getConstructor(builder.getClass());
return (ConfigInstance) constructor.newInstance(builder);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
| Same pattern as for FileConfigSubscription
| config/src/main/java/com/yahoo/config/subscription/impl/ConfigSetSubscription.java | Same pattern as for FileConfigSubscription | <ide><path>onfig/src/main/java/com/yahoo/config/subscription/impl/ConfigSetSubscription.java
<ide> ConfigState<T> configState = getConfigState();
<ide> // User forced reload
<ide> if (checkReloaded()) {
<del> updateInstance(myInstance);
<add> setConfigIfChanged((T)myInstance);
<ide> return true;
<ide> }
<ide> if (!myInstance.equals(configState.getConfig())) {
<del> updateInstance(myInstance);
<add> setConfigIfChangedIncGen((T)myInstance);
<ide> return true;
<ide> }
<ide> sleep();
<ide> } catch (InterruptedException e) {
<ide> throw new RuntimeException("nextConfig aborted", e);
<ide> }
<del> }
<del>
<del> @SuppressWarnings("unchecked")
<del> private void updateInstance(ConfigInstance myInstance) {
<del> setConfigIfChangedIncGen((T)myInstance);
<ide> }
<ide>
<ide> @Override |
|
JavaScript | apache-2.0 | 4ba78f919eda61631a63658d269132088c3ac02f | 0 | rhysbrettbowen/PlastronJS | // (c) 2012 Rhys Brett-Bowen, Catch.com
// goog.mvc may be freely distributed under the MIT license.
// For all details and documentation:
// https://github.com/rhysbrettbowen/goog.mvc
goog.provide('mvc.Control');
goog.require('goog.dom');
goog.require('goog.object');
goog.require('goog.ui.Component');
/**
* instantiate with a mvc.Model
*
* @constructor
* @param {mvc.Model} model to link with the control.
* @extends {goog.ui.Component}
*/
mvc.Control = function(model) {
goog.base(this);
this.setModel(model);
this.eventHolder_ = {
listeners: {},
handlers: {}
};
this.modelListeners_ = [];
};
goog.inherits(mvc.Control, goog.ui.Component);
/**
* Functions that can be passed to the mvc.Model.bind
*
* @enum {Function}
*/
mvc.Control.Fn = {
TEXT: goog.dom.setTextContent,
VAL: function(el, val) {el.value = val;},
CLASS: goog.dom.classes.add
};
/**
* remove the element and dispose
*/
mvc.Control.prototype.remove = function() {
goog.dom.removeNode(this.getElement());
this.dispose();
};
/**
* Internal use. Handles and delegates events
*
* @private
* @param {string} type of event.
* @param {Event} e the original event.
*/
mvc.Control.prototype.handleEvents_ = function(type, e) {
if (!this.eventHolder_.handlers[type])
return;
// go through handlers in order and stop if propagation stopped
goog.array.forEach(this.eventHolder_.handlers[type], function(handler) {
if (e.propagationStopped_) {
return;
}
// if no selector or matches selector then fire
if (!handler.selectors.length ||
goog.array.some(handler.selectors, function(className) {
return goog.isFunction(className) ?
className(e) :
goog.dom.classes.has(/** @type {!Node} */(e.target),
className);
})) {
goog.bind(handler.fn, handler.handler)(e);
}
});
};
/**
* delegating events. An event type is needed as well as a handling function.
* if a third parameter is passed then elements with that class will be
* listened to, otherwise the whole component. Returns a uid that can be used
* to end the listener with the off method
*
* @param {string} eventName the event type to listen for.
* @param {Function} fn the function to run on the event.
* @param {string|Array.<string>|Function=} opt_className or names to
* check element against to see if listener function should fire. if it is
* a function then it takes the event and returns true if it matches.
* @param {*=} opt_handler object to bind 'this' to, otherwise mvc.Control.
* @param {number=} opt_priority default is 50, lower is more important.
* @return {number} uid to use with off method.
*/
mvc.Control.prototype.on = function(
eventName, fn, opt_className, opt_handler, opt_priority) {
// initialize
if (!this.eventHolder_) {
this.eventHolder_ = {
listeners: {},
handlers: {}
};
}
if (!this.eventHolder_.handlers[eventName]) {
this.eventHolder_.handlers[eventName] = [];
}
if (!this.eventHolder_.listeners[eventName]) {
this.eventHolder_.listeners[eventName] = this.getHandler().listen(
this.getElement(), eventName,
goog.bind(this.handleEvents_, this, eventName));
}
if (!goog.isDef(opt_className)) {
opt_className = [];
}
var obj = {
selectors: (goog.isArray(opt_className) ?
opt_className : [opt_className]),
fn: fn,
uid: null,
handler: (opt_handler || this),
priority: (opt_priority || 50)
};
obj.uid = goog.getUid(obj);
// insert in array based on priority
goog.array.insertAt(this.eventHolder_.handlers[eventName], obj,
goog.array.findIndexRight(this.eventHolder_.handlers[eventName],
function(obj) {
return obj.priority <= (opt_priority || 50);
}
) + 1);
return obj.uid;
};
/**
* same as on, but will only fire once
*
* @param {string} eventName the event type to listen for.
* @param {Function} fn the function to run on the event.
* @param {string|Array.<string>|Function=} opt_className or names to
* check element against to see if listener function should fire.if it is
* a function then it takes the event and returns true if it matches.
* @param {*=} opt_handler object to bind 'this' to, otherwise mvc.Control.
* @param {number=} opt_priority default is 50, lower is more important.
* @return {number} uid to use with off method.
*/
mvc.Control.prototype.once = function(
eventName, fn, opt_className, opt_handler, opt_priority) {
var uid;
var onceFn = function() {
fn.apply(/** @type {Object} */(opt_handler || this),
Array.prototype.slice.call(arguments));
this.off(uid);
};
uid = this.on(eventName, onceFn, opt_className);
return uid;
};
/**
* same as on but assumes the event type is a click
*
* @param {Function} fn the function to run on the event.
* @param {string|Array.<string>|Function=} opt_className or names to
* check element against to see if listener function should fire. if it is
* a function then it takes the event and returns true if it matches.
* @param {*=} opt_handler object to bind 'this' to, otherwise mvc.Control.
* @param {number=} opt_priority default is 50, lower is more important.
* @return {number} uid to use with off method.
*/
mvc.Control.prototype.click = function(
fn, opt_className, opt_handler, opt_priority) {
return this.on(goog.events.EventType.CLICK,
fn, opt_className, opt_handler, opt_priority);
};
/**
* take off a lister by it's id
*
* @param {string} uid of event listener to turn off.
*/
mvc.Control.prototype.off = function(uid) {
goog.object.forEach(this.eventHolder_.handlers, function(val, key) {
goog.array.removeIf(val, function(handler) {
return handler.uid == uid;
});
});
};
/**
* pass in a string like "#elementId", ".className" or "tagName[ .className]"
* to get array of elements with the id, class or tag and class name
*
* @param {string} selector string to use to find elements.
* @return {?goog.array.ArrayLike} elements found.
*/
mvc.Control.prototype.getEls = function(selector) {
if (selector.charAt(0) == '-')
selector = '.' + selector.substring(1);
if (selector.charAt(0) == '.') {
return goog.dom.getElementsByClass(selector.substring(1),
/** @type {Element} */(this.getElement())) || [];
}
if (selector.charAt(0) == '#') {
return [goog.dom.getElement(selector)];
}
return goog.dom.getElementsByTagNameAndClass(selector.replace(/\s.*/, ''),
selector.indexOf('.') > 0 ? selector.replace(/.*\./, '') : null,
/** @type {Element} */(this.getElement()));
};
/**
* Allows easy binding of a model's attribute to an element or a function.
* bind('name', function(value), handler) allows you to run a function and
* optionally bind it to the handler. You can also pass in an array of names
* to listen for a change on any of the attributes.
*
* @param {Array|string} name of attributes to listen to.
* @param {Function} fn function to run when change.
* @param {*=} opt_handler object for 'this' of function.
* @return {number} id to use for unbind.
*/
mvc.Control.prototype.bind = function(name, fn, opt_handler) {
var id = this.getModel().bind(name, fn, opt_handler || this);
this.modelListeners_.push(id);
return id;
};
/**
* bind to any change event
*
* @param {Function} fn function to bind.
* @param {Object=} opt_handler object to bind 'this' to.
* @return {number} id to use for unbind.
*/
mvc.Control.prototype.bindAll = function(fn, opt_handler) {
var id = this.getModel().bindAll(fn, opt_handler || this);
this.modelListeners_.push(id);
return id;
};
/**
* @param {Function} fn function to run when model is disposed.
* @param {Object=} opt_handler object for 'this' of function.
* @return {number} id to use for unbind.
*/
mvc.Control.prototype.bindUnload = function(fn, opt_handler) {
var id = this.getModel().bindUnload(fn, opt_handler || this);
this.modelListeners_.push(id);
return id;
};
/**
* use this to bind functions to a change in any of the collections models
*
* @param {Function} fn function to run on model change.
* @param {Object=} opt_handler to set 'this' of function.
* @return {number} uid to use with unbind.
*/
mvc.Control.prototype.anyModelChange = function(fn, opt_handler) {
var id = this.getModel().anyModelChange(fn, opt_handler || this);
this.modelListeners_.push(id);
return id;
};
/**
* use this to bind functions to a change in any of the collections models
*
* @param {Function} fn function to run on model change.
* @param {Object=} opt_handler to set 'this' of function.
* @return {number} uid to use with unbind.
*/
mvc.Control.prototype.modelChange = function(fn, opt_handler) {
var id = this.getModel().modelChange(fn, opt_handler || this);
this.modelListeners_.push(id);
return id;
};
/**
* unbind a listener by id
*
* @param {number} id returned form bind or bindall.
* @return {boolean} if found and removed.
*/
mvc.Control.prototype.unbind = function(id) {
return this.getModel().unbind(id);
};
/**
* @inheritDoc
*/
mvc.Control.prototype.disposeInternal = function() {
goog.array.forEach(this.modelListeners_, function(id) {
this.unbind(id);
}, this);
this.eventHolder_ = null;
goog.base(this, 'disposeInternal');
};
| control.js | // (c) 2012 Rhys Brett-Bowen, Catch.com
// goog.mvc may be freely distributed under the MIT license.
// For all details and documentation:
// https://github.com/rhysbrettbowen/goog.mvc
goog.provide('mvc.Control');
goog.require('goog.dom');
goog.require('goog.object');
goog.require('goog.ui.Component');
/**
* instantiate with a mvc.Model
*
* @constructor
* @param {mvc.Model} model to link with the control.
* @extends {goog.ui.Component}
*/
mvc.Control = function(model) {
goog.base(this);
this.setModel(model);
this.eventHolder_ = {
listeners: {},
handlers: {}
};
this.modelListeners_ = [];
};
goog.inherits(mvc.Control, goog.ui.Component);
/**
* Functions that can be passed to the mvc.Model.bind
*
* @enum {Function}
*/
mvc.Control.Fn = {
TEXT: goog.dom.setTextContent,
VAL: function(el, val) {el.value = val;},
CLASS: goog.dom.classes.add
};
/**
* remove the element and dispose
*/
mvc.Control.prototype.remove = function() {
goog.dom.removeNode(this.getElement());
this.dispose();
};
/**
* Internal use. Handles and delegates events
*
* @private
* @param {string} type of event.
* @param {Event} e the original event.
*/
mvc.Control.prototype.handleEvents_ = function(type, e) {
if (!this.eventHolder_.handlers[type])
return;
// go through handlers in order and stop if propagation stopped
goog.array.forEach(this.eventHolder_.handlers[type], function(handler) {
if (e.propagationStopped_) {
return;
}
// if no selector or matches selector then fire
if (!handler.selectors.length ||
goog.array.some(handler.selectors, function(className) {
return goog.isFunction(className) ?
className(e) :
goog.dom.classes.has(/** @type {!Node} */(e.target),
className);
})) {
goog.bind(handler.fn, handler.handler)(e);
}
});
};
/**
* delegating events. An event type is needed as well as a handling function.
* if a third parameter is passed then elements with that class will be
* listened to, otherwise the whole component. Returns a uid that can be used
* to end the listener with the off method
*
* @param {string} eventName the event type to listen for.
* @param {Function} fn the function to run on the event.
* @param {string|Array.<string>|Function=} opt_className or names to
* check element against to see if listener function should fire. if it is
* a function then it takes the event and returns true if it matches.
* @param {*=} opt_handler object to bind 'this' to, otherwise mvc.Control.
* @param {number=} opt_priority default is 50, lower is more important.
* @return {number} uid to use with off method.
*/
mvc.Control.prototype.on = function(
eventName, fn, opt_className, opt_handler, opt_priority) {
// initialize
if (!this.eventHolder_) {
this.eventHolder_ = {
listeners: {},
handlers: {}
};
}
if (!this.eventHolder_.handlers[eventName]) {
this.eventHolder_.handlers[eventName] = [];
}
if (!this.eventHolder_.listeners[eventName]) {
this.eventHolder_.listeners[eventName] = this.getHandler().listen(
this.getElement(), eventName,
goog.bind(this.handleEvents_, this, eventName));
}
if (!goog.isDef(opt_className)) {
opt_className = [];
}
var obj = {
selectors: (goog.isArray(opt_className) ?
opt_className : [opt_className]),
fn: fn,
uid: null,
handler: (opt_handler || this),
priority: (opt_priority || 50)
};
obj.uid = goog.getUid(obj);
// insert in array based on priority
goog.array.insertAt(this.eventHolder_.handlers[eventName], obj,
goog.array.findIndexRight(this.eventHolder_.handlers[eventName],
function(obj) {
return obj.priority <= (opt_priority || 50);
}
) + 1);
return obj.uid;
};
/**
* same as on, but will only fire once
*
* @param {string} eventName the event type to listen for.
* @param {Function} fn the function to run on the event.
* @param {string|Array.<string>|Function=} opt_className or names to
* check element against to see if listener function should fire.if it is
* a function then it takes the event and returns true if it matches.
* @param {*=} opt_handler object to bind 'this' to, otherwise mvc.Control.
* @param {number=} opt_priority default is 50, lower is more important.
* @return {number} uid to use with off method.
*/
mvc.Control.prototype.once = function(
eventName, fn, opt_className, opt_handler, opt_priority) {
var uid;
var onceFn = function() {
fn.apply(/** @type {Object} */(opt_handler || this),
Array.prototype.slice.call(arguments));
this.off(uid);
};
uid = this.on(eventName, onceFn, opt_className);
return uid;
};
/**
* same as on but assumes the event type is a click
*
* @param {Function} fn the function to run on the event.
* @param {string|Array.<string>|Function=} opt_className or names to
* check element against to see if listener function should fire. if it is
* a function then it takes the event and returns true if it matches.
* @param {*=} opt_handler object to bind 'this' to, otherwise mvc.Control.
* @param {number=} opt_priority default is 50, lower is more important.
* @return {number} uid to use with off method.
*/
mvc.Control.prototype.click = function(
fn, opt_className, opt_handler, opt_priority) {
return this.on(goog.events.EventType.CLICK,
fn, opt_className, opt_handler, opt_priority);
};
/**
* take off a lister by it's id
*
* @param {string} uid of event listener to turn off.
*/
mvc.Control.prototype.off = function(uid) {
goog.object.forEach(this.eventHolder_.handlers, function(val, key) {
goog.array.removeIf(val, function(handler) {
return handler.uid == uid;
});
});
};
/**
* pass in a string like "#elementId", ".className" or "tagName[ .className]"
* to get array of elements with the id, class or tag and class name
*
* @param {string} selector string to use to find elements.
* @return {?goog.array.ArrayLike} elements found.
*/
mvc.Control.prototype.getEls = function(selector) {
if (selector.charAt(0) == '-')
selector = '.' + selector.substring(1);
if (selector.charAt(0) == '.') {
return goog.dom.getElementsByClass(selector.substring(1),
/** @type {Element} */(this.getElement())) || [];
}
if (selector.charAt(0) == '#') {
return [goog.dom.getElement(selector)];
}
return goog.dom.getElementsByTagNameAndClass(selector.replace(/\s.*/, ''),
selector.indexOf('.') > 0 ? selector.replace(/.*\./, '') : null,
/** @type {Element} */(this.getElement()));
};
/**
* Allows easy binding of a model's attribute to an element or a function.
* bind('name', function(value), handler) allows you to run a function and
* optionally bind it to the handler. You can also pass in an array of names
* to listen for a change on any of the attributes.
*
* @param {Array|string} name of attributes to listen to.
* @param {Function} fn function to run when change.
* @param {*=} opt_handler object for 'this' of function.
* @return {number} id to use for unbind.
*/
mvc.Control.prototype.bind = function(name, fn, opt_handler) {
var id = this.getModel().bind(name, fn, opt_handler || this);
this.modelListeners_.push(id);
return id;
};
/**
* bind to any change event
*
* @param {Function} fn function to bind.
* @param {Object=} opt_handler object to bind 'this' to.
* @return {number} id to use for unbind.
*/
mvc.Control.prototype.bindAll = function(fn, opt_handler) {
var id = this.getModel().bindAll(fn, opt_handler || this);
this.modelListeners_.push(id);
return id;
};
/**
* @param {Function} fn function to run when model is disposed.
* @param {Object=} opt_handler object for 'this' of function.
* @return {number} id to use for unbind.
*/
mvc.Model.prototype.bindUnload = function(fn, opt_handler) {
var id = this.getModel().bindUnload(fn, opt_handler || this);
this.modelListeners_.push(id);
return id;
};
/**
* use this to bind functions to a change in any of the collections models
*
* @param {Function} fn function to run on model change.
* @param {Object=} opt_handler to set 'this' of function.
* @return {number} uid to use with unbind.
*/
mvc.Control.prototype.anyModelChange = function(fn, opt_handler) {
var id = this.getModel().anyModelChange(fn, opt_handler || this);
this.modelListeners_.push(id);
return id;
};
/**
* use this to bind functions to a change in any of the collections models
*
* @param {Function} fn function to run on model change.
* @param {Object=} opt_handler to set 'this' of function.
* @return {number} uid to use with unbind.
*/
mvc.Control.prototype.modelChange = function(fn, opt_handler) {
var id = this.getModel().modelChange(fn, opt_handler || this);
this.modelListeners_.push(id);
return id;
};
/**
* unbind a listener by id
*
* @param {number} id returned form bind or bindall.
* @return {boolean} if found and removed.
*/
mvc.Control.prototype.unbind = function(id) {
return this.getModel().unbind(id);
};
/**
* @inheritDoc
*/
mvc.Control.prototype.disposeInternal = function() {
goog.array.forEach(this.modelListeners_, function(id) {
this.unbind(id);
}, this);
this.eventHolder_ = null;
goog.base(this, 'disposeInternal');
};
| fix typo
| control.js | fix typo | <ide><path>ontrol.js
<ide> * @param {Object=} opt_handler object for 'this' of function.
<ide> * @return {number} id to use for unbind.
<ide> */
<del>mvc.Model.prototype.bindUnload = function(fn, opt_handler) {
<add>mvc.Control.prototype.bindUnload = function(fn, opt_handler) {
<ide> var id = this.getModel().bindUnload(fn, opt_handler || this);
<ide> this.modelListeners_.push(id);
<ide> return id; |
|
JavaScript | mit | 2ce81d1394ae6a91a320d233467b47da85bc12bc | 0 | wolfib/sequenceTubeMap,wolfib/sequenceTubeMap | /*jshint loopfunc: true */
/*jshint esversion: 6*/
var sequenceTubeMap = (function () {
var offsetX = 0;
var offsetY = 0;
const color = d3.scale.category10().domain([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
var svg;
var inputNodes = [];
var inputTracks = [];
var numberOfNodes;
var numberOfTracks;
var nodeMap; //maps node names to node indices
var edges = []; //contains concrete coordinate info about the different tracks
var arcs = [[], [], [], []]; //contains coords if the edges' 90° angles
var assignment = []; //contains info about lane assignments sorted by order
var extraLeft = []; //info whether nodes have to be moved further apart because of multiple 180° directional changes at the same horizontal order
var extraRight = []; //info whether nodes have to be moved further apart because of multiple 180° directional changes at the same horizontal order
var maxOrder; //horizontal order of the rightmost node
var nextNodeIsAlwaysToTheRight = true;
function create(inputSvg, nodes, tracks) {
svg = inputSvg;
//inputNodes = nodes.slice(0); //no deep copy necessary because inner stuff does not change
//inputTracks = tracks.slice(0);
inputNodes = (JSON.parse(JSON.stringify(nodes))); //deep copy
inputTracks = (JSON.parse(JSON.stringify(tracks)));
createTubeMap();
}
function moveTrackToFirstPosition(index) {
var i, j;
var nodesToInvert = [];
var currentSequence;
inputTracks.unshift(inputTracks[index]); //add element to beginning
inputTracks.splice(index + 1, 1); //remove 1 element from the middle
currentSequence = inputTracks[0].sequence;
for (i = 0; i < currentSequence.length; i++) {
if (currentSequence[i].charAt(0) === '-') {
currentSequence[i] = currentSequence[i].substr(1);
nodesToInvert.push(currentSequence[i]);
}
}
//console.log("nodes to invert:");
//console.log(nodesToInvert);
for (i = 1; i < inputTracks.length; i++) {
currentSequence = inputTracks[i].sequence;
for (j = 0; j < currentSequence.length; j++) {
if (currentSequence[j].charAt(0) !== '-') {
if (nodesToInvert.indexOf(currentSequence[j]) !== -1) {
currentSequence[j] = "-" + currentSequence[j];
//console.log("Track " + i + "[" + j + "] CHANGED TO " + currentSequence[j]);
}
} else {
if (nodesToInvert.indexOf(currentSequence[j].substr(1)) !== -1) {
currentSequence[j] = currentSequence[j].substr(1);
}
}
}
}
//console.log(inputTracks);
createTubeMap();
}
function switchAlwaysMoveRight() {
nextNodeIsAlwaysToTheRight = ! nextNodeIsAlwaysToTheRight;
createTubeMap();
}
function createTubeMap() {
//clear svg for (re-)drawing
var nodes = (JSON.parse(JSON.stringify(inputNodes))); //deep copy (can add stuff to copy and leave original unchanged)
var tracks = (JSON.parse(JSON.stringify(inputTracks)));
svg.selectAll("*").remove();
edges = [];
arcs = [[], [], [], []];
assignment = [];
extraLeft = [];
extraRight = [];
numberOfNodes = nodes.length;
numberOfTracks = tracks.length;
//console.log("number of tracks: " + numberOfTracks);
nodeMap = generateNodeMap(nodes);
generateNodeSuccessors(nodes, tracks);
generateNodeDegree(nodes, tracks);
generateNodeOrder(nodes, tracks);
maxOrder = getMaxOrder(nodes);
for (var i = 0; i <= maxOrder; i++) {
console.log('order ' + i + ': ');
nodes.forEach(function(node) {
if (node.order === i) console.log(node.name);
});
}
//generateNodeDegree(nodes, tracks);
switchNodeOrientation(nodes, tracks);
generateLaneAssignment(nodes, tracks);
generateNodeXCoords(nodes, tracks);
movePositionWithinSVG(nodes, tracks);
generateEdgesFromPath(nodes, tracks, edges);
console.log("Assignment:");
console.log(assignment);
console.log("Tracks:");
console.log(tracks);
console.log("Nodes:");
console.log(nodes);
console.log("Arcs:");
console.log(arcs);
console.log("Edges:");
console.log(edges);
removeUnusedNodes(nodes);
drawEdges(edges);
if (arcs[0].length > 0) drawTopLeftEdgeArcs(arcs[0]);
if (arcs[1].length > 0) drawTopRightEdgeArcs(arcs[1]);
if (arcs[2].length > 0) drawBottomRightEdgeArcs(arcs[2]);
if (arcs[3].length > 0) drawBottomLeftEdgeArcs(arcs[3]);
drawNodes(nodes);
}
function removeUnusedNodes(nodes) {
var i;
for (i = nodes.length - 1; i >= 0; i--) {
if (nodes[i].degree === 0) {
nodes.splice(i, 1);
}
}
numberOfNodes = nodes.length;
}
function movePositionWithinSVG(nodes, tracks) {
var minLane = Number.MAX_SAFE_INTEGER;
var maxLane = Number.MIN_SAFE_INTEGER;
var maxX = Number.MIN_SAFE_INTEGER;
tracks.forEach(function (track) {
track.path.forEach(function (node) {
if (node.lane < minLane) minLane = node.lane;
if (node.lane > maxLane) maxLane = node.lane;
});
});
//console.log(minLane + ' ' + maxLane);
//offsetX = 0;
offsetY = -100 - 22 * minLane;
nodes.forEach(function(node) {
node.y = offsetY + 110 + 22 * node.yCoord;
if (node.x + 20 * node.width > maxX) maxX = node.x + 20 * node.width;
});
//console.log(maxX);
svg.attr("height", 20 + 22 * (maxLane - minLane));
svg.attr("width", maxX);
}
function generateNodeMap(nodes) { //map node names to node indices
var nodeMap = new Map();
nodes.forEach(function(node, index) {
nodeMap.set(node.name, index);
});
return nodeMap;
}
function generateNodeSuccessors(nodes, tracks) { //adds a successor-array to each node containing the names of the nodes coming directly after the current node
var i;
var currentNode;
var followerID;
var modifiedSequence = [];
nodes.forEach(function(node) {
node.successors = [];
node.predecessors = [];
});
tracks.forEach(function(track) {
modifiedSequence = uninvert(track.sequence);
for(i = 0; i < modifiedSequence.length - 1; i++) {
currentNode = nodes[nodeMap.get(modifiedSequence[i])];
followerID = modifiedSequence[i + 1];
if (currentNode.successors.indexOf(followerID) === -1) {
currentNode.successors.push(followerID);
}
if (nodes[nodeMap.get(followerID)].predecessors.indexOf(modifiedSequence[i]) === -1) {
nodes[nodeMap.get(followerID)].predecessors.push(modifiedSequence[i]);
}
}
});
}
function generateNodeOrderOfSingleTrack(sequence, nodes) { //calculates order values for all nodes along a single track
currentOrder = 0;
sequence.forEach(function(nodeName) {
currentNode = nodes[nodeMap.get(nodeName)];
if (! currentNode.hasOwnProperty("order")) { //default case
currentNode.order = currentOrder;
currentOrder++;
} else { //track has a repeat revisiting a node
//currentOrder = currentNode.order + 1;
}
});
}
function generateNodeOrderLeftEnd(sequence, nodes) { //calculate the order-value of nodes contained in sequence which are to the left of the first node which already has an order-value
var anchorIndex = 0;
var nodeNames = new Map();
var currentOrder;
var currentNode;
while (! nodes[nodeMap.get(sequence[anchorIndex])].hasOwnProperty("order")) anchorIndex++; //anchor = first node in common with existing graph
for (j = anchorIndex - 1; j >= 0; j--) { //count number of nodes to the left of anchorIndex counting repeated nodes only once
nodeNames.set(sequence[j], true);
}
currentOrder = nodes[nodeMap.get(sequence[anchorIndex])].order - nodeNames.size; //order of first node
for (j = 0; j < anchorIndex; j++) { //assign order to nodes
currentNode = nodes[nodeMap.get(sequence[j])];
if (! currentNode.hasOwnProperty("order")) {
currentNode.order = currentOrder;
currentOrder++;
}
}
if (nodes[nodeMap.get(sequence[0])].order < 0) {
increaseOrderForAllNodes(nodes, -nodes[nodeMap.get(sequence[0])].order);
}
return anchorIndex;
}
function generateNodeOrder(nodes, tracks) { //generate global sequence of nodes from left to right, starting with first track and adding other tracks sequentially
var modifiedSequence;
var i;
var j;
var currentOrder;
var currentNode;
var rightIndex;
var leftIndex;
generateNodeOrderOfSingleTrack(tracks[0].sequence, nodes); //calculate order values for all nodes of the first track
for (i = 1; i < tracks.length; i++) {
console.log("Node order for track " + i + " " + tracks[i].id);
modifiedSequence = uninvert(tracks[i].sequence);
//modifiedSequence = tracks[i].sequence;
//console.log(tracks[i].sequence);
//console.log(modifiedSequence);
rightIndex = generateNodeOrderLeftEnd(modifiedSequence, nodes); //calculate order values for all nodes until the first anchor
while (rightIndex < modifiedSequence.length) { //move right until the end of the sequence
//find next anchor node
leftIndex = rightIndex;
rightIndex++;
while ((rightIndex < modifiedSequence.length) && (! nodes[nodeMap.get(modifiedSequence[rightIndex])].hasOwnProperty("order"))) rightIndex++;
if (rightIndex < modifiedSequence.length) { //middle segment between two anchors
currentOrder = nodes[nodeMap.get(modifiedSequence[leftIndex])].order + 1; //start with order value of leftAnchor + 1
for (j = leftIndex + 1; j < rightIndex; j++) {
nodes[nodeMap.get(modifiedSequence[j])].order = currentOrder; //assign order values
//console.log(modifiedSequence[j] + " -> " + currentOrder);
currentOrder++;
}
if (nodes[nodeMap.get(modifiedSequence[rightIndex])].order > nodes[nodeMap.get(modifiedSequence[leftIndex])].order) { //if order-value of left anchor < order-value of right anchor
if (nodes[nodeMap.get(modifiedSequence[rightIndex])].order < currentOrder) { //and the right anchor now has a lower order-value than our newly added nodes
console.log('first');
increaseOrderForSuccessors(nodes, nodes[nodeMap.get(modifiedSequence[rightIndex])], currentOrder);
}
} else { //potential node reversal: check for ordering conflict, if no conflict found move node at rightIndex further to the right in order to not create a track reversal
if (! isSuccessor(nodes[nodeMap.get(modifiedSequence[rightIndex])], nodes[nodeMap.get(modifiedSequence[leftIndex])], nodes)) { //no real reversal
//console.log("hier");
//console.log(isSuccessor(nodes[nodeMap.get(modifiedSequence[rightIndex])], nodes[nodeMap.get(modifiedSequence[leftIndex])], nodes));
console.log('second');
increaseOrderForSuccessors(nodes, nodes[nodeMap.get(modifiedSequence[rightIndex])], currentOrder);
} else { //real reversal
//if (! nextNodeIsAlwaysToTheRight) {
if ((tracks[i].sequence[leftIndex].charAt(0) === '-') || (nodes[nodeMap.get(modifiedSequence[leftIndex + 1])].degree < 2)) {
//if (nodes[nodeMap.get(modifiedSequence[leftIndex + 1])].degree < 2) {
currentOrder = nodes[nodeMap.get(modifiedSequence[leftIndex])].order - 1; //start with order value of leftAnchor + 1
for (j = leftIndex + 1; j < rightIndex; j++) {
nodes[nodeMap.get(modifiedSequence[j])].order = currentOrder; //assign order values
//console.log(modifiedSequence[j] + " -> " + currentOrder);
currentOrder--;
}
}
}
}
} else { //right segment to the right of last anchor
currentOrder = nodes[nodeMap.get(modifiedSequence[leftIndex])].order + 1;
for (j = leftIndex + 1; j < modifiedSequence.length; j++) {
currentNode = nodes[nodeMap.get(modifiedSequence[j])];
if (! currentNode.hasOwnProperty("order")) {
currentNode.order = currentOrder;
currentOrder++;
}
}
}
}
}
}
function generateNodeOrderALT(nodes, tracks) { //generate global sequence of nodes from left to right, starting with first track and adding other tracks sequentially
var modifiedSequence;
var i;
var j;
var currentOrder;
var currentNode;
var rightIndex;
var leftIndex;
generateNodeOrderOfSingleTrack(tracks[0].sequence, nodes); //calculate order values for all nodes of the first track
for (i = 1; i < tracks.length; i++) {
//console.log("Node order for track " + i + " " + tracks[i].id);
modifiedSequence = uninvert(tracks[i].sequence);
//console.log(tracks[i].sequence);
//console.log(modifiedSequence);
rightIndex = generateNodeOrderLeftEnd(modifiedSequence, nodes); //calculate order values for all nodes until the first anchor
while (rightIndex < modifiedSequence.length) { //move right until the end of the sequence
//find next anchor node
leftIndex = rightIndex;
rightIndex++;
while ((rightIndex < modifiedSequence.length) && (! nodes[nodeMap.get(modifiedSequence[rightIndex])].hasOwnProperty("order"))) rightIndex++;
if (rightIndex < modifiedSequence.length) { //middle segment between two anchors
currentOrder = nodes[nodeMap.get(modifiedSequence[leftIndex])].order + 1; //start with order value of leftAnchor + 1
for (j = leftIndex + 1; j < rightIndex; j++) {
nodes[nodeMap.get(modifiedSequence[j])].order = currentOrder; //assign order values
//console.log(modifiedSequence[j] + " -> " + currentOrder);
currentOrder++;
}
if (nodes[nodeMap.get(modifiedSequence[rightIndex])].order > nodes[nodeMap.get(modifiedSequence[leftIndex])].order) { //if order-value of left anchor < order-value of right anchor
if (nodes[nodeMap.get(modifiedSequence[rightIndex])].order < currentOrder) { //and the right anchor now has a lower order-value than our newly added nodes
increaseOrderForSuccessors(nodes, nodes[nodeMap.get(modifiedSequence[rightIndex])], currentOrder);
}
} else { //potential node reversal: check for ordering conflict, if no conflict found move node at rightIndex further to the right in order to not create a track reversal
if (! isSuccessor(nodes[nodeMap.get(modifiedSequence[rightIndex])], nodes[nodeMap.get(modifiedSequence[leftIndex])], nodes)) { //no real reversal
//console.log("hier");
//console.log(isSuccessor(nodes[nodeMap.get(modifiedSequence[rightIndex])], nodes[nodeMap.get(modifiedSequence[leftIndex])], nodes));
increaseOrderForSuccessors(nodes, nodes[nodeMap.get(modifiedSequence[rightIndex])], currentOrder);
} else { //real reversal
if (! nextNodeIsAlwaysToTheRight) {
currentOrder = nodes[nodeMap.get(modifiedSequence[leftIndex])].order - 1; //start with order value of leftAnchor + 1
for (j = leftIndex + 1; j < rightIndex; j++) {
nodes[nodeMap.get(modifiedSequence[j])].order = currentOrder; //assign order values
//console.log(modifiedSequence[j] + " -> " + currentOrder);
currentOrder--;
}
}
}
}
} else { //right segment to the right of last anchor
currentOrder = nodes[nodeMap.get(modifiedSequence[leftIndex])].order + 1;
for (j = leftIndex + 1; j < modifiedSequence.length; j++) {
currentNode = nodes[nodeMap.get(modifiedSequence[j])];
if (! currentNode.hasOwnProperty("order")) {
currentNode.order = currentOrder;
currentOrder++;
}
}
}
}
}
}
function isSuccessor(first, second, nodes) { //checks if second is a successor of first
var visitedNodes = [];
return isSuccessorRecursive(first, second, visitedNodes, nodes);
}
function isSuccessorRecursive(first, second, visitedNodes, nodes) {
var i;
if (first.name === second.name) {
return true;
}
for (i = 0; i < first.successors.length; i++) {
//if(first.successors[i] === second.name) return true;
if (visitedNodes.indexOf(first.successors[i]) === -1) {
visitedNodes.push(first.successors[i]);
if (isSuccessorRecursive(nodes[nodeMap.get(first.successors[i])], second, visitedNodes, nodes)) {
return true;
}
}
}
return false;
}
function getMaxOrder(nodes) { //get order number of the rightmost node
var max = -1;
nodes.forEach(function(node) {
if ((node.hasOwnProperty("order")) && (node.order > max)) max = node.order;
});
return max;
}
function uninvert(sequence) { //generates sequence keeping the order but removing all "-"s from nodes
var result = [];
var i;
for (i = 0; i < sequence.length; i++) {
if (sequence[i].charAt(0) !== '-') {
result.push(sequence[i]);
} else {
result.push(sequence[i].substr(1));
}
}
return result;
}
function increaseOrderForAllNodes(nodes, amount) { //increases the order-value of all nodes by amount
console.log('increase for all');
nodes.forEach(function(node) {
if (node.hasOwnProperty("order")) node.order += amount;
});
}
function increaseOrderForSuccessors(nodes, currentNode, order) { //increases the order-value for currentNode and (if necessary) successor nodes recursively
console.log("increasing orders from " + currentNode.name + " to " + order);
var increasedOrders = {};
increaseOrderForSuccessorsRecursive(nodes, currentNode, order, currentNode, increasedOrders);
//console.log(increasedOrders);
for (var nodeName in increasedOrders) {
if (increasedOrders.hasOwnProperty(nodeName)) {
console.log(nodeName + ': ' + nodes[nodeMap.get(nodeName)].order + ' -> ' + increasedOrders[nodeName]);
nodes[nodeMap.get(nodeName)].order = increasedOrders[nodeName];
}
}
}
function increaseOrderForSuccessorsRecursive(nodes, currentNode, order, startingNode, increasedOrders) {
if ((currentNode.hasOwnProperty("order")) && (currentNode.order < order)) {
if ((! increasedOrders.hasOwnProperty(currentNode.name)) || (increasedOrders[currentNode.name] < order)) {
increasedOrders[currentNode.name] = order;
currentNode.successors.forEach(function(successor) {
if (nodes[nodeMap.get(successor)].order > currentNode.order) { //only increase order of successors if they lie to the right of the currentNode (not for repeats/translocations)
increaseOrderForSuccessorsRecursive(nodes, nodes[nodeMap.get(successor)], order + 1, startingNode, increasedOrders);
}
});
if (currentNode !== startingNode) {
currentNode.predecessors.forEach(function(predecessor) {
if (nodes[nodeMap.get(predecessor)].order > currentNode.order) { //only increase order of predecessors if they lie to the right of the currentNode (not for repeats/translocations)
//console.log("predecessor: from " + currentNode.name + " to " + predecessor + " = " + (order + 1));
increaseOrderForSuccessorsRecursive(nodes, nodes[nodeMap.get(predecessor)], order + 1, startingNode, increasedOrders);
}
});
}
}
}
}
function generateNodeDegree(nodes, tracks) { //calculates the node degree: the number of tracks passing through the node / the node height
nodes.forEach(function(node) { node.tracks = []; });
tracks.forEach(function(track) {
//console.log(track.id);
track.sequence.forEach(function(nodeName) {
//nodes[nodeMap.get(nodeName)].tracks=[];
var noMinusName = nodeName;
if (noMinusName.charAt(0) === '-') noMinusName = noMinusName.substr(1);
nodes[nodeMap.get(noMinusName)].tracks.push(track.id);
});
});
nodes.forEach(function(node) {
if (node.hasOwnProperty("tracks")) node.degree = node.tracks.length;
});
}
function switchNodeOrientation(nodes, tracks) {
var toSwitch = {};
var i, j;
var nodeName, prevNode, nextNode, currentNode;
for (i = 1; i < tracks.length; i++) {
//TODO: first element
for (j = 1; j < tracks[i].sequence.length - 1; j++) {
nodeName = tracks[i].sequence[j];
if (nodeName.charAt(0) === "-") nodeName = nodeName.substr(1);
currentNode = nodes[nodeMap.get(nodeName)];
if (tracks[0].sequence.indexOf(nodeName) === -1) { //do not change orientation for nodes which are part of the pivot track
if (tracks[i].sequence[j - 1].charAt(0) !== "-") prevNode = nodes[nodeMap.get(tracks[i].sequence[j - 1])];
else prevNode = nodes[nodeMap.get(tracks[i].sequence[j - 1].substr(1))];
if (tracks[i].sequence[j + 1].charAt(0) !== "-") nextNode = nodes[nodeMap.get(tracks[i].sequence[j + 1])];
else nextNode = nodes[nodeMap.get(tracks[i].sequence[j + 1].substr(1))];
if ((prevNode.order < currentNode.order) && (currentNode.order < nextNode.order)) {
if (! toSwitch.hasOwnProperty(nodeName)) toSwitch[nodeName] = 0;
if (tracks[i].sequence[j].charAt(0) === "-") toSwitch[nodeName] += 1;
else toSwitch[nodeName] -= 1;
}
if ((prevNode.order > currentNode.order) && (currentNode.order > nextNode.order)) {
if (! toSwitch.hasOwnProperty(nodeName)) toSwitch[nodeName] = 0;
if (tracks[i].sequence[j].charAt(0) === "-") toSwitch[nodeName] -= 1;
else toSwitch[nodeName] += 1;
}
}
}
//TODO: last element
}
tracks.forEach(function(track, trackIndex) {
track.sequence.forEach(function(node, nodeIndex) {
nodeName = node;
if (nodeName.charAt(0) === "-") nodeName = nodeName.substr(1);
if ((toSwitch.hasOwnProperty(nodeName)) && (toSwitch[nodeName] > 0)) {
if (node.charAt(0) === "-") tracks[trackIndex].sequence[nodeIndex] = node.substr(1);
else tracks[trackIndex].sequence[nodeIndex] = "-" + node;
}
});
});
}
function generateNodeXCoords(nodes, tracks) { //calculates the concrete values for the nodes' x-coordinates
var extra;
var currentX;
var nextX;
var currentOrder;
nodes.sort(compareNodesByOrder);
nodeMap = generateNodeMap(nodes);
extra = calculateExtraSpace(nodes, tracks);
currentX = 0;
nextX = offsetX + 20;
currentOrder = -1;
nodes.forEach(function(node, index) {
if (node.hasOwnProperty("order")) {
if (node.order > currentOrder) {
currentOrder = node.order;
currentX = nextX + 10 * extra[node.order];
}
node.x = currentX;
nextX = Math.max(nextX, currentX + 20 + 20 * node.width);
} else {
console.log("Node " + node.name + " has no order property");
}
});
}
function calculateExtraSpace(nodes, tracks) { //calculates additional horizontal space needed between two nodes
//two neighboring nodes have to be moved further apart if there is a lot going on in between them
//-> edges turning to vertical orientation should not overlap
var i;
var leftSideEdges = [];
var rightSideEdges = [];
var extra = [];
for (i = 0; i <= maxOrder; i++) {
leftSideEdges.push(0);
rightSideEdges.push(0);
}
tracks.forEach(function(track, trackID) {
for (i = 1; i < track.path.length; i++) {
if (track.path[i].order === track.path[i - 1].order) { //repeat or translocation
if (track.path[i].isForward === true) leftSideEdges[track.path[i].order]++;
else rightSideEdges[track.path[i].order]++;
}
}
});
/*console.log("left side edges:");
console.log(leftSideEdges);
console.log("right side edges:");
console.log(rightSideEdges);*/
extra.push(Math.max(0, leftSideEdges[0] - 1));
for (i = 1; i <= maxOrder; i++) {
extra.push(Math.max(0, leftSideEdges[i] - 1) + Math.max(0, rightSideEdges[i - 1] - 1));
}
return extra;
}
function generateLaneAssignment(nodes, tracks) { //create and fill assignment-variable, which contains info about tracks and lanes for each order-value
var i;
var j;
var segmentNumber;
var currentNodeId;
var currentNodeIsForward;
var currentNode;
var previousNode;
var previousNodeIsForward;
var prevSegmentPerOrderPerTrack = [];
for (i = 0; i <= maxOrder; i++) {
assignment[i] = [];
prevSegmentPerOrderPerTrack[i] = [];
for (j = 0; j < numberOfTracks; j++) {
prevSegmentPerOrderPerTrack[i][j] = null;
}
}
tracks.forEach(function(track, trackNo) {
//add info for start of track
currentNodeId = track.sequence[0];
if (currentNodeId.charAt(0) != '-') {
currentNodeIsForward = true;
} else {
currentNodeId = currentNodeId.substr(1);
currentNodeIsForward = false;
}
currentNode = nodes[nodeMap.get(currentNodeId)];
track.path = [];
track.path.push({order: currentNode.order, lane: null, isForward: currentNodeIsForward, node: currentNodeId});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: 0, node: currentNodeId, isForward: currentNodeIsForward, lane: null});
addToAssignment(currentNode.order, currentNodeId, trackNo, 0, prevSegmentPerOrderPerTrack);
segmentNumber = 1;
for (i = 1; i < track.sequence.length; i++) {
previousNode = currentNode;
previousNodeIsForward = currentNodeIsForward;
currentNodeId = track.sequence[i];
currentNodeIsForward = true;
if (currentNodeId.charAt(0) === '-') {
currentNodeId = currentNodeId.substr(1);
currentNodeIsForward = false;
}
currentNode = nodes[nodeMap.get(currentNodeId)];
if (currentNode.order > previousNode.order) {
if (! previousNodeIsForward) {
track.path.push({order: previousNode.order, lane: null, isForward: true, node: null});
//assignment[previousNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: null, isForward: true, lane: null});
addToAssignment(previousNode.order, null, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
}
for (j = previousNode.order + 1; j < currentNode.order; j++) {
track.path.push({order: j, lane: null, isForward: true, node: null});
//assignment[j].push({trackNo: trackNo, segmentNo: segmentNumber, node: null, isForward: true, lane: null});
addToAssignment(j, null, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
}
if (! currentNodeIsForward) {
track.path.push({order: currentNode.order, lane: null, isForward: true, node: null});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: null, isForward: true, lane: null});
addToAssignment(currentNode.order, null, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
track.path.push({order: currentNode.order, lane: null, isForward: false, node: currentNodeId});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: currentNodeId, isForward: false, lane: null});
addToAssignment(currentNode.order, currentNodeId, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
} else {
track.path.push({order: currentNode.order, lane: null, isForward: true, node: currentNodeId});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: currentNodeId, isForward: true, lane: null});
addToAssignment(currentNode.order, currentNodeId, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
}
} else if (currentNode.order < previousNode.order) {
if (previousNodeIsForward) {
track.path.push({order: previousNode.order, lane: null, isForward: false, node: null});
//assignment[previousNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: null, isForward: false, lane: null});
addToAssignment(previousNode.order, null, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
}
for (j = previousNode.order - 1; j > currentNode.order; j--) {
track.path.push({order: j, lane: null, isForward: false, node: null});
//assignment[j].push({trackNo: trackNo, segmentNo: segmentNumber, node: null, isForward: false, lane: null});
addToAssignment(j, null, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
}
if (currentNodeIsForward) {
track.path.push({order: currentNode.order, lane: null, isForward: false, node: null});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: null, isForward: false, lane: null});
addToAssignment(currentNode.order, null, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
track.path.push({order: currentNode.order, lane: null, isForward: true, node: currentNodeId});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: currentNodeId, isForward: true, lane: null});
addToAssignment(currentNode.order, currentNodeId, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
} else {
track.path.push({order: currentNode.order, lane: null, isForward: false, node: currentNodeId});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: currentNodeId, isForward: false, lane: null});
addToAssignment(currentNode.order, currentNodeId, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
}
} else { //currentNode.order === previousNode.order
if (currentNodeIsForward !== previousNodeIsForward) {
track.path.push({order: currentNode.order, lane: null, isForward: currentNodeIsForward, node: currentNodeId});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: currentNodeId, isForward: currentNodeIsForward, lane: null});
addToAssignment(currentNode.order, currentNodeId, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
} else {
track.path.push({order: currentNode.order, lane: null, isForward: !currentNodeIsForward, node: null});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: null, isForward: !currentNodeIsForward, lane: null});
addToAssignment(currentNode.order, null, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
track.path.push({order: currentNode.order, lane: null, isForward: currentNodeIsForward, node: currentNodeId});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: currentNodeId, isForward: currentNodeIsForward, lane: null});
addToAssignment(currentNode.order, currentNodeId, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
}
}
}
});
for (i = 0; i <= maxOrder; i++) {
//for (i = 0; i <= 3; i++) {
//console.log("order " + i + ":");
generateSingleLaneAssignment(assignment[i], i, nodes, tracks); //this is where the lanes get assigned
}
}
function addToAssignment(order, nodeID, trackNo, segmentID, prevSegmentPerOrderPerTrack) {
var compareToFromSame;
var i;
compareToFromSame = null;
if (prevSegmentPerOrderPerTrack[order][trackNo] !== null) {
compareToFromSame = prevSegmentPerOrderPerTrack[order][trackNo];
}
if (nodeID === null) {
assignment[order].push({type: "single", name: null, tracks: [{trackID: trackNo, segmentID: segmentID, compareToFromSame: compareToFromSame}]});
//console.log("HIER: " + assignment[order][assignment[order].length - 1].tracks[0]);
prevSegmentPerOrderPerTrack[order][trackNo] = assignment[order][assignment[order].length - 1].tracks[0];
} else {
for (i = 0; i < assignment[order].length; i++) {
if (assignment[order][i].name === nodeID) { //add to existing node in assignment
assignment[order][i].type = "multiple";
assignment[order][i].tracks.push({trackID: trackNo, segmentID: segmentID, compareToFromSame: compareToFromSame});
prevSegmentPerOrderPerTrack[order][trackNo] = assignment[order][i].tracks[assignment[order][i].tracks.length - 1];
return;
}
}
//create new node in assignment
assignment[order].push({type: "single", name: nodeID, tracks: [{trackID: trackNo, segmentID: segmentID, compareToFromSame: compareToFromSame}]});
prevSegmentPerOrderPerTrack[order][trackNo] = assignment[order][assignment[order].length - 1].tracks[0];
}
}
function generateSingleLaneAssignment(assignment, order, nodes, tracks) {
var i, j, index, currentLane;
//for (i = 0; i < assignment.length; i++) {
assignment.forEach(function(node) {
node.idealLane = 0;
//for (j = 0: j < assignment[i].tracks.length) {
node.tracks.forEach(function(track) {
if (track.segmentID === 0) {
track.idealLane = track.trackID;
} else {
if (tracks[track.trackID].path[track.segmentID - 1].order === order - 1) {
track.idealLane = tracks[track.trackID].path[track.segmentID - 1].lane;
} else if ((track.segmentID < tracks[track.trackID].path.length - 1) && (tracks[track.trackID].path[track.segmentID + 1].order === order - 1)) {
track.idealLane = tracks[track.trackID].path[track.segmentID + 1].lane;
} else {
index = track.segmentID - 1;
//while (! ((tracks[track.trackID].path[index].order === order) && (tracks[track.trackID].path[index].hasOwnProperty("lane")))) index--;
//while (! ((tracks[track.trackID].path[index].order === order) && (tracks[track.trackID].path[index].lane !== null))) index--;
while (tracks[track.trackID].path[index].order !== order - 1) index--;
track.idealLane = tracks[track.trackID].path[index].lane;
}
}
node.idealLane += track.idealLane;
});
node.idealLane /= node.tracks.length;
});
currentLane = 0;
var sumOfLaneChanges = 0;
var totalLanes = 0;
assignment.sort(compareByIdealLane);
assignment.forEach(function(node) {
//node.yCoord = assignment[i][j].lane;
//node.y = offsetY + 110 + 22 * node.yCoord;
//console.log(node.name + "HIER " + nodeMap.get(node.name));
if (node.name !== null) {
nodes[nodeMap.get(node.name)].yCoord = currentLane;
nodes[nodeMap.get(node.name)].y = offsetY + 110 + 22 * currentLane;
//nodes[nodeMap.get(node.name)].y = offsetY + 90 + 22 * currentLane;
}
node.tracks.sort(compareByIdealLane);
node.tracks.forEach(function(track) {
//console.log("Track " + track.trackID + " (" + track.segmentID + ") --> Lane " + currentLane);
track.lane = currentLane;
tracks[track.trackID].path[track.segmentID].lane = currentLane;
sumOfLaneChanges += currentLane - track.idealLane;
totalLanes++;
currentLane++;
});
});
var moveBy = Math.round(sumOfLaneChanges / totalLanes - 0.000001);
if ((moveBy !== 0) && (totalLanes > numberOfTracks)) {
//console.log("move by " + moveBy);
assignment.forEach(function(node) {
if (node.name !== null) {
nodes[nodeMap.get(node.name)].yCoord -= moveBy;
nodes[nodeMap.get(node.name)].y -= 22 * moveBy;
}
node.tracks.forEach(function(track) {
//console.log("Track " + track.trackID + " (" + track.segmentID + ") --> Lane " + currentLane);
track.lane -= moveBy;
tracks[track.trackID].path[track.segmentID].lane -= moveBy;
});
});
}
}
function compareByIdealLane(a, b) {
if (a.hasOwnProperty("idealLane")) {
if (b.hasOwnProperty("idealLane")) {
if (a.idealLane < b.idealLane) return -1;
else if (a.idealLane > b.idealLane) return 1;
else return 0;
} else return -1;
} else {
if (b.hasOwnProperty("idealLane")) return 1;
else return 0;
}
}
function sortNumber(a,b) { return a - b; }
function swap(array, i, j) {
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
function compareNodesByOrder(a, b) {
if (a.hasOwnProperty("order")) {
if (b.hasOwnProperty("order")) {
if (a.order < b.order) return -1;
else if (a.order > b.order) return 1;
else return 0;
} else return -1;
} else {
if (b.hasOwnProperty("order")) return 1;
else return 0;
}
}
function generateEdgesFromPath(nodes, tracks, edges) {
var i;
var xStart;
var xEnd;
var y;
var yEnd;
for (i = 0; i <= maxOrder; i++) {
extraLeft.push(0);
extraRight.push(0);
}
//generate x coords where each order starts and ends
var orderStartX = [];
var orderEndX = [];
nodes.forEach(function(node) {
if (node.hasOwnProperty("order")) {
orderStartX[node.order] = node.x;
if (orderEndX[node.order] === undefined) orderEndX[node.order] = node.x + 20 * (node.width - 1);
else orderEndX[node.order] = Math.max(orderEndX[node.order], node.x + 20 * (node.width - 1));
}
});
tracks.forEach(function(track, trackID) {
//start of path
if (track.sequence[0].charAt(0) === '-') { //The track starts with an inversed node (TODO: change to isForward)
//TODO: ADD STUFF HERE
} else { //The track starts with a forward node
xStart = orderStartX[track.path[0].order] - 20;
xEnd = orderEndX[track.path[0].order];
y = offsetY + 110 + 22 * track.path[0].lane;
edges.push({source: {x: xStart, y: y}, target: {x: xEnd, y: y}, color: track.id});
}
//middle of path
for (i = 1; i < track.path.length; i++) {
if (track.path[i].order - 1 === track.path[i - 1].order) { //regular forward connection
xStart = orderEndX[track.path[i - 1].order];
xEnd = orderStartX[track.path[i].order];
y = offsetY + 110 + 22 * track.path[i - 1].lane;
yEnd = offsetY + 110 + 22 * track.path[i].lane;
edges.push({source: {x: xStart, y: y}, target: {x: xEnd, y: yEnd}, color: track.id});
} else if (track.path[i].order + 1 === track.path[i - 1].order) { //regular backward connection
xStart = orderEndX[track.path[i].order];
xEnd = orderStartX[track.path[i - 1].order];
y = offsetY + 110 + 22 * track.path[i].lane;
yEnd = offsetY + 110 + 22 * track.path[i - 1].lane;
edges.push({source: {x: xStart, y: y}, target: {x: xEnd, y: yEnd}, color: track.id});
} else { //change of direction
if (track.path[i - 1].isForward) {
generateForwardToReverse(track.path[i].order, track.path[i].lane, track.path[i - 1].lane, track.id, orderEndX);
} else {
generateReverseToForward(track.path[i].order, track.path[i].lane, track.path[i - 1].lane, track.id, orderStartX);
}
}
//edge within node
xStart = orderStartX[track.path[i].order];
xEnd = orderEndX[track.path[i].order];
y = offsetY + 110 + 22 * track.path[i].lane;
edges.push({source: {x: xStart, y: y}, target: {x: xEnd, y: y}, color: track.id});
}
//ending edges
if (!track.path[track.path.length - 1].isForward) { //The track ends with an inversed node
//TODO: ADD STUFF HERE
} else { //The track endss with a forward node
xStart = orderEndX[track.path[track.path.length - 1].order];
xEnd = xStart + 20;
y = offsetY + 110 + 22 * track.path[track.path.length - 1].lane;
edges.push({source: {x: xStart, y: y}, target: {x: xEnd, y: y}, color: track.id});
}
});
}
function generateForwardToReverse(order, lane1, lane2, trackID, orderEndX) {
var temp;
var x;
var y;
var y2;
x = orderEndX[order] + 5 + 10 * extraRight[order];
if (lane1 > lane2) {
temp = lane1;
lane1 = lane2;
lane2 = temp;
}
y = offsetY + 110 + 22 * lane1 + 10;
y2 = offsetY + 110 + 22 * lane2 + 10;
//console.log("order: " + order + ", lane1: " + lane1 + ", lane2: " + lane2);
edges.push({source: {x: x - 5 - 10 * extraRight[order], y: y - 10}, target: {x: x, y: y - 10}, color: trackID}); //right (elongate edge within node)
arcs[1].push({ x: x, y: y, color: trackID}); //from right to down
edges.push({source: {x: x + 10, y: y}, target: {x: x + 10, y: y2 - 20}, color: trackID}); //down
arcs[2].push({ x: x, y: y2 - 20, color: trackID});
edges.push({source: {x: x - 5 - 10 * extraRight[order], y: y2 - 10}, target: {x: x, y: y2 - 10}, color: trackID}); //right (elongate edge within node)
extraRight[order]++;
}
function generateReverseToForward(order, lane1, lane2, trackID, orderStartX) {
var temp;
var x;
var y;
var y2;
if (lane1 > lane2) {
temp = lane1;
lane1 = lane2;
lane2 = temp;
}
y = offsetY + 110 + 22 * lane1 + 10;
y2 = offsetY + 110 + 22 * lane2 + 10;
x = orderStartX[order] - 35 - 10 * extraLeft[order];
edges.push({source: {x: x + 30, y: y - 10}, target: {x: x + 35 + 10 * extraLeft[order], y: y - 10}, color: trackID}); //left
arcs[0].push({ x: x + 30, y: y, color: trackID}); //from left to down
edges.push({source: {x: x + 20, y: y}, target: {x: x + 20, y: y2 - 20}, color: trackID}); //down
arcs[3].push({ x: x + 30, y: y2 - 20, color: trackID}); //from down to right
edges.push({source: {x: x + 30, y: y2 - 10}, target: {x: x + 35 + 10 * extraLeft[order], y: y2 - 10}, color: trackID}); //right
extraLeft[order]++;
}
function drawNodes(nodes) {
//Draw central white rectangle for node background
svg.selectAll(".nodeBackgroundRect")
.data(nodes)
.enter()
.append("rect")
.attr("class", "backgr")
.attr("x", function(d) { return d.x - 10; })
.attr("y", function(d) { return d.y; })
.attr("width", function(d) { return 20 * d.width; })
.attr("height", function(d) { return (d.degree - 1) * 22; });
//Draw top white rectangle for node background
svg.selectAll(".nodeBackgroundRect")
.data(nodes)
.enter()
.append("rect")
.attr("class", "backgr")
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y - 10; })
.attr("width", function(d) { return (d.width - 1) * 20; })
.attr("height", 10);
//Draw bottom white rectangle for node background
svg.selectAll(".nodeBackgroundRect")
.data(nodes)
.enter()
.append("rect")
.attr("class", "backgr")
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return (d.y + (22 * (d.degree - 1))); })
.attr("width", function(d) { return (d.width - 1) * 20; })
.attr("height", 8);
//Draw top-left circle segment (white background) for nodes
var topLeftSegment = d3.svg.arc()
.innerRadius(0)
.outerRadius(10)
.startAngle(-0.5 * Math.PI)
.endAngle(0 * Math.PI);
svg.selectAll(".nodeBackgroundTopLeft")
.data(nodes)
.enter()
.append("path")
.attr("class", "backgr")
.attr("d", topLeftSegment)
.attr("transform", function(d) {return "translate(" + d.x + ", " + d.y + ")"; });
//Draw top-right circle segment (white background) for nodes
var topRightSegment = d3.svg.arc()
.innerRadius(0)
.outerRadius(10)
.startAngle(0 * Math.PI)
.endAngle(0.5 * Math.PI);
svg.selectAll(".nodeBackgroundTopRight")
.data(nodes)
.enter()
.append("path")
.attr("class", "backgr")
.attr("d", topRightSegment)
.attr("transform", function(d) {return "translate(" + (d.x + 20 * (d.width -1)) + ", " + d.y + ")"; });
//Draw bottom-left circle segment (white background) for nodes
var bottomLeftSegment = d3.svg.arc()
.innerRadius(0)
.outerRadius(10)
.startAngle(1 * Math.PI)
.endAngle(1.5 * Math.PI);
svg.selectAll(".nodeBackgroundBottomLeft")
.data(nodes)
.enter()
.append("path")
.attr("class", "backgr")
.attr("d", bottomLeftSegment)
.attr("transform", function(d) {return "translate(" + d.x + ", " + (d.y + (22 * (d.degree - 1))) + ")"; });
//Draw bottom-right circle segment (white background) for nodes
var bottomRightSegment = d3.svg.arc()
.innerRadius(0)
.outerRadius(10)
.startAngle(0.5 * Math.PI)
.endAngle(1 * Math.PI);
svg.selectAll(".nodeBackgroundBottomRight")
.data(nodes)
.enter()
.append("path")
.attr("class", "backgr")
.attr("d", bottomRightSegment)
.attr("transform", function(d) {return "translate(" + (d.x + 20 * (d.width -1)) + ", " + (d.y + (22 * (d.degree - 1))) + ")"; });
//Draw top-left arc for nodes
var topLeftArc = d3.svg.arc()
.innerRadius(8)
.outerRadius(10)
.startAngle(-0.5 * Math.PI)
.endAngle(0 * Math.PI);
svg.selectAll(".topLeftArc")
.data(nodes)
.enter()
.append("path")
.attr("class", "arc")
.attr("d", topLeftArc)
.attr("transform", function(d) {return "translate(" + d.x + ", " + d.y + ")"; });
//Draw top-right arc for nodes
var topRightArc = d3.svg.arc()
.innerRadius(8)
.outerRadius(10)
.startAngle(0 * Math.PI)
.endAngle(0.5 * Math.PI);
svg.selectAll(".topRightArc")
.data(nodes)
.enter()
.append("path")
.attr("class", "arc")
.attr("d", topRightArc)
.attr("transform", function(d) {return "translate(" + (d.x + 20 * (d.width -1)) + ", " + d.y + ")"; });
//Draw bottom-left arc for nodes
var bottomLeftArc = d3.svg.arc()
.innerRadius(8)
.outerRadius(10)
.startAngle(1 * Math.PI)
.endAngle(1.5 * Math.PI);
svg.selectAll(".bottomLeftArc")
.data(nodes)
.enter()
.append("path")
.attr("class", "arc")
.attr("d", bottomLeftArc)
.attr("transform", function(d) {return "translate(" + d.x + ", " + (d.y + (22 * (d.degree - 1))) + ")"; });
//Draw bottom-right arc for nodes
var bottomRightArc = d3.svg.arc()
.innerRadius(8)
.outerRadius(10)
.startAngle(0.5 * Math.PI)
.endAngle(1 * Math.PI);
svg.selectAll(".bottomRightArc")
.data(nodes)
.enter()
.append("path")
.attr("class", "arc")
.attr("d", bottomRightArc)
.attr("transform", function(d) {return "translate(" + (d.x + 20 * (d.width -1)) + ", " + (d.y + (22 * (d.degree - 1))) + ")"; });
svg.selectAll(".arcLinkLeft") //linke Verbindung zw. Halbkreisen
.data(nodes)
.enter()
.append("rect")
.attr("class", "arc")
.attr("x", function(d) { return d.x - 10; })
.attr("y", function(d) { return d.y; })
.attr("width", 2)
.attr("height", function(d) { return (d.degree - 1) * 22; });
svg.selectAll(".arcLinkRight") //rechte Verbindung zw. Halbkreisen
.data(nodes)
.enter()
.append("rect")
.attr("class", "arc")
.attr("x", function(d) { return d.x + 8 + 20 * (d.width -1); })
.attr("y", function(d) { return d.y; })
.attr("width", 2)
.attr("height", function(d) { return (d.degree - 1) * 22; });
svg.selectAll(".arcLinkTop") //top Verbindung zw. Halbkreisen
.data(nodes)
.enter()
.append("rect")
.attr("class", "arc")
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y - 10; })
.attr("width", function(d) { return (d.width - 1) * 20; })
.attr("height", 2);
svg.selectAll(".arcLinkBottom") //bottom Verbindung zw. Halbkreisen
.data(nodes)
.enter()
.append("rect")
.attr("class", "arc")
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return (d.y + 8 + (22 * (d.degree - 1))); })
.attr("width", function(d) { return (d.width - 1) * 20; })
.attr("height", 2);
}
function drawEdges(edges) {
//Create Paths for edges
var diagonal = d3.svg.diagonal()
.source(function(d) { return {"x":d.source.y, "y":d.source.x}; })
.target(function(d) { return {"x":d.target.y, "y":d.target.x}; })
.projection(function(d) { return [d.y, d.x]; });
//Draw edges
var link = svg.selectAll(".link")
.data(edges)
.enter().append("path")
//.attr("class", "link")
.attr("class", function(d) {return "link track" + d.color; })
.attr("d", diagonal)
.on("mouseover", handleMouseOver)
.on("mouseout", handleMouseOut)
.on("click", handleMouseClick)
//.style("stroke", function(d, i) { return color(i); });
.style("stroke", function(d) { return color(d.color); });
}
function drawTopRightEdgeArcs(arcs) {
var topRightEdgeArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(0 * Math.PI)
.endAngle(0.5 * Math.PI);
svg.selectAll(".topRightArc")
.data(arcs)
.enter()
.append("path")
.attr("class", function(d) {return "link topRightArctrack" + d.color; })
.attr("d", topRightEdgeArc)
//.style("stroke", function(d) { return color(d.color); })
.on("mouseover", handleMouseOver)
.on("mouseout", handleMouseOut)
.on("click", handleMouseClick)
.style("fill", function(d) { return color(d.color); })
.attr("transform", function(d) {return "translate(" + d.x + ", " + d.y + ")"; });
}
function drawTopLeftEdgeArcs(arcs) {
var topLeftEdgeArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(0 * Math.PI)
.endAngle(-0.5 * Math.PI);
svg.selectAll(".topLeftArc")
.data(arcs)
.enter()
.append("path")
.attr("class", function(d) {return "link topLeftArctrack" + d.color; })
.attr("d", topLeftEdgeArc)
//.style("stroke", function(d) { return color(d.color); })
.on("mouseover", handleMouseOver)
.on("mouseout", handleMouseOut)
.on("click", handleMouseClick)
.style("fill", function(d) { return color(d.color); })
.attr("transform", function(d) {return "translate(" + d.x + ", " + d.y + ")"; });
}
function drawBottomRightEdgeArcs(arcs) {
var bottomRightEdgeArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(0.5 * Math.PI)
.endAngle(1 * Math.PI);
svg.selectAll(".bottomRightArc")
.data(arcs)
.enter()
.append("path")
.attr("class", function(d) {return "link bottomRightArctrack" + d.color; })
.attr("d", bottomRightEdgeArc)
//.style("stroke", function(d) { return color(d.color); })
.on("mouseover", handleMouseOver)
.on("mouseout", handleMouseOut)
.on("click", handleMouseClick)
.style("fill", function(d) { return color(d.color); })
.attr("transform", function(d) {return "translate(" + d.x + ", " + d.y + ")"; });
}
function drawBottomLeftEdgeArcs(arcs) {
var bottomLeftEdgeArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(1 * Math.PI)
.endAngle(1.5 * Math.PI);
svg.selectAll(".bottomLeftArc")
.data(arcs)
.enter()
.append("path")
.attr("class", function(d) {return "link bottomLeftArctrack" + d.color; })
.attr("d", bottomLeftEdgeArc)
//.style("stroke", function(d) { return color(d.color); })
.on("mouseover", handleMouseOver)
.on("mouseout", handleMouseOut)
.on("click", handleMouseClick)
.style("fill", function(d) { return color(d.color); })
.attr("transform", function(d) {return "translate(" + d.x + ", " + d.y + ")"; });
}
function handleMouseOver() { // Highlight track on mouseover
var currentClass = d3.select(this).attr("class");
currentClass = /track[0-9]*/.exec(currentClass);
//currentClass = /track[\S]*/.exec(currentClass);
//console.log(currentClass[0]);
svg.selectAll("." + currentClass)
//.style("stroke", "#000000")
.style("stroke-width", "10px");
var topRightArc = d3.svg.arc()
.innerRadius(5)
.outerRadius(15)
.startAngle(0 * Math.PI)
.endAngle(0.5 * Math.PI);
svg.selectAll(".topRightArc" + currentClass)
.attr("d", topRightArc);
var topLeftArc = d3.svg.arc()
.innerRadius(5)
.outerRadius(15)
.startAngle(0 * Math.PI)
.endAngle(-0.5 * Math.PI);
svg.selectAll(".topLeftArc" + currentClass)
.attr("d", topLeftArc);
var bottomRightArc = d3.svg.arc()
.innerRadius(5)
.outerRadius(15)
.startAngle(0.5 * Math.PI)
.endAngle(1 * Math.PI);
svg.selectAll(".bottomRightArc" + currentClass)
.attr("d", bottomRightArc);
var bottomLeftArc = d3.svg.arc()
.innerRadius(5)
.outerRadius(15)
.startAngle(1 * Math.PI)
.endAngle(1.5 * Math.PI);
svg.selectAll(".bottomLeftArc" + currentClass)
.attr("d", bottomLeftArc);
}
function handleMouseOut() { // Restore original appearance on mouseout
var currentClass = d3.select(this).attr("class");
currentClass = /track[0-9]*/.exec(currentClass);
svg.selectAll("." + currentClass)
//.style("stroke", function(d) { return color(d.color); });
.style("stroke-width", "7px");
var topRightArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(0 * Math.PI)
.endAngle(0.5 * Math.PI);
svg.selectAll(".topRightArc" + currentClass)
.attr("d", topRightArc);
var topLeftArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(0 * Math.PI)
.endAngle(-0.5 * Math.PI);
svg.selectAll(".topLeftArc" + currentClass)
.attr("d", topLeftArc);
var bottomRightArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(0.5 * Math.PI)
.endAngle(1 * Math.PI);
svg.selectAll(".bottomRightArc" + currentClass)
.attr("d", bottomRightArc);
var bottomLeftArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(1 * Math.PI)
.endAngle(1.5 * Math.PI);
svg.selectAll(".bottomLeftArc" + currentClass)
.attr("d", bottomLeftArc);
}
function handleMouseClick() { // Move clicked track to first position
var trackNo = d3.select(this).attr("class");
trackNo = /[0-9]+/.exec(trackNo);
var index = 0;
//console.log("trackno: " + trackNo);
while ((index < 10) && (inputTracks[index].id != trackNo)) index++;
//console.log("index: " + index);
moveTrackToFirstPosition(index);
}
function vgExtractNodes(vg) {
var result = [];
vg.node.forEach(function(node) {
//result.push({ name: "" + node.id, width: 1});
//result.push({ name: "" + node.id, width: node.sequence.length});
result.push({ name: "" + node.id, width: (1 + Math.log2(node.sequence.length))});
});
return result;
}
function vgExtractTracks(vg) {
var result =[];
vg.path.forEach(function(path, index) {
var sequence = [];
var isCompletelyReverse = true;
path.mapping.forEach(function(pos) {
if ((pos.position.hasOwnProperty('is_reverse')) && (pos.position.is_reverse === true)) {
sequence.push("-" + pos.position.node_id);
} else {
sequence.push("" + pos.position.node_id);
isCompletelyReverse = false;
}
});
//if ((path.mapping[0].position.hasOwnProperty('is_reverse')) && (path.mapping[0].position.is_reverse === true)) sequence.reverse();
if (isCompletelyReverse) {
console.log("completely reverse " + index);
console.log(sequence);
sequence.reverse();
sequence.forEach(function(node, index2) {
sequence[index2] = node.substr(1);
});
console.log(sequence);
}
//result.push({id: path.name, sequence: sequence});
result.push({id: index, sequence: sequence});
});
return result;
}
function vgMergeNodes(nodes, tracks) {
var mergeForward = {};
var i, index;
var mergeBackward = {};
var nodeName;
tracks.forEach(function(track) {
for (i = 0; i < track.sequence.length; i++) {
if (track.sequence[i].charAt(0) !== '-') { //forward Node
if (!mergeForward.hasOwnProperty(track.sequence[i])) {
if ((i < track.sequence.length - 1) && (track.sequence[i + 1].charAt(0) !== '-')) {
mergeForward[track.sequence[i]] = {mergeWith: track.sequence[i + 1], isPossible: true};
}
} else {
if ((i === track.sequence.length - 1) || (mergeForward[track.sequence[i]].mergeWith != track.sequence[i + 1])) {
mergeForward[track.sequence[i]].isPossible = false;
}
}
} else { //reverse Node
nodeName = track.sequence[i].substr(1);
if (!mergeForward.hasOwnProperty(nodeName)) {
if ((i > 0) && (track.sequence[i - 1].charAt(0) === '-')) {
mergeForward[nodeName] = {mergeWith: track.sequence[i - 1].substr(1), isPossible: true};
}
} else {
if ((i === 0) || (mergeForward[nodeName].mergeWith != track.sequence[i - 1].substr(1))) {
mergeForward[nodeName].isPossible = false;
}
}
}
}
});
console.log("Merge Forward: " + Object.keys(mergeForward).length);
console.log(mergeForward);
for (var prop in mergeForward) {
if (mergeForward.hasOwnProperty(prop)) {
if (mergeForward[prop].isPossible === true) {
mergeBackward[mergeForward[prop].mergeWith] = {mergeWith: prop, isPossible: true};
}
}
}
console.log("Merge Backward:" + Object.keys(mergeBackward).length);
console.log(mergeBackward);
tracks.forEach(function(track) {
for (i = 0; i < track.sequence.length; i++) {
if (track.sequence[i].charAt(0) !== '-') { //forward Node
if (mergeBackward.hasOwnProperty(track.sequence[i])) {
if ((i === 0) || (mergeBackward[track.sequence[i]].mergeWith !== track.sequence[i - 1])) {
mergeBackward[track.sequence[i]].isPossible = false;
}
}
} else { //reverse Node
if (mergeBackward.hasOwnProperty(track.sequence[i].substr(1))) {
if ((i === track.sequence.length - 1) || (mergeBackward[track.sequence[i].substr(1)].mergeWith !== track.sequence[i + 1].substr(1))) {
mergeBackward[track.sequence[i].substr(1)].isPossible = false;
}
}
}
}
});
var count = 0;
for (prop in mergeBackward) {
if (mergeBackward.hasOwnProperty(prop)) {
if (mergeBackward[prop].isPossible === true) {
count++;
console.log("merge " + mergeBackward[prop].mergeWith + " with " + prop);
}
}
}
console.log(count + " merges");
//actually merge the nodes by removing the corresponding nodes from track data
tracks.forEach(function(track) {
for (i = track.sequence.length - 1; i >= 0; i--) {
nodeName = track.sequence[i];
if (nodeName.charAt(0) === '-') nodeName = nodeName.substr(1);
if ((mergeBackward.hasOwnProperty(nodeName)) && (mergeBackward[nodeName].isPossible === true)) {
track.sequence.splice(i, 1);
}
}
});
//remove the nodes from node-Array
for (prop in mergeBackward) {
if (mergeBackward.hasOwnProperty(prop)) {
if (mergeBackward[prop].isPossible === true) {
index = 0;
//console.log("looking for " + mergeBackward[prop])
while (nodes[index].name !== prop) index++;
nodes.splice(index, 1);
}
}
}
return {nodes: nodes, tracks: tracks};
}
return {
create: create,
switch: switchAlwaysMoveRight,
vgExtractNodes: vgExtractNodes,
vgExtractTracks: vgExtractTracks,
vgMergeNodes: vgMergeNodes
};
})();
| sequenceTubeMap.js | /*jshint loopfunc: true */
/*jshint esversion: 6*/
var sequenceTubeMap = (function () {
var offsetX = 0;
var offsetY = 0;
const color = d3.scale.category10().domain([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
var svg;
var inputNodes = [];
var inputTracks = [];
var numberOfNodes;
var numberOfTracks;
var nodeMap; //maps node names to node indices
var edges = []; //contains concrete coordinate info about the different tracks
var arcs = [[], [], [], []]; //contains coords if the edges' 90° angles
var assignment = []; //contains info about lane assignments sorted by order
var extraLeft = []; //info whether nodes have to be moved further apart because of multiple 180° directional changes at the same horizontal order
var extraRight = []; //info whether nodes have to be moved further apart because of multiple 180° directional changes at the same horizontal order
var maxOrder; //horizontal order of the rightmost node
var nextNodeIsAlwaysToTheRight = true;
function create(inputSvg, nodes, tracks) {
svg = inputSvg;
//inputNodes = nodes.slice(0); //no deep copy necessary because inner stuff does not change
//inputTracks = tracks.slice(0);
inputNodes = (JSON.parse(JSON.stringify(nodes))); //deep copy
inputTracks = (JSON.parse(JSON.stringify(tracks)));
createTubeMap();
}
function moveTrackToFirstPosition(index) {
var i, j;
var nodesToInvert = [];
var currentSequence;
inputTracks.unshift(inputTracks[index]); //add element to beginning
inputTracks.splice(index + 1, 1); //remove 1 element from the middle
currentSequence = inputTracks[0].sequence;
for (i = 0; i < currentSequence.length; i++) {
if (currentSequence[i].charAt(0) === '-') {
currentSequence[i] = currentSequence[i].substr(1);
nodesToInvert.push(currentSequence[i]);
}
}
//console.log("nodes to invert:");
//console.log(nodesToInvert);
for (i = 1; i < inputTracks.length; i++) {
currentSequence = inputTracks[i].sequence;
for (j = 0; j < currentSequence.length; j++) {
if (currentSequence[j].charAt(0) !== '-') {
if (nodesToInvert.indexOf(currentSequence[j]) !== -1) {
currentSequence[j] = "-" + currentSequence[j];
//console.log("Track " + i + "[" + j + "] CHANGED TO " + currentSequence[j]);
}
} else {
if (nodesToInvert.indexOf(currentSequence[j].substr(1)) !== -1) {
currentSequence[j] = currentSequence[j].substr(1);
}
}
}
}
//console.log(inputTracks);
createTubeMap();
}
function switchAlwaysMoveRight() {
nextNodeIsAlwaysToTheRight = ! nextNodeIsAlwaysToTheRight;
createTubeMap();
}
function createTubeMap() {
//clear svg for (re-)drawing
var nodes = (JSON.parse(JSON.stringify(inputNodes))); //deep copy (can add stuff to copy and leave original unchanged)
var tracks = (JSON.parse(JSON.stringify(inputTracks)));
svg.selectAll("*").remove();
edges = [];
arcs = [[], [], [], []];
assignment = [];
extraLeft = [];
extraRight = [];
numberOfNodes = nodes.length;
numberOfTracks = tracks.length;
//console.log("number of tracks: " + numberOfTracks);
nodeMap = generateNodeMap(nodes);
generateNodeSuccessors(nodes, tracks);
generateNodeOrder(nodes, tracks);
maxOrder = getMaxOrder(nodes);
generateNodeDegree(nodes, tracks);
switchNodeOrientation(nodes, tracks);
generateLaneAssignment(nodes, tracks);
generateNodeXCoords(nodes, tracks);
movePositionWithinSVG(nodes, tracks);
generateEdgesFromPath(nodes, tracks, edges);
console.log("Assignment:");
console.log(assignment);
console.log("Tracks:");
console.log(tracks);
console.log("Nodes:");
console.log(nodes);
console.log("Arcs:");
console.log(arcs);
console.log("Edges:");
console.log(edges);
removeUnusedNodes(nodes);
drawEdges(edges);
if (arcs[0].length > 0) drawTopLeftEdgeArcs(arcs[0]);
if (arcs[1].length > 0) drawTopRightEdgeArcs(arcs[1]);
if (arcs[2].length > 0) drawBottomRightEdgeArcs(arcs[2]);
if (arcs[3].length > 0) drawBottomLeftEdgeArcs(arcs[3]);
drawNodes(nodes);
}
function removeUnusedNodes(nodes) {
var i;
for (i = nodes.length - 1; i >= 0; i--) {
if (nodes[i].degree === 0) {
nodes.splice(i, 1);
}
}
numberOfNodes = nodes.length;
}
function movePositionWithinSVG(nodes, tracks) {
var minLane = Number.MAX_SAFE_INTEGER;
var maxLane = Number.MIN_SAFE_INTEGER;
var maxX = Number.MIN_SAFE_INTEGER;
tracks.forEach(function (track) {
track.path.forEach(function (node) {
if (node.lane < minLane) minLane = node.lane;
if (node.lane > maxLane) maxLane = node.lane;
});
});
//console.log(minLane + ' ' + maxLane);
//offsetX = 0;
offsetY = -100 - 22 * minLane;
nodes.forEach(function(node) {
node.y = offsetY + 110 + 22 * node.yCoord;
if (node.x + 20 * node.width > maxX) maxX = node.x + 20 * node.width;
});
//console.log(maxX);
svg.attr("height", 20 + 22 * (maxLane - minLane));
svg.attr("width", maxX);
}
function generateNodeMap(nodes) { //map node names to node indices
var nodeMap = new Map();
nodes.forEach(function(node, index) {
nodeMap.set(node.name, index);
});
return nodeMap;
}
function generateNodeSuccessors(nodes, tracks) { //adds a successor-array to each node containing the names of the nodes coming directly after the current node
var i;
var currentNode;
var followerID;
var modifiedSequence = [];
nodes.forEach(function(node) {
node.successors = [];
node.predecessors = [];
});
tracks.forEach(function(track) {
modifiedSequence = uninvert(track.sequence);
for(i = 0; i < modifiedSequence.length - 1; i++) {
currentNode = nodes[nodeMap.get(modifiedSequence[i])];
followerID = modifiedSequence[i + 1];
if (currentNode.successors.indexOf(followerID) === -1) {
currentNode.successors.push(followerID);
}
if (nodes[nodeMap.get(followerID)].predecessors.indexOf(modifiedSequence[i]) === -1) {
nodes[nodeMap.get(followerID)].predecessors.push(modifiedSequence[i]);
}
}
});
}
function generateNodeOrderOfSingleTrack(sequence, nodes) { //calculates order values for all nodes along a single track
currentOrder = 0;
sequence.forEach(function(nodeName) {
currentNode = nodes[nodeMap.get(nodeName)];
if (! currentNode.hasOwnProperty("order")) { //default case
currentNode.order = currentOrder;
currentOrder++;
} else { //track has a repeat revisiting a node
//currentOrder = currentNode.order + 1;
}
});
}
function generateNodeOrderLeftEnd(sequence, nodes) { //calculate the order-value of nodes contained in sequence which are to the left of the first node which already has an order-value
var anchorIndex = 0;
var nodeNames = new Map();
var currentOrder;
var currentNode;
while (! nodes[nodeMap.get(sequence[anchorIndex])].hasOwnProperty("order")) anchorIndex++; //anchor = first node in common with existing graph
for (j = anchorIndex - 1; j >= 0; j--) { //count number of nodes to the left of anchorIndex counting repeated nodes only once
nodeNames.set(sequence[j], true);
}
currentOrder = nodes[nodeMap.get(sequence[anchorIndex])].order - nodeNames.size; //order of first node
for (j = 0; j < anchorIndex; j++) { //assign order to nodes
currentNode = nodes[nodeMap.get(sequence[j])];
if (! currentNode.hasOwnProperty("order")) {
currentNode.order = currentOrder;
currentOrder++;
}
}
if (nodes[nodeMap.get(sequence[0])].order < 0) {
increaseOrderForAllNodes(nodes, -nodes[nodeMap.get(sequence[0])].order);
}
return anchorIndex;
}
function generateNodeOrder(nodes, tracks) { //generate global sequence of nodes from left to right, starting with first track and adding other tracks sequentially
var modifiedSequence;
var i;
var j;
var currentOrder;
var currentNode;
var rightIndex;
var leftIndex;
generateNodeOrderOfSingleTrack(tracks[0].sequence, nodes); //calculate order values for all nodes of the first track
for (i = 1; i < tracks.length; i++) {
//console.log("Node order for track " + i + " " + tracks[i].id);
modifiedSequence = uninvert(tracks[i].sequence);
//console.log(tracks[i].sequence);
//console.log(modifiedSequence);
rightIndex = generateNodeOrderLeftEnd(modifiedSequence, nodes); //calculate order values for all nodes until the first anchor
while (rightIndex < modifiedSequence.length) { //move right until the end of the sequence
//find next anchor node
leftIndex = rightIndex;
rightIndex++;
while ((rightIndex < modifiedSequence.length) && (! nodes[nodeMap.get(modifiedSequence[rightIndex])].hasOwnProperty("order"))) rightIndex++;
if (rightIndex < modifiedSequence.length) { //middle segment between two anchors
currentOrder = nodes[nodeMap.get(modifiedSequence[leftIndex])].order + 1; //start with order value of leftAnchor + 1
for (j = leftIndex + 1; j < rightIndex; j++) {
nodes[nodeMap.get(modifiedSequence[j])].order = currentOrder; //assign order values
//console.log(modifiedSequence[j] + " -> " + currentOrder);
currentOrder++;
}
if (nodes[nodeMap.get(modifiedSequence[rightIndex])].order > nodes[nodeMap.get(modifiedSequence[leftIndex])].order) { //if order-value of left anchor < order-value of right anchor
if (nodes[nodeMap.get(modifiedSequence[rightIndex])].order < currentOrder) { //and the right anchor now has a lower order-value than our newly added nodes
increaseOrderForSuccessors(nodes, nodes[nodeMap.get(modifiedSequence[rightIndex])], currentOrder);
}
} else { //potential node reversal: check for ordering conflict, if no conflict found move node at rightIndex further to the right in order to not create a track reversal
if (! isSuccessor(nodes[nodeMap.get(modifiedSequence[rightIndex])], nodes[nodeMap.get(modifiedSequence[leftIndex])], nodes)) { //no real reversal
//console.log("hier");
//console.log(isSuccessor(nodes[nodeMap.get(modifiedSequence[rightIndex])], nodes[nodeMap.get(modifiedSequence[leftIndex])], nodes));
increaseOrderForSuccessors(nodes, nodes[nodeMap.get(modifiedSequence[rightIndex])], currentOrder);
} else { //real reversal
if (! nextNodeIsAlwaysToTheRight) {
currentOrder = nodes[nodeMap.get(modifiedSequence[leftIndex])].order - 1; //start with order value of leftAnchor + 1
for (j = leftIndex + 1; j < rightIndex; j++) {
nodes[nodeMap.get(modifiedSequence[j])].order = currentOrder; //assign order values
//console.log(modifiedSequence[j] + " -> " + currentOrder);
currentOrder--;
}
}
}
}
} else { //right segment to the right of last anchor
currentOrder = nodes[nodeMap.get(modifiedSequence[leftIndex])].order + 1;
for (j = leftIndex + 1; j < modifiedSequence.length; j++) {
currentNode = nodes[nodeMap.get(modifiedSequence[j])];
if (! currentNode.hasOwnProperty("order")) {
currentNode.order = currentOrder;
currentOrder++;
}
}
}
}
}
}
function isSuccessor(first, second, nodes) { //checks if second is a successor of first
var visitedNodes = [];
return isSuccessorRecursive(first, second, visitedNodes, nodes);
}
function isSuccessorRecursive(first, second, visitedNodes, nodes) {
var i;
if (first.name === second.name) {
return true;
}
for (i = 0; i < first.successors.length; i++) {
//if(first.successors[i] === second.name) return true;
if (visitedNodes.indexOf(first.successors[i]) === -1) {
visitedNodes.push(first.successors[i]);
if (isSuccessorRecursive(nodes[nodeMap.get(first.successors[i])], second, visitedNodes, nodes)) {
return true;
}
}
}
return false;
}
function getMaxOrder(nodes) { //get order number of the rightmost node
var max = -1;
nodes.forEach(function(node) {
if ((node.hasOwnProperty("order")) && (node.order > max)) max = node.order;
});
return max;
}
function uninvert(sequence) { //generates sequence "corrected" for inversions i.e. A B C -D -E -F G H becomes A B C F E D G H
//the univerted sequence is how the nodes are arranged from left to right in the display
var result = [];
var i;
for (i = 0; i < sequence.length; i++) {
if (sequence[i].charAt(0) !== '-') {
result.push(sequence[i]);
} else {
result.push(sequence[i].substr(1));
}
}
return result;
}
function increaseOrderForAllNodes(nodes, amount) { //increases the order-value of all nodes by amount
nodes.forEach(function(node) {
if (node.hasOwnProperty("order")) node.order += amount;
});
}
function increaseOrderForSuccessors(nodes, currentNode, order) { //increases the order-value for currentNode and (if necessary) successor nodes recursively
//console.log("increasing orders from " + currentNode.name + " to " + order);
var increasedOrders = {};
increaseOrderForSuccessorsRecursive(nodes, currentNode, order, currentNode, increasedOrders);
//console.log(increasedOrders);
for (var nodeName in increasedOrders) {
if (increasedOrders.hasOwnProperty(nodeName)) {
nodes[nodeMap.get(nodeName)].order = increasedOrders[nodeName];
}
}
}
function increaseOrderForSuccessorsRecursive(nodes, currentNode, order, startingNode, increasedOrders) {
if ((currentNode.hasOwnProperty("order")) && (currentNode.order < order)) {
if ((! increasedOrders.hasOwnProperty(currentNode.name)) || (increasedOrders[currentNode.name] < order)) {
increasedOrders[currentNode.name] = order;
currentNode.successors.forEach(function(successor) {
if (nodes[nodeMap.get(successor)].order > currentNode.order) { //only increase order of successors if they lie to the right of the currentNode (not for repeats/translocations)
increaseOrderForSuccessorsRecursive(nodes, nodes[nodeMap.get(successor)], order + 1, startingNode, increasedOrders);
}
});
if (currentNode !== startingNode) {
currentNode.predecessors.forEach(function(predecessor) {
if (nodes[nodeMap.get(predecessor)].order > currentNode.order) { //only increase order of predecessors if they lie to the right of the currentNode (not for repeats/translocations)
//console.log("predecessor: from " + currentNode.name + " to " + predecessor + " = " + (order + 1));
increaseOrderForSuccessorsRecursive(nodes, nodes[nodeMap.get(predecessor)], order + 1, startingNode, increasedOrders);
}
});
}
}
}
}
function generateNodeDegree(nodes, tracks) { //calculates the node degree: the number of tracks passing through the node / the node height
nodes.forEach(function(node) { node.tracks = []; });
tracks.forEach(function(track) {
//console.log(track.id);
track.sequence.forEach(function(nodeName) {
//nodes[nodeMap.get(nodeName)].tracks=[];
var noMinusName = nodeName;
if (noMinusName.charAt(0) === '-') noMinusName = noMinusName.substr(1);
nodes[nodeMap.get(noMinusName)].tracks.push(track.id);
});
});
nodes.forEach(function(node) {
if (node.hasOwnProperty("tracks")) node.degree = node.tracks.length;
});
}
function switchNodeOrientation(nodes, tracks) {
var toSwitch = {};
var i, j;
var nodeName, prevNode, nextNode, currentNode;
for (i = 1; i < tracks.length; i++) {
//TODO: first element
for (j = 1; j < tracks[i].sequence.length - 1; j++) {
nodeName = tracks[i].sequence[j];
if (nodeName.charAt(0) === "-") nodeName = nodeName.substr(1);
currentNode = nodes[nodeMap.get(nodeName)];
if (tracks[0].sequence.indexOf(nodeName) === -1) { //do not change orientation for nodes which are part of the pivot track
if (tracks[i].sequence[j - 1].charAt(0) !== "-") prevNode = nodes[nodeMap.get(tracks[i].sequence[j - 1])];
else prevNode = nodes[nodeMap.get(tracks[i].sequence[j - 1].substr(1))];
if (tracks[i].sequence[j + 1].charAt(0) !== "-") nextNode = nodes[nodeMap.get(tracks[i].sequence[j + 1])];
else nextNode = nodes[nodeMap.get(tracks[i].sequence[j + 1].substr(1))];
if ((prevNode.order < currentNode.order) && (currentNode.order < nextNode.order)) {
if (! toSwitch.hasOwnProperty(nodeName)) toSwitch[nodeName] = 0;
if (tracks[i].sequence[j].charAt(0) === "-") toSwitch[nodeName] += 1;
else toSwitch[nodeName] -= 1;
}
if ((prevNode.order > currentNode.order) && (currentNode.order > nextNode.order)) {
if (! toSwitch.hasOwnProperty(nodeName)) toSwitch[nodeName] = 0;
if (tracks[i].sequence[j].charAt(0) === "-") toSwitch[nodeName] -= 1;
else toSwitch[nodeName] += 1;
}
}
}
//TODO: last element
}
tracks.forEach(function(track, trackIndex) {
track.sequence.forEach(function(node, nodeIndex) {
nodeName = node;
if (nodeName.charAt(0) === "-") nodeName = nodeName.substr(1);
if ((toSwitch.hasOwnProperty(nodeName)) && (toSwitch[nodeName] > 0)) {
if (node.charAt(0) === "-") tracks[trackIndex].sequence[nodeIndex] = node.substr(1);
else tracks[trackIndex].sequence[nodeIndex] = "-" + node;
}
});
});
}
function generateNodeXCoords(nodes, tracks) { //calculates the concrete values for the nodes' x-coordinates
var extra;
var currentX;
var nextX;
var currentOrder;
nodes.sort(compareNodesByOrder);
nodeMap = generateNodeMap(nodes);
extra = calculateExtraSpace(nodes, tracks);
currentX = 0;
nextX = offsetX + 20;
currentOrder = -1;
nodes.forEach(function(node, index) {
if (node.hasOwnProperty("order")) {
if (node.order > currentOrder) {
currentOrder = node.order;
currentX = nextX + 10 * extra[node.order];
}
node.x = currentX;
nextX = Math.max(nextX, currentX + 20 + 20 * node.width);
} else {
console.log("Node " + node.name + " has no order property");
}
});
}
function calculateExtraSpace(nodes, tracks) { //calculates additional horizontal space needed between two nodes
//two neighboring nodes have to be moved further apart if there is a lot going on in between them
//-> edges turning to vertical orientation should not overlap
var i;
var leftSideEdges = [];
var rightSideEdges = [];
var extra = [];
for (i = 0; i <= maxOrder; i++) {
leftSideEdges.push(0);
rightSideEdges.push(0);
}
tracks.forEach(function(track, trackID) {
for (i = 1; i < track.path.length; i++) {
if (track.path[i].order === track.path[i - 1].order) { //repeat or translocation
if (track.path[i].isForward === true) leftSideEdges[track.path[i].order]++;
else rightSideEdges[track.path[i].order]++;
}
}
});
/*console.log("left side edges:");
console.log(leftSideEdges);
console.log("right side edges:");
console.log(rightSideEdges);*/
extra.push(Math.max(0, leftSideEdges[0] - 1));
for (i = 1; i <= maxOrder; i++) {
extra.push(Math.max(0, leftSideEdges[i] - 1) + Math.max(0, rightSideEdges[i - 1] - 1));
}
return extra;
}
function generateLaneAssignment(nodes, tracks) { //create and fill assignment-variable, which contains info about tracks and lanes for each order-value
var i;
var j;
var segmentNumber;
var currentNodeId;
var currentNodeIsForward;
var currentNode;
var previousNode;
var previousNodeIsForward;
var prevSegmentPerOrderPerTrack = [];
for (i = 0; i <= maxOrder; i++) {
assignment[i] = [];
prevSegmentPerOrderPerTrack[i] = [];
for (j = 0; j < numberOfTracks; j++) {
prevSegmentPerOrderPerTrack[i][j] = null;
}
}
tracks.forEach(function(track, trackNo) {
//add info for start of track
currentNodeId = track.sequence[0];
if (currentNodeId.charAt(0) != '-') {
currentNodeIsForward = true;
} else {
currentNodeId = currentNodeId.substr(1);
currentNodeIsForward = false;
}
currentNode = nodes[nodeMap.get(currentNodeId)];
track.path = [];
track.path.push({order: currentNode.order, lane: null, isForward: currentNodeIsForward, node: currentNodeId});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: 0, node: currentNodeId, isForward: currentNodeIsForward, lane: null});
addToAssignment(currentNode.order, currentNodeId, trackNo, 0, prevSegmentPerOrderPerTrack);
segmentNumber = 1;
for (i = 1; i < track.sequence.length; i++) {
previousNode = currentNode;
previousNodeIsForward = currentNodeIsForward;
currentNodeId = track.sequence[i];
currentNodeIsForward = true;
if (currentNodeId.charAt(0) === '-') {
currentNodeId = currentNodeId.substr(1);
currentNodeIsForward = false;
}
currentNode = nodes[nodeMap.get(currentNodeId)];
if (currentNode.order > previousNode.order) {
if (! previousNodeIsForward) {
track.path.push({order: previousNode.order, lane: null, isForward: true, node: null});
//assignment[previousNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: null, isForward: true, lane: null});
addToAssignment(previousNode.order, null, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
}
for (j = previousNode.order + 1; j < currentNode.order; j++) {
track.path.push({order: j, lane: null, isForward: true, node: null});
//assignment[j].push({trackNo: trackNo, segmentNo: segmentNumber, node: null, isForward: true, lane: null});
addToAssignment(j, null, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
}
if (! currentNodeIsForward) {
track.path.push({order: currentNode.order, lane: null, isForward: true, node: null});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: null, isForward: true, lane: null});
addToAssignment(currentNode.order, null, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
track.path.push({order: currentNode.order, lane: null, isForward: false, node: currentNodeId});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: currentNodeId, isForward: false, lane: null});
addToAssignment(currentNode.order, currentNodeId, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
} else {
track.path.push({order: currentNode.order, lane: null, isForward: true, node: currentNodeId});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: currentNodeId, isForward: true, lane: null});
addToAssignment(currentNode.order, currentNodeId, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
}
} else if (currentNode.order < previousNode.order) {
if (previousNodeIsForward) {
track.path.push({order: previousNode.order, lane: null, isForward: false, node: null});
//assignment[previousNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: null, isForward: false, lane: null});
addToAssignment(previousNode.order, null, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
}
for (j = previousNode.order - 1; j > currentNode.order; j--) {
track.path.push({order: j, lane: null, isForward: false, node: null});
//assignment[j].push({trackNo: trackNo, segmentNo: segmentNumber, node: null, isForward: false, lane: null});
addToAssignment(j, null, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
}
if (currentNodeIsForward) {
track.path.push({order: currentNode.order, lane: null, isForward: false, node: null});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: null, isForward: false, lane: null});
addToAssignment(currentNode.order, null, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
track.path.push({order: currentNode.order, lane: null, isForward: true, node: currentNodeId});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: currentNodeId, isForward: true, lane: null});
addToAssignment(currentNode.order, currentNodeId, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
} else {
track.path.push({order: currentNode.order, lane: null, isForward: false, node: currentNodeId});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: currentNodeId, isForward: false, lane: null});
addToAssignment(currentNode.order, currentNodeId, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
}
} else { //currentNode.order === previousNode.order
if (currentNodeIsForward !== previousNodeIsForward) {
track.path.push({order: currentNode.order, lane: null, isForward: currentNodeIsForward, node: currentNodeId});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: currentNodeId, isForward: currentNodeIsForward, lane: null});
addToAssignment(currentNode.order, currentNodeId, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
} else {
track.path.push({order: currentNode.order, lane: null, isForward: !currentNodeIsForward, node: null});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: null, isForward: !currentNodeIsForward, lane: null});
addToAssignment(currentNode.order, null, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
track.path.push({order: currentNode.order, lane: null, isForward: currentNodeIsForward, node: currentNodeId});
//assignment[currentNode.order].push({trackNo: trackNo, segmentNo: segmentNumber, node: currentNodeId, isForward: currentNodeIsForward, lane: null});
addToAssignment(currentNode.order, currentNodeId, trackNo, segmentNumber, prevSegmentPerOrderPerTrack);
segmentNumber++;
}
}
}
});
for (i = 0; i <= maxOrder; i++) {
//for (i = 0; i <= 3; i++) {
//console.log("order " + i + ":");
generateSingleLaneAssignment(assignment[i], i, nodes, tracks); //this is where the lanes get assigned
}
}
function addToAssignment(order, nodeID, trackNo, segmentID, prevSegmentPerOrderPerTrack) {
var compareToFromSame;
var i;
compareToFromSame = null;
if (prevSegmentPerOrderPerTrack[order][trackNo] !== null) {
compareToFromSame = prevSegmentPerOrderPerTrack[order][trackNo];
}
if (nodeID === null) {
assignment[order].push({type: "single", name: null, tracks: [{trackID: trackNo, segmentID: segmentID, compareToFromSame: compareToFromSame}]});
//console.log("HIER: " + assignment[order][assignment[order].length - 1].tracks[0]);
prevSegmentPerOrderPerTrack[order][trackNo] = assignment[order][assignment[order].length - 1].tracks[0];
} else {
for (i = 0; i < assignment[order].length; i++) {
if (assignment[order][i].name === nodeID) { //add to existing node in assignment
assignment[order][i].type = "multiple";
assignment[order][i].tracks.push({trackID: trackNo, segmentID: segmentID, compareToFromSame: compareToFromSame});
prevSegmentPerOrderPerTrack[order][trackNo] = assignment[order][i].tracks[assignment[order][i].tracks.length - 1];
return;
}
}
//create new node in assignment
assignment[order].push({type: "single", name: nodeID, tracks: [{trackID: trackNo, segmentID: segmentID, compareToFromSame: compareToFromSame}]});
prevSegmentPerOrderPerTrack[order][trackNo] = assignment[order][assignment[order].length - 1].tracks[0];
}
}
function generateSingleLaneAssignment(assignment, order, nodes, tracks) {
var i, j, index, currentLane;
//for (i = 0; i < assignment.length; i++) {
assignment.forEach(function(node) {
node.idealLane = 0;
//for (j = 0: j < assignment[i].tracks.length) {
node.tracks.forEach(function(track) {
if (track.segmentID === 0) {
track.idealLane = track.trackID;
} else {
if (tracks[track.trackID].path[track.segmentID - 1].order === order - 1) {
track.idealLane = tracks[track.trackID].path[track.segmentID - 1].lane;
} else if ((track.segmentID < tracks[track.trackID].path.length - 1) && (tracks[track.trackID].path[track.segmentID + 1].order === order - 1)) {
track.idealLane = tracks[track.trackID].path[track.segmentID + 1].lane;
} else {
index = track.segmentID - 1;
//while (! ((tracks[track.trackID].path[index].order === order) && (tracks[track.trackID].path[index].hasOwnProperty("lane")))) index--;
//while (! ((tracks[track.trackID].path[index].order === order) && (tracks[track.trackID].path[index].lane !== null))) index--;
while (tracks[track.trackID].path[index].order !== order - 1) index--;
track.idealLane = tracks[track.trackID].path[index].lane;
}
}
node.idealLane += track.idealLane;
});
node.idealLane /= node.tracks.length;
});
currentLane = 0;
var sumOfLaneChanges = 0;
var totalLanes = 0;
assignment.sort(compareByIdealLane);
assignment.forEach(function(node) {
//node.yCoord = assignment[i][j].lane;
//node.y = offsetY + 110 + 22 * node.yCoord;
//console.log(node.name + "HIER " + nodeMap.get(node.name));
if (node.name !== null) {
nodes[nodeMap.get(node.name)].yCoord = currentLane;
nodes[nodeMap.get(node.name)].y = offsetY + 110 + 22 * currentLane;
//nodes[nodeMap.get(node.name)].y = offsetY + 90 + 22 * currentLane;
}
node.tracks.sort(compareByIdealLane);
node.tracks.forEach(function(track) {
//console.log("Track " + track.trackID + " (" + track.segmentID + ") --> Lane " + currentLane);
track.lane = currentLane;
tracks[track.trackID].path[track.segmentID].lane = currentLane;
sumOfLaneChanges += currentLane - track.idealLane;
totalLanes++;
currentLane++;
});
});
var moveBy = Math.round(sumOfLaneChanges / totalLanes - 0.000001);
if ((moveBy !== 0) && (totalLanes > numberOfTracks)) {
//console.log("move by " + moveBy);
assignment.forEach(function(node) {
if (node.name !== null) {
nodes[nodeMap.get(node.name)].yCoord -= moveBy;
nodes[nodeMap.get(node.name)].y -= 22 * moveBy;
}
node.tracks.forEach(function(track) {
//console.log("Track " + track.trackID + " (" + track.segmentID + ") --> Lane " + currentLane);
track.lane -= moveBy;
tracks[track.trackID].path[track.segmentID].lane -= moveBy;
});
});
}
}
function compareByIdealLane(a, b) {
if (a.hasOwnProperty("idealLane")) {
if (b.hasOwnProperty("idealLane")) {
if (a.idealLane < b.idealLane) return -1;
else if (a.idealLane > b.idealLane) return 1;
else return 0;
} else return -1;
} else {
if (b.hasOwnProperty("idealLane")) return 1;
else return 0;
}
}
function sortNumber(a,b) { return a - b; }
function swap(array, i, j) {
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
function compareNodesByOrder(a, b) {
if (a.hasOwnProperty("order")) {
if (b.hasOwnProperty("order")) {
if (a.order < b.order) return -1;
else if (a.order > b.order) return 1;
else return 0;
} else return -1;
} else {
if (b.hasOwnProperty("order")) return 1;
else return 0;
}
}
function generateEdgesFromPath(nodes, tracks, edges) {
var i;
var xStart;
var xEnd;
var y;
var yEnd;
for (i = 0; i <= maxOrder; i++) {
extraLeft.push(0);
extraRight.push(0);
}
//generate x coords where each order starts and ends
var orderStartX = [];
var orderEndX = [];
nodes.forEach(function(node) {
if (node.hasOwnProperty("order")) {
orderStartX[node.order] = node.x;
if (orderEndX[node.order] === undefined) orderEndX[node.order] = node.x + 20 * (node.width - 1);
else orderEndX[node.order] = Math.max(orderEndX[node.order], node.x + 20 * (node.width - 1));
}
});
tracks.forEach(function(track, trackID) {
//start of path
if (track.sequence[0].charAt(0) === '-') { //The track starts with an inversed node (TODO: change to isForward)
//TODO: ADD STUFF HERE
} else { //The track starts with a forward node
xStart = orderStartX[track.path[0].order] - 20;
xEnd = orderEndX[track.path[0].order];
y = offsetY + 110 + 22 * track.path[0].lane;
edges.push({source: {x: xStart, y: y}, target: {x: xEnd, y: y}, color: track.id});
}
//middle of path
for (i = 1; i < track.path.length; i++) {
if (track.path[i].order - 1 === track.path[i - 1].order) { //regular forward connection
xStart = orderEndX[track.path[i - 1].order];
xEnd = orderStartX[track.path[i].order];
y = offsetY + 110 + 22 * track.path[i - 1].lane;
yEnd = offsetY + 110 + 22 * track.path[i].lane;
edges.push({source: {x: xStart, y: y}, target: {x: xEnd, y: yEnd}, color: track.id});
} else if (track.path[i].order + 1 === track.path[i - 1].order) { //regular backward connection
xStart = orderEndX[track.path[i].order];
xEnd = orderStartX[track.path[i - 1].order];
y = offsetY + 110 + 22 * track.path[i].lane;
yEnd = offsetY + 110 + 22 * track.path[i - 1].lane;
edges.push({source: {x: xStart, y: y}, target: {x: xEnd, y: yEnd}, color: track.id});
} else { //change of direction
if (track.path[i - 1].isForward) {
generateForwardToReverse(track.path[i].order, track.path[i].lane, track.path[i - 1].lane, track.id, orderEndX);
} else {
generateReverseToForward(track.path[i].order, track.path[i].lane, track.path[i - 1].lane, track.id, orderStartX);
}
}
//edge within node
xStart = orderStartX[track.path[i].order];
xEnd = orderEndX[track.path[i].order];
y = offsetY + 110 + 22 * track.path[i].lane;
edges.push({source: {x: xStart, y: y}, target: {x: xEnd, y: y}, color: track.id});
}
//ending edges
if (!track.path[track.path.length - 1].isForward) { //The track ends with an inversed node
//TODO: ADD STUFF HERE
} else { //The track endss with a forward node
xStart = orderEndX[track.path[track.path.length - 1].order];
xEnd = xStart + 20;
y = offsetY + 110 + 22 * track.path[track.path.length - 1].lane;
edges.push({source: {x: xStart, y: y}, target: {x: xEnd, y: y}, color: track.id});
}
});
}
function generateForwardToReverse(order, lane1, lane2, trackID, orderEndX) {
var temp;
var x;
var y;
var y2;
x = orderEndX[order] + 5 + 10 * extraRight[order];
if (lane1 > lane2) {
temp = lane1;
lane1 = lane2;
lane2 = temp;
}
y = offsetY + 110 + 22 * lane1 + 10;
y2 = offsetY + 110 + 22 * lane2 + 10;
//console.log("order: " + order + ", lane1: " + lane1 + ", lane2: " + lane2);
edges.push({source: {x: x - 5 - 10 * extraRight[order], y: y - 10}, target: {x: x, y: y - 10}, color: trackID}); //right (elongate edge within node)
arcs[1].push({ x: x, y: y, color: trackID}); //from right to down
edges.push({source: {x: x + 10, y: y}, target: {x: x + 10, y: y2 - 20}, color: trackID}); //down
arcs[2].push({ x: x, y: y2 - 20, color: trackID});
edges.push({source: {x: x - 5 - 10 * extraRight[order], y: y2 - 10}, target: {x: x, y: y2 - 10}, color: trackID}); //right (elongate edge within node)
extraRight[order]++;
}
function generateReverseToForward(order, lane1, lane2, trackID, orderStartX) {
var temp;
var x;
var y;
var y2;
if (lane1 > lane2) {
temp = lane1;
lane1 = lane2;
lane2 = temp;
}
y = offsetY + 110 + 22 * lane1 + 10;
y2 = offsetY + 110 + 22 * lane2 + 10;
x = orderStartX[order] - 35 - 10 * extraLeft[order];
edges.push({source: {x: x + 30, y: y - 10}, target: {x: x + 35 + 10 * extraLeft[order], y: y - 10}, color: trackID}); //left
arcs[0].push({ x: x + 30, y: y, color: trackID}); //from left to down
edges.push({source: {x: x + 20, y: y}, target: {x: x + 20, y: y2 - 20}, color: trackID}); //down
arcs[3].push({ x: x + 30, y: y2 - 20, color: trackID}); //from down to right
edges.push({source: {x: x + 30, y: y2 - 10}, target: {x: x + 35 + 10 * extraLeft[order], y: y2 - 10}, color: trackID}); //right
extraLeft[order]++;
}
function drawNodes(nodes) {
//Draw central white rectangle for node background
svg.selectAll(".nodeBackgroundRect")
.data(nodes)
.enter()
.append("rect")
.attr("class", "backgr")
.attr("x", function(d) { return d.x - 10; })
.attr("y", function(d) { return d.y; })
.attr("width", function(d) { return 20 * d.width; })
.attr("height", function(d) { return (d.degree - 1) * 22; });
//Draw top white rectangle for node background
svg.selectAll(".nodeBackgroundRect")
.data(nodes)
.enter()
.append("rect")
.attr("class", "backgr")
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y - 10; })
.attr("width", function(d) { return (d.width - 1) * 20; })
.attr("height", 10);
//Draw bottom white rectangle for node background
svg.selectAll(".nodeBackgroundRect")
.data(nodes)
.enter()
.append("rect")
.attr("class", "backgr")
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return (d.y + (22 * (d.degree - 1))); })
.attr("width", function(d) { return (d.width - 1) * 20; })
.attr("height", 8);
//Draw top-left circle segment (white background) for nodes
var topLeftSegment = d3.svg.arc()
.innerRadius(0)
.outerRadius(10)
.startAngle(-0.5 * Math.PI)
.endAngle(0 * Math.PI);
svg.selectAll(".nodeBackgroundTopLeft")
.data(nodes)
.enter()
.append("path")
.attr("class", "backgr")
.attr("d", topLeftSegment)
.attr("transform", function(d) {return "translate(" + d.x + ", " + d.y + ")"; });
//Draw top-right circle segment (white background) for nodes
var topRightSegment = d3.svg.arc()
.innerRadius(0)
.outerRadius(10)
.startAngle(0 * Math.PI)
.endAngle(0.5 * Math.PI);
svg.selectAll(".nodeBackgroundTopRight")
.data(nodes)
.enter()
.append("path")
.attr("class", "backgr")
.attr("d", topRightSegment)
.attr("transform", function(d) {return "translate(" + (d.x + 20 * (d.width -1)) + ", " + d.y + ")"; });
//Draw bottom-left circle segment (white background) for nodes
var bottomLeftSegment = d3.svg.arc()
.innerRadius(0)
.outerRadius(10)
.startAngle(1 * Math.PI)
.endAngle(1.5 * Math.PI);
svg.selectAll(".nodeBackgroundBottomLeft")
.data(nodes)
.enter()
.append("path")
.attr("class", "backgr")
.attr("d", bottomLeftSegment)
.attr("transform", function(d) {return "translate(" + d.x + ", " + (d.y + (22 * (d.degree - 1))) + ")"; });
//Draw bottom-right circle segment (white background) for nodes
var bottomRightSegment = d3.svg.arc()
.innerRadius(0)
.outerRadius(10)
.startAngle(0.5 * Math.PI)
.endAngle(1 * Math.PI);
svg.selectAll(".nodeBackgroundBottomRight")
.data(nodes)
.enter()
.append("path")
.attr("class", "backgr")
.attr("d", bottomRightSegment)
.attr("transform", function(d) {return "translate(" + (d.x + 20 * (d.width -1)) + ", " + (d.y + (22 * (d.degree - 1))) + ")"; });
//Draw top-left arc for nodes
var topLeftArc = d3.svg.arc()
.innerRadius(8)
.outerRadius(10)
.startAngle(-0.5 * Math.PI)
.endAngle(0 * Math.PI);
svg.selectAll(".topLeftArc")
.data(nodes)
.enter()
.append("path")
.attr("class", "arc")
.attr("d", topLeftArc)
.attr("transform", function(d) {return "translate(" + d.x + ", " + d.y + ")"; });
//Draw top-right arc for nodes
var topRightArc = d3.svg.arc()
.innerRadius(8)
.outerRadius(10)
.startAngle(0 * Math.PI)
.endAngle(0.5 * Math.PI);
svg.selectAll(".topRightArc")
.data(nodes)
.enter()
.append("path")
.attr("class", "arc")
.attr("d", topRightArc)
.attr("transform", function(d) {return "translate(" + (d.x + 20 * (d.width -1)) + ", " + d.y + ")"; });
//Draw bottom-left arc for nodes
var bottomLeftArc = d3.svg.arc()
.innerRadius(8)
.outerRadius(10)
.startAngle(1 * Math.PI)
.endAngle(1.5 * Math.PI);
svg.selectAll(".bottomLeftArc")
.data(nodes)
.enter()
.append("path")
.attr("class", "arc")
.attr("d", bottomLeftArc)
.attr("transform", function(d) {return "translate(" + d.x + ", " + (d.y + (22 * (d.degree - 1))) + ")"; });
//Draw bottom-right arc for nodes
var bottomRightArc = d3.svg.arc()
.innerRadius(8)
.outerRadius(10)
.startAngle(0.5 * Math.PI)
.endAngle(1 * Math.PI);
svg.selectAll(".bottomRightArc")
.data(nodes)
.enter()
.append("path")
.attr("class", "arc")
.attr("d", bottomRightArc)
.attr("transform", function(d) {return "translate(" + (d.x + 20 * (d.width -1)) + ", " + (d.y + (22 * (d.degree - 1))) + ")"; });
svg.selectAll(".arcLinkLeft") //linke Verbindung zw. Halbkreisen
.data(nodes)
.enter()
.append("rect")
.attr("class", "arc")
.attr("x", function(d) { return d.x - 10; })
.attr("y", function(d) { return d.y; })
.attr("width", 2)
.attr("height", function(d) { return (d.degree - 1) * 22; });
svg.selectAll(".arcLinkRight") //rechte Verbindung zw. Halbkreisen
.data(nodes)
.enter()
.append("rect")
.attr("class", "arc")
.attr("x", function(d) { return d.x + 8 + 20 * (d.width -1); })
.attr("y", function(d) { return d.y; })
.attr("width", 2)
.attr("height", function(d) { return (d.degree - 1) * 22; });
svg.selectAll(".arcLinkTop") //top Verbindung zw. Halbkreisen
.data(nodes)
.enter()
.append("rect")
.attr("class", "arc")
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y - 10; })
.attr("width", function(d) { return (d.width - 1) * 20; })
.attr("height", 2);
svg.selectAll(".arcLinkBottom") //bottom Verbindung zw. Halbkreisen
.data(nodes)
.enter()
.append("rect")
.attr("class", "arc")
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return (d.y + 8 + (22 * (d.degree - 1))); })
.attr("width", function(d) { return (d.width - 1) * 20; })
.attr("height", 2);
}
function drawEdges(edges) {
//Create Paths for edges
var diagonal = d3.svg.diagonal()
.source(function(d) { return {"x":d.source.y, "y":d.source.x}; })
.target(function(d) { return {"x":d.target.y, "y":d.target.x}; })
.projection(function(d) { return [d.y, d.x]; });
//Draw edges
var link = svg.selectAll(".link")
.data(edges)
.enter().append("path")
//.attr("class", "link")
.attr("class", function(d) {return "link track" + d.color; })
.attr("d", diagonal)
.on("mouseover", handleMouseOver)
.on("mouseout", handleMouseOut)
.on("click", handleMouseClick)
//.style("stroke", function(d, i) { return color(i); });
.style("stroke", function(d) { return color(d.color); });
}
function drawTopRightEdgeArcs(arcs) {
var topRightEdgeArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(0 * Math.PI)
.endAngle(0.5 * Math.PI);
svg.selectAll(".topRightArc")
.data(arcs)
.enter()
.append("path")
.attr("class", function(d) {return "link topRightArctrack" + d.color; })
.attr("d", topRightEdgeArc)
//.style("stroke", function(d) { return color(d.color); })
.on("mouseover", handleMouseOver)
.on("mouseout", handleMouseOut)
.on("click", handleMouseClick)
.style("fill", function(d) { return color(d.color); })
.attr("transform", function(d) {return "translate(" + d.x + ", " + d.y + ")"; });
}
function drawTopLeftEdgeArcs(arcs) {
var topLeftEdgeArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(0 * Math.PI)
.endAngle(-0.5 * Math.PI);
svg.selectAll(".topLeftArc")
.data(arcs)
.enter()
.append("path")
.attr("class", function(d) {return "link topLeftArctrack" + d.color; })
.attr("d", topLeftEdgeArc)
//.style("stroke", function(d) { return color(d.color); })
.on("mouseover", handleMouseOver)
.on("mouseout", handleMouseOut)
.on("click", handleMouseClick)
.style("fill", function(d) { return color(d.color); })
.attr("transform", function(d) {return "translate(" + d.x + ", " + d.y + ")"; });
}
function drawBottomRightEdgeArcs(arcs) {
var bottomRightEdgeArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(0.5 * Math.PI)
.endAngle(1 * Math.PI);
svg.selectAll(".bottomRightArc")
.data(arcs)
.enter()
.append("path")
.attr("class", function(d) {return "link bottomRightArctrack" + d.color; })
.attr("d", bottomRightEdgeArc)
//.style("stroke", function(d) { return color(d.color); })
.on("mouseover", handleMouseOver)
.on("mouseout", handleMouseOut)
.on("click", handleMouseClick)
.style("fill", function(d) { return color(d.color); })
.attr("transform", function(d) {return "translate(" + d.x + ", " + d.y + ")"; });
}
function drawBottomLeftEdgeArcs(arcs) {
var bottomLeftEdgeArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(1 * Math.PI)
.endAngle(1.5 * Math.PI);
svg.selectAll(".bottomLeftArc")
.data(arcs)
.enter()
.append("path")
.attr("class", function(d) {return "link bottomLeftArctrack" + d.color; })
.attr("d", bottomLeftEdgeArc)
//.style("stroke", function(d) { return color(d.color); })
.on("mouseover", handleMouseOver)
.on("mouseout", handleMouseOut)
.on("click", handleMouseClick)
.style("fill", function(d) { return color(d.color); })
.attr("transform", function(d) {return "translate(" + d.x + ", " + d.y + ")"; });
}
function handleMouseOver() { // Highlight track on mouseover
var currentClass = d3.select(this).attr("class");
currentClass = /track[0-9]*/.exec(currentClass);
//currentClass = /track[\S]*/.exec(currentClass);
//console.log(currentClass[0]);
svg.selectAll("." + currentClass)
//.style("stroke", "#000000")
.style("stroke-width", "10px");
var topRightArc = d3.svg.arc()
.innerRadius(5)
.outerRadius(15)
.startAngle(0 * Math.PI)
.endAngle(0.5 * Math.PI);
svg.selectAll(".topRightArc" + currentClass)
.attr("d", topRightArc);
var topLeftArc = d3.svg.arc()
.innerRadius(5)
.outerRadius(15)
.startAngle(0 * Math.PI)
.endAngle(-0.5 * Math.PI);
svg.selectAll(".topLeftArc" + currentClass)
.attr("d", topLeftArc);
var bottomRightArc = d3.svg.arc()
.innerRadius(5)
.outerRadius(15)
.startAngle(0.5 * Math.PI)
.endAngle(1 * Math.PI);
svg.selectAll(".bottomRightArc" + currentClass)
.attr("d", bottomRightArc);
var bottomLeftArc = d3.svg.arc()
.innerRadius(5)
.outerRadius(15)
.startAngle(1 * Math.PI)
.endAngle(1.5 * Math.PI);
svg.selectAll(".bottomLeftArc" + currentClass)
.attr("d", bottomLeftArc);
}
function handleMouseOut() { // Restore original appearance on mouseout
var currentClass = d3.select(this).attr("class");
currentClass = /track[0-9]*/.exec(currentClass);
svg.selectAll("." + currentClass)
//.style("stroke", function(d) { return color(d.color); });
.style("stroke-width", "7px");
var topRightArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(0 * Math.PI)
.endAngle(0.5 * Math.PI);
svg.selectAll(".topRightArc" + currentClass)
.attr("d", topRightArc);
var topLeftArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(0 * Math.PI)
.endAngle(-0.5 * Math.PI);
svg.selectAll(".topLeftArc" + currentClass)
.attr("d", topLeftArc);
var bottomRightArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(0.5 * Math.PI)
.endAngle(1 * Math.PI);
svg.selectAll(".bottomRightArc" + currentClass)
.attr("d", bottomRightArc);
var bottomLeftArc = d3.svg.arc()
.innerRadius(6)
.outerRadius(13)
.startAngle(1 * Math.PI)
.endAngle(1.5 * Math.PI);
svg.selectAll(".bottomLeftArc" + currentClass)
.attr("d", bottomLeftArc);
}
function handleMouseClick() { // Move clicked track to first position
var trackNo = d3.select(this).attr("class");
trackNo = /[0-9]+/.exec(trackNo);
var index = 0;
//console.log("trackno: " + trackNo);
while ((index < 10) && (inputTracks[index].id != trackNo)) index++;
//console.log("index: " + index);
moveTrackToFirstPosition(index);
}
function vgExtractNodes(vg) {
var result = [];
vg.node.forEach(function(node) {
//result.push({ name: "" + node.id, width: 1});
//result.push({ name: "" + node.id, width: node.sequence.length});
result.push({ name: "" + node.id, width: (1 + Math.log2(node.sequence.length))});
});
return result;
}
function vgExtractTracks(vg) {
var result =[];
vg.path.forEach(function(path, index) {
var sequence = [];
var isCompletelyReverse = true;
path.mapping.forEach(function(pos) {
if ((pos.position.hasOwnProperty('is_reverse')) && (pos.position.is_reverse === true)) {
sequence.push("-" + pos.position.node_id);
} else {
sequence.push("" + pos.position.node_id);
isCompletelyReverse = false;
}
});
//if ((path.mapping[0].position.hasOwnProperty('is_reverse')) && (path.mapping[0].position.is_reverse === true)) sequence.reverse();
if (isCompletelyReverse) {
console.log("completely reverse " + index);
console.log(sequence);
sequence.reverse();
sequence.forEach(function(node, index2) {
sequence[index2] = node.substr(1);
});
console.log(sequence);
}
//result.push({id: path.name, sequence: sequence});
result.push({id: index, sequence: sequence});
});
return result;
}
function vgMergeNodes(nodes, tracks) {
var mergeForward = {};
var i, index;
var mergeBackward = {};
var nodeName;
tracks.forEach(function(track) {
for (i = 0; i < track.sequence.length; i++) {
if (track.sequence[i].charAt(0) !== '-') { //forward Node
if (!mergeForward.hasOwnProperty(track.sequence[i])) {
if ((i < track.sequence.length - 1) && (track.sequence[i + 1].charAt(0) !== '-')) {
mergeForward[track.sequence[i]] = {mergeWith: track.sequence[i + 1], isPossible: true};
}
} else {
if ((i === track.sequence.length - 1) || (mergeForward[track.sequence[i]].mergeWith != track.sequence[i + 1])) {
mergeForward[track.sequence[i]].isPossible = false;
}
}
} else { //reverse Node
nodeName = track.sequence[i].substr(1);
if (!mergeForward.hasOwnProperty(nodeName)) {
if ((i > 0) && (track.sequence[i - 1].charAt(0) === '-')) {
mergeForward[nodeName] = {mergeWith: track.sequence[i - 1].substr(1), isPossible: true};
}
} else {
if ((i === 0) || (mergeForward[nodeName].mergeWith != track.sequence[i - 1].substr(1))) {
mergeForward[nodeName].isPossible = false;
}
}
}
}
});
console.log("Merge Forward: " + Object.keys(mergeForward).length);
console.log(mergeForward);
for (var prop in mergeForward) {
if (mergeForward.hasOwnProperty(prop)) {
if (mergeForward[prop].isPossible === true) {
mergeBackward[mergeForward[prop].mergeWith] = {mergeWith: prop, isPossible: true};
}
}
}
console.log("Merge Backward:" + Object.keys(mergeBackward).length);
console.log(mergeBackward);
tracks.forEach(function(track) {
for (i = 0; i < track.sequence.length; i++) {
if (track.sequence[i].charAt(0) !== '-') { //forward Node
if (mergeBackward.hasOwnProperty(track.sequence[i])) {
if ((i === 0) || (mergeBackward[track.sequence[i]].mergeWith !== track.sequence[i - 1])) {
mergeBackward[track.sequence[i]].isPossible = false;
}
}
} else { //reverse Node
if (mergeBackward.hasOwnProperty(track.sequence[i].substr(1))) {
if ((i === track.sequence.length - 1) || (mergeBackward[track.sequence[i].substr(1)].mergeWith !== track.sequence[i + 1].substr(1))) {
mergeBackward[track.sequence[i].substr(1)].isPossible = false;
}
}
}
}
});
var count = 0;
for (prop in mergeBackward) {
if (mergeBackward.hasOwnProperty(prop)) {
if (mergeBackward[prop].isPossible === true) {
count++;
console.log("merge " + mergeBackward[prop].mergeWith + " with " + prop);
}
}
}
console.log(count + " merges");
//actually merge the nodes by removing the corresponding nodes from track data
tracks.forEach(function(track) {
for (i = track.sequence.length - 1; i >= 0; i--) {
nodeName = track.sequence[i];
if (nodeName.charAt(0) === '-') nodeName = nodeName.substr(1);
if ((mergeBackward.hasOwnProperty(nodeName)) && (mergeBackward[nodeName].isPossible === true)) {
track.sequence.splice(i, 1);
}
}
});
//remove the nodes from node-Array
for (prop in mergeBackward) {
if (mergeBackward.hasOwnProperty(prop)) {
if (mergeBackward[prop].isPossible === true) {
index = 0;
//console.log("looking for " + mergeBackward[prop])
while (nodes[index].name !== prop) index++;
nodes.splice(index, 1);
}
}
}
return {nodes: nodes, tracks: tracks};
}
return {
create: create,
switch: switchAlwaysMoveRight,
vgExtractNodes: vgExtractNodes,
vgExtractTracks: vgExtractTracks,
vgMergeNodes: vgMergeNodes
};
})();
| Modify generateNodeOrder() to improve placement of nodes
Modify generateNodeOrder() to automatically decide whether to place new nodes
to the left or to the right of the previous node. This is only relevant for
inversions where depending on circumstances sometimes either option is
preferable.
| sequenceTubeMap.js | Modify generateNodeOrder() to improve placement of nodes | <ide><path>equenceTubeMap.js
<ide> //console.log("number of tracks: " + numberOfTracks);
<ide> nodeMap = generateNodeMap(nodes);
<ide> generateNodeSuccessors(nodes, tracks);
<add> generateNodeDegree(nodes, tracks);
<ide> generateNodeOrder(nodes, tracks);
<ide> maxOrder = getMaxOrder(nodes);
<del> generateNodeDegree(nodes, tracks);
<add>
<add> for (var i = 0; i <= maxOrder; i++) {
<add> console.log('order ' + i + ': ');
<add> nodes.forEach(function(node) {
<add> if (node.order === i) console.log(node.name);
<add> });
<add> }
<add>
<add> //generateNodeDegree(nodes, tracks);
<ide> switchNodeOrientation(nodes, tracks);
<ide> generateLaneAssignment(nodes, tracks);
<ide>
<ide> }
<ide>
<ide> function generateNodeOrder(nodes, tracks) { //generate global sequence of nodes from left to right, starting with first track and adding other tracks sequentially
<add> var modifiedSequence;
<add> var i;
<add> var j;
<add> var currentOrder;
<add> var currentNode;
<add> var rightIndex;
<add> var leftIndex;
<add>
<add> generateNodeOrderOfSingleTrack(tracks[0].sequence, nodes); //calculate order values for all nodes of the first track
<add>
<add> for (i = 1; i < tracks.length; i++) {
<add> console.log("Node order for track " + i + " " + tracks[i].id);
<add> modifiedSequence = uninvert(tracks[i].sequence);
<add> //modifiedSequence = tracks[i].sequence;
<add> //console.log(tracks[i].sequence);
<add> //console.log(modifiedSequence);
<add> rightIndex = generateNodeOrderLeftEnd(modifiedSequence, nodes); //calculate order values for all nodes until the first anchor
<add> while (rightIndex < modifiedSequence.length) { //move right until the end of the sequence
<add> //find next anchor node
<add> leftIndex = rightIndex;
<add> rightIndex++;
<add> while ((rightIndex < modifiedSequence.length) && (! nodes[nodeMap.get(modifiedSequence[rightIndex])].hasOwnProperty("order"))) rightIndex++;
<add>
<add> if (rightIndex < modifiedSequence.length) { //middle segment between two anchors
<add> currentOrder = nodes[nodeMap.get(modifiedSequence[leftIndex])].order + 1; //start with order value of leftAnchor + 1
<add> for (j = leftIndex + 1; j < rightIndex; j++) {
<add> nodes[nodeMap.get(modifiedSequence[j])].order = currentOrder; //assign order values
<add> //console.log(modifiedSequence[j] + " -> " + currentOrder);
<add> currentOrder++;
<add> }
<add>
<add> if (nodes[nodeMap.get(modifiedSequence[rightIndex])].order > nodes[nodeMap.get(modifiedSequence[leftIndex])].order) { //if order-value of left anchor < order-value of right anchor
<add> if (nodes[nodeMap.get(modifiedSequence[rightIndex])].order < currentOrder) { //and the right anchor now has a lower order-value than our newly added nodes
<add> console.log('first');
<add> increaseOrderForSuccessors(nodes, nodes[nodeMap.get(modifiedSequence[rightIndex])], currentOrder);
<add> }
<add> } else { //potential node reversal: check for ordering conflict, if no conflict found move node at rightIndex further to the right in order to not create a track reversal
<add> if (! isSuccessor(nodes[nodeMap.get(modifiedSequence[rightIndex])], nodes[nodeMap.get(modifiedSequence[leftIndex])], nodes)) { //no real reversal
<add> //console.log("hier");
<add> //console.log(isSuccessor(nodes[nodeMap.get(modifiedSequence[rightIndex])], nodes[nodeMap.get(modifiedSequence[leftIndex])], nodes));
<add> console.log('second');
<add> increaseOrderForSuccessors(nodes, nodes[nodeMap.get(modifiedSequence[rightIndex])], currentOrder);
<add> } else { //real reversal
<add> //if (! nextNodeIsAlwaysToTheRight) {
<add> if ((tracks[i].sequence[leftIndex].charAt(0) === '-') || (nodes[nodeMap.get(modifiedSequence[leftIndex + 1])].degree < 2)) {
<add> //if (nodes[nodeMap.get(modifiedSequence[leftIndex + 1])].degree < 2) {
<add> currentOrder = nodes[nodeMap.get(modifiedSequence[leftIndex])].order - 1; //start with order value of leftAnchor + 1
<add> for (j = leftIndex + 1; j < rightIndex; j++) {
<add> nodes[nodeMap.get(modifiedSequence[j])].order = currentOrder; //assign order values
<add> //console.log(modifiedSequence[j] + " -> " + currentOrder);
<add> currentOrder--;
<add> }
<add> }
<add> }
<add> }
<add> } else { //right segment to the right of last anchor
<add> currentOrder = nodes[nodeMap.get(modifiedSequence[leftIndex])].order + 1;
<add> for (j = leftIndex + 1; j < modifiedSequence.length; j++) {
<add> currentNode = nodes[nodeMap.get(modifiedSequence[j])];
<add> if (! currentNode.hasOwnProperty("order")) {
<add> currentNode.order = currentOrder;
<add> currentOrder++;
<add> }
<add> }
<add> }
<add> }
<add> }
<add> }
<add>
<add>
<add> function generateNodeOrderALT(nodes, tracks) { //generate global sequence of nodes from left to right, starting with first track and adding other tracks sequentially
<ide> var modifiedSequence;
<ide> var i;
<ide> var j;
<ide> return max;
<ide> }
<ide>
<del> function uninvert(sequence) { //generates sequence "corrected" for inversions i.e. A B C -D -E -F G H becomes A B C F E D G H
<del> //the univerted sequence is how the nodes are arranged from left to right in the display
<add> function uninvert(sequence) { //generates sequence keeping the order but removing all "-"s from nodes
<ide> var result = [];
<ide> var i;
<ide>
<ide> }
<ide>
<ide> function increaseOrderForAllNodes(nodes, amount) { //increases the order-value of all nodes by amount
<add> console.log('increase for all');
<ide> nodes.forEach(function(node) {
<ide> if (node.hasOwnProperty("order")) node.order += amount;
<ide> });
<ide> }
<ide>
<ide> function increaseOrderForSuccessors(nodes, currentNode, order) { //increases the order-value for currentNode and (if necessary) successor nodes recursively
<del> //console.log("increasing orders from " + currentNode.name + " to " + order);
<add> console.log("increasing orders from " + currentNode.name + " to " + order);
<ide> var increasedOrders = {};
<ide> increaseOrderForSuccessorsRecursive(nodes, currentNode, order, currentNode, increasedOrders);
<ide> //console.log(increasedOrders);
<ide> for (var nodeName in increasedOrders) {
<ide> if (increasedOrders.hasOwnProperty(nodeName)) {
<add> console.log(nodeName + ': ' + nodes[nodeMap.get(nodeName)].order + ' -> ' + increasedOrders[nodeName]);
<ide> nodes[nodeMap.get(nodeName)].order = increasedOrders[nodeName];
<ide> }
<ide> } |
|
JavaScript | mit | 7df1b7887a2cceba948b7ba48ec46c1faa54cd0a | 0 | lautarobock/brew-o-matic,lautarobock/brew-o-matic,lautarobock/brew-o-matic | var model = require('../domain/model.js');
/**
* POST from TILT
* @Params body {"SG":"1.020","Temp":"66.8","Color":"BLACK","Timepoint":"42746.416989097226","Beer":"Brown #51","Comment":""}
*/
exports.updateTilt = function(req, res) {
model.Recipe.findOne({_id:req.params.id}).exec(function(err,recipe) {
if (recipe.tiltValues.length > 2) {
//si los ultimos 3 valoes son iguales elimino el anteultimo
var lastPos = recipe.tiltValues.length-1;
var last = recipe.tiltValues[lastPos];
var prev = recipe.tiltValues[lastPos-1];
if ( last.temp === prev.temp && prev.temp === fahrenheitToCelsius(req.body.Temp) &&
last.sg === prev.sg && prev.sg === parseFloat(req.body.SG)) {
recipe.tiltValues.pop();
}
}
recipe.tiltValues.push({
date: new Date(),
sg: parseFloat(req.body.SG),
temp: fahrenheitToCelsius(req.body.Temp)
})
recipe.save(function(err) {
if ( err ) {
res.send(500,{error: 'Error al actializr TITL en la receta'});
} else {
console.log('Params', req.params.id);
console.log('Query', JSON.stringify(req.query));
console.log('Body', JSON.stringify(req.body));
res.send({"result":"success", "row": recipe.tiltValues[recipe.tiltValues.length-1]});
}
});
});
};
function fahrenheitToCelsius(fahrenheit) {
fahrenheit = parseFloat(fahrenheit);
if (fahrenheit === '') {
return null;
}
if (isNaN(fahrenheit)) {
return null;
}
return (5 / 9) * (fahrenheit - 32)
} | routes/tilt.js | var model = require('../domain/model.js');
/**
* POST from TILT
* @Params body {"SG":"1.020","Temp":"66.8","Color":"BLACK","Timepoint":"42746.416989097226","Beer":"Brown #51","Comment":""}
*/
exports.updateTilt = function(req, res) {
model.Recipe.findOne({_id:req.params.id}).exec(function(err,recipe) {
if (recipe.tiltValues.length > 2) {
//si los ultimos 3 valoes son iguales elimino el anteultimo
var lastPos = recipe.tiltValues.length-1;
var last = recipe.tiltValues[lastPos];
var prev = recipe.tiltValues[lastPos-1];
if ( last.temp === prev.temp && prev.temp === fahrenheitToCelsius(req.body.Temp) &&
last.sg === prev.sg && prev.sg === parseFloat(req.body.SG)) {
recipe.pop();
}
}
recipe.tiltValues.push({
date: new Date(),
sg: parseFloat(req.body.SG),
temp: fahrenheitToCelsius(req.body.Temp)
})
recipe.save(function(err) {
if ( err ) {
res.send(500,{error: 'Error al actializr TITL en la receta'});
} else {
console.log('Params', req.params.id);
console.log('Query', JSON.stringify(req.query));
console.log('Body', JSON.stringify(req.body));
res.send({"result":"success", "row": recipe.tiltValues[recipe.tiltValues.length-1]});
}
});
});
};
function fahrenheitToCelsius(fahrenheit) {
fahrenheit = parseFloat(fahrenheit);
if (fahrenheit === '') {
return null;
}
if (isNaN(fahrenheit)) {
return null;
}
return (5 / 9) * (fahrenheit - 32)
} | optimize tilt remove repeated values
| routes/tilt.js | optimize tilt remove repeated values | <ide><path>outes/tilt.js
<ide> var prev = recipe.tiltValues[lastPos-1];
<ide> if ( last.temp === prev.temp && prev.temp === fahrenheitToCelsius(req.body.Temp) &&
<ide> last.sg === prev.sg && prev.sg === parseFloat(req.body.SG)) {
<del> recipe.pop();
<add> recipe.tiltValues.pop();
<ide> }
<ide> }
<ide> recipe.tiltValues.push({ |
|
Java | apache-2.0 | ae2564fae2b4be43e463e4d3d112c8d2646c8e1f | 0 | yummy222/android_page_curl,tsdl2013/android_page_curl,hgl888/android_page_curl,cailingxiao/android_page_curl,zhenian/android_page_curl,harism/android_page_curl,mondoktamas/android_page_curl,changjiashuai/android_page_curl,cags12/android_page_curl,shyamkumarm/android_page_curl,HiWong/android_page_curl,yytang2012/android_page_curl,suedinym/android_page_curl | package fi.harism.curl;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.Vector;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.graphics.RectF;
import android.opengl.GLUtils;
/**
* Class implementing actual curl.
*
* @author harism
*/
public class CurlMesh {
private static final boolean DRAW_HELPERS = false;
private static final boolean DRAW_POLYGON_OUTLINES = false;
private static final float[] SHADOW_INNER_COLOR = { 0f, 0f, 0f, .7f };
private static final float[] SHADOW_OUTER_COLOR = { 0f, 0f, 0f, 0f };
private static final double BACKFACE_ALPHA = .4f;
private static final double FRONTFACE_ALPHA = 1f;
private boolean mSwapAlpha = false;
// For testing purposes.
private int mHelperLinesCount;
private FloatBuffer mHelperLines;
// Buffers for feeding rasterizer.
private FloatBuffer mVertices;
private FloatBuffer mTexCoords;
private FloatBuffer mColors;
private int mVerticesCountFront;
private int mVerticesCountBack;
private FloatBuffer mShadowColors;
private FloatBuffer mShadowVertices;
private int mDropShadowCount;
private int mSelfShadowCount;
private int mMaxCurlSplits;
private Vertex[] mRectangle = new Vertex[4];
private int[] mTextureIds;
private Bitmap mBitmap;
/**
* Constructor for mesh object.
*
* @param rect
* Rect for the surface.
* @param texRect
* Texture coordinates.
* @param maxCurlSplits
* Maximum number curl can be divided into.
*/
public CurlMesh(int maxCurlSplits) {
mMaxCurlSplits = maxCurlSplits;
for (int i = 0; i < 4; ++i) {
mRectangle[i] = new Vertex();
}
if (DRAW_HELPERS) {
mHelperLinesCount = 3;
ByteBuffer hvbb = ByteBuffer
.allocateDirect(mHelperLinesCount * 2 * 2 * 4);
hvbb.order(ByteOrder.nativeOrder());
mHelperLines = hvbb.asFloatBuffer();
mHelperLines.position(0);
}
int maxVerticesCount = 4 + 2 * mMaxCurlSplits;
ByteBuffer vbb = ByteBuffer.allocateDirect(maxVerticesCount * 3 * 4);
vbb.order(ByteOrder.nativeOrder());
mVertices = vbb.asFloatBuffer();
mVertices.position(0);
ByteBuffer tbb = ByteBuffer.allocateDirect(maxVerticesCount * 2 * 4);
tbb.order(ByteOrder.nativeOrder());
mTexCoords = tbb.asFloatBuffer();
mTexCoords.position(0);
ByteBuffer cbb = ByteBuffer.allocateDirect(maxVerticesCount * 4 * 4);
cbb.order(ByteOrder.nativeOrder());
mColors = cbb.asFloatBuffer();
mColors.position(0);
int maxShadowVerticesCount = (mMaxCurlSplits + 1) * 2 * 2;
ByteBuffer scbb = ByteBuffer
.allocateDirect(maxShadowVerticesCount * 4 * 4);
scbb.order(ByteOrder.nativeOrder());
mShadowColors = scbb.asFloatBuffer();
mShadowColors.position(0);
ByteBuffer sibb = ByteBuffer
.allocateDirect(maxShadowVerticesCount * 2 * 4);
sibb.order(ByteOrder.nativeOrder());
mShadowVertices = sibb.asFloatBuffer();
mShadowVertices.position(0);
mDropShadowCount = mSelfShadowCount = 0;
}
/**
* Curl calculation.
*
* @param curlPos
* Position for curl center.
* @param directionVec
* Curl direction.
* @param radius
* Radius of curl.
*/
public synchronized void curl(PointF curlPos, PointF directionVec,
double radius) {
// First add some 'helper' lines used for development.
if (DRAW_HELPERS) {
mHelperLines.position(0);
mHelperLines.put(curlPos.x);
mHelperLines.put(curlPos.y - 1.0f);
mHelperLines.put(curlPos.x);
mHelperLines.put(curlPos.y + 1.0f);
mHelperLines.put(curlPos.x - 1.0f);
mHelperLines.put(curlPos.y);
mHelperLines.put(curlPos.x + 1.0f);
mHelperLines.put(curlPos.y);
mHelperLines.put(curlPos.x);
mHelperLines.put(curlPos.y);
mHelperLines.put(curlPos.x + directionVec.x * 2);
mHelperLines.put(curlPos.y + directionVec.y * 2);
mHelperLines.position(0);
}
// Actual 'curl' implementation starts here.
mVertices.position(0);
mTexCoords.position(0);
mColors.position(0);
// Calculate curl direction.
double curlAngle = Math.acos(directionVec.x);
curlAngle = directionVec.y > 0 ? -curlAngle : curlAngle;
// Initiate rotated 'rectangle' which's is translated to curlPos and
// rotated so that curl direction heads to (1,0).
Vector<Vertex> rotatedVertices = new Vector<Vertex>();
for (int i = 0; i < 4; ++i) {
Vertex v = new Vertex(mRectangle[i]);
v.translate(-curlPos.x, -curlPos.y);
v.rotateZ(-curlAngle);
int j = 0;
for (; j < rotatedVertices.size(); ++j) {
Vertex v2 = rotatedVertices.elementAt(j);
// We want to test for equality but rotating messes this unless
// we check against certain error margin instead.
double errormargin = 0.001f;
if (Math.abs(v.mPosX - v2.mPosX) <= errormargin
&& v.mPosY < v2.mPosY) {
break;
}
if (Math.abs(v.mPosX - v2.mPosX) > errormargin
&& v.mPosX > v2.mPosX) {
break;
}
}
rotatedVertices.add(j, v);
}
mVerticesCountFront = mVerticesCountBack = 0;
Vector<ShadowVertex> dropShadowVertices = new Vector<ShadowVertex>();
Vector<ShadowVertex> selfShadowVertices = new Vector<ShadowVertex>();
// Our rectangle lines/vertex indices.
int lines[] = { 0, 1, 2, 0, 3, 1, 3, 2 };
// Length of 'curl' curve.
double curlLength = Math.PI * radius;
// Calculate scan lines.
Vector<Double> scanLines = new Vector<Double>();
if (mMaxCurlSplits > 0) {
scanLines.add((double) 0);
}
for (int i = 1; i < mMaxCurlSplits; ++i) {
scanLines.add((-curlLength * i) / (mMaxCurlSplits - 1));
}
scanLines.add(rotatedVertices.elementAt(3).mPosX - 1);
// Start from right most vertex.
double scanXmax = rotatedVertices.elementAt(0).mPosX + 1;
Vector<Vertex> out = new Vector<Vertex>();
for (int i = 0; i < scanLines.size(); ++i) {
double scanXmin = scanLines.elementAt(i);
// First iterate vertices within scan area.
for (int j = 0; j < rotatedVertices.size(); ++j) {
Vertex v = rotatedVertices.elementAt(j);
if (v.mPosX >= scanXmin && v.mPosX < scanXmax) {
Vertex n = new Vertex(v);
out.add(n);
}
}
// Search for line intersections.
for (int j = 0; j < lines.length; j += 2) {
Vertex v1 = rotatedVertices.elementAt(lines[j]);
Vertex v2 = rotatedVertices.elementAt(lines[j + 1]);
if ((v1.mPosX > scanXmin && v2.mPosX < scanXmin)
|| (v2.mPosX > scanXmin && v1.mPosX < scanXmin)) {
Vertex n = new Vertex(v2);
n.mPosX = scanXmin;
double c = (scanXmin - v2.mPosX) / (v1.mPosX - v2.mPosX);
n.mPosY += (v1.mPosY - v2.mPosY) * c;
n.mTexX += (v1.mTexX - v2.mTexX) * c;
n.mTexY += (v1.mTexY - v2.mTexY) * c;
out.add(n);
}
}
// Add vertices to out buffers.
while (out.size() > 0) {
Vertex v = out.remove(0);
// Untouched vertices.
if (i == 0) {
v.mAlpha = mSwapAlpha ? BACKFACE_ALPHA : FRONTFACE_ALPHA;
mVerticesCountFront++;
}
// 'Completely' rotated vertices.
else if (i == scanLines.size() - 1 || radius == 0) {
v.mPosX = -(curlLength + v.mPosX);
v.mPosZ = 2 * radius;
v.mAlpha = mSwapAlpha ? FRONTFACE_ALPHA : BACKFACE_ALPHA;
mVerticesCountBack++;
}
// Vertex lies within 'curl'.
else {
double rotY = Math.PI / 2;
rotY -= Math.PI * (v.mPosX / curlLength);
// rotY = -rotY;
v.mPosX = radius * Math.cos(rotY);
v.mPosZ = radius + (radius * -Math.sin(rotY));
v.mColor = Math.sqrt(Math.cos(rotY) + 1);
if (v.mPosZ >= radius) {
v.mAlpha = mSwapAlpha ? FRONTFACE_ALPHA
: BACKFACE_ALPHA;
mVerticesCountBack++;
} else {
v.mAlpha = mSwapAlpha ? BACKFACE_ALPHA
: FRONTFACE_ALPHA;
mVerticesCountFront++;
}
}
// Rotate vertex back to 'world' coordinates.
v.rotateZ(curlAngle);
v.translate(curlPos.x, curlPos.y);
addVertex(v);
// Drop shadow is cast 'behind' the curl.
if (v.mPosZ > 0 && v.mPosZ <= radius) {
// TODO: There is some overlapping in some cases, not all
// vertices should be added to shadow.
ShadowVertex sv = new ShadowVertex();
sv.mPosX = v.mPosX;
sv.mPosY = v.mPosY;
sv.mPenumbraX = (v.mPosZ / 4) * -directionVec.x;
sv.mPenumbraY = (v.mPosZ / 4) * -directionVec.y;
int idx = (dropShadowVertices.size() + 1) / 2;
dropShadowVertices.add(idx, sv);
}
// Self shadow is cast partly over mesh.
if (v.mPosZ > radius) {
// TODO: Shadow penumbra direction is not good, shouldn't be
// calculated using only directionVec.
ShadowVertex sv = new ShadowVertex();
sv.mPosX = v.mPosX;
sv.mPosY = v.mPosY;
sv.mPenumbraX = ((v.mPosZ - radius) / 4) * directionVec.x;
sv.mPenumbraY = ((v.mPosZ - radius) / 4) * directionVec.y;
int idx = (selfShadowVertices.size() + 1) / 2;
selfShadowVertices.add(idx, sv);
}
}
scanXmax = scanXmin;
}
mVertices.position(0);
mTexCoords.position(0);
mColors.position(0);
// Add shadow Vertices.
mShadowColors.position(0);
mShadowVertices.position(0);
mDropShadowCount = 0;
for (int i = 0; i < dropShadowVertices.size(); ++i) {
ShadowVertex sv = dropShadowVertices.get(i);
mShadowVertices.put((float) sv.mPosX);
mShadowVertices.put((float) sv.mPosY);
mShadowVertices.put((float) (sv.mPosX + sv.mPenumbraX));
mShadowVertices.put((float) (sv.mPosY + sv.mPenumbraY));
mShadowColors.put(SHADOW_INNER_COLOR);
mShadowColors.put(SHADOW_OUTER_COLOR);
mDropShadowCount += 2;
}
mSelfShadowCount = 0;
for (int i = 0; i < selfShadowVertices.size(); ++i) {
ShadowVertex sv = selfShadowVertices.get(i);
mShadowVertices.put((float) sv.mPosX);
mShadowVertices.put((float) sv.mPosY);
mShadowVertices.put((float) (sv.mPosX + sv.mPenumbraX));
mShadowVertices.put((float) (sv.mPosY + sv.mPenumbraY));
mShadowColors.put(SHADOW_INNER_COLOR);
mShadowColors.put(SHADOW_OUTER_COLOR);
mSelfShadowCount += 2;
}
mShadowColors.position(0);
mShadowVertices.position(0);
}
/**
* Draw our mesh.
*/
public synchronized void draw(GL10 gl) {
// First allocate texture if there is not one yet.
if (mTextureIds == null) {
// Generate texture.
mTextureIds = new int[1];
gl.glGenTextures(1, mTextureIds, 0);
// Set texture attributes.
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_CLAMP_TO_EDGE);
}
// If mBitmap != null we have new texture.
if (mBitmap != null) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, Bitmap
.createScaledBitmap(mBitmap,
getNextHighestPO2(mBitmap.getWidth()),
getNextHighestPO2(mBitmap.getHeight()), true), 0);
mBitmap = null;
}
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]);
// Some 'global' settings.
gl.glEnable(GL10.GL_BLEND);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertices);
// Enable texture coordinates.
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexCoords);
// Enable color array.
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColors);
// Draw blank / 'white' front facing vertices.
gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ZERO);
gl.glDisable(GL10.GL_TEXTURE_2D);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mVerticesCountFront);
// Draw front facing texture.
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mVerticesCountFront);
// Draw blank / 'white' back facing vertices.
gl.glDisable(GL10.GL_TEXTURE_2D);
gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ZERO);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, mVerticesCountFront,
mVerticesCountBack);
// Draw back facing texture.
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, mVerticesCountFront,
mVerticesCountBack);
gl.glDisable(GL10.GL_TEXTURE_2D);
// Disable textures and color array.
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
if (DRAW_POLYGON_OUTLINES || DRAW_HELPERS) {
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glEnable(GL10.GL_LINE_SMOOTH);
gl.glLineWidth(1.0f);
}
if (DRAW_POLYGON_OUTLINES) {
gl.glColor4f(0.5f, 0.5f, 1.0f, 1.0f);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertices);
gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, mVerticesCountFront);
}
if (DRAW_HELPERS) {
gl.glColor4f(1.0f, 0.5f, 0.5f, 1.0f);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, mHelperLines);
gl.glDrawArrays(GL10.GL_LINES, 0, mHelperLinesCount * 2);
}
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL10.GL_FLOAT, 0, mShadowColors);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, mShadowVertices);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mDropShadowCount);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, mDropShadowCount,
mSelfShadowCount);
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
/**
* Resets mesh to 'initial' state.
*/
public synchronized void reset() {
mVertices.position(0);
mTexCoords.position(0);
mColors.position(0);
for (int i = 0; i < 4; ++i) {
addVertex(mRectangle[i]);
}
mVerticesCountFront = 4;
mVerticesCountBack = 0;
mVertices.position(0);
mTexCoords.position(0);
mColors.position(0);
mDropShadowCount = mSelfShadowCount = 0;
}
/**
* Sets new texture for this mesh.
*/
public void setBitmap(Bitmap bitmap) {
mBitmap = bitmap;
}
/**
* Update mesh bounds.
*/
public synchronized void setRect(RectF r) {
mRectangle[0].mPosX = r.left;
mRectangle[0].mPosY = r.top;
mRectangle[1].mPosX = r.left;
mRectangle[1].mPosY = r.bottom;
mRectangle[2].mPosX = r.right;
mRectangle[2].mPosY = r.top;
mRectangle[3].mPosX = r.right;
mRectangle[3].mPosY = r.bottom;
}
/**
* Update texture bounds.
*/
public synchronized void setTexRect(RectF r) {
mRectangle[0].mTexX = r.left;
mRectangle[0].mTexY = r.top;
mRectangle[1].mTexX = r.left;
mRectangle[1].mTexY = r.bottom;
mRectangle[2].mTexX = r.right;
mRectangle[2].mTexY = r.top;
mRectangle[3].mTexX = r.right;
mRectangle[3].mTexY = r.bottom;
mSwapAlpha = r.left > r.right;
for (int i = 0; i < 4; ++i) {
mRectangle[i].mAlpha = mSwapAlpha ? BACKFACE_ALPHA
: FRONTFACE_ALPHA;
}
}
/**
* Adds vertex to buffers.
*/
private void addVertex(Vertex vertex) {
mVertices.put((float) vertex.mPosX);
mVertices.put((float) vertex.mPosY);
mVertices.put((float) vertex.mPosZ);
mTexCoords.put((float) vertex.mTexX);
mTexCoords.put((float) vertex.mTexY);
mColors.put((float) vertex.mColor);
mColors.put((float) vertex.mColor);
mColors.put((float) vertex.mColor);
mColors.put((float) vertex.mAlpha);
}
/**
* Calculates the next highest power of two for a given integer.
*
* @param n
* the number
* @return a power of two equal to or higher than n
*/
private int getNextHighestPO2(int n) {
n -= 1;
n = n | (n >> 1);
n = n | (n >> 2);
n = n | (n >> 4);
n = n | (n >> 8);
n = n | (n >> 16);
n = n | (n >> 32);
return n + 1;
}
/**
* Holder for shadow vertex information.
*/
private class ShadowVertex {
public double mPosX;
public double mPosY;
public double mPenumbraX;
public double mPenumbraY;
}
/**
* Holder for vertex information.
*/
private class Vertex {
public double mPosX;
public double mPosY;
public double mPosZ;
public double mTexX;
public double mTexY;
public double mColor;
public double mAlpha;
public Vertex() {
mPosX = mPosY = mPosZ = mTexX = mTexY = 0;
mColor = mAlpha = 1;
}
public Vertex(Vertex vertex) {
mPosX = vertex.mPosX;
mPosY = vertex.mPosY;
mPosZ = vertex.mPosZ;
mTexX = vertex.mTexX;
mTexY = vertex.mTexY;
mColor = vertex.mColor;
mAlpha = vertex.mAlpha;
}
public void rotateZ(double theta) {
double cos = Math.cos(theta);
double sin = Math.sin(theta);
double x = mPosX * cos + mPosY * sin;
double y = mPosX * -sin + mPosY * cos;
mPosX = x;
mPosY = y;
}
public void translate(double dx, double dy) {
mPosX += dx;
mPosY += dy;
}
}
}
| src/fi/harism/curl/CurlMesh.java | package fi.harism.curl;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.Vector;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.graphics.RectF;
import android.opengl.GLUtils;
/**
* Class implementing actual curl.
*
* @author harism
*/
public class CurlMesh {
private static final boolean DRAW_HELPERS = false;
private static final boolean DRAW_POLYGON_OUTLINES = false;
private static final float[] SHADOW_INNER_COLOR = { 0f, 0f, 0f, .7f };
private static final float[] SHADOW_OUTER_COLOR = { 0f, 0f, 0f, 0f };
private static final double BACKFACE_ALPHA = .4f;
private static final double FRONTFACE_ALPHA = 1f;
private boolean mSwapAlpha = false;
// For testing purposes.
private int mHelperLinesCount;
private FloatBuffer mHelperLines;
// Buffers for feeding rasterizer.
private FloatBuffer mVertices;
private FloatBuffer mTexCoords;
private FloatBuffer mColors;
private int mVerticesCountFront;
private int mVerticesCountBack;
private FloatBuffer mShadowColors;
private FloatBuffer mShadowVertices;
private int mDropShadowCount;
private int mSelfShadowCount;
private int mMaxCurlSplits;
private Vertex[] mRectangle = new Vertex[4];
private int[] mTextureIds;
private Bitmap mBitmap;
/**
* Constructor for mesh object.
*
* @param rect
* Rect for the surface.
* @param texRect
* Texture coordinates.
* @param maxCurlSplits
* Maximum number curl can be divided into.
*/
public CurlMesh(int maxCurlSplits) {
mMaxCurlSplits = maxCurlSplits;
for (int i = 0; i < 4; ++i) {
mRectangle[i] = new Vertex();
}
if (DRAW_HELPERS) {
mHelperLinesCount = 3;
ByteBuffer hvbb = ByteBuffer
.allocateDirect(mHelperLinesCount * 2 * 2 * 4);
hvbb.order(ByteOrder.nativeOrder());
mHelperLines = hvbb.asFloatBuffer();
mHelperLines.position(0);
}
int maxVerticesCount = 4 + 2 * mMaxCurlSplits;
ByteBuffer vbb = ByteBuffer.allocateDirect(maxVerticesCount * 3 * 4);
vbb.order(ByteOrder.nativeOrder());
mVertices = vbb.asFloatBuffer();
mVertices.position(0);
ByteBuffer tbb = ByteBuffer.allocateDirect(maxVerticesCount * 2 * 4);
tbb.order(ByteOrder.nativeOrder());
mTexCoords = tbb.asFloatBuffer();
mTexCoords.position(0);
ByteBuffer cbb = ByteBuffer.allocateDirect(maxVerticesCount * 4 * 4);
cbb.order(ByteOrder.nativeOrder());
mColors = cbb.asFloatBuffer();
mColors.position(0);
int maxShadowVerticesCount = (mMaxCurlSplits + 1) * 2 * 2;
ByteBuffer scbb = ByteBuffer
.allocateDirect(maxShadowVerticesCount * 4 * 4);
scbb.order(ByteOrder.nativeOrder());
mShadowColors = scbb.asFloatBuffer();
mShadowColors.position(0);
ByteBuffer sibb = ByteBuffer
.allocateDirect(maxShadowVerticesCount * 2 * 4);
sibb.order(ByteOrder.nativeOrder());
mShadowVertices = sibb.asFloatBuffer();
mShadowVertices.position(0);
mDropShadowCount = mSelfShadowCount = 0;
}
/**
* Curl calculation.
*
* @param curlPos
* Position for curl center.
* @param directionVec
* Curl direction.
* @param radius
* Radius of curl.
*/
public synchronized void curl(PointF curlPos, PointF directionVec,
double radius) {
// First add some 'helper' lines used for development.
if (DRAW_HELPERS) {
mHelperLines.position(0);
mHelperLines.put(curlPos.x);
mHelperLines.put(curlPos.y - 1.0f);
mHelperLines.put(curlPos.x);
mHelperLines.put(curlPos.y + 1.0f);
mHelperLines.put(curlPos.x - 1.0f);
mHelperLines.put(curlPos.y);
mHelperLines.put(curlPos.x + 1.0f);
mHelperLines.put(curlPos.y);
mHelperLines.put(curlPos.x);
mHelperLines.put(curlPos.y);
mHelperLines.put(curlPos.x + directionVec.x * 2);
mHelperLines.put(curlPos.y + directionVec.y * 2);
mHelperLines.position(0);
}
// Actual 'curl' implementation starts here.
mVertices.position(0);
mTexCoords.position(0);
mColors.position(0);
// Calculate curl direction.
double curlAngle = Math.acos(directionVec.x);
curlAngle = directionVec.y > 0 ? -curlAngle : curlAngle;
// Initiate rotated 'rectangle' which's is translated to curlPos and
// rotated so that curl direction heads to (1,0).
Vector<Vertex> rotatedVertices = new Vector<Vertex>();
for (int i = 0; i < 4; ++i) {
Vertex v = new Vertex(mRectangle[i]);
v.translate(-curlPos.x, -curlPos.y);
v.rotateZ(-curlAngle);
int j = 0;
for (; j < rotatedVertices.size(); ++j) {
Vertex v2 = rotatedVertices.elementAt(j);
// We want to test for equality but rotating messes this unless
// we check against certain error margin instead.
double errormargin = 0.001f;
if (Math.abs(v.mPosX - v2.mPosX) <= errormargin
&& v.mPosY < v2.mPosY) {
break;
}
if (Math.abs(v.mPosX - v2.mPosX) > errormargin
&& v.mPosX > v2.mPosX) {
break;
}
}
rotatedVertices.add(j, v);
}
mVerticesCountFront = mVerticesCountBack = 0;
Vector<ShadowVertex> dropShadowVertices = new Vector<ShadowVertex>();
Vector<ShadowVertex> selfShadowVertices = new Vector<ShadowVertex>();
// Our rectangle lines/vertex indices.
int lines[] = { 0, 1, 2, 0, 3, 1, 3, 2 };
// Length of 'curl' curve.
double curlLength = Math.PI * radius;
// Calculate scan lines.
Vector<Double> scanLines = new Vector<Double>();
if (mMaxCurlSplits > 0) {
scanLines.add((double) 0);
}
for (int i = 1; i < mMaxCurlSplits; ++i) {
scanLines.add((-curlLength * i) / (mMaxCurlSplits - 1));
}
scanLines.add(rotatedVertices.elementAt(3).mPosX - 1);
// Start from right most vertex.
double scanXmax = rotatedVertices.elementAt(0).mPosX + 1;
Vector<Vertex> out = new Vector<Vertex>();
for (int i = 0; i < scanLines.size(); ++i) {
double scanXmin = scanLines.elementAt(i);
// First iterate vertices within scan area.
for (int j = 0; j < rotatedVertices.size(); ++j) {
Vertex v = rotatedVertices.elementAt(j);
if (v.mPosX >= scanXmin && v.mPosX < scanXmax) {
Vertex n = new Vertex(v);
out.add(n);
}
}
// Search for line intersections.
for (int j = 0; j < lines.length; j += 2) {
Vertex v1 = rotatedVertices.elementAt(lines[j]);
Vertex v2 = rotatedVertices.elementAt(lines[j + 1]);
if ((v1.mPosX > scanXmin && v2.mPosX < scanXmin)
|| (v2.mPosX > scanXmin && v1.mPosX < scanXmin)) {
Vertex n = new Vertex(v2);
n.mPosX = scanXmin;
double c = (scanXmin - v2.mPosX) / (v1.mPosX - v2.mPosX);
n.mPosY += (v1.mPosY - v2.mPosY) * c;
n.mTexX += (v1.mTexX - v2.mTexX) * c;
n.mTexY += (v1.mTexY - v2.mTexY) * c;
out.add(n);
}
}
// Add vertices to out buffers.
while (out.size() > 0) {
Vertex v = out.remove(0);
// Untouched vertices.
if (i == 0) {
v.mAlpha = mSwapAlpha ? BACKFACE_ALPHA : FRONTFACE_ALPHA;
mVerticesCountFront++;
}
// 'Completely' rotated vertices.
else if (i == scanLines.size() - 1 || radius == 0) {
v.mPosX = -(curlLength + v.mPosX);
v.mPosZ = 2 * radius;
v.mAlpha = mSwapAlpha ? FRONTFACE_ALPHA : BACKFACE_ALPHA;
mVerticesCountBack++;
}
// Vertex lies within 'curl'.
else {
double rotY = Math.PI / 2;
rotY -= Math.PI * (v.mPosX / curlLength);
// rotY = -rotY;
v.mPosX = radius * Math.cos(rotY);
v.mPosZ = radius + (radius * -Math.sin(rotY));
v.mColor = Math.sqrt(Math.cos(rotY) + 1);
if (v.mPosZ >= radius) {
v.mAlpha = mSwapAlpha ? FRONTFACE_ALPHA
: BACKFACE_ALPHA;
mVerticesCountBack++;
} else {
v.mAlpha = mSwapAlpha ? BACKFACE_ALPHA
: FRONTFACE_ALPHA;
mVerticesCountFront++;
}
}
// Rotate vertex back to 'world' coordinates.
v.rotateZ(curlAngle);
v.translate(curlPos.x, curlPos.y);
addVertex(v);
// Drop shadow is cast 'behind' the curl.
if (v.mPosZ > 0 && v.mPosZ <= radius) {
// TODO: There is some overlapping in some cases, not all
// vertices should be added to shadow.
ShadowVertex sv = new ShadowVertex();
sv.mPosX = v.mPosX;
sv.mPosY = v.mPosY;
sv.mPenumbraX = (v.mPosZ / 4) * -directionVec.x;
sv.mPenumbraY = (v.mPosZ / 4) * -directionVec.y;
int idx = (dropShadowVertices.size() + 1) / 2;
dropShadowVertices.add(idx, sv);
}
// Self shadow is cast partly over mesh.
if (v.mPosZ > radius) {
// TODO: Shadow penumbra direction is not good, shouldn't be
// calculated using only directionVec.
ShadowVertex sv = new ShadowVertex();
sv.mPosX = v.mPosX;
sv.mPosY = v.mPosY;
sv.mPenumbraX = ((v.mPosZ - radius) / 4) * directionVec.x;
sv.mPenumbraY = ((v.mPosZ - radius) / 4) * directionVec.y;
int idx = (selfShadowVertices.size() + 1) / 2;
selfShadowVertices.add(idx, sv);
}
}
scanXmax = scanXmin;
}
mVertices.position(0);
mTexCoords.position(0);
mColors.position(0);
// Add shadow Vertices.
mShadowColors.position(0);
mShadowVertices.position(0);
mDropShadowCount = 0;
for (int i = 0; i < dropShadowVertices.size(); ++i) {
ShadowVertex sv = dropShadowVertices.get(i);
mShadowVertices.put((float) sv.mPosX);
mShadowVertices.put((float) sv.mPosY);
mShadowVertices.put((float) (sv.mPosX + sv.mPenumbraX));
mShadowVertices.put((float) (sv.mPosY + sv.mPenumbraY));
mShadowColors.put(SHADOW_INNER_COLOR);
mShadowColors.put(SHADOW_OUTER_COLOR);
mDropShadowCount += 2;
}
mSelfShadowCount = 0;
for (int i = 0; i < selfShadowVertices.size(); ++i) {
ShadowVertex sv = selfShadowVertices.get(i);
mShadowVertices.put((float) sv.mPosX);
mShadowVertices.put((float) sv.mPosY);
mShadowVertices.put((float) (sv.mPosX + sv.mPenumbraX));
mShadowVertices.put((float) (sv.mPosY + sv.mPenumbraY));
mShadowColors.put(SHADOW_INNER_COLOR);
mShadowColors.put(SHADOW_OUTER_COLOR);
mSelfShadowCount += 2;
}
mShadowColors.position(0);
mShadowVertices.position(0);
}
/**
* Draw our mesh.
*/
public synchronized void draw(GL10 gl) {
// First allocate texture if there is not one yet.
if (mTextureIds == null) {
// Generate texture.
mTextureIds = new int[1];
gl.glGenTextures(1, mTextureIds, 0);
// Set texture attributes.
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_CLAMP_TO_EDGE);
}
// If mBitmap != null we have new texture.
if (mBitmap != null) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmap, 0);
mBitmap = null;
}
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]);
// Some 'global' settings.
gl.glEnable(GL10.GL_BLEND);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertices);
// Enable texture coordinates.
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexCoords);
// Enable color array.
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColors);
// Draw blank / 'white' front facing vertices.
gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ZERO);
gl.glDisable(GL10.GL_TEXTURE_2D);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mVerticesCountFront);
// Draw front facing texture.
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mVerticesCountFront);
// Draw blank / 'white' back facing vertices.
gl.glDisable(GL10.GL_TEXTURE_2D);
gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ZERO);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, mVerticesCountFront,
mVerticesCountBack);
// Draw back facing texture.
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, mVerticesCountFront,
mVerticesCountBack);
gl.glDisable(GL10.GL_TEXTURE_2D);
// Disable textures and color array.
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
if (DRAW_POLYGON_OUTLINES || DRAW_HELPERS) {
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glEnable(GL10.GL_LINE_SMOOTH);
gl.glLineWidth(1.0f);
}
if (DRAW_POLYGON_OUTLINES) {
gl.glColor4f(0.5f, 0.5f, 1.0f, 1.0f);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertices);
gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, mVerticesCountFront);
}
if (DRAW_HELPERS) {
gl.glColor4f(1.0f, 0.5f, 0.5f, 1.0f);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, mHelperLines);
gl.glDrawArrays(GL10.GL_LINES, 0, mHelperLinesCount * 2);
}
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL10.GL_FLOAT, 0, mShadowColors);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, mShadowVertices);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mDropShadowCount);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, mDropShadowCount,
mSelfShadowCount);
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
/**
* Resets mesh to 'initial' state.
*/
public synchronized void reset() {
mVertices.position(0);
mTexCoords.position(0);
mColors.position(0);
for (int i = 0; i < 4; ++i) {
addVertex(mRectangle[i]);
}
mVerticesCountFront = 4;
mVerticesCountBack = 0;
mVertices.position(0);
mTexCoords.position(0);
mColors.position(0);
mDropShadowCount = mSelfShadowCount = 0;
}
/**
* Sets new texture for this mesh.
*/
public void setBitmap(Bitmap bitmap) {
mBitmap = bitmap;
}
/**
* Update mesh bounds.
*/
public synchronized void setRect(RectF r) {
mRectangle[0].mPosX = r.left;
mRectangle[0].mPosY = r.top;
mRectangle[1].mPosX = r.left;
mRectangle[1].mPosY = r.bottom;
mRectangle[2].mPosX = r.right;
mRectangle[2].mPosY = r.top;
mRectangle[3].mPosX = r.right;
mRectangle[3].mPosY = r.bottom;
}
/**
* Update texture bounds.
*/
public synchronized void setTexRect(RectF r) {
mRectangle[0].mTexX = r.left;
mRectangle[0].mTexY = r.top;
mRectangle[1].mTexX = r.left;
mRectangle[1].mTexY = r.bottom;
mRectangle[2].mTexX = r.right;
mRectangle[2].mTexY = r.top;
mRectangle[3].mTexX = r.right;
mRectangle[3].mTexY = r.bottom;
mSwapAlpha = r.left > r.right;
for (int i = 0; i < 4; ++i) {
mRectangle[i].mAlpha = mSwapAlpha ? BACKFACE_ALPHA
: FRONTFACE_ALPHA;
}
}
/**
* Adds vertex to buffers.
*/
private void addVertex(Vertex vertex) {
mVertices.put((float) vertex.mPosX);
mVertices.put((float) vertex.mPosY);
mVertices.put((float) vertex.mPosZ);
mTexCoords.put((float) vertex.mTexX);
mTexCoords.put((float) vertex.mTexY);
mColors.put((float) vertex.mColor);
mColors.put((float) vertex.mColor);
mColors.put((float) vertex.mColor);
mColors.put((float) vertex.mAlpha);
}
/**
* Holder for shadow vertex information.
*/
private class ShadowVertex {
public double mPosX;
public double mPosY;
public double mPenumbraX;
public double mPenumbraY;
}
/**
* Holder for vertex information.
*/
private class Vertex {
public double mPosX;
public double mPosY;
public double mPosZ;
public double mTexX;
public double mTexY;
public double mColor;
public double mAlpha;
public Vertex() {
mPosX = mPosY = mPosZ = mTexX = mTexY = 0;
mColor = mAlpha = 1;
}
public Vertex(Vertex vertex) {
mPosX = vertex.mPosX;
mPosY = vertex.mPosY;
mPosZ = vertex.mPosZ;
mTexX = vertex.mTexX;
mTexY = vertex.mTexY;
mColor = vertex.mColor;
mAlpha = vertex.mAlpha;
}
public void rotateZ(double theta) {
double cos = Math.cos(theta);
double sin = Math.sin(theta);
double x = mPosX * cos + mPosY * sin;
double y = mPosX * -sin + mPosY * cos;
mPosX = x;
mPosY = y;
}
public void translate(double dx, double dy) {
mPosX += dx;
mPosY += dy;
}
}
}
| Bitmap is scaled up to nearest power of 2 before setting it as
a texture. | src/fi/harism/curl/CurlMesh.java | Bitmap is scaled up to nearest power of 2 before setting it as a texture. | <ide><path>rc/fi/harism/curl/CurlMesh.java
<ide> // If mBitmap != null we have new texture.
<ide> if (mBitmap != null) {
<ide> gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]);
<del> GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmap, 0);
<add> GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, Bitmap
<add> .createScaledBitmap(mBitmap,
<add> getNextHighestPO2(mBitmap.getWidth()),
<add> getNextHighestPO2(mBitmap.getHeight()), true), 0);
<ide> mBitmap = null;
<ide> }
<ide>
<ide> }
<ide>
<ide> /**
<add> * Calculates the next highest power of two for a given integer.
<add> *
<add> * @param n
<add> * the number
<add> * @return a power of two equal to or higher than n
<add> */
<add> private int getNextHighestPO2(int n) {
<add> n -= 1;
<add> n = n | (n >> 1);
<add> n = n | (n >> 2);
<add> n = n | (n >> 4);
<add> n = n | (n >> 8);
<add> n = n | (n >> 16);
<add> n = n | (n >> 32);
<add> return n + 1;
<add> }
<add>
<add> /**
<ide> * Holder for shadow vertex information.
<ide> */
<ide> private class ShadowVertex { |
|
Java | apache-2.0 | 07dda233ec91d50aeff374cb978e0821d86136a9 | 0 | awhitford/DependencyCheck,stevespringett/DependencyCheck,hansjoachim/DependencyCheck,dwvisser/DependencyCheck,stevespringett/DependencyCheck,adilakhter/DependencyCheck,awhitford/DependencyCheck,awhitford/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,recena/DependencyCheck,dwvisser/DependencyCheck,jeremylong/DependencyCheck,hansjoachim/DependencyCheck,jeremylong/DependencyCheck,awhitford/DependencyCheck,adilakhter/DependencyCheck,stevespringett/DependencyCheck,recena/DependencyCheck,recena/DependencyCheck,adilakhter/DependencyCheck,dwvisser/DependencyCheck,awhitford/DependencyCheck,colezlaw/DependencyCheck,recena/DependencyCheck,wmaintw/DependencyCheck,stefanneuhaus/DependencyCheck,hansjoachim/DependencyCheck,dwvisser/DependencyCheck,hansjoachim/DependencyCheck,wmaintw/DependencyCheck,wmaintw/DependencyCheck,jeremylong/DependencyCheck,colezlaw/DependencyCheck,adilakhter/DependencyCheck,stefanneuhaus/DependencyCheck,colezlaw/DependencyCheck,adilakhter/DependencyCheck,stevespringett/DependencyCheck,adilakhter/DependencyCheck,hansjoachim/DependencyCheck,jeremylong/DependencyCheck,colezlaw/DependencyCheck,dwvisser/DependencyCheck,colezlaw/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,wmaintw/DependencyCheck,stefanneuhaus/DependencyCheck,stevespringett/DependencyCheck,wmaintw/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,awhitford/DependencyCheck,awhitford/DependencyCheck,hansjoachim/DependencyCheck,hansjoachim/DependencyCheck,recena/DependencyCheck,colezlaw/DependencyCheck,colezlaw/DependencyCheck,stefanneuhaus/DependencyCheck,dwvisser/DependencyCheck,recena/DependencyCheck,jeremylong/DependencyCheck,wmaintw/DependencyCheck,awhitford/DependencyCheck,stefanneuhaus/DependencyCheck,stevespringett/DependencyCheck,stevespringett/DependencyCheck | /*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2012 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.analyzer;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import org.jsoup.Jsoup;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.dependency.Confidence;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.EvidenceCollection;
import org.owasp.dependencycheck.xml.pom.License;
import org.owasp.dependencycheck.xml.pom.PomUtils;
import org.owasp.dependencycheck.xml.pom.Model;
import org.owasp.dependencycheck.utils.FileUtils;
import org.owasp.dependencycheck.utils.Settings;
/**
* Used to load a JAR file and collect information that can be used to determine the associated CPE.
*
* @author Jeremy Long
*/
public class JarAnalyzer extends AbstractFileTypeAnalyzer {
//<editor-fold defaultstate="collapsed" desc="Constants and Member Variables">
/**
* The logger.
*/
private static final Logger LOGGER = Logger.getLogger(JarAnalyzer.class.getName());
/**
* The buffer size to use when extracting files from the archive.
*/
private static final int BUFFER_SIZE = 4096;
/**
* The count of directories created during analysis. This is used for creating temporary directories.
*/
private static int dirCount = 0;
/**
* The system independent newline character.
*/
private static final String NEWLINE = System.getProperty("line.separator");
/**
* A list of values in the manifest to ignore as they only result in false positives.
*/
private static final Set<String> IGNORE_VALUES = newHashSet(
"Sun Java System Application Server");
/**
* A list of elements in the manifest to ignore.
*/
private static final Set<String> IGNORE_KEYS = newHashSet(
"built-by",
"created-by",
"builtby",
"createdby",
"build-jdk",
"buildjdk",
"ant-version",
"antversion",
"dynamicimportpackage",
"dynamicimport-package",
"dynamic-importpackage",
"dynamic-import-package",
"import-package",
"ignore-package",
"export-package",
"importpackage",
"ignorepackage",
"exportpackage",
"sealed",
"manifest-version",
"archiver-version",
"manifestversion",
"archiverversion",
"classpath",
"class-path",
"tool",
"bundle-manifestversion",
"bundlemanifestversion",
"bundle-vendor",
"include-resource",
"embed-dependency",
"ipojo-components",
"ipojo-extension",
"eclipse-sourcereferences");
/**
* item in some manifest, should be considered medium confidence.
*/
private static final String BUNDLE_VERSION = "Bundle-Version"; //: 2.1.2
/**
* item in some manifest, should be considered medium confidence.
*/
private static final String BUNDLE_DESCRIPTION = "Bundle-Description"; //: Apache Struts 2
/**
* item in some manifest, should be considered medium confidence.
*/
private static final String BUNDLE_NAME = "Bundle-Name"; //: Struts 2 Core
/**
* item in some manifest, should be considered medium confidence.
*/
private static final String BUNDLE_VENDOR = "Bundle-Vendor"; //: Apache Software Foundation
/**
* A pattern to detect HTML within text.
*/
private static final Pattern HTML_DETECTION_PATTERN = Pattern.compile("\\<[a-z]+.*/?\\>", Pattern.CASE_INSENSITIVE);
//</editor-fold>
/**
* Constructs a new JarAnalyzer.
*/
public JarAnalyzer() {
}
//<editor-fold defaultstate="collapsed" desc="All standard implmentation details of Analyzer">
/**
* The name of the analyzer.
*/
private static final String ANALYZER_NAME = "Jar Analyzer";
/**
* The phase that this analyzer is intended to run in.
*/
private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.INFORMATION_COLLECTION;
/**
* The set of file extensions supported by this analyzer.
*/
private static final Set<String> EXTENSIONS = newHashSet("jar", "war");
/**
* Returns a list of file EXTENSIONS supported by this analyzer.
*
* @return a list of file EXTENSIONS supported by this analyzer.
*/
@Override
public Set<String> getSupportedExtensions() {
return EXTENSIONS;
}
/**
* Returns the name of the analyzer.
*
* @return the name of the analyzer.
*/
@Override
public String getName() {
return ANALYZER_NAME;
}
/**
* Returns the phase that the analyzer is intended to run in.
*
* @return the phase that the analyzer is intended to run in.
*/
public AnalysisPhase getAnalysisPhase() {
return ANALYSIS_PHASE;
}
//</editor-fold>
/**
* Returns the key used in the properties file to reference the analyzer's enabled property.
*
* @return the analyzer's enabled property setting key
*/
@Override
protected String getAnalyzerEnabledSettingKey() {
return Settings.KEYS.ANALYZER_JAR_ENABLED;
}
/**
* Loads a specified JAR file and collects information from the manifest and checksums to identify the correct CPE
* information.
*
* @param dependency the dependency to analyze.
* @param engine the engine that is scanning the dependencies
* @throws AnalysisException is thrown if there is an error reading the JAR file.
*/
@Override
public void analyzeFileType(Dependency dependency, Engine engine) throws AnalysisException {
try {
final List<ClassNameInformation> classNames = collectClassNames(dependency);
final String fileName = dependency.getFileName().toLowerCase();
if (classNames.isEmpty()
&& (fileName.endsWith("-sources.jar")
|| fileName.endsWith("-javadoc.jar")
|| fileName.endsWith("-src.jar")
|| fileName.endsWith("-doc.jar"))) {
engine.getDependencies().remove(dependency);
}
final boolean hasManifest = parseManifest(dependency, classNames);
final boolean hasPOM = analyzePOM(dependency, classNames, engine);
final boolean addPackagesAsEvidence = !(hasManifest && hasPOM);
analyzePackageNames(classNames, dependency, addPackagesAsEvidence);
} catch (IOException ex) {
throw new AnalysisException("Exception occurred reading the JAR file.", ex);
}
}
/**
* Attempts to find a pom.xml within the JAR file. If found it extracts information and adds it to the evidence. This will
* attempt to interpolate the strings contained within the pom.properties if one exists.
*
* @param dependency the dependency being analyzed
* @param classes a collection of class name information
* @param engine the analysis engine, used to add additional dependencies
* @throws AnalysisException is thrown if there is an exception parsing the pom
* @return whether or not evidence was added to the dependency
*/
protected boolean analyzePOM(Dependency dependency, List<ClassNameInformation> classes, Engine engine) throws AnalysisException {
boolean foundSomething = false;
final JarFile jar;
try {
jar = new JarFile(dependency.getActualFilePath());
} catch (IOException ex) {
final String msg = String.format("Unable to read JarFile '%s'.", dependency.getActualFilePath());
//final AnalysisException ax = new AnalysisException(msg, ex);
LOGGER.log(Level.WARNING, msg);
LOGGER.log(Level.FINE, "", ex);
return false;
}
List<String> pomEntries;
try {
pomEntries = retrievePomListing(jar);
} catch (IOException ex) {
final String msg = String.format("Unable to read Jar file entries in '%s'.", dependency.getActualFilePath());
//final AnalysisException ax = new AnalysisException(msg, ex);
LOGGER.log(Level.WARNING, msg);
LOGGER.log(Level.FINE, msg, ex);
return false;
}
File externalPom = null;
if (pomEntries.isEmpty()) {
String pomPath = dependency.getActualFilePath();
pomPath = pomPath.substring(0, pomPath.lastIndexOf('.')) + ".pom";
externalPom = new File(pomPath);
if (externalPom.isFile()) {
pomEntries.add(pomPath);
} else {
return false;
}
}
for (String path : pomEntries) {
LOGGER.fine(String.format("Reading pom entry: %s", path));
Properties pomProperties = null;
try {
if (externalPom == null) {
pomProperties = retrievePomProperties(path, jar);
}
} catch (IOException ex) {
LOGGER.log(Level.FINEST, "ignore this, failed reading a non-existent pom.properties", ex);
}
Model pom = null;
try {
if (pomEntries.size() > 1) {
//extract POM to its own directory and add it as its own dependency
final Dependency newDependency = new Dependency();
pom = extractPom(path, jar, newDependency);
final String displayPath = String.format("%s%s%s",
dependency.getFilePath(),
File.separator,
path);
final String displayName = String.format("%s%s%s",
dependency.getFileName(),
File.separator,
path);
newDependency.setFileName(displayName);
newDependency.setFilePath(displayPath);
pom.processProperties(pomProperties);
setPomEvidence(newDependency, pom, null);
engine.getDependencies().add(newDependency);
Collections.sort(engine.getDependencies());
} else {
if (externalPom == null) {
pom = PomUtils.readPom(path, jar);
} else {
pom = PomUtils.readPom(externalPom);
}
pom.processProperties(pomProperties);
foundSomething |= setPomEvidence(dependency, pom, classes);
}
} catch (AnalysisException ex) {
final String msg = String.format("An error occured while analyzing '%s'.", dependency.getActualFilePath());
LOGGER.log(Level.WARNING, msg);
LOGGER.log(Level.FINE, "", ex);
}
}
return foundSomething;
}
/**
* Given a path to a pom.xml within a JarFile, this method attempts to load a sibling pom.properties if one exists.
*
* @param path the path to the pom.xml within the JarFile
* @param jar the JarFile to load the pom.properties from
* @return a Properties object or null if no pom.properties was found
* @throws IOException thrown if there is an exception reading the pom.properties
*/
private Properties retrievePomProperties(String path, final JarFile jar) throws IOException {
Properties pomProperties = null;
final String propPath = path.substring(0, path.length() - 7) + "pom.properies";
final ZipEntry propEntry = jar.getEntry(propPath);
if (propEntry != null) {
Reader reader = null;
try {
reader = new InputStreamReader(jar.getInputStream(propEntry), "UTF-8");
pomProperties = new Properties();
pomProperties.load(reader);
LOGGER.fine(String.format("Read pom.properties: %s", propPath));
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
LOGGER.log(Level.FINEST, "close error", ex);
}
}
}
}
return pomProperties;
}
/**
* Searches a JarFile for pom.xml entries and returns a listing of these entries.
*
* @param jar the JarFile to search
* @return a list of pom.xml entries
* @throws IOException thrown if there is an exception reading a JarEntry
*/
private List<String> retrievePomListing(final JarFile jar) throws IOException {
final List<String> pomEntries = new ArrayList<String>();
final Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
final String entryName = (new File(entry.getName())).getName().toLowerCase();
if (!entry.isDirectory() && "pom.xml".equals(entryName)) {
LOGGER.fine(String.format("POM Entry found: %s", entry.getName()));
pomEntries.add(entry.getName());
}
}
return pomEntries;
}
/**
* Retrieves the specified POM from a jar file and converts it to a Model.
*
* @param path the path to the pom.xml file within the jar file
* @param jar the jar file to extract the pom from
* @param dependency the dependency being analyzed
* @return returns the POM object
* @throws AnalysisException is thrown if there is an exception extracting or parsing the POM
* {@link org.owasp.dependencycheck.jaxb.pom.generated.Model} object
*/
private Model extractPom(String path, JarFile jar, Dependency dependency) throws AnalysisException {
InputStream input = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
final File tmpDir = getNextTempDirectory();
final File file = new File(tmpDir, "pom.xml");
try {
final ZipEntry entry = jar.getEntry(path);
input = jar.getInputStream(entry);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, BUFFER_SIZE);
int count;
final byte[] data = new byte[BUFFER_SIZE];
while ((count = input.read(data, 0, BUFFER_SIZE)) != -1) {
bos.write(data, 0, count);
}
bos.flush();
dependency.setActualFilePath(file.getAbsolutePath());
} catch (IOException ex) {
final String msg = String.format("An error occurred reading '%s' from '%s'.", path, dependency.getFilePath());
LOGGER.warning(msg);
LOGGER.log(Level.SEVERE, "", ex);
} finally {
closeStream(bos);
closeStream(fos);
closeStream(input);
}
return PomUtils.readPom(file);
}
/**
* Silently closes an input stream ignoring errors.
*
* @param stream an input stream to close
*/
private void closeStream(InputStream stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex);
}
}
}
/**
* Silently closes an output stream ignoring errors.
*
* @param stream an output stream to close
*/
private void closeStream(OutputStream stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex);
}
}
}
/**
* Sets evidence from the pom on the supplied dependency.
*
* @param dependency the dependency to set data on
* @param pom the information from the pom
* @param classes a collection of ClassNameInformation - containing data about the fully qualified class names within the JAR
* file being analyzed
* @return true if there was evidence within the pom that we could use; otherwise false
*/
public static boolean setPomEvidence(Dependency dependency, Model pom, List<ClassNameInformation> classes) {
boolean foundSomething = false;
boolean addAsIdentifier = true;
if (pom == null) {
return foundSomething;
}
String groupid = pom.getGroupId();
String parentGroupId = pom.getParentGroupId();
String artifactid = pom.getArtifactId();
String parentArtifactId = pom.getParentArtifactId();
String version = pom.getVersion();
String parentVersion = pom.getParentVersion();
if ("org.sonatype.oss".equals(parentGroupId) && "oss-parent".equals(parentArtifactId)) {
parentGroupId = null;
parentArtifactId = null;
parentVersion = null;
}
if ((groupid == null || groupid.isEmpty()) && parentGroupId != null && !parentGroupId.isEmpty()) {
groupid = parentGroupId;
}
final String originalGroupID = groupid;
if (groupid.startsWith("org.") || groupid.startsWith("com.")) {
groupid = groupid.substring(4);
}
if ((artifactid == null || artifactid.isEmpty()) && parentArtifactId != null && !parentArtifactId.isEmpty()) {
artifactid = parentArtifactId;
}
final String originalArtifactID = artifactid;
if (artifactid.startsWith("org.") || artifactid.startsWith("com.")) {
artifactid = artifactid.substring(4);
}
if ((version == null || version.isEmpty()) && parentVersion != null && !parentVersion.isEmpty()) {
version = parentVersion;
}
if (groupid != null && !groupid.isEmpty()) {
foundSomething = true;
dependency.getVendorEvidence().addEvidence("pom", "groupid", groupid, Confidence.HIGHEST);
dependency.getProductEvidence().addEvidence("pom", "groupid", groupid, Confidence.LOW);
addMatchingValues(classes, groupid, dependency.getVendorEvidence());
addMatchingValues(classes, groupid, dependency.getProductEvidence());
if (parentGroupId != null && !parentGroupId.isEmpty() && !parentGroupId.equals(groupid)) {
dependency.getVendorEvidence().addEvidence("pom", "parent-groupid", parentGroupId, Confidence.MEDIUM);
dependency.getProductEvidence().addEvidence("pom", "parent-groupid", parentGroupId, Confidence.LOW);
addMatchingValues(classes, parentGroupId, dependency.getVendorEvidence());
addMatchingValues(classes, parentGroupId, dependency.getProductEvidence());
}
} else {
addAsIdentifier = false;
}
if (artifactid != null && !artifactid.isEmpty()) {
foundSomething = true;
dependency.getProductEvidence().addEvidence("pom", "artifactid", artifactid, Confidence.HIGHEST);
dependency.getVendorEvidence().addEvidence("pom", "artifactid", artifactid, Confidence.LOW);
addMatchingValues(classes, artifactid, dependency.getVendorEvidence());
addMatchingValues(classes, artifactid, dependency.getProductEvidence());
if (parentArtifactId != null && !parentArtifactId.isEmpty() && !parentArtifactId.equals(artifactid)) {
dependency.getProductEvidence().addEvidence("pom", "parent-artifactid", parentArtifactId, Confidence.MEDIUM);
dependency.getVendorEvidence().addEvidence("pom", "parent-artifactid", parentArtifactId, Confidence.LOW);
addMatchingValues(classes, parentArtifactId, dependency.getVendorEvidence());
addMatchingValues(classes, parentArtifactId, dependency.getProductEvidence());
}
} else {
addAsIdentifier = false;
}
if (version != null && !version.isEmpty()) {
foundSomething = true;
dependency.getVersionEvidence().addEvidence("pom", "version", version, Confidence.HIGHEST);
if (parentVersion != null && !parentVersion.isEmpty() && !parentVersion.equals(version)) {
dependency.getVersionEvidence().addEvidence("pom", "parent-version", version, Confidence.LOW);
}
} else {
addAsIdentifier = false;
}
if (addAsIdentifier) {
dependency.addIdentifier("maven", String.format("%s:%s:%s", originalGroupID, originalArtifactID, version), null, Confidence.HIGH);
}
// org name
final String org = pom.getOrganization();
if (org != null && !org.isEmpty()) {
dependency.getVendorEvidence().addEvidence("pom", "organization name", org, Confidence.HIGH);
dependency.getProductEvidence().addEvidence("pom", "organization name", org, Confidence.LOW);
addMatchingValues(classes, org, dependency.getVendorEvidence());
addMatchingValues(classes, org, dependency.getProductEvidence());
}
//pom name
final String pomName = pom.getName();
if (pomName
!= null && !pomName.isEmpty()) {
foundSomething = true;
dependency.getProductEvidence().addEvidence("pom", "name", pomName, Confidence.HIGH);
dependency.getVendorEvidence().addEvidence("pom", "name", pomName, Confidence.HIGH);
addMatchingValues(classes, pomName, dependency.getVendorEvidence());
addMatchingValues(classes, pomName, dependency.getProductEvidence());
}
//Description
final String description = pom.getDescription();
if (description != null && !description.isEmpty()) {
foundSomething = true;
final String trimmedDescription = addDescription(dependency, description, "pom", "description");
addMatchingValues(classes, trimmedDescription, dependency.getVendorEvidence());
addMatchingValues(classes, trimmedDescription, dependency.getProductEvidence());
}
extractLicense(pom, dependency);
return foundSomething;
}
/**
* Analyzes the path information of the classes contained within the JarAnalyzer to try and determine possible vendor or
* product names. If any are found they are stored in the packageVendor and packageProduct hashSets.
*
* @param classNames a list of class names
* @param dependency a dependency to analyze
* @param addPackagesAsEvidence a flag indicating whether or not package names should be added as evidence.
*/
protected void analyzePackageNames(List<ClassNameInformation> classNames,
Dependency dependency, boolean addPackagesAsEvidence) {
final Map<String, Integer> vendorIdentifiers = new HashMap<String, Integer>();
final Map<String, Integer> productIdentifiers = new HashMap<String, Integer>();
analyzeFullyQualifiedClassNames(classNames, vendorIdentifiers, productIdentifiers);
final int classCount = classNames.size();
final EvidenceCollection vendor = dependency.getVendorEvidence();
final EvidenceCollection product = dependency.getProductEvidence();
for (Map.Entry<String, Integer> entry : vendorIdentifiers.entrySet()) {
final float ratio = entry.getValue() / (float) classCount;
if (ratio > 0.5) {
//TODO remove weighting
vendor.addWeighting(entry.getKey());
if (addPackagesAsEvidence && entry.getKey().length() > 1) {
vendor.addEvidence("jar", "package name", entry.getKey(), Confidence.LOW);
}
}
}
for (Map.Entry<String, Integer> entry : productIdentifiers.entrySet()) {
final float ratio = entry.getValue() / (float) classCount;
if (ratio > 0.5) {
product.addWeighting(entry.getKey());
if (addPackagesAsEvidence && entry.getKey().length() > 1) {
product.addEvidence("jar", "package name", entry.getKey(), Confidence.LOW);
}
}
}
}
/**
* <p>
* Reads the manifest from the JAR file and collects the entries. Some vendorKey entries are:</p>
* <ul><li>Implementation Title</li>
* <li>Implementation Version</li> <li>Implementation Vendor</li>
* <li>Implementation VendorId</li> <li>Bundle Name</li> <li>Bundle Version</li> <li>Bundle Vendor</li> <li>Bundle
* Description</li> <li>Main Class</li> </ul>
* However, all but a handful of specific entries are read in.
*
* @param dependency A reference to the dependency
* @param classInformation a collection of class information
* @return whether evidence was identified parsing the manifest
* @throws IOException if there is an issue reading the JAR file
*/
protected boolean parseManifest(Dependency dependency, List<ClassNameInformation> classInformation) throws IOException {
boolean foundSomething = false;
JarFile jar = null;
try {
jar = new JarFile(dependency.getActualFilePath());
final Manifest manifest = jar.getManifest();
if (manifest == null) {
//don't log this for javadoc or sources jar files
if (!dependency.getFileName().toLowerCase().endsWith("-sources.jar")
&& !dependency.getFileName().toLowerCase().endsWith("-javadoc.jar")
&& !dependency.getFileName().toLowerCase().endsWith("-src.jar")
&& !dependency.getFileName().toLowerCase().endsWith("-doc.jar")) {
LOGGER.log(Level.FINE,
String.format("Jar file '%s' does not contain a manifest.",
dependency.getFileName()));
}
return false;
}
final Attributes atts = manifest.getMainAttributes();
final EvidenceCollection vendorEvidence = dependency.getVendorEvidence();
final EvidenceCollection productEvidence = dependency.getProductEvidence();
final EvidenceCollection versionEvidence = dependency.getVersionEvidence();
final String source = "Manifest";
for (Entry<Object, Object> entry : atts.entrySet()) {
String key = entry.getKey().toString();
String value = atts.getValue(key);
if (HTML_DETECTION_PATTERN.matcher(value).find()) {
value = Jsoup.parse(value).text();
}
if (IGNORE_VALUES.contains(value)) {
continue;
} else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_TITLE.toString())) {
foundSomething = true;
productEvidence.addEvidence(source, key, value, Confidence.HIGH);
addMatchingValues(classInformation, value, productEvidence);
} else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VERSION.toString())) {
foundSomething = true;
versionEvidence.addEvidence(source, key, value, Confidence.HIGH);
} else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VENDOR.toString())) {
foundSomething = true;
vendorEvidence.addEvidence(source, key, value, Confidence.HIGH);
addMatchingValues(classInformation, value, vendorEvidence);
} else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VENDOR_ID.toString())) {
foundSomething = true;
vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, vendorEvidence);
} else if (key.equalsIgnoreCase(BUNDLE_DESCRIPTION)) {
foundSomething = true;
addDescription(dependency, value, "manifest", key);
//productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, productEvidence);
} else if (key.equalsIgnoreCase(BUNDLE_NAME)) {
foundSomething = true;
productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, productEvidence);
// //the following caused false positives.
// } else if (key.equalsIgnoreCase(BUNDLE_VENDOR)) {
// foundSomething = true;
// vendorEvidence.addEvidence(source, key, value, Confidence.HIGH);
// addMatchingValues(classInformation, value, vendorEvidence);
} else if (key.equalsIgnoreCase(BUNDLE_VERSION)) {
foundSomething = true;
versionEvidence.addEvidence(source, key, value, Confidence.HIGH);
} else if (key.equalsIgnoreCase(Attributes.Name.MAIN_CLASS.toString())) {
continue;
//skipping main class as if this has important information to add
// it will be added during class name analysis... if other fields
// have the information from the class name then they will get added...
// foundSomething = true;
// productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
// vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
// addMatchingValues(classInformation, value, vendorEvidence);
// addMatchingValues(classInformation, value, productEvidence);
} else {
key = key.toLowerCase();
if (!IGNORE_KEYS.contains(key)
&& !key.endsWith("jdk")
&& !key.contains("lastmodified")
&& !key.endsWith("package")
&& !key.endsWith("classpath")
&& !key.endsWith("class-path")
&& !key.endsWith("-scm") //todo change this to a regex?
&& !key.startsWith("scm-")
&& !value.trim().startsWith("scm:")
&& !isImportPackage(key, value)
&& !isPackage(key, value)) {
foundSomething = true;
if (key.contains("version")) {
if (key.contains("specification")) {
versionEvidence.addEvidence(source, key, value, Confidence.LOW);
} else {
versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
}
} else if ("build-id".equals(key)) {
int pos = value.indexOf('(');
if (pos >= 0) {
value = value.substring(0, pos - 1);
}
pos = value.indexOf('[');
if (pos >= 0) {
value = value.substring(0, pos - 1);
}
versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
} else if (key.contains("title")) {
productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, productEvidence);
} else if (key.contains("vendor")) {
if (key.contains("specification")) {
vendorEvidence.addEvidence(source, key, value, Confidence.LOW);
} else {
vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, vendorEvidence);
}
} else if (key.contains("name")) {
productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, vendorEvidence);
addMatchingValues(classInformation, value, productEvidence);
} else if (key.contains("license")) {
addLicense(dependency, value);
} else {
if (key.contains("description")) {
addDescription(dependency, value, "manifest", key);
} else {
productEvidence.addEvidence(source, key, value, Confidence.LOW);
vendorEvidence.addEvidence(source, key, value, Confidence.LOW);
addMatchingValues(classInformation, value, vendorEvidence);
addMatchingValues(classInformation, value, productEvidence);
if (value.matches(".*\\d.*")) {
final StringTokenizer tokenizer = new StringTokenizer(value, " ");
while (tokenizer.hasMoreElements()) {
final String s = tokenizer.nextToken();
if (s.matches("^[0-9.]+$")) {
versionEvidence.addEvidence(source, key, s, Confidence.LOW);
}
}
}
}
}
}
}
}
} finally {
if (jar != null) {
jar.close();
}
}
return foundSomething;
}
/**
* Adds a description to the given dependency. If the description contains one of the following strings beyond 100 characters,
* then the description used will be trimmed to that position:
* <ul><li>"such as"</li><li>"like "</li><li>"will use "</li><li>"* uses "</li></ul>
*
* @param dependency a dependency
* @param description the description
* @param source the source of the evidence
* @param key the "name" of the evidence
* @return if the description is trimmed, the trimmed version is returned; otherwise the original description is returned
*/
public static String addDescription(Dependency dependency, String description, String source, String key) {
if (dependency.getDescription() == null) {
dependency.setDescription(description);
}
String desc;
if (HTML_DETECTION_PATTERN.matcher(description).find()) {
desc = Jsoup.parse(description).text();
} else {
desc = description;
}
dependency.setDescription(desc);
if (desc.length() > 100) {
desc = desc.replaceAll("\\s\\s+", " ");
final int posSuchAs = desc.toLowerCase().indexOf("such as ", 100);
final int posLike = desc.toLowerCase().indexOf("like ", 100);
final int posWillUse = desc.toLowerCase().indexOf("will use ", 100);
final int posUses = desc.toLowerCase().indexOf(" uses ", 100);
int pos = -1;
pos = Math.max(pos, posSuchAs);
if (pos >= 0 && posLike >= 0) {
pos = Math.min(pos, posLike);
} else {
pos = Math.max(pos, posLike);
}
if (pos >= 0 && posWillUse >= 0) {
pos = Math.min(pos, posWillUse);
} else {
pos = Math.max(pos, posWillUse);
}
if (pos >= 0 && posUses >= 0) {
pos = Math.min(pos, posUses);
} else {
pos = Math.max(pos, posUses);
}
if (pos > 0) {
final StringBuilder sb = new StringBuilder(pos + 3);
sb.append(desc.substring(0, pos));
sb.append("...");
desc = sb.toString();
}
dependency.getProductEvidence().addEvidence(source, key, desc, Confidence.LOW);
dependency.getVendorEvidence().addEvidence(source, key, desc, Confidence.LOW);
} else {
dependency.getProductEvidence().addEvidence(source, key, desc, Confidence.MEDIUM);
dependency.getVendorEvidence().addEvidence(source, key, desc, Confidence.MEDIUM);
}
return desc;
}
/**
* Adds a license to the given dependency.
*
* @param d a dependency
* @param license the license
*/
private void addLicense(Dependency d, String license) {
if (d.getLicense() == null) {
d.setLicense(license);
} else if (!d.getLicense().contains(license)) {
d.setLicense(d.getLicense() + NEWLINE + license);
}
}
/**
* The parent directory for the individual directories per archive.
*/
private File tempFileLocation = null;
/**
* Initializes the JarAnalyzer.
*
* @throws Exception is thrown if there is an exception creating a temporary directory
*/
@Override
public void initializeFileTypeAnalyzer() throws Exception {
final File baseDir = Settings.getTempDirectory();
tempFileLocation = File.createTempFile("check", "tmp", baseDir);
if (!tempFileLocation.delete()) {
final String msg = String.format("Unable to delete temporary file '%s'.", tempFileLocation.getAbsolutePath());
throw new AnalysisException(msg);
}
if (!tempFileLocation.mkdirs()) {
final String msg = String.format("Unable to create directory '%s'.", tempFileLocation.getAbsolutePath());
throw new AnalysisException(msg);
}
}
/**
* Deletes any files extracted from the JAR during analysis.
*/
@Override
public void close() {
if (tempFileLocation != null && tempFileLocation.exists()) {
LOGGER.log(Level.FINE, "Attempting to delete temporary files");
final boolean success = FileUtils.delete(tempFileLocation);
if (!success) {
LOGGER.log(Level.WARNING,
"Failed to delete some temporary files, see the log for more details");
}
}
}
/**
* Determines if the key value pair from the manifest is for an "import" type entry for package names.
*
* @param key the key from the manifest
* @param value the value from the manifest
* @return true or false depending on if it is believed the entry is an "import" entry
*/
private boolean isImportPackage(String key, String value) {
final Pattern packageRx = Pattern.compile("^([a-zA-Z0-9_#\\$\\*\\.]+\\s*[,;]\\s*)+([a-zA-Z0-9_#\\$\\*\\.]+\\s*)?$");
final boolean matches = packageRx.matcher(value).matches();
return matches && (key.contains("import") || key.contains("include") || value.length() > 10);
}
/**
* Cycles through an enumeration of JarEntries, contained within the dependency, and returns a list of the class names. This
* does not include core Java package names (i.e. java.* or javax.*).
*
* @param dependency the dependency being analyzed
* @return an list of fully qualified class names
*/
private List<ClassNameInformation> collectClassNames(Dependency dependency) {
final List<ClassNameInformation> classNames = new ArrayList<ClassNameInformation>();
JarFile jar = null;
try {
jar = new JarFile(dependency.getActualFilePath());
final Enumeration entries = jar.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = (JarEntry) entries.nextElement();
final String name = entry.getName().toLowerCase();
//no longer stripping "|com\\.sun" - there are some com.sun jar files with CVEs.
if (name.endsWith(".class") && !name.matches("^javax?\\..*$")) {
final ClassNameInformation className = new ClassNameInformation(name.substring(0, name.length() - 6));
classNames.add(className);
}
}
} catch (IOException ex) {
final String msg = String.format("Unable to open jar file '%s'.", dependency.getFileName());
LOGGER.log(Level.WARNING, msg);
LOGGER.log(Level.FINE, null, ex);
} finally {
if (jar != null) {
try {
jar.close();
} catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex);
}
}
}
return classNames;
}
/**
* Cycles through the list of class names and places the package levels 0-3 into the provided maps for vendor and product.
* This is helpful when analyzing vendor/product as many times this is included in the package name.
*
* @param classNames a list of class names
* @param vendor HashMap of possible vendor names from package names (e.g. owasp)
* @param product HashMap of possible product names from package names (e.g. dependencycheck)
*/
private void analyzeFullyQualifiedClassNames(List<ClassNameInformation> classNames,
Map<String, Integer> vendor, Map<String, Integer> product) {
for (ClassNameInformation entry : classNames) {
final List<String> list = entry.getPackageStructure();
addEntry(vendor, list.get(0));
if (list.size() == 2) {
addEntry(product, list.get(1));
}
if (list.size() == 3) {
addEntry(vendor, list.get(1));
addEntry(product, list.get(1));
addEntry(product, list.get(2));
}
if (list.size() >= 4) {
addEntry(vendor, list.get(1));
addEntry(vendor, list.get(2));
addEntry(product, list.get(1));
addEntry(product, list.get(2));
addEntry(product, list.get(3));
}
}
}
/**
* Adds an entry to the specified collection and sets the Integer (e.g. the count) to 1. If the entry already exists in the
* collection then the Integer is incremented by 1.
*
* @param collection a collection of strings and their occurrence count
* @param key the key to add to the collection
*/
private void addEntry(Map<String, Integer> collection, String key) {
if (collection.containsKey(key)) {
collection.put(key, collection.get(key) + 1);
} else {
collection.put(key, 1);
}
}
/**
* Cycles through the collection of class name information to see if parts of the package names are contained in the provided
* value. If found, it will be added as the HIGHEST confidence evidence because we have more then one source corroborating the
* value.
*
* @param classes a collection of class name information
* @param value the value to check to see if it contains a package name
* @param evidence the evidence collection to add new entries too
*/
private static void addMatchingValues(List<ClassNameInformation> classes, String value, EvidenceCollection evidence) {
if (value == null || value.isEmpty() || classes == null || classes.isEmpty()) {
return;
}
final String text = value.toLowerCase();
for (ClassNameInformation cni : classes) {
for (String key : cni.getPackageStructure()) {
if (text.contains(key)) { //note, package structure elements are already lowercase.
evidence.addEvidence("jar", "package name", key, Confidence.HIGHEST);
}
}
}
}
/**
* Simple check to see if the attribute from a manifest is just a package name.
*
* @param key the key of the value to check
* @param value the value to check
* @return true if the value looks like a java package name, otherwise false
*/
private boolean isPackage(String key, String value) {
return !key.matches(".*(version|title|vendor|name|license|description).*")
&& value.matches("^([a-zA-Z_][a-zA-Z0-9_\\$]*(\\.[a-zA-Z_][a-zA-Z0-9_\\$]*)*)?$");
}
/**
* Extracts the license information from the pom and adds it to the dependency.
*
* @param pom the pom object
* @param dependency the dependency to add license information too
*/
public static void extractLicense(Model pom, Dependency dependency) {
//license
if (pom.getLicenses() != null) {
String license = null;
for (License lic : pom.getLicenses()) {
String tmp = null;
if (lic.getName() != null) {
tmp = lic.getName();
}
if (lic.getUrl() != null) {
if (tmp == null) {
tmp = lic.getUrl();
} else {
tmp += ": " + lic.getUrl();
}
}
if (tmp == null) {
continue;
}
if (HTML_DETECTION_PATTERN.matcher(tmp).find()) {
tmp = Jsoup.parse(tmp).text();
}
if (license == null) {
license = tmp;
} else {
license += "\n" + tmp;
}
}
if (license != null) {
dependency.setLicense(license);
}
}
}
/**
* Stores information about a class name.
*/
protected static class ClassNameInformation {
/**
* <p>
* Stores information about a given class name. This class will keep the fully qualified class name and a list of the
* important parts of the package structure. Up to the first four levels of the package structure are stored, excluding a
* leading "org" or "com". Example:</p>
* <code>ClassNameInformation obj = new ClassNameInformation("org.owasp.dependencycheck.analyzer.JarAnalyzer");
* System.out.println(obj.getName());
* for (String p : obj.getPackageStructure())
* System.out.println(p);
* </code>
* <p>
* Would result in:</p>
* <code>org.owasp.dependencycheck.analyzer.JarAnalyzer
* owasp
* dependencycheck
* analyzer
* jaranalyzer</code>
*
* @param className a fully qualified class name
*/
ClassNameInformation(String className) {
name = className;
if (name.contains("/")) {
final String[] tmp = className.toLowerCase().split("/");
int start = 0;
int end = 3;
if ("com".equals(tmp[0]) || "org".equals(tmp[0])) {
start = 1;
end = 4;
}
if (tmp.length <= end) {
end = tmp.length - 1;
}
for (int i = start; i <= end; i++) {
packageStructure.add(tmp[i]);
}
} else {
packageStructure.add(name);
}
}
/**
* The fully qualified class name.
*/
private String name;
/**
* Get the value of name
*
* @return the value of name
*/
public String getName() {
return name;
}
/**
* Set the value of name
*
* @param name new value of name
*/
public void setName(String name) {
this.name = name;
}
/**
* Up to the first four levels of the package structure, excluding a leading "org" or "com".
*/
private final ArrayList<String> packageStructure = new ArrayList<String>();
/**
* Get the value of packageStructure
*
* @return the value of packageStructure
*/
public ArrayList<String> getPackageStructure() {
return packageStructure;
}
}
/**
* Retrieves the next temporary directory to extract an archive too.
*
* @return a directory
* @throws AnalysisException thrown if unable to create temporary directory
*/
private File getNextTempDirectory() throws AnalysisException {
dirCount += 1;
final File directory = new File(tempFileLocation, String.valueOf(dirCount));
//getting an exception for some directories not being able to be created; might be because the directory already exists?
if (directory.exists()) {
return getNextTempDirectory();
}
if (!directory.mkdirs()) {
final String msg = String.format("Unable to create temp directory '%s'.", directory.getAbsolutePath());
throw new AnalysisException(msg);
}
return directory;
}
}
| dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/JarAnalyzer.java | /*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2012 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.analyzer;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import org.jsoup.Jsoup;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.dependency.Confidence;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.EvidenceCollection;
import org.owasp.dependencycheck.xml.pom.License;
import org.owasp.dependencycheck.xml.pom.PomUtils;
import org.owasp.dependencycheck.xml.pom.Model;
import org.owasp.dependencycheck.utils.FileUtils;
import org.owasp.dependencycheck.utils.Settings;
/**
* Used to load a JAR file and collect information that can be used to determine the associated CPE.
*
* @author Jeremy Long
*/
public class JarAnalyzer extends AbstractFileTypeAnalyzer {
//<editor-fold defaultstate="collapsed" desc="Constants and Member Variables">
/**
* The logger.
*/
private static final Logger LOGGER = Logger.getLogger(JarAnalyzer.class.getName());
/**
* The buffer size to use when extracting files from the archive.
*/
private static final int BUFFER_SIZE = 4096;
/**
* The count of directories created during analysis. This is used for creating temporary directories.
*/
private static int dirCount = 0;
/**
* The system independent newline character.
*/
private static final String NEWLINE = System.getProperty("line.separator");
/**
* A list of values in the manifest to ignore as they only result in false positives.
*/
private static final Set<String> IGNORE_VALUES = newHashSet(
"Sun Java System Application Server");
/**
* A list of elements in the manifest to ignore.
*/
private static final Set<String> IGNORE_KEYS = newHashSet(
"built-by",
"created-by",
"builtby",
"createdby",
"build-jdk",
"buildjdk",
"ant-version",
"antversion",
"dynamicimportpackage",
"dynamicimport-package",
"dynamic-importpackage",
"dynamic-import-package",
"import-package",
"ignore-package",
"export-package",
"importpackage",
"ignorepackage",
"exportpackage",
"sealed",
"manifest-version",
"archiver-version",
"manifestversion",
"archiverversion",
"classpath",
"class-path",
"tool",
"bundle-manifestversion",
"bundlemanifestversion",
"include-resource",
"embed-dependency",
"ipojo-components",
"ipojo-extension",
"eclipse-sourcereferences");
/**
* item in some manifest, should be considered medium confidence.
*/
private static final String BUNDLE_VERSION = "Bundle-Version"; //: 2.1.2
/**
* item in some manifest, should be considered medium confidence.
*/
private static final String BUNDLE_DESCRIPTION = "Bundle-Description"; //: Apache Struts 2
/**
* item in some manifest, should be considered medium confidence.
*/
private static final String BUNDLE_NAME = "Bundle-Name"; //: Struts 2 Core
/**
* item in some manifest, should be considered medium confidence.
*/
private static final String BUNDLE_VENDOR = "Bundle-Vendor"; //: Apache Software Foundation
/**
* A pattern to detect HTML within text.
*/
private static final Pattern HTML_DETECTION_PATTERN = Pattern.compile("\\<[a-z]+.*/?\\>", Pattern.CASE_INSENSITIVE);
//</editor-fold>
/**
* Constructs a new JarAnalyzer.
*/
public JarAnalyzer() {
}
//<editor-fold defaultstate="collapsed" desc="All standard implmentation details of Analyzer">
/**
* The name of the analyzer.
*/
private static final String ANALYZER_NAME = "Jar Analyzer";
/**
* The phase that this analyzer is intended to run in.
*/
private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.INFORMATION_COLLECTION;
/**
* The set of file extensions supported by this analyzer.
*/
private static final Set<String> EXTENSIONS = newHashSet("jar", "war");
/**
* Returns a list of file EXTENSIONS supported by this analyzer.
*
* @return a list of file EXTENSIONS supported by this analyzer.
*/
@Override
public Set<String> getSupportedExtensions() {
return EXTENSIONS;
}
/**
* Returns the name of the analyzer.
*
* @return the name of the analyzer.
*/
@Override
public String getName() {
return ANALYZER_NAME;
}
/**
* Returns the phase that the analyzer is intended to run in.
*
* @return the phase that the analyzer is intended to run in.
*/
public AnalysisPhase getAnalysisPhase() {
return ANALYSIS_PHASE;
}
//</editor-fold>
/**
* Returns the key used in the properties file to reference the analyzer's enabled property.
*
* @return the analyzer's enabled property setting key
*/
@Override
protected String getAnalyzerEnabledSettingKey() {
return Settings.KEYS.ANALYZER_JAR_ENABLED;
}
/**
* Loads a specified JAR file and collects information from the manifest and checksums to identify the correct CPE
* information.
*
* @param dependency the dependency to analyze.
* @param engine the engine that is scanning the dependencies
* @throws AnalysisException is thrown if there is an error reading the JAR file.
*/
@Override
public void analyzeFileType(Dependency dependency, Engine engine) throws AnalysisException {
try {
final List<ClassNameInformation> classNames = collectClassNames(dependency);
final String fileName = dependency.getFileName().toLowerCase();
if (classNames.isEmpty()
&& (fileName.endsWith("-sources.jar")
|| fileName.endsWith("-javadoc.jar")
|| fileName.endsWith("-src.jar")
|| fileName.endsWith("-doc.jar"))) {
engine.getDependencies().remove(dependency);
}
final boolean hasManifest = parseManifest(dependency, classNames);
final boolean hasPOM = analyzePOM(dependency, classNames, engine);
final boolean addPackagesAsEvidence = !(hasManifest && hasPOM);
analyzePackageNames(classNames, dependency, addPackagesAsEvidence);
} catch (IOException ex) {
throw new AnalysisException("Exception occurred reading the JAR file.", ex);
}
}
/**
* Attempts to find a pom.xml within the JAR file. If found it extracts information and adds it to the evidence. This will
* attempt to interpolate the strings contained within the pom.properties if one exists.
*
* @param dependency the dependency being analyzed
* @param classes a collection of class name information
* @param engine the analysis engine, used to add additional dependencies
* @throws AnalysisException is thrown if there is an exception parsing the pom
* @return whether or not evidence was added to the dependency
*/
protected boolean analyzePOM(Dependency dependency, List<ClassNameInformation> classes, Engine engine) throws AnalysisException {
boolean foundSomething = false;
final JarFile jar;
try {
jar = new JarFile(dependency.getActualFilePath());
} catch (IOException ex) {
final String msg = String.format("Unable to read JarFile '%s'.", dependency.getActualFilePath());
//final AnalysisException ax = new AnalysisException(msg, ex);
LOGGER.log(Level.WARNING, msg);
LOGGER.log(Level.FINE, "", ex);
return false;
}
List<String> pomEntries;
try {
pomEntries = retrievePomListing(jar);
} catch (IOException ex) {
final String msg = String.format("Unable to read Jar file entries in '%s'.", dependency.getActualFilePath());
//final AnalysisException ax = new AnalysisException(msg, ex);
LOGGER.log(Level.WARNING, msg);
LOGGER.log(Level.FINE, msg, ex);
return false;
}
File externalPom = null;
if (pomEntries.isEmpty()) {
String pomPath = dependency.getActualFilePath();
pomPath = pomPath.substring(0, pomPath.lastIndexOf('.')) + ".pom";
externalPom = new File(pomPath);
if (externalPom.isFile()) {
pomEntries.add(pomPath);
} else {
return false;
}
}
for (String path : pomEntries) {
LOGGER.fine(String.format("Reading pom entry: %s", path));
Properties pomProperties = null;
try {
if (externalPom == null) {
pomProperties = retrievePomProperties(path, jar);
}
} catch (IOException ex) {
LOGGER.log(Level.FINEST, "ignore this, failed reading a non-existent pom.properties", ex);
}
Model pom = null;
try {
if (pomEntries.size() > 1) {
//extract POM to its own directory and add it as its own dependency
final Dependency newDependency = new Dependency();
pom = extractPom(path, jar, newDependency);
final String displayPath = String.format("%s%s%s",
dependency.getFilePath(),
File.separator,
path);
final String displayName = String.format("%s%s%s",
dependency.getFileName(),
File.separator,
path);
newDependency.setFileName(displayName);
newDependency.setFilePath(displayPath);
pom.processProperties(pomProperties);
setPomEvidence(newDependency, pom, null);
engine.getDependencies().add(newDependency);
Collections.sort(engine.getDependencies());
} else {
if (externalPom == null) {
pom = PomUtils.readPom(path, jar);
} else {
pom = PomUtils.readPom(externalPom);
}
pom.processProperties(pomProperties);
foundSomething |= setPomEvidence(dependency, pom, classes);
}
} catch (AnalysisException ex) {
final String msg = String.format("An error occured while analyzing '%s'.", dependency.getActualFilePath());
LOGGER.log(Level.WARNING, msg);
LOGGER.log(Level.FINE, "", ex);
}
}
return foundSomething;
}
/**
* Given a path to a pom.xml within a JarFile, this method attempts to load a sibling pom.properties if one exists.
*
* @param path the path to the pom.xml within the JarFile
* @param jar the JarFile to load the pom.properties from
* @return a Properties object or null if no pom.properties was found
* @throws IOException thrown if there is an exception reading the pom.properties
*/
private Properties retrievePomProperties(String path, final JarFile jar) throws IOException {
Properties pomProperties = null;
final String propPath = path.substring(0, path.length() - 7) + "pom.properies";
final ZipEntry propEntry = jar.getEntry(propPath);
if (propEntry != null) {
Reader reader = null;
try {
reader = new InputStreamReader(jar.getInputStream(propEntry), "UTF-8");
pomProperties = new Properties();
pomProperties.load(reader);
LOGGER.fine(String.format("Read pom.properties: %s", propPath));
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
LOGGER.log(Level.FINEST, "close error", ex);
}
}
}
}
return pomProperties;
}
/**
* Searches a JarFile for pom.xml entries and returns a listing of these entries.
*
* @param jar the JarFile to search
* @return a list of pom.xml entries
* @throws IOException thrown if there is an exception reading a JarEntry
*/
private List<String> retrievePomListing(final JarFile jar) throws IOException {
final List<String> pomEntries = new ArrayList<String>();
final Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
final String entryName = (new File(entry.getName())).getName().toLowerCase();
if (!entry.isDirectory() && "pom.xml".equals(entryName)) {
LOGGER.fine(String.format("POM Entry found: %s", entry.getName()));
pomEntries.add(entry.getName());
}
}
return pomEntries;
}
/**
* Retrieves the specified POM from a jar file and converts it to a Model.
*
* @param path the path to the pom.xml file within the jar file
* @param jar the jar file to extract the pom from
* @param dependency the dependency being analyzed
* @return returns the POM object
* @throws AnalysisException is thrown if there is an exception extracting or parsing the POM
* {@link org.owasp.dependencycheck.jaxb.pom.generated.Model} object
*/
private Model extractPom(String path, JarFile jar, Dependency dependency) throws AnalysisException {
InputStream input = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
final File tmpDir = getNextTempDirectory();
final File file = new File(tmpDir, "pom.xml");
try {
final ZipEntry entry = jar.getEntry(path);
input = jar.getInputStream(entry);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, BUFFER_SIZE);
int count;
final byte[] data = new byte[BUFFER_SIZE];
while ((count = input.read(data, 0, BUFFER_SIZE)) != -1) {
bos.write(data, 0, count);
}
bos.flush();
dependency.setActualFilePath(file.getAbsolutePath());
} catch (IOException ex) {
final String msg = String.format("An error occurred reading '%s' from '%s'.", path, dependency.getFilePath());
LOGGER.warning(msg);
LOGGER.log(Level.SEVERE, "", ex);
} finally {
closeStream(bos);
closeStream(fos);
closeStream(input);
}
return PomUtils.readPom(file);
}
/**
* Silently closes an input stream ignoring errors.
*
* @param stream an input stream to close
*/
private void closeStream(InputStream stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex);
}
}
}
/**
* Silently closes an output stream ignoring errors.
*
* @param stream an output stream to close
*/
private void closeStream(OutputStream stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex);
}
}
}
/**
* Sets evidence from the pom on the supplied dependency.
*
* @param dependency the dependency to set data on
* @param pom the information from the pom
* @param classes a collection of ClassNameInformation - containing data about the fully qualified class names within the JAR
* file being analyzed
* @return true if there was evidence within the pom that we could use; otherwise false
*/
public static boolean setPomEvidence(Dependency dependency, Model pom, List<ClassNameInformation> classes) {
boolean foundSomething = false;
boolean addAsIdentifier = true;
if (pom == null) {
return foundSomething;
}
String groupid = pom.getGroupId();
String parentGroupId = pom.getParentGroupId();
String artifactid = pom.getArtifactId();
String parentArtifactId = pom.getParentArtifactId();
String version = pom.getVersion();
String parentVersion = pom.getParentVersion();
if ("org.sonatype.oss".equals(parentGroupId) && "oss-parent".equals(parentArtifactId)) {
parentGroupId = null;
parentArtifactId = null;
parentVersion = null;
}
if ((groupid == null || groupid.isEmpty()) && parentGroupId != null && !parentGroupId.isEmpty()) {
groupid = parentGroupId;
}
final String originalGroupID = groupid;
if (groupid.startsWith("org.") || groupid.startsWith("com.")) {
groupid = groupid.substring(4);
}
if ((artifactid == null || artifactid.isEmpty()) && parentArtifactId != null && !parentArtifactId.isEmpty()) {
artifactid = parentArtifactId;
}
final String originalArtifactID = artifactid;
if (artifactid.startsWith("org.") || artifactid.startsWith("com.")) {
artifactid = artifactid.substring(4);
}
if ((version == null || version.isEmpty()) && parentVersion != null && !parentVersion.isEmpty()) {
version = parentVersion;
}
if (groupid != null && !groupid.isEmpty()) {
foundSomething = true;
dependency.getVendorEvidence().addEvidence("pom", "groupid", groupid, Confidence.HIGHEST);
dependency.getProductEvidence().addEvidence("pom", "groupid", groupid, Confidence.LOW);
addMatchingValues(classes, groupid, dependency.getVendorEvidence());
addMatchingValues(classes, groupid, dependency.getProductEvidence());
if (parentGroupId != null && !parentGroupId.isEmpty() && !parentGroupId.equals(groupid)) {
dependency.getVendorEvidence().addEvidence("pom", "parent-groupid", parentGroupId, Confidence.MEDIUM);
dependency.getProductEvidence().addEvidence("pom", "parent-groupid", parentGroupId, Confidence.LOW);
addMatchingValues(classes, parentGroupId, dependency.getVendorEvidence());
addMatchingValues(classes, parentGroupId, dependency.getProductEvidence());
}
} else {
addAsIdentifier = false;
}
if (artifactid != null && !artifactid.isEmpty()) {
foundSomething = true;
dependency.getProductEvidence().addEvidence("pom", "artifactid", artifactid, Confidence.HIGHEST);
dependency.getVendorEvidence().addEvidence("pom", "artifactid", artifactid, Confidence.LOW);
addMatchingValues(classes, artifactid, dependency.getVendorEvidence());
addMatchingValues(classes, artifactid, dependency.getProductEvidence());
if (parentArtifactId != null && !parentArtifactId.isEmpty() && !parentArtifactId.equals(artifactid)) {
dependency.getProductEvidence().addEvidence("pom", "parent-artifactid", parentArtifactId, Confidence.MEDIUM);
dependency.getVendorEvidence().addEvidence("pom", "parent-artifactid", parentArtifactId, Confidence.LOW);
addMatchingValues(classes, parentArtifactId, dependency.getVendorEvidence());
addMatchingValues(classes, parentArtifactId, dependency.getProductEvidence());
}
} else {
addAsIdentifier = false;
}
if (version != null && !version.isEmpty()) {
foundSomething = true;
dependency.getVersionEvidence().addEvidence("pom", "version", version, Confidence.HIGHEST);
if (parentVersion != null && !parentVersion.isEmpty() && !parentVersion.equals(version)) {
dependency.getVersionEvidence().addEvidence("pom", "parent-version", version, Confidence.LOW);
}
} else {
addAsIdentifier = false;
}
if (addAsIdentifier) {
dependency.addIdentifier("maven", String.format("%s:%s:%s", originalGroupID, originalArtifactID, version), null, Confidence.HIGH);
}
// org name
final String org = pom.getOrganization();
if (org != null && !org.isEmpty()) {
dependency.getVendorEvidence().addEvidence("pom", "organization name", org, Confidence.HIGH);
dependency.getProductEvidence().addEvidence("pom", "organization name", org, Confidence.LOW);
addMatchingValues(classes, org, dependency.getVendorEvidence());
addMatchingValues(classes, org, dependency.getProductEvidence());
}
//pom name
final String pomName = pom.getName();
if (pomName
!= null && !pomName.isEmpty()) {
foundSomething = true;
dependency.getProductEvidence().addEvidence("pom", "name", pomName, Confidence.HIGH);
dependency.getVendorEvidence().addEvidence("pom", "name", pomName, Confidence.HIGH);
addMatchingValues(classes, pomName, dependency.getVendorEvidence());
addMatchingValues(classes, pomName, dependency.getProductEvidence());
}
//Description
final String description = pom.getDescription();
if (description != null && !description.isEmpty()) {
foundSomething = true;
final String trimmedDescription = addDescription(dependency, description, "pom", "description");
addMatchingValues(classes, trimmedDescription, dependency.getVendorEvidence());
addMatchingValues(classes, trimmedDescription, dependency.getProductEvidence());
}
extractLicense(pom, dependency);
return foundSomething;
}
/**
* Analyzes the path information of the classes contained within the JarAnalyzer to try and determine possible vendor or
* product names. If any are found they are stored in the packageVendor and packageProduct hashSets.
*
* @param classNames a list of class names
* @param dependency a dependency to analyze
* @param addPackagesAsEvidence a flag indicating whether or not package names should be added as evidence.
*/
protected void analyzePackageNames(List<ClassNameInformation> classNames,
Dependency dependency, boolean addPackagesAsEvidence) {
final Map<String, Integer> vendorIdentifiers = new HashMap<String, Integer>();
final Map<String, Integer> productIdentifiers = new HashMap<String, Integer>();
analyzeFullyQualifiedClassNames(classNames, vendorIdentifiers, productIdentifiers);
final int classCount = classNames.size();
final EvidenceCollection vendor = dependency.getVendorEvidence();
final EvidenceCollection product = dependency.getProductEvidence();
for (Map.Entry<String, Integer> entry : vendorIdentifiers.entrySet()) {
final float ratio = entry.getValue() / (float) classCount;
if (ratio > 0.5) {
//TODO remove weighting
vendor.addWeighting(entry.getKey());
if (addPackagesAsEvidence && entry.getKey().length() > 1) {
vendor.addEvidence("jar", "package name", entry.getKey(), Confidence.LOW);
}
}
}
for (Map.Entry<String, Integer> entry : productIdentifiers.entrySet()) {
final float ratio = entry.getValue() / (float) classCount;
if (ratio > 0.5) {
product.addWeighting(entry.getKey());
if (addPackagesAsEvidence && entry.getKey().length() > 1) {
product.addEvidence("jar", "package name", entry.getKey(), Confidence.LOW);
}
}
}
}
/**
* <p>
* Reads the manifest from the JAR file and collects the entries. Some vendorKey entries are:</p>
* <ul><li>Implementation Title</li>
* <li>Implementation Version</li> <li>Implementation Vendor</li>
* <li>Implementation VendorId</li> <li>Bundle Name</li> <li>Bundle Version</li> <li>Bundle Vendor</li> <li>Bundle
* Description</li> <li>Main Class</li> </ul>
* However, all but a handful of specific entries are read in.
*
* @param dependency A reference to the dependency
* @param classInformation a collection of class information
* @return whether evidence was identified parsing the manifest
* @throws IOException if there is an issue reading the JAR file
*/
protected boolean parseManifest(Dependency dependency, List<ClassNameInformation> classInformation) throws IOException {
boolean foundSomething = false;
JarFile jar = null;
try {
jar = new JarFile(dependency.getActualFilePath());
final Manifest manifest = jar.getManifest();
if (manifest == null) {
//don't log this for javadoc or sources jar files
if (!dependency.getFileName().toLowerCase().endsWith("-sources.jar")
&& !dependency.getFileName().toLowerCase().endsWith("-javadoc.jar")
&& !dependency.getFileName().toLowerCase().endsWith("-src.jar")
&& !dependency.getFileName().toLowerCase().endsWith("-doc.jar")) {
LOGGER.log(Level.FINE,
String.format("Jar file '%s' does not contain a manifest.",
dependency.getFileName()));
}
return false;
}
final Attributes atts = manifest.getMainAttributes();
final EvidenceCollection vendorEvidence = dependency.getVendorEvidence();
final EvidenceCollection productEvidence = dependency.getProductEvidence();
final EvidenceCollection versionEvidence = dependency.getVersionEvidence();
final String source = "Manifest";
for (Entry<Object, Object> entry : atts.entrySet()) {
String key = entry.getKey().toString();
String value = atts.getValue(key);
if (HTML_DETECTION_PATTERN.matcher(value).find()) {
value = Jsoup.parse(value).text();
}
if (IGNORE_VALUES.contains(value)) {
continue;
} else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_TITLE.toString())) {
foundSomething = true;
productEvidence.addEvidence(source, key, value, Confidence.HIGH);
addMatchingValues(classInformation, value, productEvidence);
} else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VERSION.toString())) {
foundSomething = true;
versionEvidence.addEvidence(source, key, value, Confidence.HIGH);
} else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VENDOR.toString())) {
foundSomething = true;
vendorEvidence.addEvidence(source, key, value, Confidence.HIGH);
addMatchingValues(classInformation, value, vendorEvidence);
} else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VENDOR_ID.toString())) {
foundSomething = true;
vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, vendorEvidence);
} else if (key.equalsIgnoreCase(BUNDLE_DESCRIPTION)) {
foundSomething = true;
addDescription(dependency, value, "manifest", key);
//productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, productEvidence);
} else if (key.equalsIgnoreCase(BUNDLE_NAME)) {
foundSomething = true;
productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, productEvidence);
} else if (key.equalsIgnoreCase(BUNDLE_VENDOR)) {
foundSomething = true;
vendorEvidence.addEvidence(source, key, value, Confidence.HIGH);
addMatchingValues(classInformation, value, vendorEvidence);
} else if (key.equalsIgnoreCase(BUNDLE_VERSION)) {
foundSomething = true;
versionEvidence.addEvidence(source, key, value, Confidence.HIGH);
} else if (key.equalsIgnoreCase(Attributes.Name.MAIN_CLASS.toString())) {
continue;
//skipping main class as if this has important information to add
// it will be added during class name analysis... if other fields
// have the information from the class name then they will get added...
// foundSomething = true;
// productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
// vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
// addMatchingValues(classInformation, value, vendorEvidence);
// addMatchingValues(classInformation, value, productEvidence);
} else {
key = key.toLowerCase();
if (!IGNORE_KEYS.contains(key)
&& !key.endsWith("jdk")
&& !key.contains("lastmodified")
&& !key.endsWith("package")
&& !key.endsWith("classpath")
&& !key.endsWith("class-path")
&& !key.endsWith("-scm") //todo change this to a regex?
&& !key.startsWith("scm-")
&& !value.trim().startsWith("scm:")
&& !isImportPackage(key, value)
&& !isPackage(key, value)) {
foundSomething = true;
if (key.contains("version")) {
if (key.contains("specification")) {
versionEvidence.addEvidence(source, key, value, Confidence.LOW);
} else {
versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
}
} else if ("build-id".equals(key)) {
int pos = value.indexOf('(');
if (pos >= 0) {
value = value.substring(0, pos - 1);
}
pos = value.indexOf('[');
if (pos >= 0) {
value = value.substring(0, pos - 1);
}
versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
} else if (key.contains("title")) {
productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, productEvidence);
} else if (key.contains("vendor")) {
if (key.contains("specification")) {
vendorEvidence.addEvidence(source, key, value, Confidence.LOW);
} else {
vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, vendorEvidence);
}
} else if (key.contains("name")) {
productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, vendorEvidence);
addMatchingValues(classInformation, value, productEvidence);
} else if (key.contains("license")) {
addLicense(dependency, value);
} else {
if (key.contains("description")) {
addDescription(dependency, value, "manifest", key);
} else {
productEvidence.addEvidence(source, key, value, Confidence.LOW);
vendorEvidence.addEvidence(source, key, value, Confidence.LOW);
addMatchingValues(classInformation, value, vendorEvidence);
addMatchingValues(classInformation, value, productEvidence);
if (value.matches(".*\\d.*")) {
final StringTokenizer tokenizer = new StringTokenizer(value, " ");
while (tokenizer.hasMoreElements()) {
final String s = tokenizer.nextToken();
if (s.matches("^[0-9.]+$")) {
versionEvidence.addEvidence(source, key, s, Confidence.LOW);
}
}
}
}
}
}
}
}
} finally {
if (jar != null) {
jar.close();
}
}
return foundSomething;
}
/**
* Adds a description to the given dependency. If the description contains one of the following strings beyond 100 characters,
* then the description used will be trimmed to that position:
* <ul><li>"such as"</li><li>"like "</li><li>"will use "</li><li>"* uses "</li></ul>
*
* @param dependency a dependency
* @param description the description
* @param source the source of the evidence
* @param key the "name" of the evidence
* @return if the description is trimmed, the trimmed version is returned; otherwise the original description is returned
*/
public static String addDescription(Dependency dependency, String description, String source, String key) {
if (dependency.getDescription() == null) {
dependency.setDescription(description);
}
String desc;
if (HTML_DETECTION_PATTERN.matcher(description).find()) {
desc = Jsoup.parse(description).text();
} else {
desc = description;
}
dependency.setDescription(desc);
if (desc.length() > 100) {
desc = desc.replaceAll("\\s\\s+", " ");
final int posSuchAs = desc.toLowerCase().indexOf("such as ", 100);
final int posLike = desc.toLowerCase().indexOf("like ", 100);
final int posWillUse = desc.toLowerCase().indexOf("will use ", 100);
final int posUses = desc.toLowerCase().indexOf(" uses ", 100);
int pos = -1;
pos = Math.max(pos, posSuchAs);
if (pos >= 0 && posLike >= 0) {
pos = Math.min(pos, posLike);
} else {
pos = Math.max(pos, posLike);
}
if (pos >= 0 && posWillUse >= 0) {
pos = Math.min(pos, posWillUse);
} else {
pos = Math.max(pos, posWillUse);
}
if (pos >= 0 && posUses >= 0) {
pos = Math.min(pos, posUses);
} else {
pos = Math.max(pos, posUses);
}
if (pos > 0) {
final StringBuilder sb = new StringBuilder(pos + 3);
sb.append(desc.substring(0, pos));
sb.append("...");
desc = sb.toString();
}
dependency.getProductEvidence().addEvidence(source, key, desc, Confidence.LOW);
dependency.getVendorEvidence().addEvidence(source, key, desc, Confidence.LOW);
} else {
dependency.getProductEvidence().addEvidence(source, key, desc, Confidence.MEDIUM);
dependency.getVendorEvidence().addEvidence(source, key, desc, Confidence.MEDIUM);
}
return desc;
}
/**
* Adds a license to the given dependency.
*
* @param d a dependency
* @param license the license
*/
private void addLicense(Dependency d, String license) {
if (d.getLicense() == null) {
d.setLicense(license);
} else if (!d.getLicense().contains(license)) {
d.setLicense(d.getLicense() + NEWLINE + license);
}
}
/**
* The parent directory for the individual directories per archive.
*/
private File tempFileLocation = null;
/**
* Initializes the JarAnalyzer.
*
* @throws Exception is thrown if there is an exception creating a temporary directory
*/
@Override
public void initializeFileTypeAnalyzer() throws Exception {
final File baseDir = Settings.getTempDirectory();
tempFileLocation = File.createTempFile("check", "tmp", baseDir);
if (!tempFileLocation.delete()) {
final String msg = String.format("Unable to delete temporary file '%s'.", tempFileLocation.getAbsolutePath());
throw new AnalysisException(msg);
}
if (!tempFileLocation.mkdirs()) {
final String msg = String.format("Unable to create directory '%s'.", tempFileLocation.getAbsolutePath());
throw new AnalysisException(msg);
}
}
/**
* Deletes any files extracted from the JAR during analysis.
*/
@Override
public void close() {
if (tempFileLocation != null && tempFileLocation.exists()) {
LOGGER.log(Level.FINE, "Attempting to delete temporary files");
final boolean success = FileUtils.delete(tempFileLocation);
if (!success) {
LOGGER.log(Level.WARNING,
"Failed to delete some temporary files, see the log for more details");
}
}
}
/**
* Determines if the key value pair from the manifest is for an "import" type entry for package names.
*
* @param key the key from the manifest
* @param value the value from the manifest
* @return true or false depending on if it is believed the entry is an "import" entry
*/
private boolean isImportPackage(String key, String value) {
final Pattern packageRx = Pattern.compile("^([a-zA-Z0-9_#\\$\\*\\.]+\\s*[,;]\\s*)+([a-zA-Z0-9_#\\$\\*\\.]+\\s*)?$");
final boolean matches = packageRx.matcher(value).matches();
return matches && (key.contains("import") || key.contains("include") || value.length() > 10);
}
/**
* Cycles through an enumeration of JarEntries, contained within the dependency, and returns a list of the class names. This
* does not include core Java package names (i.e. java.* or javax.*).
*
* @param dependency the dependency being analyzed
* @return an list of fully qualified class names
*/
private List<ClassNameInformation> collectClassNames(Dependency dependency) {
final List<ClassNameInformation> classNames = new ArrayList<ClassNameInformation>();
JarFile jar = null;
try {
jar = new JarFile(dependency.getActualFilePath());
final Enumeration entries = jar.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = (JarEntry) entries.nextElement();
final String name = entry.getName().toLowerCase();
//no longer stripping "|com\\.sun" - there are some com.sun jar files with CVEs.
if (name.endsWith(".class") && !name.matches("^javax?\\..*$")) {
final ClassNameInformation className = new ClassNameInformation(name.substring(0, name.length() - 6));
classNames.add(className);
}
}
} catch (IOException ex) {
final String msg = String.format("Unable to open jar file '%s'.", dependency.getFileName());
LOGGER.log(Level.WARNING, msg);
LOGGER.log(Level.FINE, null, ex);
} finally {
if (jar != null) {
try {
jar.close();
} catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex);
}
}
}
return classNames;
}
/**
* Cycles through the list of class names and places the package levels 0-3 into the provided maps for vendor and product.
* This is helpful when analyzing vendor/product as many times this is included in the package name.
*
* @param classNames a list of class names
* @param vendor HashMap of possible vendor names from package names (e.g. owasp)
* @param product HashMap of possible product names from package names (e.g. dependencycheck)
*/
private void analyzeFullyQualifiedClassNames(List<ClassNameInformation> classNames,
Map<String, Integer> vendor, Map<String, Integer> product) {
for (ClassNameInformation entry : classNames) {
final List<String> list = entry.getPackageStructure();
addEntry(vendor, list.get(0));
if (list.size() == 2) {
addEntry(product, list.get(1));
}
if (list.size() == 3) {
addEntry(vendor, list.get(1));
addEntry(product, list.get(1));
addEntry(product, list.get(2));
}
if (list.size() >= 4) {
addEntry(vendor, list.get(1));
addEntry(vendor, list.get(2));
addEntry(product, list.get(1));
addEntry(product, list.get(2));
addEntry(product, list.get(3));
}
}
}
/**
* Adds an entry to the specified collection and sets the Integer (e.g. the count) to 1. If the entry already exists in the
* collection then the Integer is incremented by 1.
*
* @param collection a collection of strings and their occurrence count
* @param key the key to add to the collection
*/
private void addEntry(Map<String, Integer> collection, String key) {
if (collection.containsKey(key)) {
collection.put(key, collection.get(key) + 1);
} else {
collection.put(key, 1);
}
}
/**
* Cycles through the collection of class name information to see if parts of the package names are contained in the provided
* value. If found, it will be added as the HIGHEST confidence evidence because we have more then one source corroborating the
* value.
*
* @param classes a collection of class name information
* @param value the value to check to see if it contains a package name
* @param evidence the evidence collection to add new entries too
*/
private static void addMatchingValues(List<ClassNameInformation> classes, String value, EvidenceCollection evidence) {
if (value == null || value.isEmpty() || classes == null || classes.isEmpty()) {
return;
}
final String text = value.toLowerCase();
for (ClassNameInformation cni : classes) {
for (String key : cni.getPackageStructure()) {
if (text.contains(key)) { //note, package structure elements are already lowercase.
evidence.addEvidence("jar", "package name", key, Confidence.HIGHEST);
}
}
}
}
/**
* Simple check to see if the attribute from a manifest is just a package name.
*
* @param key the key of the value to check
* @param value the value to check
* @return true if the value looks like a java package name, otherwise false
*/
private boolean isPackage(String key, String value) {
return !key.matches(".*(version|title|vendor|name|license|description).*")
&& value.matches("^([a-zA-Z_][a-zA-Z0-9_\\$]*(\\.[a-zA-Z_][a-zA-Z0-9_\\$]*)*)?$");
}
/**
* Extracts the license information from the pom and adds it to the dependency.
*
* @param pom the pom object
* @param dependency the dependency to add license information too
*/
public static void extractLicense(Model pom, Dependency dependency) {
//license
if (pom.getLicenses() != null) {
String license = null;
for (License lic : pom.getLicenses()) {
String tmp = null;
if (lic.getName() != null) {
tmp = lic.getName();
}
if (lic.getUrl() != null) {
if (tmp == null) {
tmp = lic.getUrl();
} else {
tmp += ": " + lic.getUrl();
}
}
if (tmp == null) {
continue;
}
if (HTML_DETECTION_PATTERN.matcher(tmp).find()) {
tmp = Jsoup.parse(tmp).text();
}
if (license == null) {
license = tmp;
} else {
license += "\n" + tmp;
}
}
if (license != null) {
dependency.setLicense(license);
}
}
}
/**
* Stores information about a class name.
*/
protected static class ClassNameInformation {
/**
* <p>
* Stores information about a given class name. This class will keep the fully qualified class name and a list of the
* important parts of the package structure. Up to the first four levels of the package structure are stored, excluding a
* leading "org" or "com". Example:</p>
* <code>ClassNameInformation obj = new ClassNameInformation("org.owasp.dependencycheck.analyzer.JarAnalyzer");
* System.out.println(obj.getName());
* for (String p : obj.getPackageStructure())
* System.out.println(p);
* </code>
* <p>
* Would result in:</p>
* <code>org.owasp.dependencycheck.analyzer.JarAnalyzer
* owasp
* dependencycheck
* analyzer
* jaranalyzer</code>
*
* @param className a fully qualified class name
*/
ClassNameInformation(String className) {
name = className;
if (name.contains("/")) {
final String[] tmp = className.toLowerCase().split("/");
int start = 0;
int end = 3;
if ("com".equals(tmp[0]) || "org".equals(tmp[0])) {
start = 1;
end = 4;
}
if (tmp.length <= end) {
end = tmp.length - 1;
}
for (int i = start; i <= end; i++) {
packageStructure.add(tmp[i]);
}
} else {
packageStructure.add(name);
}
}
/**
* The fully qualified class name.
*/
private String name;
/**
* Get the value of name
*
* @return the value of name
*/
public String getName() {
return name;
}
/**
* Set the value of name
*
* @param name new value of name
*/
public void setName(String name) {
this.name = name;
}
/**
* Up to the first four levels of the package structure, excluding a leading "org" or "com".
*/
private final ArrayList<String> packageStructure = new ArrayList<String>();
/**
* Get the value of packageStructure
*
* @return the value of packageStructure
*/
public ArrayList<String> getPackageStructure() {
return packageStructure;
}
}
/**
* Retrieves the next temporary directory to extract an archive too.
*
* @return a directory
* @throws AnalysisException thrown if unable to create temporary directory
*/
private File getNextTempDirectory() throws AnalysisException {
dirCount += 1;
final File directory = new File(tempFileLocation, String.valueOf(dirCount));
//getting an exception for some directories not being able to be created; might be because the directory already exists?
if (directory.exists()) {
return getNextTempDirectory();
}
if (!directory.mkdirs()) {
final String msg = String.format("Unable to create temp directory '%s'.", directory.getAbsolutePath());
throw new AnalysisException(msg);
}
return directory;
}
}
| patch for issue #229 to remove bundle vendor from the evidence
Former-commit-id: a5a24422d5edfb23d3ea4d4c617044051d454860 | dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/JarAnalyzer.java | patch for issue #229 to remove bundle vendor from the evidence | <ide><path>ependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/JarAnalyzer.java
<ide> "tool",
<ide> "bundle-manifestversion",
<ide> "bundlemanifestversion",
<add> "bundle-vendor",
<ide> "include-resource",
<ide> "embed-dependency",
<ide> "ipojo-components",
<ide> foundSomething = true;
<ide> productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
<ide> addMatchingValues(classInformation, value, productEvidence);
<del> } else if (key.equalsIgnoreCase(BUNDLE_VENDOR)) {
<del> foundSomething = true;
<del> vendorEvidence.addEvidence(source, key, value, Confidence.HIGH);
<del> addMatchingValues(classInformation, value, vendorEvidence);
<add>// //the following caused false positives.
<add>// } else if (key.equalsIgnoreCase(BUNDLE_VENDOR)) {
<add>// foundSomething = true;
<add>// vendorEvidence.addEvidence(source, key, value, Confidence.HIGH);
<add>// addMatchingValues(classInformation, value, vendorEvidence);
<ide> } else if (key.equalsIgnoreCase(BUNDLE_VERSION)) {
<ide> foundSomething = true;
<ide> versionEvidence.addEvidence(source, key, value, Confidence.HIGH); |
|
Java | apache-2.0 | 5b593de1f4fbf41b91bfa6f74175bc2f1c7a562d | 0 | henrichg/PhoneProfilesPlus | package sk.henrichg.phoneprofilesplus;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.UiModeManager;
import android.app.WallpaperManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.provider.Settings.Global;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.IconCompat;
import androidx.work.Data;
import androidx.work.ExistingWorkPolicy;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import com.noob.noobcameraflash.managers.NoobCameraManager;
import com.stericson.rootshell.execution.Command;
import com.stericson.rootshell.execution.Shell;
import com.stericson.roottools.RootTools;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static android.app.Notification.DEFAULT_VIBRATE;
class ActivateProfileHelper {
static boolean disableScreenTimeoutInternalChange = false;
static boolean brightnessDialogInternalChange = false;
// bluetooth calls volume stream
static final int STREAM_BLUETOOTH_SCO = 6;
//static final String ADAPTIVE_BRIGHTNESS_SETTING_NAME = "screen_auto_brightness_adj";
// Setting.Global "zen_mode"
static final int ZENMODE_ALL = 0;
static final int ZENMODE_PRIORITY = 1;
static final int ZENMODE_NONE = 2;
static final int ZENMODE_ALARMS = 3;
@SuppressWarnings("WeakerAccess")
static final int ZENMODE_SILENT = 99;
static final int SUBSCRIPTRION_VOICE = 1;
static final int SUBSCRIPTRION_SMS = 2;
static final int SUBSCRIPTRION_DATA = 3;
//static final String EXTRA_MERGED_PROFILE = "merged_profile";
//static final String EXTRA_FOR_PROFILE_ACTIVATION = "for_profile_activation";
private static final String PREF_RINGER_VOLUME = "ringer_volume";
private static final String PREF_NOTIFICATION_VOLUME = "notification_volume";
private static final String PREF_RINGER_MODE = "ringer_mode";
private static final String PREF_ZEN_MODE = "zen_mode";
private static final String PREF_LOCKSCREEN_DISABLED = "lockscreenDisabled";
private static final String PREF_ACTIVATED_PROFILE_SCREEN_TIMEOUT = "activated_profile_screen_timeout";
static final String PREF_MERGED_RING_NOTIFICATION_VOLUMES = "merged_ring_notification_volumes";
static final String EXTRA_PROFILE_NAME = "profile_name";
@SuppressLint("MissingPermission")
private static void doExecuteForRadios(Context context, Profile profile)
{
/*if (PPApplication.logEnabled()) {
PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "profile=" + profile);
if (profile != null)
PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "profile._name=" + profile._name);
}*/
if (profile == null)
return;
PPApplication.sleep(300);
Context appContext = context.getApplicationContext();
// switch on/off SIM
if (Build.VERSION.SDK_INT >= 26) {
final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
int phoneCount = telephonyManager.getPhoneCount();
if (phoneCount > 1) {
if (profile._deviceOnOffSIM1 != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_ONOFF_SIM1, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM1");
//boolean _isSIM1On = isSIMOn(appContext, 1);
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios","_isSIM1On="+_isSIM1On);
boolean _setSIM1OnOff = false;
switch (profile._deviceOnOffSIM1) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM1 1");
_setSIM1OnOff = true;
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM1 2");
//noinspection DuplicateBranchesInSwitch
_setSIM1OnOff = true;
break;
}
if ( _setSIM1OnOff) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setSIMOnOff()");
//noinspection ConstantConditions
setSIMOnOff(appContext, _setSIM1OnOff, 1);
PPApplication.sleep(200);
}
}
//else
// PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM1 NOT ALLOWED");
}
if (profile._deviceOnOffSIM2 != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_ONOFF_SIM2, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM2");
//boolean _isSIM2On = isSIMOn(appContext, 2);
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios","_isSIM2On="+_isSIM2On);
boolean _setSIM2OnOff = false;
switch (profile._deviceOnOffSIM2) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM2 1");
_setSIM2OnOff = true;
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM2 2");
//noinspection DuplicateBranchesInSwitch
_setSIM2OnOff = true;
break;
}
if ( _setSIM2OnOff) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setSIMOnOff()");
//noinspection ConstantConditions
setSIMOnOff(appContext, _setSIM2OnOff, 2);
PPApplication.sleep(200);
}
}
//else
// PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM1 NOT ALLOWED");
}
}
}
}
// change default SIM
if (Build.VERSION.SDK_INT >= 26) {
if (!profile._deviceDefaultSIMCards.equals("0|0|0")) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_DEFAULT_SIM_CARDS, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.doExecuteForRadios", "profile._deviceDefaultSIMCards="+profile._deviceDefaultSIMCards);
String[] splits = profile._deviceDefaultSIMCards.split("\\|");
try {
String voice = splits[0];
if (!voice.equals("0")) {
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.doExecuteForRadios", "voice value="+Integer.parseInt(voice));
setDefaultSimCard(context, SUBSCRIPTRION_VOICE, Integer.parseInt(voice));
}
} catch (Exception e) {
PPApplication.recordException(e);
}
try {
String sms = splits[1];
if (!sms.equals("0")) {
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.doExecuteForRadios", "sms value="+Integer.parseInt(sms));
setDefaultSimCard(context, SUBSCRIPTRION_SMS, Integer.parseInt(sms));
}
} catch (Exception e) {
PPApplication.recordException(e);
}
try {
String data = splits[2];
if (!data.equals("0")) {
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.doExecuteForRadios", "data value="+Integer.parseInt(data));
setDefaultSimCard(context, SUBSCRIPTRION_DATA, Integer.parseInt(data));
}
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
}
// setup network type
// in array.xml, networkTypeGSMValues are 100+ values
if (profile._deviceNetworkType >= 100) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_NETWORK_TYPE, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceNetworkType");
// in array.xml, networkTypeGSMValues are 100+ values
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setPreferredNetworkType()");
setPreferredNetworkType(appContext, profile._deviceNetworkType - 100, 0);
PPApplication.sleep(200);
}
}
if (Build.VERSION.SDK_INT >= 26) {
final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
int phoneCount = telephonyManager.getPhoneCount();
if (phoneCount > 1) {
if (profile._deviceNetworkTypeSIM1 >= 100) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_NETWORK_TYPE_SIM1, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceNetworkType");
// in array.xml, networkTypeGSMValues are 100+ values
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setPreferredNetworkType()");
setPreferredNetworkType(appContext, profile._deviceNetworkTypeSIM1 - 100, 1);
PPApplication.sleep(200);
}
}
if (profile._deviceNetworkTypeSIM2 >= 100) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_NETWORK_TYPE_SIM2, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceNetworkType");
// in array.xml, networkTypeGSMValues are 100+ values
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setPreferredNetworkType()");
setPreferredNetworkType(appContext, profile._deviceNetworkTypeSIM2 - 100, 2);
PPApplication.sleep(200);
}
}
}
}
}
// setup mobile data
if (profile._deviceMobileData != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_MOBILE_DATA, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileData");
boolean _isMobileData = isMobileData(appContext, 0);
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios","_isMobileData="+_isMobileData);
boolean _setMobileData = false;
switch (profile._deviceMobileData) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileData 1");
if (!_isMobileData) {
_isMobileData = true;
_setMobileData = true;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileData 2");
if (_isMobileData) {
_isMobileData = false;
_setMobileData = true;
}
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileData 3");
_isMobileData = !_isMobileData;
_setMobileData = true;
break;
}
if (_setMobileData) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setMobileData()");
setMobileData(appContext, _isMobileData, 0);
PPApplication.sleep(200);
}
}
//else
// PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "_deviceMobileData NOT ALLOWED");
}
if (Build.VERSION.SDK_INT >= 26) {
final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
int phoneCount = telephonyManager.getPhoneCount();
if (phoneCount > 1) {
if (profile._deviceMobileDataSIM1 != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_MOBILE_DATA_SIM1, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM1");
boolean _isMobileData = isMobileData(appContext, 1);
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios","_isMobileData="+_isMobileData);
boolean _setMobileData = false;
switch (profile._deviceMobileDataSIM1) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM1 1");
if (!_isMobileData) {
_isMobileData = true;
_setMobileData = true;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM1 2");
if (_isMobileData) {
_isMobileData = false;
_setMobileData = true;
}
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM1 3");
_isMobileData = !_isMobileData;
_setMobileData = true;
break;
}
if (_setMobileData) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setMobileData()");
setMobileData(appContext, _isMobileData, 1);
PPApplication.sleep(200);
}
}
//else
// PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM1 NOT ALLOWED");
}
if (profile._deviceMobileDataSIM2 != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_MOBILE_DATA_SIM2, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM2");
boolean _isMobileData = isMobileData(appContext, 2);
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios","_isMobileData="+_isMobileData);
boolean _setMobileData = false;
switch (profile._deviceMobileDataSIM2) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM2 1");
if (!_isMobileData) {
_isMobileData = true;
_setMobileData = true;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM2 2");
if (_isMobileData) {
_isMobileData = false;
_setMobileData = true;
}
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM2 3");
_isMobileData = !_isMobileData;
_setMobileData = true;
break;
}
if (_setMobileData) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setMobileData()");
setMobileData(appContext, _isMobileData, 2);
PPApplication.sleep(200);
}
}
//else
// PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM2 NOT ALLOWED");
}
}
}
}
// setup WiFi AP
boolean canChangeWifi = true;
if (profile._deviceWiFiAP != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_WIFI_AP, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFiAP");
if (Build.VERSION.SDK_INT < 28) {
WifiApManager wifiApManager = null;
try {
wifiApManager = new WifiApManager(appContext);
} catch (Exception e) {
PPApplication.recordException(e);
}
if (wifiApManager != null) {
boolean setWifiAPState = false;
boolean doNotChangeWifi = false;
boolean isWifiAPEnabled = wifiApManager.isWifiAPEnabled();
switch (profile._deviceWiFiAP) {
case 1:
case 4:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFiAP 1");
if (!isWifiAPEnabled) {
isWifiAPEnabled = true;
setWifiAPState = true;
doNotChangeWifi = profile._deviceWiFiAP == 4;
canChangeWifi = profile._deviceWiFiAP == 4;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFiAP 2");
if (isWifiAPEnabled) {
isWifiAPEnabled = false;
setWifiAPState = true;
canChangeWifi = true;
}
break;
case 3:
case 5:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFiAP 3");
isWifiAPEnabled = !isWifiAPEnabled;
setWifiAPState = true;
doNotChangeWifi = profile._deviceWiFiAP == 5;
if (doNotChangeWifi)
canChangeWifi = true;
else
canChangeWifi = !isWifiAPEnabled;
break;
}
if (setWifiAPState) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setWifiAP()");
setWifiAP(wifiApManager, isWifiAPEnabled, doNotChangeWifi, appContext);
PPApplication.sleep(3000);
}
}
}
else if (Build.VERSION.SDK_INT < 30) {
// not working in Android 11+
boolean setWifiAPState = false;
boolean doNotChangeWifi = false;
boolean isWifiAPEnabled = CmdWifiAP.isEnabled();
switch (profile._deviceWiFiAP) {
case 1:
case 4:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFiAP 1");
if (!isWifiAPEnabled) {
isWifiAPEnabled = true;
setWifiAPState = true;
doNotChangeWifi = profile._deviceWiFiAP == 4;
canChangeWifi = profile._deviceWiFiAP == 4;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFiAP 2");
if (isWifiAPEnabled) {
isWifiAPEnabled = false;
setWifiAPState = true;
canChangeWifi = true;
}
break;
case 3:
case 5:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFiAP 3");
isWifiAPEnabled = !isWifiAPEnabled;
setWifiAPState = true;
doNotChangeWifi = profile._deviceWiFiAP == 5;
if (doNotChangeWifi)
canChangeWifi = true;
else
canChangeWifi = !isWifiAPEnabled;
break;
}
if (setWifiAPState) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "CmdWifiAP.setWifiAP()");
CmdWifiAP.setWifiAP(isWifiAPEnabled, doNotChangeWifi, context, profile._name);
PPApplication.sleep(1000);
}
}
}
}
if (canChangeWifi) {
// setup Wi-Fi
if (profile._deviceWiFi != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_WIFI, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFi");
boolean isWifiAPEnabled;
if (Build.VERSION.SDK_INT < 28)
isWifiAPEnabled = WifiApManager.isWifiAPEnabled(appContext);
else
isWifiAPEnabled = CmdWifiAP.isEnabled();
// PPApplication.logE("[WIFI] ActivateProfileHelper.doExecuteForRadios", "isWifiAPEnabled="+isWifiAPEnabled);
if ((!isWifiAPEnabled) || (profile._deviceWiFi >= 4)) { // only when wifi AP is not enabled, change wifi
WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null) {
int wifiState = wifiManager.getWifiState();
boolean isWifiEnabled = ((wifiState == WifiManager.WIFI_STATE_ENABLED) || (wifiState == WifiManager.WIFI_STATE_ENABLING));
boolean setWifiState = false;
switch (profile._deviceWiFi) {
case 1:
case 4:
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFi 1,4");
if (!isWifiEnabled) {
isWifiEnabled = true;
setWifiState = true;
}
break;
case 2:
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFi 2");
if (isWifiEnabled) {
isWifiEnabled = false;
setWifiState = true;
}
break;
case 3:
case 5:
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFi 3,5");
isWifiEnabled = !isWifiEnabled;
setWifiState = true;
break;
}
// PPApplication.logE("[WIFI] ActivateProfileHelper.doExecuteForRadios", "isWifiEnabled="+isWifiEnabled);
// PPApplication.logE("[WIFI] ActivateProfileHelper.doExecuteForRadios", "setWifiState="+setWifiState);
if (isWifiEnabled) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setWifiEnabledForScan()");
// when wifi is enabled from profile, no disable wifi after scan
WifiScanWorker.setWifiEnabledForScan(appContext, false);
}
if (setWifiState) {
try {
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setWifiEnabled()");
//PPApplication.logE("#### setWifiEnabled", "from ActivateProfileHelper.doExecuteForRadio");
//if (Build.VERSION.SDK_INT >= 29)
// CmdWifi.setWifi(isWifiEnabled);
//else
wifiManager.setWifiEnabled(isWifiEnabled);
//CmdWifi.setWifiEnabled(isWifiAPEnabled);
} catch (Exception e) {
//WTF?: DOOGEE- X5pro - java.lang.SecurityException: Permission Denial: Enable WiFi requires com.mediatek.permission.CTA_ENABLE_WIFI
//Log.e("ActivateProfileHelper.doExecuteForRadios", Log.getStackTraceString(e));
//PPApplication.recordException(e);;
showError(context, profile._name, Profile.PARAMETER_TYPE_WIFI);
}
PPApplication.sleep(200);
}
}
}
}
}
// connect to SSID
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_CONNECT_TO_SSID, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
if (!profile._deviceConnectToSSID.equals(Profile.CONNECTTOSSID_JUSTANY)) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceConnectToSSID");
if (Permissions.checkLocation(appContext)) {
WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null) {
int wifiState = wifiManager.getWifiState();
if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
// check if wifi is connected
ConnectivityManager connManager = null;
try {
connManager = (ConnectivityManager) appContext.getSystemService(Context.CONNECTIVITY_SERVICE);
} catch (Exception e) {
// java.lang.NullPointerException: missing IConnectivityManager
// Dual SIM?? Bug in Android ???
PPApplication.recordException(e);
}
if (connManager != null) {
boolean wifiConnected = false;
/*if (Build.VERSION.SDK_INT < 28) {
NetworkInfo activeNetwork = connManager.getActiveNetworkInfo();
wifiConnected = (activeNetwork != null) &&
(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) &&
activeNetwork.isConnected();
}
else*/ {
Network[] activeNetworks=connManager.getAllNetworks();
for(Network network : activeNetworks){
try {
//NetworkInfo networkInfo = connManager.getNetworkInfo(network);
//if ((networkInfo != null) && networkInfo.isConnected()) {
NetworkCapabilities networkCapabilities = connManager.getNetworkCapabilities(network);
if ((networkCapabilities != null) && networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
wifiConnected = WifiNetworkCallback.connected;
break;
}
//}
} catch (Exception ee) {
PPApplication.recordException(ee);
}
}
}
WifiInfo wifiInfo = null;
if (wifiConnected)
wifiInfo = wifiManager.getConnectionInfo();
List<WifiConfiguration> list = null;
if (Permissions.hasPermission(appContext, Manifest.permission.ACCESS_FINE_LOCATION))
list = wifiManager.getConfiguredNetworks();
if (list != null) {
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals(profile._deviceConnectToSSID)) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceConnectToSSID wifiConnected="+wifiConnected);
if (wifiConnected) {
if (!wifiInfo.getSSID().equals(i.SSID)) {
if (PhoneProfilesService.getInstance() != null)
PhoneProfilesService.getInstance().connectToSSIDStarted = true;
// connected to another SSID
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
}
} else
wifiManager.enableNetwork(i.networkId, true);
break;
}
}
}
}
}
}
}
}
//else {
// WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
// int wifiState = wifiManager.getWifiState();
// if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
// wifiManager.disconnect();
// wifiManager.reconnect();
// }
//}
if (PhoneProfilesService.getInstance() != null)
PhoneProfilesService.getInstance().connectToSSID = profile._deviceConnectToSSID;
}
}
// setup bluetooth
if (profile._deviceBluetooth != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_BLUETOOTH, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceBluetooth");
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //BluetoothScanWorker.getBluetoothAdapter(context);
if (bluetoothAdapter != null) {
boolean isBluetoothEnabled = bluetoothAdapter.isEnabled();
boolean setBluetoothState = false;
switch (profile._deviceBluetooth) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceBluetooth 1");
if (!isBluetoothEnabled) {
isBluetoothEnabled = true;
setBluetoothState = true;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceBluetooth 2");
if (isBluetoothEnabled) {
isBluetoothEnabled = false;
setBluetoothState = true;
}
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceBluetooth 3");
isBluetoothEnabled = !isBluetoothEnabled;
setBluetoothState = true;
break;
}
/*if (PPApplication.logEnabled()) {
PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "setBluetoothState=" + setBluetoothState);
PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "isBluetoothEnabled=" + isBluetoothEnabled);
}*/
if (isBluetoothEnabled) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setBluetoothEnabledForScan()");
// when bluetooth is enabled from profile, no disable bluetooth after scan
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "isBluetoothEnabled=true; setBluetoothEnabledForScan=false");
BluetoothScanWorker.setBluetoothEnabledForScan(appContext, false);
}
if (setBluetoothState) {
try {
//if (Build.VERSION.SDK_INT >= 26)
// CmdBluetooth.setBluetooth(isBluetoothEnabled);
//else {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "enable/disable bluetooth adapter");
if (isBluetoothEnabled)
bluetoothAdapter.enable();
else
bluetoothAdapter.disable();
//}
} catch (Exception e) {
// WTF?: DOOGEE - X5pro -> java.lang.SecurityException: Permission Denial: Enable bluetooth requires com.mediatek.permission.CTA_ENABLE_BT
//Log.e("ActivateProfileHelper.doExecuteForRadio", Log.getStackTraceString(e));
//PPApplication.recordException(e);;
}
}
}
}
}
// setup location mode
if (profile._deviceLocationMode != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_LOCATION_MODE, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceLocationMode");
switch (profile._deviceLocationMode) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceLocationMode 1");
setLocationMode(appContext, Settings.Secure.LOCATION_MODE_OFF);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceLocationMode 2");
setLocationMode(appContext, Settings.Secure.LOCATION_MODE_SENSORS_ONLY);
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceLocationMode 3");
setLocationMode(appContext, Settings.Secure.LOCATION_MODE_BATTERY_SAVING);
break;
case 4:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceLocationMode 4");
setLocationMode(appContext, Settings.Secure.LOCATION_MODE_HIGH_ACCURACY);
break;
}
}
}
// setup GPS
if (profile._deviceGPS != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_GPS, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceGPS");
//String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
boolean isEnabled = false;
boolean ok = true;
/*if (android.os.Build.VERSION.SDK_INT < 19)
isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
else {*/
LocationManager locationManager = (LocationManager) appContext.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null)
isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
else
ok = false;
//}
if (ok) {
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "isEnabled=" + isEnabled);
switch (profile._deviceGPS) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceGPS 1");
setGPS(appContext, true);
//setLocationMode(appContext, true);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceGPS 2");
setGPS(appContext, false);
//setLocationMode(appContext, false);
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceGPS 3");
//setLocationMode(appContext, true);
//setLocationMode(appContext, false);
setGPS(appContext, !isEnabled);
break;
}
}
}
}
// setup NFC
if (profile._deviceNFC != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_NFC, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceNFC");
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(appContext);
if (nfcAdapter != null) {
switch (profile._deviceNFC) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceNFC 1");
setNFC(appContext, true);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceNFC 2");
setNFC(appContext, false);
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceNFC 3");
setNFC(appContext, !nfcAdapter.isEnabled());
break;
}
}
}
}
}
private static void executeForRadios(final Profile profile, Context context)
{
/*if (PPApplication.logEnabled()) {
PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "profile=" + profile);
if (profile != null)
PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "profile._name=" + profile._name);
}*/
if (profile == null)
return;
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadRadios();
final Handler handler = new Handler(PPApplication.handlerThreadRadios.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadRadios", "START run - from=ActivateProfileHelper.executeForRadios");
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_executeForRadios");
wakeLock.acquire(10 * 60 * 1000);
}
boolean _isAirplaneMode = false;
boolean _setAirplaneMode = false;
if (profile._deviceAirplaneMode != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_AIRPLANE_MODE, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
_isAirplaneMode = isAirplaneMode(appContext);
switch (profile._deviceAirplaneMode) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "_deviceAirplaneMode 1");
if (!_isAirplaneMode) {
_isAirplaneMode = true;
_setAirplaneMode = true;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "_deviceAirplaneMode 2");
if (_isAirplaneMode) {
_isAirplaneMode = false;
_setAirplaneMode = true;
}
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "_deviceAirplaneMode 3");
_isAirplaneMode = !_isAirplaneMode;
_setAirplaneMode = true;
break;
}
}
}
if (_setAirplaneMode /*&& _isAirplaneMode*/) {
// switch ON airplane mode, set it before doExecuteForRadios
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "setAirplaneMode()");
setAirplaneMode(/*context,*/ _isAirplaneMode);
PPApplication.sleep(2500);
//PPApplication.logE("ActivateProfileHelper.executeForRadios", "after sleep");
}
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "doExecuteForRadios()");
doExecuteForRadios(appContext, profile);
/*if (_setAirplaneMode && (!_isAirplaneMode)) {
// 200 milliseconds is in doExecuteForRadios
PPApplication.sleep(1800);
// switch OFF airplane mode, set if after executeForRadios
setAirplaneMode(context, _isAirplaneMode);
}*/
//PPApplication.sleep(500);
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "end");
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
});
}
static boolean isAudibleRinging(int ringerMode, int zenMode/*, boolean onlyVibrateSilent*/) {
/*if (onlyVibrateSilent)
return (!((ringerMode == Profile.RINGERMODE_VIBRATE) || (ringerMode == Profile.RINGERMODE_SILENT) ||
((ringerMode == Profile.RINGERMODE_ZENMODE) &&
((zenMode == Profile.ZENMODE_ALL_AND_VIBRATE) || (zenMode == Profile.ZENMODE_PRIORITY_AND_VIBRATE)))
));
else*/
return (!((ringerMode == Profile.RINGERMODE_VIBRATE) || (ringerMode == Profile.RINGERMODE_SILENT) ||
((ringerMode == Profile.RINGERMODE_ZENMODE) &&
((zenMode == Profile.ZENMODE_NONE) || (zenMode == Profile.ZENMODE_ALL_AND_VIBRATE) ||
(zenMode == Profile.ZENMODE_PRIORITY_AND_VIBRATE) || (zenMode == Profile.ZENMODE_ALARMS)))
));
}
private static boolean isVibrateRingerMode(int ringerMode/*, int zenMode*/) {
return (ringerMode == Profile.RINGERMODE_VIBRATE);
}
static boolean isAudibleSystemRingerMode(AudioManager audioManager, int systemZenMode/*, Context context*/) {
/*int ringerMode = audioManager.getRingerMode();
PPApplication.logE("ActivateProfileHelper.isAudibleSystemRingerMode", "ringerMode="+ringerMode);
if (ringerMode != AudioManager.RINGER_MODE_NORMAL) {
if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
int zenMode = getSystemZenMode(context, -1);
return (zenMode == ActivateProfileHelper.ZENMODE_PRIORITY);
}
else
return false;
}
else
return true;*/
int systemRingerMode = audioManager.getRingerMode();
//int systemZenMode = getSystemZenMode(context/*, -1*/);
/*return (audibleRingerMode) ||
((systemZenMode == ActivateProfileHelper.ZENMODE_PRIORITY) &&
(systemRingerMode != AudioManager.RINGER_MODE_VIBRATE));*/
/*if (PPApplication.logEnabled()) {
PPApplication.logE("ActivateProfileHelper.isAudibleSystemRingerMode", "systemRingerMode=" + systemRingerMode);
PPApplication.logE("ActivateProfileHelper.isAudibleSystemRingerMode", "systemZenMode=" + systemZenMode);
}*/
boolean audibleRingerMode;
// In AOSP, when systemZenMode == ActivateProfileHelper.ZENMODE_PRIORITY, systemRingerMode == AudioManager.RINGER_MODE_SILENT :-/
if (systemZenMode == ActivateProfileHelper.ZENMODE_PRIORITY) {
audibleRingerMode = (systemRingerMode == AudioManager.RINGER_MODE_NORMAL) ||
(systemRingerMode == AudioManager.RINGER_MODE_SILENT);
}
else
audibleRingerMode = systemRingerMode == AudioManager.RINGER_MODE_NORMAL;
boolean audibleZenMode = (systemZenMode == -1) ||
(systemZenMode == ActivateProfileHelper.ZENMODE_ALL) ||
(systemZenMode == ActivateProfileHelper.ZENMODE_PRIORITY);
return audibleRingerMode && audibleZenMode;
}
/*
private static void correctVolume0(AudioManager audioManager) {
int ringerMode, zenMode;
ringerMode = PPApplication.getRingerMode(context);
zenMode = PPApplication.getZenMode(context);
if ((ringerMode == 1) || (ringerMode == 2) || (ringerMode == 4) ||
((ringerMode == 5) && ((zenMode == 1) || (zenMode == 2)))) {
// any "nonVIBRATE" ringer mode is selected
if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
// actual system ringer mode = vibrate
// volume changed it to vibrate
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_RING, 1, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
PhoneProfilesService.ringingVolume = 1;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, 1);
}
}
}
*/
static void getMergedRingNotificationVolumes(Context context) {
synchronized (PPApplication.profileActivationMutex) {
ApplicationPreferences.prefMergedRingNotificationVolumes =
ApplicationPreferences.getSharedPreferences(context).getBoolean(PREF_MERGED_RING_NOTIFICATION_VOLUMES, true);
}
}
static boolean getMergedRingNotificationVolumes() {
//PPApplication.logE("ActivateProfileHelper.getMergedRingNotificationVolumes", "force set="+ApplicationPreferences.applicationForceSetMergeRingNotificationVolumes(context));
//PPApplication.logE("ActivateProfileHelper.getMergedRingNotificationVolumes", "merged="+ApplicationPreferences.preferences.getBoolean(PREF_MERGED_RING_NOTIFICATION_VOLUMES, true));
if (ApplicationPreferences.applicationForceSetMergeRingNotificationVolumes > 0)
return ApplicationPreferences.applicationForceSetMergeRingNotificationVolumes == 1;
else
return ApplicationPreferences.prefMergedRingNotificationVolumes;
}
// test if ring and notification volumes are merged
static void setMergedRingNotificationVolumes(Context context/*, boolean force*/) {
synchronized (PPApplication.profileActivationMutex) {
//PPApplication.logE("ActivateProfileHelper.setMergedRingNotificationVolumes", "xxx");
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context);
setMergedRingNotificationVolumes(context, /*force,*/ editor);
editor.apply();
}
}
static void setMergedRingNotificationVolumes(Context context, /*boolean force,*/ SharedPreferences.Editor editor) {
synchronized (PPApplication.profileActivationMutex) {
//PPApplication.logE("ActivateProfileHelper.setMergedRingNotificationVolumes", "xxx");
Context appContext = context.getApplicationContext();
//if (!ApplicationPreferences.getSharedPreferences(appContext).contains(PREF_MERGED_RING_NOTIFICATION_VOLUMES) || force) {
try {
boolean merged;
AudioManager audioManager = (AudioManager) appContext.getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) {
//RingerModeChangeReceiver.internalChange = true;
int ringerMode = audioManager.getRingerMode();
int maximumNotificationValue = audioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);
int oldRingVolume = audioManager.getStreamVolume(AudioManager.STREAM_RING);
int oldNotificationVolume = audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
if (oldRingVolume == oldNotificationVolume) {
int newNotificationVolume;
if (oldNotificationVolume == maximumNotificationValue)
newNotificationVolume = oldNotificationVolume - 1;
else
newNotificationVolume = oldNotificationVolume + 1;
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, newNotificationVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
PPApplication.sleep(2000);
merged = audioManager.getStreamVolume(AudioManager.STREAM_RING) == newNotificationVolume;
} else
merged = false;
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, oldNotificationVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
audioManager.setRingerMode(ringerMode);
//PPApplication.logE("ActivateProfileHelper.setMergedRingNotificationVolumes", "merged=" + merged);
editor.putBoolean(PREF_MERGED_RING_NOTIFICATION_VOLUMES, merged);
ApplicationPreferences.prefMergedRingNotificationVolumes = merged;
}
} catch (Exception e) {
//PPApplication.recordException(e);
}
//}
}
}
@SuppressLint("NewApi")
private static void setVolumes(Context context, Profile profile, AudioManager audioManager, int systemZenMode,
int linkUnlink, boolean forProfileActivation, boolean forRingerMode)
{
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile=" + profile);
if (profile == null)
return;
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile._name=" + profile._name);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "linkUnlink=" + linkUnlink);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "forProfileActivation=" + forProfileActivation);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "forRingerMode=" + forRingerMode);
Context appContext = context.getApplicationContext();
int ringerMode = ApplicationPreferences.prefRingerMode;
//PPApplication.logE("ActivateProfileHelper.setVolumes", "ringerMode=" + ringerMode);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile._volumeMuteSound=" + profile._volumeMuteSound);
if (profile._volumeMuteSound) {
if (isAudibleSystemRingerMode(audioManager, systemZenMode) || (ringerMode == 0)) {
if (!audioManager.isStreamMute(AudioManager.STREAM_RING))
audioManager.adjustStreamVolume(AudioManager.STREAM_RING, AudioManager.ADJUST_MUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (!audioManager.isStreamMute(AudioManager.STREAM_NOTIFICATION))
audioManager.adjustStreamVolume(AudioManager.STREAM_NOTIFICATION, AudioManager.ADJUST_MUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (!audioManager.isStreamMute(AudioManager.STREAM_SYSTEM))
audioManager.adjustStreamVolume(AudioManager.STREAM_SYSTEM, AudioManager.ADJUST_MUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (!audioManager.isStreamMute(AudioManager.STREAM_DTMF))
audioManager.adjustStreamVolume(AudioManager.STREAM_DTMF, AudioManager.ADJUST_MUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
if (!audioManager.isStreamMute(AudioManager.STREAM_MUSIC))
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
else {
if (isAudibleSystemRingerMode(audioManager, systemZenMode) || (ringerMode == 0)) {
if (audioManager.isStreamMute(AudioManager.STREAM_RING))
audioManager.adjustStreamVolume(AudioManager.STREAM_RING, AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (audioManager.isStreamMute(AudioManager.STREAM_NOTIFICATION))
audioManager.adjustStreamVolume(AudioManager.STREAM_NOTIFICATION, AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (audioManager.isStreamMute(AudioManager.STREAM_SYSTEM))
audioManager.adjustStreamVolume(AudioManager.STREAM_SYSTEM, AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (audioManager.isStreamMute(AudioManager.STREAM_DTMF))
audioManager.adjustStreamVolume(AudioManager.STREAM_DTMF, AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
if (audioManager.isStreamMute(AudioManager.STREAM_MUSIC))
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
// get mute state before set of all volumes; system stream may set mute to true
boolean ringMuted = audioManager.isStreamMute(AudioManager.STREAM_RING);
boolean notificationMuted = audioManager.isStreamMute(AudioManager.STREAM_NOTIFICATION);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "ring mute status="+ringMuted);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "notification mute status="+notificationMuted);
boolean systemMuted = audioManager.isStreamMute(AudioManager.STREAM_SYSTEM);
boolean dtmfMuted = audioManager.isStreamMute(AudioManager.STREAM_DTMF);
boolean musicMuted = audioManager.isStreamMute(AudioManager.STREAM_MUSIC);
if (forRingerMode) {
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeRingtoneChange()=" + profile.getVolumeRingtoneChange());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeRingtoneValue()=" + profile.getVolumeRingtoneValue());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeNotificationChange()=" + profile.getVolumeNotificationChange());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeNotificationValue()=" + profile.getVolumeNotificationValue());
if (!profile._volumeMuteSound) {
if (!ringMuted) {
if (profile.getVolumeRingtoneChange()) {
if (forProfileActivation) {
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
setRingerVolume(appContext, profile.getVolumeRingtoneValue());
}
}
}
if (!notificationMuted) {
if (profile.getVolumeNotificationChange()) {
if (forProfileActivation) {
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
setNotificationVolume(appContext, profile.getVolumeNotificationValue());
}
}
}
}
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeAccessibilityChange()=" + profile.getVolumeAccessibilityChange());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeAccessibilityValue()=" + profile.getVolumeAccessibilityValue());
if (forProfileActivation) {
if (Build.VERSION.SDK_INT >= 26) {
if (profile.getVolumeAccessibilityChange()) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_ACCESSIBILITY /* 10 */, profile.getVolumeAccessibilityValue(), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.STREAM_ACCESSIBILITY, profile.getVolumeAccessibilityValue());
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
}
//PPApplication.logE("ActivateProfileHelper.setVolumes", "isAudibleSystemRingerMode=" + isAudibleSystemRingerMode(audioManager, systemZenMode/*, appContext*/));
if (!profile._volumeMuteSound) {
//if (isAudibleRinging(ringerMode, zenMode, true) || (ringerMode == 0)) {
if (isAudibleSystemRingerMode(audioManager, systemZenMode/*, appContext*/) || (ringerMode == 0)) {
// test only system ringer mode
//PPApplication.logE("ActivateProfileHelper.setVolumes", "ringer/notification/system change");
//if (Permissions.checkAccessNotificationPolicy(context)) {
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeDTMFChange()=" + profile.getVolumeDTMFChange());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeDTMFValue()=" + profile.getVolumeDTMFValue());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeSystemChange()=" + profile.getVolumeSystemChange());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeSystemValue()=" + profile.getVolumeSystemValue());
if (forProfileActivation) {
if (!dtmfMuted) {
if (profile.getVolumeDTMFChange()) {
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
try {
audioManager.setStreamVolume(AudioManager.STREAM_DTMF /* 8 */, profile.getVolumeDTMFValue(), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_DTMF, profile.getVolumeDTMFValue());
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
if (!systemMuted) {
if (profile.getVolumeSystemChange()) {
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
try {
audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM /* 1 */, profile.getVolumeSystemValue(), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_SYSTEM, profile.getVolumeSystemValue());
//correctVolume0(audioManager);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
}
//PPApplication.logE("ActivateProfileHelper.setVolumes", "ActivateProfileHelper.getMergedRingNotificationVolumes()=" + ActivateProfileHelper.getMergedRingNotificationVolumes());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "ApplicationPreferences.applicationUnlinkRingerNotificationVolumes=" + ApplicationPreferences.applicationUnlinkRingerNotificationVolumes);
boolean volumesSet = false;
//TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (/*(telephony != null) &&*/ ActivateProfileHelper.getMergedRingNotificationVolumes() && ApplicationPreferences.applicationUnlinkRingerNotificationVolumes) {
//PPApplication.logE("ActivateProfileHelper.setVolumes", "do unlink volumes");
if ((!ringMuted) && (!notificationMuted)) {
//PPApplication.logE("ActivateProfileHelper.setVolumes", "linkUnlink=" + linkUnlink);
//int callState = telephony.getCallState();
if ((linkUnlink == PhoneCallBroadcastReceiver.LINKMODE_UNLINK)/* ||
(callState == TelephonyManager.CALL_STATE_RINGING)*/) {
// for separating ringing and notification
// in ringing state ringer volumes must by set
// and notification volumes must not by set
int volume = ApplicationPreferences.prefRingerVolume;
// PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-RINGING-unlink ringer volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING /* 2 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (PhoneProfilesService.getInstance() != null)
PhoneProfilesService.getInstance().ringingVolume = volume;
//PhoneProfilesService.notificationVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION /* 5 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
//correctVolume0(audioManager);
if (!profile.getVolumeNotificationChange())
setNotificationVolume(appContext, volume);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
volumesSet = true;
} else if (linkUnlink == PhoneCallBroadcastReceiver.LINKMODE_LINK) {
// for separating ringing and notification
// in not ringing state ringer and notification volume must by change
int volume = ApplicationPreferences.prefRingerVolume;
// PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING-link ringer volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING /* 2 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (PhoneProfilesService.getInstance() != null)
PhoneProfilesService.getInstance().ringingVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
if (!profile.getVolumeNotificationChange())
setNotificationVolume(appContext, volume);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
volume = ApplicationPreferences.prefNotificationVolume;
// PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING-link notification volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION /* 5 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//PhoneProfilesService.notificationVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
} catch (Exception e) {
PPApplication.recordException(e);
}
}
//correctVolume0(audioManager);
volumesSet = true;
} else if ((linkUnlink == PhoneCallBroadcastReceiver.LINKMODE_NONE)/* ||
(callState == TelephonyManager.CALL_STATE_IDLE)*/) {
int volume = ApplicationPreferences.prefRingerVolume;
// PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING-none ringer volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING /* 2 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (PhoneProfilesService.getInstance() != null)
PhoneProfilesService.getInstance().ringingVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, volume);
//correctVolume0(audioManager);
if (!profile.getVolumeNotificationChange())
setNotificationVolume(appContext, volume);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
volume = ApplicationPreferences.prefNotificationVolume;
// PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING-none notification volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION /* 5 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//PhoneProfilesService.notificationVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, volume);
//correctVolume0(audioManager);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
volumesSet = true;
}
}
}
if (!volumesSet) {
// reverted order for disabled unlink
int volume;
if (!ActivateProfileHelper.getMergedRingNotificationVolumes()) {
if (!notificationMuted) {
volume = ApplicationPreferences.prefNotificationVolume;
//PPApplication.logE("ActivateProfileHelper.setVolumes", "no doUnlink notification volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION /* 5 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//PhoneProfilesService.notificationVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, volume);
//correctVolume0(audioManager);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "notification volume set");
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
}
if (!ringMuted) {
volume = ApplicationPreferences.prefRingerVolume;
//PPApplication.logE("ActivateProfileHelper.setVolumes", "no doUnlink ringer volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING /* 2 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (PhoneProfilesService.getInstance() != null)
PhoneProfilesService.getInstance().ringingVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, volume);
//correctVolume0(audioManager);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "ringer volume set");
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
}
//}
//else
// PPApplication.logE("ActivateProfileHelper.setVolumes", "not granted");
}
}
}
/*if (PPApplication.logEnabled()) {
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeMediaChange()=" + profile.getVolumeMediaChange());
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeMediaValue()=" + profile.getVolumeMediaValue());
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeAlarmChange()=" + profile.getVolumeAlarmChange());
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeAlarmValue()=" + profile.getVolumeAlarmValue());
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeVoiceChange()=" + profile.getVolumeVoiceChange());
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeVoiceValue()=" + profile.getVolumeVoiceValue());
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeBluetoothSCOChange()=" + profile.getVolumeBluetoothSCOChange());
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeBluetoothSCOValue()=" + profile.getVolumeBluetoothSCOValue());
}*/
if (forProfileActivation) {
if (profile.getVolumeBluetoothSCOChange()) {
try {
audioManager.setStreamVolume(ActivateProfileHelper.STREAM_BLUETOOTH_SCO, profile.getVolumeBluetoothSCOValue(), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_VOICE, profile.getVolumeVoiceValue());
} catch (Exception e) {
PPApplication.recordException(e);
}
}
if (profile.getVolumeVoiceChange()) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL /* 0 */, profile.getVolumeVoiceValue(), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_VOICE, profile.getVolumeVoiceValue());
} catch (Exception e) {
PPApplication.recordException(e);
}
}
if (profile.getVolumeAlarmChange()) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_ALARM /* 4 */, profile.getVolumeAlarmValue(), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_ALARM, profile.getVolumeAlarmValue());
} catch (Exception e) {
PPApplication.recordException(e);
}
}
if (!profile._volumeMuteSound) {
if (!musicMuted) {
if (profile.getVolumeMediaChange()) {
setMediaVolume(appContext, audioManager, profile.getVolumeMediaValue());
}
}
}
}
//int value = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
//PPApplication.logE("[VOL] ActivateProfileHelper.setVolumes", "STREAM_VOICE_CALL="+value);
}
static void setMediaVolume(Context context, AudioManager audioManager, int value) {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "value="+value);
// Fatal Exception: java.lang.SecurityException: Only SystemUI can disable the safe media volume:
// Neither user 10118 nor current process has android.permission.STATUS_BAR_SERVICE.
try {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "set media volume (1)");
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC /* 3 */, value, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_MUSIC, profile.getVolumeMediaValue());
} catch (SecurityException e) {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "set media volume (1) - SecurityException");
//PPApplication.recordException(e);
Context appContext = context.getApplicationContext();
// adb shell pm grant sk.henrichg.phoneprofilesplus android.permission.WRITE_SECURE_SETTINGS
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "WRITE_SECURE_SETTINGS granted");
try {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "disable safe volume without root");
Settings.Global.putInt(appContext.getContentResolver(), "audio_safe_volume_state", 2);
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "set media volume (2)");
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC /* 3 */, value, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
catch (Exception e2) {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "set media volume (2) - Exception");
PPApplication.recordException(e2);
}
}
else {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "WRITE_SECURE_SETTINGS NOT granted");
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false))) {
synchronized (PPApplication.rootMutex) {
String command1 = "settings put global audio_safe_volume_state 2";
Command command = new Command(0, false, command1);
try {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "disable safe volume with root");
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setMediaVolume");
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "set media volume (3)");
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC /* 3 */, value, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
} catch (Exception ee) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//PPApplication.recordException(e);;
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "set media volume (3) - Exception");
}
}
}
}
} catch (Exception e3) {
PPApplication.recordException(e3);
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "set media volume (1) - Exception");
}
}
/*
private static void setZenMode(Context context, int zenMode, AudioManager audioManager, int systemZenMode, int ringerMode)
{
//if (android.os.Build.VERSION.SDK_INT >= 21)
//{
//if (PPApplication.logEnabled()) {
// PPApplication.logE("ActivateProfileHelper.setZenMode", "zenMode=" + zenMode);
// PPApplication.logE("ActivateProfileHelper.setZenMode", "ringerMode=" + ringerMode);
//}
Context appContext = context.getApplicationContext();
//int systemZenMode = getSystemZenMode(appContext); //, -1);
//PPApplication.logE("ActivateProfileHelper.setZenMode", "systemZenMode=" + systemZenMode);
//int systemRingerMode = audioManager.getRingerMode();
//PPApplication.logE("ActivateProfileHelper.setZenMode", "systemRingerMode=" + systemRingerMode);
if ((zenMode != ZENMODE_SILENT) && canChangeZenMode(appContext)) {
//PPApplication.logE("ActivateProfileHelper.setZenMode", "not ZENMODE_SILENT and can change zen mode");
try {
if (ringerMode != -1) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
audioManager.setRingerMode(ringerMode);
if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) {
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
}
else {
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
}
//if (!((zenMode == ZENMODE_PRIORITY) && (ringerMode == AudioManager.RINGER_MODE_VIBRATE))) {
PPApplication.sleep(500);
//}
}
if ((zenMode != systemZenMode) || (zenMode == ZENMODE_PRIORITY)) {
//PPApplication.logE("ActivateProfileHelper.setZenMode", "change zen mode");
RingerModeChangeReceiver.notUnlinkVolumes = false;
PPNotificationListenerService.requestInterruptionFilter(appContext, zenMode);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, zenMode);
}
//if (zenMode == ZENMODE_PRIORITY) {
// PPApplication.logE("ActivateProfileHelper.setZenMode", "change ringer mode");
// PPApplication.sleep(1000);
// //audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
// audioManager.setRingerMode(ringerMode);
//}
} catch (Exception e) {
PPApplication.recordException(e);
}
} else {
//PPApplication.logE("ActivateProfileHelper.setZenMode", "ZENMODE_SILENT or not can change zen mode");
try {
//noinspection SwitchStatementWithTooFewBranches
switch (zenMode) {
case ZENMODE_SILENT:
//audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
//PPApplication.sleep(1000);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
if ((systemZenMode != ZENMODE_ALL) && canChangeZenMode(appContext)) {
//PPApplication.logE("ActivateProfileHelper.setZenMode", "change zen mode");
RingerModeChangeReceiver.notUnlinkVolumes = false;
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALL);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALL);
PPApplication.sleep(500);
}
RingerModeChangeReceiver.notUnlinkVolumes = false;
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
break;
default:
RingerModeChangeReceiver.notUnlinkVolumes = false;
audioManager.setRingerMode(ringerMode);
}
} catch (Exception e) {
// may be produced this exception:
//
// java.lang.SecurityException: Not allowed to change Do Not Disturb state
//
// when changed is ringer mode in activated Do not disturb and
// GlobalGUIRoutines.activityActionExists(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS, context) returns false.
PPApplication.recordException(e);
}
}
//}
//else {
// RingerModeChangeReceiver.notUnlinkVolumes = false;
// audioManager.setRingerMode(ringerMode);
//}
}
*/
private static void setVibrateWhenRinging(Context context, Profile profile, int value) {
// if (PPApplication.logEnabled()) {
// PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "profile=" + profile);
// PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "value=" + value);
// }
int lValue = value;
if (profile != null) {
switch (profile._vibrateWhenRinging) {
case 1:
lValue = 1;
break;
case 2:
lValue = 0;
break;
}
}
// PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "lValue="+lValue);
if (lValue != -1) {
Context appContext = context.getApplicationContext();
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_VIBRATE_WHEN_RINGING, null, null, false, appContext).allowed
== PreferenceAllowed.PREFERENCE_ALLOWED) {
if (Permissions.checkVibrateWhenRinging(appContext)) {
/*if (android.os.Build.VERSION.SDK_INT < 23) { // Not working in Android M (exception)
Settings.System.putInt(appContext.getContentResolver(), "vibrate_when_ringing", lValue);
//PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "vibrate when ringing set (API < 23)");
}
else {*/
/*if (PPApplication.romIsMIUI) {
PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging",
"vibrate_in_normal="+Settings.System.getInt(context.getContentResolver(), "vibrate_in_normal",-1));
PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging",
"vibrate_in_silent="+Settings.System.getInt(context.getContentResolver(), "vibrate_in_silent",-1));
}
else*/ {
try {
Settings.System.putInt(appContext.getContentResolver(), Settings.System.VIBRATE_WHEN_RINGING, lValue);
if (PPApplication.deviceIsXiaomi && PPApplication.romIsMIUI) {
//PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "Xiaomi");
Settings.System.putInt(appContext.getContentResolver(), "vibrate_in_normal", lValue);
Settings.System.putInt(appContext.getContentResolver(), "vibrate_in_silent", lValue);
}
//PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "vibrate when ringing set (API >= 23)");
} catch (Exception ee) {
// java.lang.IllegalArgumentException: You cannot change private secure settings.
//Log.e("ActivateProfileHelper.setVibrateWhenRinging", Log.getStackTraceString(ee));
//PPApplication.recordException(ee);
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false))) {
synchronized (PPApplication.rootMutex) {
String command1;
Command command;
if (PPApplication.deviceIsXiaomi && PPApplication.romIsMIUI) {
command1 = "settings put system " + Settings.System.VIBRATE_WHEN_RINGING + " " + lValue;
String command2 = "settings put system " + "vibrate_in_normal" + " " + lValue;
String command3 = "settings put system " + "vibrate_in_silent" + " " + lValue;
command = new Command(0, false, command1, command2, command3);
} else {
command1 = "settings put system " + Settings.System.VIBRATE_WHEN_RINGING + " " + lValue;
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
command = new Command(0, false, command1); //, command2);
}
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setVibrationWhenRinging");
//PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "vibrate when ringing set (API >= 23 with root)");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setVibrateWhenRinging", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
//else
//PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "not rooted");
}
}
//}
}
//else
// PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "not permission granted");
}
//else
// PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "not profile preferences allowed");
}
}
private static boolean setTones(Context context, Profile profile) {
boolean noError = true;
Context appContext = context.getApplicationContext();
if (Permissions.checkProfileRingtones(appContext, profile, null)) {
if (profile._soundRingtoneChange == 1) {
if (!profile._soundRingtone.isEmpty()) {
try {
String[] splits = profile._soundRingtone.split("\\|");
if (!splits[0].isEmpty()) {
//Uri uri = Uri.parse(splits[0]);
Uri uri = getUriOfSavedTone(context, splits[0], RingtoneManager.TYPE_RINGTONE);
//TODO je mozne, ze to Uri z RingtoneManagera je uz grantnute, tak toto nebude treba robit.
try {
ContentResolver contentResolver = context.getContentResolver();
context.grantUriPermission(PPApplication.PACKAGE_NAME, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
//PPApplication.logE("ActivateProfileHelper.setTones", "ring tone granted");
} catch (Exception e) {
// java.lang.SecurityException: UID 10157 does not have permission to
// content://com.android.externalstorage.documents/document/93ED-1CEC%3AMirek%2Fmobil%2F.obr%C3%A1zek%2Fblack.jpg
// [user 0]; you could obtain access using ACTION_OPEN_DOCUMENT or related APIs
//Log.e("ActivateProfileHelper.setTones (1)", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
/*
if (PPApplication.deviceIsSamsung && (uri != null)) {
//Settings.System.putString(context.getContentResolver(), "ringtone_set", "1");
//Settings.System.putString(context.getContentResolver(), "ringtone_2_set", "1");
Log.e("ActivateProfileHelper.setTones", "ringtone Samsung uri="+uri.toString());
try {
uri = ContentProvider.maybeAddUserId(uri, context.getUserId());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone_2", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else
if (PPApplication.deviceIsHuawei && (PPApplication.romIsEMUI) && (uri != null)) {
Log.e("ActivateProfileHelper.setTones", "ringtone Huawei uri="+uri.toString());
try {
uri = ContentProvider.maybeAddUserId(uri, context.getUserId());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone2", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else
if (PPApplication.deviceIsXiaomi && (PPApplication.romIsMIUI) && (uri != null)) {
Log.e("ActivateProfileHelper.setTones", "ringtone Xiaomi uri="+uri.toString());
try {
uri = ContentProvider.maybeAddUserId(uri, context.getUserId());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone_sound_slot_1", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone_sound_use_uniform", "0");
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone_sound_slot_2", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else*/
RingtoneManager.setActualDefaultRingtoneUri(appContext, RingtoneManager.TYPE_RINGTONE, uri);
}
}
catch (IllegalArgumentException e) {
// java.lang.IllegalArgumentException: Invalid column: _data
//Log.e("ActivateProfileHelper.setTones (2)", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
catch (Exception e){
//Log.e("ActivateProfileHelper.setTones (3)", Log.getStackTraceString(e));
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_SET_TONE_RINGTONE, null,
profile._name, profile._icon, 0, "");
noError = false;
/*String[] splits = profile._soundRingtone.split("\\|");
if (!splits[0].isEmpty()) {
try {
boolean found = false;
RingtoneManager manager = new RingtoneManager(context);
Cursor cursor = manager.getCursor();
while (cursor.moveToNext()) {
String _uri = cursor.getString(RingtoneManager.URI_COLUMN_INDEX);
if (_uri.equals(splits[0])) {
// uri exists in RingtoneManager
found = true;
break;
}
}
if (found) {
PPApplication.setCustomKey("ActivateProfileHelper_setTone", splits[0]);
PPApplication.recordException(e);
}
} catch (Exception ee) {
PPApplication.setCustomKey("ActivateProfileHelper_setTone", splits[0]);
PPApplication.recordException(e);
}
} else
PPApplication.recordException(e);*/
}
} else {
// selected is None tone
try {
/*if (PPApplication.deviceIsSamsung) {
Log.e("ActivateProfileHelper.setTones", "ringtone Samsung uri=null");
try {
Settings.System.putString(context.getContentResolver(), "ringtone", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1 - NULL", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone_2", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2 - NULL", Log.getStackTraceString(e));
}
}
else
if (PPApplication.deviceIsHuawei && (PPApplication.romIsEMUI)) {
Log.e("ActivateProfileHelper.setTones", "ringtone Huawei uri=null");
try {
Settings.System.putString(context.getContentResolver(), "ringtone", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1 - NULL", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone2", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2 - NULL", Log.getStackTraceString(e));
}
}
else
if (PPApplication.deviceIsXiaomi && (PPApplication.romIsMIUI)) {
Log.e("ActivateProfileHelper.setTones", "ringtone Xiaomi uri=null");
try {
Settings.System.putString(context.getContentResolver(), "ringtone_sound_slot_1", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone_sound_use_uniform", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone_sound_slot_2", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else*/
RingtoneManager.setActualDefaultRingtoneUri(appContext, RingtoneManager.TYPE_RINGTONE, null);
}
catch (IllegalArgumentException e) {
// java.lang.IllegalArgumentException: Invalid column: _data
//PPApplication.recordException(e);
}
catch (Exception e){
PPApplication.recordException(e);
noError = false;
}
}
}
if (profile._soundNotificationChange == 1) {
if (!profile._soundNotification.isEmpty()) {
try {
String[] splits = profile._soundNotification.split("\\|");
if (!splits[0].isEmpty()) {
//Uri uri = Uri.parse(splits[0]);
Uri uri = getUriOfSavedTone(context, splits[0], RingtoneManager.TYPE_NOTIFICATION);
//TODO je mozne, ze to Uri z RingtoneManagera je uz grantnute, tak toto nebude treba robit.
try {
ContentResolver contentResolver = context.getContentResolver();
context.grantUriPermission(PPApplication.PACKAGE_NAME, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
//PPApplication.logE("ActivateProfileHelper.setTones", "notification tone granted");
} catch (Exception e) {
// java.lang.SecurityException: UID 10157 does not have permission to
// content://com.android.externalstorage.documents/document/93ED-1CEC%3AMirek%2Fmobil%2F.obr%C3%A1zek%2Fblack.jpg
// [user 0]; you could obtain access using ACTION_OPEN_DOCUMENT or related APIs
//Log.e("BitmapManipulator.resampleBitmapUri", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
/*if (PPApplication.deviceIsSamsung && (uri != null)) {
//Settings.System.putString(context.getContentResolver(), "ringtone_set", "1");
//Settings.System.putString(context.getContentResolver(), "ringtone_2_set", "1");
Log.e("ActivateProfileHelper.setTones", " notification Samsung uri="+uri.toString());
try {
uri = ContentProvider.maybeAddUserId(uri, context.getUserId());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "notification_sound", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "notification_sound_2", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else
if (PPApplication.deviceIsHuawei && (PPApplication.romIsEMUI) && (uri != null)) {
Log.e("ActivateProfileHelper.setTones", "notification Huawei uri="+uri.toString());
// notifikacie ine ako sms - zvlastna katergoria v Huawei
//Settings.System.putString(context.getContentResolver(), "notification_sound", uri.toString());
try {
uri = ContentProvider.maybeAddUserId(uri, context.getUserId());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "message", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "messageSub1", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else*/
// Xiaomi devices do not has dual sim notifications
RingtoneManager.setActualDefaultRingtoneUri(appContext, RingtoneManager.TYPE_NOTIFICATION, uri);
}
}
catch (IllegalArgumentException e) {
// java.lang.IllegalArgumentException: Invalid column: _data
//PPApplication.recordException(e);
}
catch (Exception e){
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_SET_TONE_NOTIFICATION, null,
profile._name, profile._icon, 0, "");
noError = false;
/*String[] splits = profile._soundNotification.split("\\|");
if (!splits[0].isEmpty()) {
try {
boolean found = false;
RingtoneManager manager = new RingtoneManager(context);
Cursor cursor = manager.getCursor();
while (cursor.moveToNext()) {
String _uri = cursor.getString(RingtoneManager.URI_COLUMN_INDEX);
if (_uri.equals(splits[0])) {
// uri exists in RingtoneManager
found = true;
break;
}
}
if (found) {
PPApplication.setCustomKey("ActivateProfileHelper_setTone", splits[0]);
PPApplication.recordException(e);
}
} catch (Exception ee) {
PPApplication.setCustomKey("ActivateProfileHelper_setTone", splits[0]);
PPApplication.recordException(e);
}
} else
PPApplication.recordException(e);*/
}
} else {
// selected is None tone
try {
/*if (PPApplication.deviceIsSamsung) {
//Settings.System.putString(context.getContentResolver(), "ringtone_set", "1");
//Settings.System.putString(context.getContentResolver(), "ringtone_2_set", "1");
Log.e("ActivateProfileHelper.setTones", " notification Samsung uri=null");
try {
Settings.System.putString(context.getContentResolver(), "notification_sound", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "notification_sound_2", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else
if (PPApplication.deviceIsHuawei && (PPApplication.romIsEMUI)) {
Log.e("ActivateProfileHelper.setTones", "notification Huawei uri=null");
// notifikacie ine ako sms - zvlastna katergoria v Huawei
//Settings.System.putString(context.getContentResolver(), "notification_sound", null);
try {
Settings.System.putString(context.getContentResolver(), "message", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "messageSub1", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else*/
// Xiaomi devices do not has dual sim notifications
RingtoneManager.setActualDefaultRingtoneUri(appContext, RingtoneManager.TYPE_NOTIFICATION, null);
}
catch (IllegalArgumentException e) {
// java.lang.IllegalArgumentException: Invalid column: _data
//PPApplication.recordException(e);
}
catch (Exception e){
PPApplication.recordException(e);
noError = false;
}
}
}
if (profile._soundAlarmChange == 1) {
if (!profile._soundAlarm.isEmpty()) {
try {
String[] splits = profile._soundAlarm.split("\\|");
if (!splits[0].isEmpty()) {
//Uri uri = Uri.parse(splits[0]);
Uri uri = getUriOfSavedTone(context, splits[0], RingtoneManager.TYPE_ALARM);
//TODO je mozne, ze to Uri z RingtoneManagera je uz grantnute, tak toto nebude treba robit.
try {
ContentResolver contentResolver = context.getContentResolver();
context.grantUriPermission(PPApplication.PACKAGE_NAME, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
//PPApplication.logE("ActivateProfileHelper.setTones", "alarm tone granted");
} catch (Exception e) {
// java.lang.SecurityException: UID 10157 does not have permission to
// content://com.android.externalstorage.documents/document/93ED-1CEC%3AMirek%2Fmobil%2F.obr%C3%A1zek%2Fblack.jpg
// [user 0]; you could obtain access using ACTION_OPEN_DOCUMENT or related APIs
//Log.e("BitmapManipulator.resampleBitmapUri", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
//Settings.System.putString(context.getContentResolver(), Settings.System.RINGTONE, splits[0]);
RingtoneManager.setActualDefaultRingtoneUri(appContext, RingtoneManager.TYPE_ALARM, uri);
}
}
catch (IllegalArgumentException e) {
// java.lang.IllegalArgumentException: Invalid column: _data
//PPApplication.recordException(e);
}
catch (Exception e){
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_SET_TONE_ALARM, null,
profile._name, profile._icon, 0, "");
noError = false;
/*String[] splits = profile._soundAlarm.split("\\|");
if (!splits[0].isEmpty()) {
try {
boolean found = false;
RingtoneManager manager = new RingtoneManager(context);
Cursor cursor = manager.getCursor();
while (cursor.moveToNext()) {
String _uri = cursor.getString(RingtoneManager.URI_COLUMN_INDEX);
if (_uri.equals(splits[0])) {
// uri exists in RingtoneManager
found = true;
break;
}
}
if (found) {
PPApplication.setCustomKey("ActivateProfileHelper_setTone", splits[0]);
PPApplication.recordException(e);
}
} catch (Exception ee) {
PPApplication.setCustomKey("ActivateProfileHelper_setTone", splits[0]);
PPApplication.recordException(e);
}
} else
PPApplication.recordException(e);*/
}
} else {
// selected is None tone
try {
//Settings.System.putString(context.getContentResolver(), Settings.System.ALARM_ALERT, null);
RingtoneManager.setActualDefaultRingtoneUri(appContext, RingtoneManager.TYPE_ALARM, null);
}
catch (IllegalArgumentException e) {
// java.lang.IllegalArgumentException: Invalid column: _data
//PPApplication.recordException(e);
}
catch (Exception e){
PPApplication.recordException(e);
noError = false;
}
}
}
}
return noError;
}
private static Uri getUriOfSavedTone(Context context, String savedTone, int toneType) {
Log.e("ActivateProfileHelper.getUriOfSavedTone", "savedTone="+savedTone);
Uri toneUri;
boolean uriFound = false;
if (savedTone.equals("")) {
toneUri = null;
uriFound = true;
}
else
if (savedTone.equals(Settings.System.DEFAULT_RINGTONE_URI.toString())) {
toneUri = Settings.System.DEFAULT_RINGTONE_URI;
uriFound = true;
}
else
if (savedTone.equals(Settings.System.DEFAULT_NOTIFICATION_URI.toString())) {
toneUri = Settings.System.DEFAULT_NOTIFICATION_URI;
uriFound = true;
}
else
if (savedTone.equals(Settings.System.DEFAULT_ALARM_ALERT_URI.toString())) {
toneUri = Settings.System.DEFAULT_ALARM_ALERT_URI;
uriFound = true;
}
else {
toneUri = null;
RingtoneManager manager = new RingtoneManager(context.getApplicationContext());
manager.setType(toneType);
Cursor ringtoneCursor = manager.getCursor();
while (ringtoneCursor.moveToNext()) {
Uri _toneUri = manager.getRingtoneUri(ringtoneCursor.getPosition());
String _uri = ringtoneCursor.getString(RingtoneManager.URI_COLUMN_INDEX);
String _id = ringtoneCursor.getString(RingtoneManager.ID_COLUMN_INDEX);
String toneFromCursor = _uri + "/" + _id;
if (toneFromCursor.equals(savedTone)) {
toneUri = _toneUri;
uriFound = true;
break;
}
}
}
if (toneUri != null)
Log.e("ActivateProfileHelper.getUriOfSavedTone", "toneUri="+toneUri.toString());
Log.e("ActivateProfileHelper.getUriOfSavedTone", "uriFound="+uriFound);
if (uriFound)
return toneUri;
else
return null;
}
static void executeForVolumes(final Profile profile, final int linkUnlinkVolumes, final boolean forProfileActivation, Context context) {
// if (PPApplication.logEnabled()) {
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "profile=" + profile);
// if (profile != null)
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "profile._name=" + profile._name);
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "linkUnlinkVolumes=" + linkUnlinkVolumes);
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "forProfileActivation=" + forProfileActivation);
// }
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadVolumes();
final Handler handler = new Handler(PPApplication.handlerThreadVolumes.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadVolumes", "START run - from=ActivateProfileHelper.executeForVolumes");
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_executeForVolumes");
wakeLock.acquire(10 * 60 * 1000);
}
int linkUnlink = PhoneCallBroadcastReceiver.LINKMODE_NONE;
if (ActivateProfileHelper.getMergedRingNotificationVolumes() &&
ApplicationPreferences.applicationUnlinkRingerNotificationVolumes) {
if (Permissions.checkPhone(appContext))
linkUnlink = linkUnlinkVolumes;
}
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "linkUnlink=" + linkUnlink);
if (profile != null) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "setTones() 1");
boolean noErrorSetTone = setTones(appContext, profile);
final AudioManager audioManager = (AudioManager) appContext.getSystemService(Context.AUDIO_SERVICE);
if ((profile._volumeRingerMode != 0) ||
profile.getVolumeRingtoneChange() ||
profile.getVolumeNotificationChange() ||
profile.getVolumeSystemChange() ||
profile.getVolumeDTMFChange()) {
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "change ringer mode");
//if (Permissions.checkProfileAccessNotificationPolicy(context, profile, null)) {
if (canChangeZenMode(appContext)) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "can change zen mode");
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "changeRingerModeForVolumeEqual0()");
changeRingerModeForVolumeEqual0(profile, audioManager, appContext);
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "changeNotificationVolumeForVolumeEqual0()");
changeNotificationVolumeForVolumeEqual0(/*context,*/ profile);
RingerModeChangeReceiver.internalChange = true;
//int systemZenMode = getSystemZenMode(appContext/*, -1*/);
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "setRingerMode()");
setRingerMode(appContext, profile, audioManager, /*systemZenMode,*/ forProfileActivation);
// get actual system zen mode (may be changed in setRingerMode())
int systemZenMode = getSystemZenMode(appContext/*, -1*/);
//PPApplication.logE("ActivateProfileHelper.executeForVolumes", "internalChange=" + RingerModeChangeReceiver.internalChange);
PPApplication.sleep(500);
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "setVolumes()");
setVolumes(appContext, profile, audioManager, systemZenMode, linkUnlink, forProfileActivation, true);
//PPApplication.logE("ActivateProfileHelper.executeForVolumes", "internalChange=" + RingerModeChangeReceiver.internalChange);
PPApplication.sleep(500);
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "start internal change work");
DisableInternalChangeWorker.enqueueWork();
/*PPApplication.startHandlerThreadInternalChangeToFalse();
final Handler handler = new Handler(PPApplication.handlerThreadInternalChangeToFalse.getLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "disable ringer mode change internal change");
RingerModeChangeReceiver.internalChange = false;
}
}, 3000);*/
//PostDelayedBroadcastReceiver.setAlarm(
// PostDelayedBroadcastReceiver.ACTION_RINGER_MODE_INTERNAL_CHANGE_TO_FALSE, 3, context);
}
}
else
/*if (profile.getVolumeMediaChange() ||
profile.getVolumeAlarmChange() ||
profile.getVolumeVoiceChange() ||
profile.getVolumeAccessibilityChange() ||
profile.getVolumeBluetoothSCOChange())*/ {
// call setVolume() for "Mute sound"
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "do not change ringer mode");
int systemZenMode = getSystemZenMode(appContext/*, -1*/);
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "setVolumes()");
setVolumes(appContext, profile, audioManager, systemZenMode, linkUnlink, forProfileActivation, false);
}
/*else {
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "ringer mode and volumes are not configured");
}*/
/*
if (profile._volumeSpeakerPhone != 0) {
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "profile._volumeSpeakerPhone="+profile._volumeSpeakerPhone);
boolean savedSpeakerphone = false; audioManager.isSpeakerphoneOn();
boolean changeSpeakerphone = false;
if (savedSpeakerphone && (profile._volumeSpeakerPhone == 2)) // 2=speakerphone off
changeSpeakerphone = true;
if ((!savedSpeakerphone) && (profile._volumeSpeakerPhone == 1)) // 1=speakerphone on
changeSpeakerphone = true;
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "changeSpeakerphone="+changeSpeakerphone);
if (changeSpeakerphone) {
/// activate SpeakerPhone
// not working in EMUI :-/
audioManager.setMode(AudioManager.MODE_IN_CALL);
// Delay 2 seconds mode changed to MODE_IN_CALL
long start = SystemClock.uptimeMillis();
do {
if (audioManager.getMode() != AudioManager.MODE_IN_CALL) {
//if (audioManager.getMode() != AudioManager.MODE_IN_COMMUNICATION) {
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "xxx - audio mode MODE_IN_CALL="+(audioManager.getMode() == AudioManager.MODE_IN_CALL));
//PPApplication.logE("PhoneCallBroadcastReceiver.callAnswered", "xxx - audio mode MODE_IN_COMMUNICATION="+(audioManager.getMode() == AudioManager.MODE_IN_COMMUNICATION));
PPApplication.sleep(500);
}
else
break;
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "SystemClock.uptimeMillis() - start="+(SystemClock.uptimeMillis() - start));
} while (SystemClock.uptimeMillis() - start < (5 * 1000));
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "yyy - audio mode MODE_IN_CALL="+(audioManager.getMode() == AudioManager.MODE_IN_CALL));
//PPApplication.logE("ActivateProfileHelper.executeForVolumes", "yyy - audio mode MODE_IN_COMMUNICATION="+(audioManager.getMode() == AudioManager.MODE_IN_COMMUNICATION));
PPApplication.sleep(500);
audioManager.setSpeakerphoneOn(profile._volumeSpeakerPhone == 1);
//PhoneCallBroadcastReceiver.speakerphoneSelected = true;
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "ACTIVATED SPEAKERPHONE");
}
}
*/
if (noErrorSetTone) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "setTones() 2");
setTones(appContext, profile);
}
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "end");
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
});
}
private static void setNotificationLed(Context context, final int value) {
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadProfileActivation();
final Handler handler = new Handler(PPApplication.handlerThreadProfileActivation.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadProfileActivation", "START run - from=ActivateProfileHelper.setNotificationLed");
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_setNotificationLed");
wakeLock.acquire(10 * 60 * 1000);
}
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_NOTIFICATION_LED, null, null, false, appContext).allowed
== PreferenceAllowed.PREFERENCE_ALLOWED) {
//if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception)
// Settings.System.putInt(appContext.getContentResolver(), "notification_light_pulse"/*Settings.System.NOTIFICATION_LIGHT_PULSE*/, value);
//else {
/* not working (private secure settings) :-/
if (Permissions.hasPermission(context, Manifest.permission.WRITE_SECURE_SETTINGS)) {
Settings.System.putInt(context.getContentResolver(), "notification_light_pulse", value);
}
else*/
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false))) {
synchronized (PPApplication.rootMutex) {
String command1 = "settings put system " + "notification_light_pulse"/*Settings.System.NOTIFICATION_LIGHT_PULSE*/ + " " + value;
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setNotificationLed");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setNotificationLed", Log.getStackTraceString(e));
//PPApplication.recordException(e);;
}
}
}
//}
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
});
}
private static void setHeadsUpNotifications(Context context, final int value) {
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadProfileActivation();
final Handler handler = new Handler(PPApplication.handlerThreadProfileActivation.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadProfileActivation", "START run - from=ActivateProfileHelper.setHeadsUpNotifications");
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_setHeadsUpNotifications");
wakeLock.acquire(10 * 60 * 1000);
}
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_HEADS_UP_NOTIFICATIONS, null, null, false, appContext).allowed
== PreferenceAllowed.PREFERENCE_ALLOWED) {
//if (android.os.Build.VERSION.SDK_INT >= 21) {
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
Global.putInt(appContext.getContentResolver(), "heads_up_notifications_enabled", value);
} else {
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false))) {
synchronized (PPApplication.rootMutex) {
String command1 = "settings put global " + "heads_up_notifications_enabled" + " " + value;
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setHeadsUpNotifications");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setHeadsUpNotifications", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
}
//}
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {
}
}
}
});
}
private static void setAlwaysOnDisplay(Context context, final int value) {
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadProfileActivation();
final Handler handler = new Handler(PPApplication.handlerThreadProfileActivation.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadProfileActivation", "START run - from=ActivateProfileHelper.setAlwaysOnDisplay");
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_setAlwaysOnDisplay");
wakeLock.acquire(10 * 60 * 1000);
}
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_ALWAYS_ON_DISPLAY, null, null, false, appContext).allowed
== PreferenceAllowed.PREFERENCE_ALLOWED) {
/* not working (private secure settings) :-/
if (Permissions.hasPermission(context, Manifest.permission.WRITE_SECURE_SETTINGS)) {
Settings.System.putInt(context.getContentResolver(), "aod_mode", value);
}
else*/
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false))) {
synchronized (PPApplication.rootMutex) {
String command1 = "settings put system " + "aod_mode" + " " + value;
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setAlwaysOnDisplay");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setAlwaysOnDisplay", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
});
}
private static void setScreenOnPermanent(Profile profile, Context context) {
//PPApplication.logE("******** ActivateProfileHelper.setScreenOnPermanent", "profile._screenOnPermanent="+profile._screenOnPermanent);
if (Permissions.checkProfileScreenOnPermanent(context, profile, null)) {
if (profile._screenOnPermanent == 1)
createKeepScreenOnView(context);
else if (profile._screenOnPermanent == 2)
removeKeepScreenOnView(context);
}
}
private static void changeRingerModeForVolumeEqual0(Profile profile, AudioManager audioManager, Context context) {
/*if (PPApplication.logEnabled()) {
PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "volumeRingtoneChange=" + profile.getVolumeRingtoneChange());
PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "volumeRingtoneValue=" + profile.getVolumeRingtoneValue());
}*/
//profile._ringerModeForZenMode = AudioManager.RINGER_MODE_NORMAL;
if (profile.getVolumeRingtoneChange()) {
if (profile.getVolumeRingtoneValue() == 0) {
profile.setVolumeRingtoneValue(1);
if (!profile._volumeMuteSound) {
//profile._ringerModeForZenMode = AudioManager.RINGER_MODE_SILENT;
// for profile ringer/zen mode = "only vibrate" do not change ringer mode to Silent
if (!isVibrateRingerMode(profile._volumeRingerMode/*, profile._volumeZenMode*/)) {
if (isAudibleRinging(profile._volumeRingerMode, profile._volumeZenMode/*, false*/)) {
// change ringer mode to Silent
//PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "changed to silent");
profile._volumeRingerMode = Profile.RINGERMODE_SILENT;
}// else
// PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "not audible ringer mode in profile");
}// else
// PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "vibrate ringer mode in profile");
}
} else {
if (profile._volumeRingerMode == 0) {
// ringer mode is not changed by profile, use system ringer and zen mode
if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
int systemZenMode = getSystemZenMode(context/*, -1*/);
if (!isAudibleSystemRingerMode(audioManager, systemZenMode/*, context*/)) {
// change ringer mode to ringing becaiuse configured is ringing volume
// Priority zen mode is audible. DO NOT DISABLE IT !!!
//PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "system ringer mode is not audible - changed to ringing");
profile._volumeRingerMode = Profile.RINGERMODE_RING;
}
}
}
}
}
}
private static boolean checkAccessNotificationPolicy(Context context) {
Context appContext = context.getApplicationContext();
try {
NotificationManager mNotificationManager = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
boolean granted = false;
if (mNotificationManager != null)
granted = mNotificationManager.isNotificationPolicyAccessGranted();
//if (granted)
// setShowRequestAccessNotificationPolicyPermission(context, true);
return granted;
} catch (Exception e) {
return false;
}
}
static boolean canChangeZenMode(Context context/*, boolean notCheckAccess*/) {
Context appContext = context.getApplicationContext();
//if (android.os.Build.VERSION.SDK_INT >= 23) {
boolean no60 = !Build.VERSION.RELEASE.equals("6.0");
if (no60 && GlobalGUIRoutines.activityActionExists(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS, context)) {
//if (notCheckAccess)
// return true;
//else
return checkAccessNotificationPolicy(appContext);
//return Permissions.checkAccessNotificationPolicy(appContext);
}
else
return PPNotificationListenerService.isNotificationListenerServiceEnabled(appContext, false);
//}
//else
//if (android.os.Build.VERSION.SDK_INT >= 21)
// return PPNotificationListenerService.isNotificationListenerServiceEnabled(appContext);
//return false;
}
private static void changeNotificationVolumeForVolumeEqual0(Profile profile) {
//if (PPApplication.logEnabled()) {
//PPApplication.logE("ActivateProfileHelper.changeNotificationVolumeForVolumeEqual0", "volumeNotificationChange=" + profile.getVolumeNotificationChange());
//PPApplication.logE("ActivateProfileHelper.changeNotificationVolumeForVolumeEqual0", "mergedRingNotificationVolumes=" + getMergedRingNotificationVolumes(context));
//PPApplication.logE("ActivateProfileHelper.changeNotificationVolumeForVolumeEqual0", "volumeNotificationValue=" + profile.getVolumeNotificationValue());
//}
if (profile.getVolumeNotificationChange() && ActivateProfileHelper.getMergedRingNotificationVolumes()) {
if (profile.getVolumeNotificationValue() == 0) {
//PPApplication.logE("ActivateProfileHelper.changeNotificationVolumeForVolumeEqual0", "changed notification value to 1");
profile.setVolumeNotificationValue(1);
}
}
}
@SuppressLint("SwitchIntDef")
static int getSystemZenMode(Context context/*, int defaultValue*/) {
Context appContext = context.getApplicationContext();
//if (android.os.Build.VERSION.SDK_INT >= 23) {
boolean no60 = !Build.VERSION.RELEASE.equals("6.0");
//PPApplication.logE("ActivateProfileHelper.getSystemZenMode", "no60="+no60);
boolean activityExists = GlobalGUIRoutines.activityActionExists(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS, context);
//PPApplication.logE("ActivateProfileHelper.getSystemZenMode", "activityExists="+activityExists);
if (no60 && activityExists) {
NotificationManager mNotificationManager = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
//PPApplication.logE("ActivateProfileHelper.getSystemZenMode", "mNotificationManager="+mNotificationManager);
if (mNotificationManager != null) {
int interruptionFilter = mNotificationManager.getCurrentInterruptionFilter();
//PPApplication.logE("ActivateProfileHelper.getSystemZenMode", "interruptionFilter="+interruptionFilter);
switch (interruptionFilter) {
case NotificationManager.INTERRUPTION_FILTER_ALARMS:
return ActivateProfileHelper.ZENMODE_ALARMS;
case NotificationManager.INTERRUPTION_FILTER_NONE:
return ActivateProfileHelper.ZENMODE_NONE;
case NotificationManager.INTERRUPTION_FILTER_PRIORITY:
return ActivateProfileHelper.ZENMODE_PRIORITY;
case NotificationManager.INTERRUPTION_FILTER_ALL:
case NotificationManager.INTERRUPTION_FILTER_UNKNOWN:
default:
return ActivateProfileHelper.ZENMODE_ALL;
}
}
}
else {
ContentResolver resolver = appContext.getContentResolver();
if (resolver != null) {
int interruptionFilter = Settings.Global.getInt(resolver, "zen_mode", -1);
switch (interruptionFilter) {
case 0:
return ActivateProfileHelper.ZENMODE_ALL;
case 1:
return ActivateProfileHelper.ZENMODE_PRIORITY;
case 2:
return ActivateProfileHelper.ZENMODE_NONE;
case 3:
return ActivateProfileHelper.ZENMODE_ALARMS;
}
}
}
/*}
if (android.os.Build.VERSION.SDK_INT < 23) {
int interruptionFilter = Settings.Global.getInt(appContext.getContentResolver(), "zen_mode", -1);
switch (interruptionFilter) {
case 0:
return ActivateProfileHelper.ZENMODE_ALL;
case 1:
return ActivateProfileHelper.ZENMODE_PRIORITY;
case 2:
return ActivateProfileHelper.ZENMODE_NONE;
case 3:
return ActivateProfileHelper.ZENMODE_ALARMS;
}
}*/
return -1; //defaultValue;
}
/*
static boolean vibrationIsOn(AudioManager audioManager, boolean testRingerMode) {
int ringerMode = -999;
if (testRingerMode)
ringerMode = audioManager.getRingerMode();
int vibrateType = -999;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1)
vibrateType = audioManager.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);
//int vibrateWhenRinging;
//if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception)
// vibrateWhenRinging = Settings.System.getInt(context.getContentResolver(), "vibrate_when_ringing", 0);
//else
// vibrateWhenRinging = Settings.System.getInt(context.getContentResolver(), Settings.System.VIBRATE_WHEN_RINGING, 0);
//if (PPApplication.logEnabled()) {
// PPApplication.logE("PPApplication.vibrationIsOn", "ringerMode=" + ringerMode);
// PPApplication.logE("PPApplication.vibrationIsOn", "vibrateType=" + vibrateType);
//}
//PPApplication.logE("PPApplication.vibrationIsOn", "vibrateWhenRinging="+vibrateWhenRinging);
return (ringerMode == AudioManager.RINGER_MODE_VIBRATE) ||
(vibrateType == AudioManager.VIBRATE_SETTING_ON) ||
(vibrateType == AudioManager.VIBRATE_SETTING_ONLY_SILENT);// ||
//(vibrateWhenRinging == 1);
}
*/
private static void setVibrateSettings(boolean vibrate, AudioManager audioManager) {
if (vibrate) {
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
}
else {
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
}
}
private static void setRingerMode(Context context, Profile profile, AudioManager audioManager, /*int systemZenMode,*/ boolean forProfileActivation)
{
//PPApplication.logE("@@@ ActivateProfileHelper.setRingerMode", "audioM.ringerMode=" + audioManager.getRingerMode());
Context appContext = context.getApplicationContext();
int ringerMode;
int zenMode;
/*if (PPApplication.logEnabled()) {
PPApplication.logE("ActivateProfileHelper.setRingerMode", "profile._volumeRingerMode=" + profile._volumeRingerMode);
PPApplication.logE("ActivateProfileHelper.setRingerMode", "profile._volumeZenMode=" + profile._volumeZenMode);
}*/
if (forProfileActivation) {
if (profile._volumeRingerMode != 0) {
saveRingerMode(appContext, profile._volumeRingerMode);
if ((profile._volumeRingerMode == Profile.RINGERMODE_ZENMODE) && (profile._volumeZenMode != 0))
saveZenMode(appContext, profile._volumeZenMode);
}
}
//if (firstCall)
// return;
ringerMode = ApplicationPreferences.prefRingerMode;
zenMode = ApplicationPreferences.prefZenMode;
/*if (PPApplication.logEnabled()) {
PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringerMode=" + ringerMode);
PPApplication.logE("ActivateProfileHelper.setRingerMode", "zenMode=" + zenMode);
PPApplication.logE("ActivateProfileHelper.setRingerMode", "_ringerModeForZenMode=" + profile._ringerModeForZenMode);
}*/
if (forProfileActivation) {
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringer mode change");
switch (ringerMode) {
case Profile.RINGERMODE_RING:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringer mode=RING");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALL);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALL);
PPApplication.sleep(500);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
setVibrateSettings(false, audioManager);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
//setZenMode(appContext, ZENMODE_ALL, audioManager, systemZenMode, AudioManager.RINGER_MODE_NORMAL);
setVibrateWhenRinging(appContext, profile, -1);
break;
case Profile.RINGERMODE_RING_AND_VIBRATE:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringer mode=RING & VIBRATE");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALL);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALL);
PPApplication.sleep(500);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
setVibrateSettings(true, audioManager);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
//setZenMode(appContext, ZENMODE_ALL, audioManager, systemZenMode, AudioManager.RINGER_MODE_NORMAL);
setVibrateWhenRinging(appContext, null, 1);
break;
case Profile.RINGERMODE_VIBRATE:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringer mode=VIBRATE");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALL);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALL);
PPApplication.sleep(500);
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
setVibrateSettings(true, audioManager);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
//setZenMode(appContext, ZENMODE_ALL, audioManager, systemZenMode, AudioManager.RINGER_MODE_VIBRATE);
setVibrateWhenRinging(appContext, null, 1);
break;
case Profile.RINGERMODE_SILENT:
//setZenMode(appContext, ZENMODE_SILENT, audioManager, systemZenMode, AudioManager.RINGER_MODE_SILENT);
if (PPApplication.deviceIsSamsung || PPApplication.romIsEMUI) {
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALL);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALL);
PPApplication.sleep(500);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
setVibrateSettings(true, audioManager);
}
else {
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
setVibrateSettings(false, audioManager);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALARMS);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALARMS);
}
setVibrateWhenRinging(appContext, profile, -1);
break;
case Profile.RINGERMODE_ZENMODE:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringer mode=ZEN MODE");
switch (zenMode) {
case Profile.ZENMODE_ALL:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "zen mode=ALL");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
setVibrateSettings(false, audioManager);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALL);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALL);
//setZenMode(appContext, ZENMODE_ALL, audioManager, systemZenMode, /*AudioManager.RINGER_MODE_NORMAL*/profile._ringerModeForZenMode);
setVibrateWhenRinging(appContext, profile, -1);
break;
case Profile.ZENMODE_PRIORITY:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "zen mode=PRIORITY");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
setVibrateSettings(false, audioManager);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
//setZenMode(appContext, ZENMODE_PRIORITY, audioManager, systemZenMode, profile._ringerModeForZenMode);
setVibrateWhenRinging(appContext, profile, -1);
break;
case Profile.ZENMODE_NONE:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "zen mode=NONE");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
setVibrateSettings(false, audioManager);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_NONE);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_NONE);
//setZenMode(appContext, ZENMODE_NONE, audioManager, systemZenMode, AudioManager.RINGER_MODE_SILENT);
break;
case Profile.ZENMODE_ALL_AND_VIBRATE:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "zen mode=ALL & VIBRATE");
// this is as Sound mode = Vibrate
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
setVibrateSettings(true, audioManager);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALL);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALL);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
//setZenMode(appContext, ZENMODE_ALL, audioManager, systemZenMode, AudioManager.RINGER_MODE_VIBRATE);
setVibrateWhenRinging(appContext, null, 1);
break;
case Profile.ZENMODE_PRIORITY_AND_VIBRATE:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "zen mode=PRIORITY & VIBRATE");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
if (Build.VERSION.SDK_INT <= 25) {
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
setVibrateSettings(true, audioManager);
//PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
}
else
if (Build.VERSION.SDK_INT <= 28) {
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
//setVibrateSettings(true, audioManager);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
PPApplication.sleep(1000);
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
setVibrateSettings(true, audioManager);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
}
else {
// must be set 2x to keep vibraton
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
setVibrateSettings(true, audioManager);
//PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
}
//setZenMode(appContext, ZENMODE_PRIORITY, audioManager, systemZenMode, AudioManager.RINGER_MODE_VIBRATE);
//setZenMode(appContext, ZENMODE_PRIORITY, audioManager, systemZenMode, AudioManager.RINGER_MODE_VIBRATE);
setVibrateWhenRinging(appContext, null, 1);
break;
case Profile.ZENMODE_ALARMS:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "zen mode=ALARMS");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
setVibrateSettings(false, audioManager);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALARMS);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALARMS);
//setZenMode(appContext, ZENMODE_ALARMS, audioManager, systemZenMode, AudioManager.RINGER_MODE_SILENT);
break;
}
break;
}
}
}
private static void executeForWallpaper(final Profile profile, Context context) {
if (profile._deviceWallpaperChange == 1)
{
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadWallpaper();
final Handler handler = new Handler(PPApplication.handlerThreadWallpaper.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadWallpaper", "START run - from=ActivateProfileHelper.executeForWallpaper");
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_executeForWallpaper");
wakeLock.acquire(10 * 60 * 1000);
}
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager wm = (WindowManager) appContext.getSystemService(Context.WINDOW_SERVICE);
if (wm != null) {
Display display = wm.getDefaultDisplay();
//if (android.os.Build.VERSION.SDK_INT >= 17)
display.getRealMetrics(displayMetrics);
//else
// display.getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
if (appContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
//noinspection SuspiciousNameCombination
height = displayMetrics.widthPixels;
//noinspection SuspiciousNameCombination
width = displayMetrics.heightPixels;
}
//PPApplication.logE("PPApplication.startHandlerThreadWallpaper", "height="+height);
//PPApplication.logE("PPApplication.startHandlerThreadWallpaper", "width="+width);
// for lock screen no double width
if ((Build.VERSION.SDK_INT < 24) || (profile._deviceWallpaperFor != 2))
width = width << 1; // best wallpaper width is twice screen width
//PPApplication.logE("PPApplication.startHandlerThreadWallpaper", "width (2)="+width);
Bitmap decodedSampleBitmap = BitmapManipulator.resampleBitmapUri(profile._deviceWallpaper, width, height, false, true, appContext);
if (decodedSampleBitmap != null) {
// set wallpaper
WallpaperManager wallpaperManager = WallpaperManager.getInstance(appContext);
try {
if (Build.VERSION.SDK_INT >= 24) {
int flags = WallpaperManager.FLAG_SYSTEM | WallpaperManager.FLAG_LOCK;
Rect visibleCropHint = null;
if (profile._deviceWallpaperFor == 1)
flags = WallpaperManager.FLAG_SYSTEM;
if (profile._deviceWallpaperFor == 2) {
flags = WallpaperManager.FLAG_LOCK;
int left = 0;
int right = decodedSampleBitmap.getWidth();
if (decodedSampleBitmap.getWidth() > width) {
left = (decodedSampleBitmap.getWidth() / 2) - (width / 2);
right = (decodedSampleBitmap.getWidth() / 2) + (width / 2);
}
visibleCropHint = new Rect(left, 0, right, decodedSampleBitmap.getHeight());
}
//noinspection WrongConstant
wallpaperManager.setBitmap(decodedSampleBitmap, visibleCropHint, true, flags);
} else
wallpaperManager.setBitmap(decodedSampleBitmap);
} catch (IOException e) {
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_SET_WALLPAPER, null,
profile._name, profile._icon, 0, "");
//Log.e("ActivateProfileHelper.executeForWallpaper", Log.getStackTraceString(e));
PPApplication.recordException(e);
} catch (Exception e) {
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_SET_WALLPAPER, null,
profile._name, profile._icon, 0, "");
//PPApplication.recordException(e);
}
}
else {
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_SET_WALLPAPER, null,
profile._name, profile._icon, 0, "");
}
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
});
}
}
private static void executeForRunApplications(final Profile profile, Context context) {
if (profile._deviceRunApplicationChange == 1)
{
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadRunApplication();
final Handler handler = new Handler(PPApplication.handlerThreadRunApplication.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadRunApplication", "START run - from=ActivateProfileHelper.executeForRunApplications");
if (PPApplication.blockProfileEventActions)
// not start applications after boot
return;
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_executeForRunApplications");
wakeLock.acquire(10 * 60 * 1000);
}
String[] splits = profile._deviceRunApplicationPackageName.split("\\|");
Intent intent;
PackageManager packageManager = appContext.getPackageManager();
//ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//List<ActivityManager.RunningAppProcessInfo> procInfo = activityManager.getRunningAppProcesses();
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","profile._name="+profile._name);
for (String split : splits) {
//Log.d("ActivateProfileHelper.executeForRunApplications","app data="+splits[i]);
int startApplicationDelay = Application.getStartApplicationDelay(split);
if (Application.getStartApplicationDelay(split) > 0) {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","run with delay");
RunApplicationWithDelayBroadcastReceiver.setDelayAlarm(appContext, startApplicationDelay, profile._name, split);
} else {
if (Application.isShortcut(split)) {
long shortcutId = Application.getShortcutId(split);
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","shortcut - shortcutId="+shortcutId);
if (shortcutId > 0) {
//Shortcut shortcut = dataWrapper.getDatabaseHandler().getShortcut(shortcutId);
Shortcut shortcut = DatabaseHandler.getInstance(appContext).getShortcut(shortcutId);
if (shortcut != null) {
try {
intent = Intent.parseUri(shortcut._intent, 0);
if (intent != null) {
//String packageName = intent.getPackage();
//if (!isRunning(procInfo, packageName)) {
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName + ": not running");
//Log.d("ActivateProfileHelper.executeForRunApplications","intent="+intent);
//noinspection TryWithIdenticalCatches
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","shortcut - ERROR (01)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_SHORTCUT, null,
profile._name, profile._icon, 0, "");
} catch (SecurityException e) {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","shortcut - ERROR (02)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_SHORTCUT, null,
profile._name, profile._icon, 0, "");
} catch (Exception e) {
PPApplication.recordException(e);
}
//} else
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName + ": running");
} else {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","shortcut - ERROR (1)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_SHORTCUT, null,
profile._name, profile._icon, 0, "");
}
} catch (Exception ee) {
PPApplication.recordException(ee);
}
} else {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","shortcut - ERROR (2)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_SHORTCUT, null,
profile._name, profile._icon, 0, "");
}
} else {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","shortcut - ERROR (3)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_SHORTCUT, null,
profile._name, profile._icon, 0, "");
}
} else if (Application.isIntent(split)) {
long intentId = Application.getIntentId(split);
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","intent - intentId="+intentId);
if (intentId > 0) {
PPIntent ppIntent = DatabaseHandler.getInstance(appContext).getIntent(intentId);
if (ppIntent != null) {
intent = ApplicationEditorIntentActivityX.createIntent(ppIntent);
if (intent != null) {
if (ppIntent._intentType == 0) {
//noinspection TryWithIdenticalCatches
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","intent - ERROR (01)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_INTENT, null,
profile._name, profile._icon, 0, "");
} catch (SecurityException e) {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","intent - ERROR (02)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_INTENT, null,
profile._name, profile._icon, 0, "");
} catch (Exception e) {
PPApplication.recordException(e);
}
} else {
try {
appContext.sendBroadcast(intent);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
} else {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","intent - ERROR (1)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_INTENT, null,
profile._name, profile._icon, 0, "");
}
} else {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","intent - ERROR (2)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_INTENT, null,
profile._name, profile._icon, 0, "");
}
} else {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","intent - ERROR (3)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_INTENT, null,
profile._name, profile._icon, 0, "");
}
} else {
String packageName = Application.getPackageName(split);
intent = packageManager.getLaunchIntentForPackage(packageName);
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","application - intent="+intent);
if (intent != null) {
//if (!isRunning(procInfo, packageName)) {
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName+": not running");
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","intent="+intent);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
//noinspection TryWithIdenticalCatches
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(intent);
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","application started");
} catch (ActivityNotFoundException e) {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","application - ERROR (01)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_APPLICATION, null,
profile._name, profile._icon, 0, "");
} catch (SecurityException e) {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","application - ERROR (02)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_APPLICATION, null,
profile._name, profile._icon, 0, "");
} catch (Exception e) {
//Log.e("ActivateProfileHelper.executeForRunApplications", Log.getStackTraceString(e));
}
//}
//else
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName+": running");
}
else {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","application - ERROR (1)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_APPLICATION, null,
profile._name, profile._icon, 0, "");
}
}
}
PPApplication.sleep(1000);
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {
}
}
}
});
}
}
//private static int processPID = -1;
private static void executeForForceStopApplications(final Profile profile, Context context) {
if (PPApplication.blockProfileEventActions)
// not force stop applications after boot
return;
Context appContext = context.getApplicationContext();
/*if ((!ApplicationPreferences.applicationNeverAskForGrantRoot(context)) &&
(PPApplication.isRooted(false))) {
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications","do force stop via root");
synchronized (PPApplication.rootMutex) {
processPID = -1;
String command1 = "pidof sk.henrichg.phoneprofilesplus";
Command command = new Command(0, false, command1) {
@Override
public void commandOutput(int id, String line) {
super.commandOutput(id, line);
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications","shell output="+line);
try {
processPID = Integer.parseInt(line);
} catch (Exception e) {
processPID = -1;
}
}
@Override
public void commandTerminated(int id, String reason) {
super.commandTerminated(id, reason);
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications","terminated="+reason);
}
@Override
public void commandCompleted(int id, int exitCode) {
super.commandCompleted(id, exitCode);
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications","completed="+exitCode);
}
};
try {
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications", "force stop application with root");
roottools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command);
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications", "processPID="+processPID);
//if (processPID != -1) {
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications", "call roottools.killProcess");
boolean killed = roottools.killProcess(PPApplication.PACKAGE_NAME);
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications", "killed="+killed);
//}
} catch (Exception ee) {
Log.e("ActivateProfileHelper.executeForForceStopApplications", Log.getStackTraceString(ee));
}
}
} else {*/
if (profile._lockDevice != 0)
// not force stop if profile has lock device enabled
return;
String applications = profile._deviceForceStopApplicationPackageName;
if (!(applications.isEmpty() || (applications.equals("-")))) {
Intent intent = new Intent(PPApplication.ACTION_FORCE_STOP_APPLICATIONS_START);
intent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);
intent.putExtra(PPApplication.EXTRA_APPLICATIONS, applications);
appContext.sendBroadcast(intent, PPApplication.PPP_EXTENDER_PERMISSION);
}
//}
}
private static void executeRootForAdaptiveBrightness(final Profile profile, Context context) {
/* not working (private secure settings) :-/
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
Settings.System.putFloat(appContext.getContentResolver(), ADAPTIVE_BRIGHTNESS_SETTING_NAME,
profile.getDeviceBrightnessAdaptiveValue(appContext));
}
else {*/
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadProfileActivation();
final Handler handler = new Handler(PPApplication.handlerThreadProfileActivation.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadProfileActivation", "START run - from=ActivateProfileHelper.executeRootForAdaptiveBrightness");
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_executeRootForAdaptiveBrightness");
wakeLock.acquire(10 * 60 * 1000);
}
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false))) {
synchronized (PPApplication.rootMutex) {
String command1 = "settings put system " + Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ + " " +
profile.getDeviceBrightnessAdaptiveValue(appContext);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.executeRootForAdaptiveBrightness");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.executeRootForAdaptiveBrightness", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
});
//}
}
static void executeForInteractivePreferences(final Profile profile, final Context context) {
if (profile == null)
return;
if (PPApplication.blockProfileEventActions)
// not start applications after boot
return;
Context appContext = context.getApplicationContext();
if (profile._deviceRunApplicationChange == 1)
{
executeForRunApplications(profile, appContext);
}
//PowerManager pm = (PowerManager) context.getSystemService(POWER_SERVICE);
KeyguardManager myKM = (KeyguardManager) appContext.getSystemService(Context.KEYGUARD_SERVICE);
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_MOBILE_DATA_PREFS, null, null, true, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED)
{
if (profile._deviceMobileDataPrefs == 1)
{
if (PPApplication.isScreenOn && (myKM != null) && !myKM.isKeyguardLocked()) {
boolean ok = true;
try {
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
appContext.startActivity(intent);
//PPApplication.logE("ActivateProfileHelper.executeForInteractivePreferences", "1. OK");
} catch (Exception e) {
ok = false;
// Xiaomi: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.android.settings/com.android.settings.Settings$DataUsageSummaryActivity}; have you declared this activity in your AndroidManifest.xml?
//Log.e("ActivateProfileHelper.executeForInteractivePreferences", "1. ERROR" + Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
if (!ok) {
ok = true;
try {
final Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
final ComponentName componentName = new ComponentName("com.android.phone", "com.android.phone.Settings");
intent.setComponent(componentName);
appContext.startActivity(intent);
//PPApplication.logE("ActivateProfileHelper.executeForInteractivePreferences", "2. OK");
} catch (Exception e) {
ok = false;
// Xiaomi: java.lang.SecurityException: Permission Denial: starting Intent { act=android.settings.DATA_ROAMING_SETTINGS flg=0x10000000 cmp=com.android.phone/.Settings } from ProcessRecord{215f88f 16252:sk.henrichg.phoneprofilesplus/u0a231} (pid=16252, uid=10231) not exported from uid 1001
//Log.e("ActivateProfileHelper.executeForInteractivePreferences", "2. ERROR" + Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
if (!ok) {
try {
final Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(intent);
//PPApplication.logE("ActivateProfileHelper.executeForInteractivePreferences", "3. OK");
} catch (Exception e) {
//Log.e("ActivateProfileHelper.executeForInteractivePreferences", "3. ERROR" + Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
else {
boolean ok = false;
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
if (GlobalGUIRoutines.activityIntentExists(intent, appContext))
ok = true;
if (!ok) {
intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.setComponent(new ComponentName("com.android.phone", "com.android.phone.Settings"));
if (GlobalGUIRoutines.activityIntentExists(intent, appContext))
ok = true;
}
if (!ok) {
intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
if (GlobalGUIRoutines.activityIntentExists(intent, appContext))
ok = true;
}
if (ok) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String title = appContext.getString(R.string.profile_activation_interactive_preference_notification_title) + " " + profile._name;
String text = appContext.getString(R.string.profile_activation_interactive_preference_notification_text) + " " +
appContext.getString(R.string.profile_preferences_deviceMobileDataPrefs);
showNotificationForInteractiveParameters(appContext, title, text, intent,
PPApplication.PROFILE_ACTIVATION_MOBILE_DATA_PREFS_NOTIFICATION_ID,
PPApplication.PROFILE_ACTIVATION_MOBILE_DATA_PREFS_NOTIFICATION_TAG);
}
}
}
}
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_NETWORK_TYPE_PREFS, null, null, true, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED)
{
if (profile._deviceNetworkTypePrefs == 1)
{
if (PPApplication.isScreenOn && (myKM != null) && !myKM.isKeyguardLocked()) {
try {
final Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(intent);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
else {
Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String title = appContext.getString(R.string.profile_activation_interactive_preference_notification_title) + " " + profile._name;
String text = appContext.getString(R.string.profile_activation_interactive_preference_notification_text) + " " +
appContext.getString(R.string.profile_preferences_deviceNetworkTypePrefs);
showNotificationForInteractiveParameters(appContext, title, text, intent,
PPApplication.PROFILE_ACTIVATION_NETWORK_TYPE_PREFS_NOTIFICATION_ID,
PPApplication.PROFILE_ACTIVATION_NETWORK_TYPE_PREFS_NOTIFICATION_TAG);
}
}
}
//if (PPApplication.hardwareCheck(PPApplication.PREF_PROFILE_DEVICE_GPS, context))
//{ No check only GPS
if (profile._deviceLocationServicePrefs == 1)
{
if (PPApplication.isScreenOn && (myKM != null) && !myKM.isKeyguardLocked()) {
try {
final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(intent);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
else {
final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
if (GlobalGUIRoutines.activityIntentExists(intent, appContext)) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String title = appContext.getString(R.string.profile_activation_interactive_preference_notification_title) + " " + profile._name;
String text = appContext.getString(R.string.profile_activation_interactive_preference_notification_text) + " " +
appContext.getString(R.string.profile_preferences_deviceLocationServicePrefs);
showNotificationForInteractiveParameters(appContext, title, text, intent,
PPApplication.PROFILE_ACTIVATION_LOCATION_PREFS_NOTIFICATION_ID,
PPApplication.PROFILE_ACTIVATION_LOCATION_PREFS_NOTIFICATION_TAG);
}
}
}
//}
if (profile._deviceWiFiAPPrefs == 1) {
if (PPApplication.isScreenOn && (myKM != null) && !myKM.isKeyguardLocked()) {
try {
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.TetherSettings"));
appContext.startActivity(intent);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
else {
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.TetherSettings"));
if (GlobalGUIRoutines.activityIntentExists(intent, appContext)) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String title = appContext.getString(R.string.profile_activation_interactive_preference_notification_title) + " " + profile._name;
String text = appContext.getString(R.string.profile_activation_interactive_preference_notification_text) + " " +
appContext.getString(R.string.profile_preferences_deviceWiFiAPPrefs);
showNotificationForInteractiveParameters(appContext, title, text, intent,
PPApplication.PROFILE_ACTIVATION_WIFI_AP_PREFS_NOTIFICATION_ID,
PPApplication.PROFILE_ACTIVATION_WIFI_AP_PREFS_NOTIFICATION_TAG);
}
}
}
}
static void execute(final Context context, final Profile profile/*, boolean merged, *//*boolean _interactive*/)
{
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "xxx");
final Context appContext = context.getApplicationContext();
// unlink ring and notifications - it is @Hide :-(
//Settings.System.putInt(appContext.getContentResolver(), Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 0);
//final Profile profile = _profile; //Profile.getMappedProfile(_profile, appContext);
// setup volume
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "executeForVolumes()");
ActivateProfileHelper.executeForVolumes(profile, PhoneCallBroadcastReceiver.LINKMODE_NONE,true, appContext);
// set vibration on touch
if (Permissions.checkProfileVibrationOnTouch(appContext, profile, null)) {
switch (profile._vibrationOnTouch) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_vibrationOnTouch 1");
Settings.System.putInt(appContext.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 1);
//Settings.System.putInt(context.getContentResolver(), Settings.Global.CHARGING_SOUNDS_ENABLED, 1);
// Settings.System.DTMF_TONE_WHEN_DIALING - working
// Settings.System.SOUND_EFFECTS_ENABLED - working
// Settings.System.LOCKSCREEN_SOUNDS_ENABLED - private secure settings :-(
// Settings.Global.CHARGING_SOUNDS_ENABLED - java.lang.IllegalArgumentException: You cannot keep your settings in the secure settings. :-/
// (G1) not working :-/
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_vibrationOnTouch 2");
Settings.System.putInt(appContext.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 0);
//Settings.System.putInt(context.getContentResolver(), Settings.Global.CHARGING_SOUNDS_ENABLED, 0);
break;
}
}
// set dtmf tone when dialing
if (Permissions.checkProfileDtmfToneWhenDialing(appContext, profile, null)) {
switch (profile._dtmfToneWhenDialing) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_dtmfToneWhenDialing 1");
Settings.System.putInt(appContext.getContentResolver(), Settings.System.DTMF_TONE_WHEN_DIALING, 1);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_dtmfToneWhenDialing 2");
Settings.System.putInt(appContext.getContentResolver(), Settings.System.DTMF_TONE_WHEN_DIALING, 0);
break;
}
}
// set sound on touch
if (Permissions.checkProfileSoundOnTouch(appContext, profile, null)) {
switch (profile._soundOnTouch) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_soundOnTouch 1");
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SOUND_EFFECTS_ENABLED, 1);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_soundOnTouch 2");
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SOUND_EFFECTS_ENABLED, 0);
break;
}
}
//// setup radio preferences
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "executeForRadios()");
ActivateProfileHelper.executeForRadios(profile, appContext);
// setup auto-sync
try {
boolean _isAutoSync = ContentResolver.getMasterSyncAutomatically();
boolean _setAutoSync = false;
switch (profile._deviceAutoSync) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoSync 1");
if (!_isAutoSync) {
_isAutoSync = true;
_setAutoSync = true;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoSync 2");
if (_isAutoSync) {
_isAutoSync = false;
_setAutoSync = true;
}
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoSync 3");
_isAutoSync = !_isAutoSync;
_setAutoSync = true;
break;
}
if (_setAutoSync)
ContentResolver.setMasterSyncAutomatically(_isAutoSync);
} catch (Exception e) {
PPApplication.recordException(e);
}
// screen on permanent
//if (Permissions.checkProfileScreenTimeout(context, profile, null)) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "setScreenOnPermanent()");
setScreenOnPermanent(profile, appContext);
//}
// screen timeout
if (Permissions.checkProfileScreenTimeout(appContext, profile, null)) {
//PowerManager pm = (PowerManager) context.getSystemService(POWER_SERVICE);
if (PPApplication.isScreenOn) {
//Log.d("ActivateProfileHelper.execute","screen on");
if (PPApplication.screenTimeoutHandler != null) {
PPApplication.screenTimeoutHandler.post(() -> {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "setScreenTimeout()");
setScreenTimeout(profile._deviceScreenTimeout, appContext);
});
}// else
// setScreenTimeout(profile._deviceScreenTimeout);
}
else {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "setActivatedProfileScreenTimeout()");
setActivatedProfileScreenTimeout(appContext, profile._deviceScreenTimeout);
}
}
//else
// PPApplication.setActivatedProfileScreenTimeout(context, 0);
// on/off lock screen
//PPApplication.logE("$$$ ActivateProfileHelper.execute","keyguard");
boolean setLockScreen = false;
switch (profile._deviceKeyguard) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceKeyguard 1");
// enable lock screen
//PPApplication.logE("$$$ ActivateProfileHelper.execute","keyguard=ON");
setLockScreenDisabled(appContext, false);
setLockScreen = true;
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceKeyguard 2");
// disable lock screen
//PPApplication.logE("$$$ ActivateProfileHelper.execute","keyguard=OFF");
setLockScreenDisabled(appContext, true);
setLockScreen = true;
break;
}
if (setLockScreen) {
//boolean isScreenOn;
//PowerManager pm = (PowerManager) context.getSystemService(POWER_SERVICE);
//if (pm != null) {
//PPApplication.logE("$$$ ActivateProfileHelper.execute", "isScreenOn=" + PPApplication.isScreenOn);
boolean keyguardShowing;
KeyguardManager kgMgr = (KeyguardManager) appContext.getSystemService(Context.KEYGUARD_SERVICE);
if (kgMgr != null) {
keyguardShowing = kgMgr.isKeyguardLocked();
//PPApplication.logE("$$$ ActivateProfileHelper.execute", "keyguardShowing=" + keyguardShowing);
if (PPApplication.isScreenOn && !keyguardShowing) {
try {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "switch keyguard");
// start PhoneProfilesService
//PPApplication.firstStartServiceStarted = false;
/*Intent serviceIntent = new Intent(context, PhoneProfilesService.class);
serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);
serviceIntent.putExtra(PhoneProfilesService.EXTRA_SWITCH_KEYGUARD, true);
PPApplication.startPPService(context, serviceIntent);*/
Intent commandIntent = new Intent(PhoneProfilesService.ACTION_COMMAND);
//commandIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);
commandIntent.putExtra(PhoneProfilesService.EXTRA_SWITCH_KEYGUARD, true);
PPApplication.runCommand(appContext, commandIntent);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
//}
}
// setup display brightness
if (Permissions.checkProfileScreenBrightness(appContext, profile, null)) {
if (profile.getDeviceBrightnessChange()) {
/*if (PPApplication.logEnabled()) {
PPApplication.logE("----- ActivateProfileHelper.execute", "set brightness: profile=" + profile._name);
PPApplication.logE("----- ActivateProfileHelper.execute", "set brightness: _deviceBrightness=" + profile._deviceBrightness);
}*/
try {
if (profile.getDeviceBrightnessAutomatic()) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "set automatic brightness");
Settings.System.putInt(appContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
if (profile.getDeviceBrightnessChangeLevel()) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "set brightness 1");
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_ADAPTIVE_BRIGHTNESS, null, null, true, appContext).allowed
== PreferenceAllowed.PREFERENCE_ALLOWED) {
Settings.System.putInt(appContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
profile.getDeviceBrightnessManualValue(appContext));
/*if (android.os.Build.VERSION.SDK_INT < 23) { // Not working in Android M (exception)
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "set adaptive brightness 1");
Settings.System.putFloat(appContext.getContentResolver(),
ADAPTIVE_BRIGHTNESS_SETTING_NAME,
profile.getDeviceBrightnessAdaptiveValue(appContext));
} else*/ {
try {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "set adaptive brightness 2");
Settings.System.putFloat(appContext.getContentResolver(),
Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ,
profile.getDeviceBrightnessAdaptiveValue(appContext));
} catch (Exception ee) {
// run service for execute radios
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "executeRootForAdaptiveBrightness()");
ActivateProfileHelper.executeRootForAdaptiveBrightness(profile, appContext);
}
}
}
}
} else {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "set manual brightness");
Settings.System.putInt(appContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
if (profile.getDeviceBrightnessChangeLevel()) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "set brightness 2");
Settings.System.putInt(appContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
profile.getDeviceBrightnessManualValue(appContext));
}
}
/*
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "start BackgroundBrightnessActivity");
Intent intent = new Intent(appContext, BackgroundBrightnessActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //this is important
float brightnessValue;
//if (profile.getDeviceBrightnessAutomatic() || (!profile.getDeviceBrightnessChangeLevel()))
brightnessValue = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
//else
// brightnessValue= profile.getDeviceBrightnessManualValue(context) / (float) 255;
intent.putExtra(BackgroundBrightnessActivity.EXTRA_BRIGHTNESS_VALUE, brightnessValue);
appContext.startActivity(intent);
*/
/*
if (PPApplication.brightnessHandler != null) {
PPApplication.brightnessHandler.post(new Runnable() {
public void run() {
PPApplication.logE("ActivateProfileHelper.execute", "brightnessHandler");
createBrightnessView(profile, context);
}
});
}// else
// createBrightnessView(context);
*/
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
// setup rotation
if (Permissions.checkProfileAutoRotation(appContext, profile, null)) {
switch (profile._deviceAutoRotate) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoRotate 1");
// set autorotate on
Settings.System.putInt(appContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);
//Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 6:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoRotate 6");
// set autorotate off
Settings.System.putInt(appContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
//Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoRotate 2");
// set autorotate off
// degree 0
Settings.System.putInt(appContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(appContext.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoRotate 3");
// set autorotate off
// degree 90
Settings.System.putInt(appContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(appContext.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_90);
break;
case 4:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoRotate 4");
// set autorotate off
// degree 180
Settings.System.putInt(appContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(appContext.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_180);
break;
case 5:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoRotate 5");
// set autorotate off
// degree 270
Settings.System.putInt(appContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(appContext.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_270);
break;
}
}
// set notification led
if (profile._notificationLed != 0) {
//if (Permissions.checkProfileNotificationLed(context, profile)) { not needed for Android 6+, because root is required
switch (profile._notificationLed) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_notificationLed 1");
setNotificationLed(appContext, 1);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_notificationLed 2");
setNotificationLed(appContext, 0);
break;
}
//}
}
// setup wallpaper
if (Permissions.checkProfileWallpaper(appContext, profile, null)) {
if (profile._deviceWallpaperChange == 1) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "executeForWallpaper()");
ActivateProfileHelper.executeForWallpaper(profile, appContext);
}
}
// set power save mode
ActivateProfileHelper.setPowerSaveMode(profile, appContext);
if (Permissions.checkProfileLockDevice(appContext, profile, null)) {
if (profile._lockDevice != 0) {
boolean keyguardLocked;
KeyguardManager kgMgr = (KeyguardManager) appContext.getSystemService(Context.KEYGUARD_SERVICE);
if (kgMgr != null) {
keyguardLocked = kgMgr.isKeyguardLocked();
//PPApplication.logE("---$$$ ActivateProfileHelper.execute", "keyguardLocked=" + keyguardLocked);
if (!keyguardLocked) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "lockDevice()");
ActivateProfileHelper.lockDevice(profile, appContext);
}
}
}
}
// enable/disable scanners
if (profile._applicationDisableWifiScanning != 0) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_applicationDisableWifiScanning");
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(appContext);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_WIFI_ENABLE_SCANNING, profile._applicationDisableWifiScanning == 2);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_WIFI_DISABLED_SCANNING_BY_PROFILE, profile._applicationDisableWifiScanning == 1);
editor.apply();
ApplicationPreferences.applicationEventWifiEnableScanning(appContext);
ApplicationPreferences.applicationEventWifiDisabledScannigByProfile(appContext);
//PPApplication.logE("[RJS] ActivateProfileHelper.execute", "_applicationDisableWifiScanning");
PPApplication.restartWifiScanner(appContext);
}
if (profile._applicationDisableBluetoothScanning != 0) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_applicationDisableBluetoothScanning");
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(appContext);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_BLUETOOTH_ENABLE_SCANNING, profile._applicationDisableBluetoothScanning == 2);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_BLUETOOTH_DISABLED_SCANNING_BY_PROFILE, profile._applicationDisableBluetoothScanning == 1);
editor.apply();
ApplicationPreferences.applicationEventBluetoothEnableScanning(appContext);
ApplicationPreferences.applicationEventBluetoothDisabledScannigByProfile(appContext);
//PPApplication.logE("[RJS] ActivateProfileHelper.execute", "_applicationDisableBluetoothScanning");
PPApplication.restartBluetoothScanner(appContext);
}
if (profile._applicationDisableLocationScanning != 0) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_applicationDisableLocationScanning");
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(appContext);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_LOCATION_ENABLE_SCANNING, profile._applicationDisableLocationScanning == 2);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_LOCATION_DISABLED_SCANNING_BY_PROFILE, profile._applicationDisableLocationScanning == 1);
editor.apply();
ApplicationPreferences.applicationEventLocationEnableScanning(appContext);
ApplicationPreferences.applicationEventLocationDisabledScannigByProfile(appContext);
//PPApplication.logE("[RJS] ActivateProfileHelper.execute", "_applicationDisableLocationScanning");
PPApplication.restartGeofenceScanner(appContext);
}
if (profile._applicationDisableMobileCellScanning != 0) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_applicationDisableMobileCellScanning");
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(appContext);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_MOBILE_CELL_ENABLE_SCANNING, profile._applicationDisableMobileCellScanning == 2);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_MOBILE_CELL_DISABLED_SCANNING_BY_PROFILE, profile._applicationDisableMobileCellScanning == 1);
editor.apply();
ApplicationPreferences.applicationEventMobileCellEnableScanning(appContext);
ApplicationPreferences.applicationEventMobileCellDisabledScannigByProfile(appContext);
//PPApplication.logE("[RJS] ActivateProfileHelper.execute", "_applicationDisableMobileCellScanning");
PPApplication.restartPhoneStateScanner(appContext);
}
if (profile._applicationDisableOrientationScanning != 0) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_applicationDisableOrientationScanning");
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(appContext);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_ORIENTATION_ENABLE_SCANNING, profile._applicationDisableOrientationScanning == 2);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_ORIENTATION_DISABLED_SCANNING_BY_PROFILE, profile._applicationDisableOrientationScanning == 1);
editor.apply();
ApplicationPreferences.applicationEventOrientationEnableScanning(appContext);
ApplicationPreferences.applicationEventOrientationDisabledScannigByProfile(appContext);
//PPApplication.logE("[RJS] ActivateProfileHelper.execute", "_applicationDisableOrientationScanning");
PPApplication.restartOrientationScanner(appContext);
}
if (profile._applicationDisableNotificationScanning != 0) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_applicationDisableNotificationScanning");
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(appContext);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_NOTIFICATION_ENABLE_SCANNING, profile._applicationDisableNotificationScanning == 2);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_NOTIFICATION_DISABLED_SCANNING_BY_PROFILE, profile._applicationDisableNotificationScanning == 1);
editor.apply();
ApplicationPreferences.applicationEventNotificationEnableScanning(appContext);
ApplicationPreferences.applicationEventNotificationDisabledScannigByProfile(appContext);
//PPApplication.logE("[RJS] ActivateProfileHelper.execute", "_applicationDisableNotificationScanning");
PPApplication.restartNotificationScanner(appContext);
}
// set heads-up notifications
if (profile._headsUpNotifications != 0) {
switch (profile._headsUpNotifications) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_headsUpNotifications 1");
setHeadsUpNotifications(appContext, 1);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_headsUpNotifications 2");
setHeadsUpNotifications(appContext, 0);
break;
}
}
// set screen dark mode
if (profile._screenDarkMode != 0) {
setScreenDarkMode(context, profile._screenDarkMode);
}
if (android.os.Build.VERSION.SDK_INT >= 26) {
// set always on display
if (profile._alwaysOnDisplay != 0) {
switch (profile._alwaysOnDisplay) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_alwaysOnDisplay 1");
setAlwaysOnDisplay(appContext, 1);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_alwaysOnDisplay 2");
setAlwaysOnDisplay(appContext, 0);
break;
}
}
}
// close all applications
if (profile._deviceCloseAllApplications == 1) {
if (!PPApplication.blockProfileEventActions) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "start work for close all applications");
// work for first start events or activate profile on boot
Data workData = new Data.Builder()
.putString(EXTRA_PROFILE_NAME, profile._name)
.build();
OneTimeWorkRequest worker =
new OneTimeWorkRequest.Builder(MainWorker.class)
.addTag(MainWorker.CLOSE_ALL_APPLICATIONS_WORK_TAG)
.setInputData(workData)
.setInitialDelay(1500, TimeUnit.MILLISECONDS)
.build();
try {
if (PPApplication.getApplicationStarted(true)) {
WorkManager workManager = PPApplication.getWorkManagerInstance();
if (workManager != null) {
// //if (PPApplication.logEnabled()) {
// ListenableFuture<List<WorkInfo>> statuses;
// statuses = workManager.getWorkInfosForUniqueWork(MainWorker.CLOSE_ALL_APPLICATIONS_WORK_TAG);
// try {
// List<WorkInfo> workInfoList = statuses.get();
// PPApplication.logE("[TEST BATTERY] ActivateProfileHelper.execute", "for=" + MainWorker.CLOSE_ALL_APPLICATIONS_WORK_TAG + " workInfoList.size()=" + workInfoList.size());
// } catch (Exception ignored) {
// }
// //}
// PPApplication.logE("[WORKER_CALL] ActivateProfileHelper.execute", "xxx");
workManager.enqueueUniqueWork(MainWorker.CLOSE_ALL_APPLICATIONS_WORK_TAG, ExistingWorkPolicy.REPLACE, worker);
}
}
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
if (profile.getGenerateNotificationGenerate()) {
PPApplication.createGeneratedByProfileNotificationChannel(appContext);
NotificationCompat.Builder mBuilder;
Intent _intent;
_intent = new Intent(appContext, EditorProfilesActivity.class);
String nTitle = profile.getGenerateNotificationTitle();
String nText = profile.getGenerateNotificationBody();
if (android.os.Build.VERSION.SDK_INT < 24) {
nTitle = appContext.getString(R.string.ppp_app_name);
nText = profile.getGenerateNotificationTitle() + ": " +
profile.getGenerateNotificationBody();
}
nTitle = nTitle + " (" + profile._name + ")";
mBuilder = new NotificationCompat.Builder(appContext, PPApplication.GENERATED_BY_PROFILE_NOTIFICATION_CHANNEL)
.setColor(ContextCompat.getColor(appContext, R.color.notificationDecorationColor))
.setContentTitle(nTitle) // title for notification
.setContentText(nText)
.setStyle(new NotificationCompat.BigTextStyle().bigText(nText))
.setAutoCancel(true); // clear notification after click
switch (profile.getGenerateNotificationIconType()) {
case 0:
mBuilder.setSmallIcon(R.drawable.ic_information_notify);
break;
case 1:
mBuilder.setSmallIcon(R.drawable.ic_exclamation_notify);
break;
default:
// not supported color profile icons
if (profile.getIsIconResourceID()) {
int iconSmallResource = R.drawable.ic_profile_default_notify;
try {
String iconIdentifier = profile.getIconIdentifier();
if ((iconIdentifier != null) && (!iconIdentifier.isEmpty())) {
Object idx = Profile.profileIconNotifyId.get(iconIdentifier);
if (idx != null)
iconSmallResource = (int) idx;
}
} catch (Exception e) {
PPApplication.recordException(e);
}
mBuilder.setSmallIcon(iconSmallResource);
} else {
profile.generateIconBitmap(appContext, false, 0, false);
if (profile._iconBitmap != null) {
mBuilder.setSmallIcon(IconCompat.createWithBitmap(profile._iconBitmap));
}
else {
int iconSmallResource;
iconSmallResource = R.drawable.ic_profile_default_notify;
mBuilder.setSmallIcon(iconSmallResource);
}
}
break;
}
PendingIntent pi = PendingIntent.getActivity(appContext, 0, _intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pi);
mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
//if (android.os.Build.VERSION.SDK_INT >= 21) {
mBuilder.setCategory(NotificationCompat.CATEGORY_EVENT);
mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
//}
Notification notification = mBuilder.build();
notification.vibrate = null;
notification.defaults &= ~DEFAULT_VIBRATE;
NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(appContext);
try {
mNotificationManager.notify(
PPApplication.GENERATED_BY_PROFILE_NOTIFICATION_TAG,
PPApplication.GENERATED_BY_PROFILE_NOTIFICATION_ID + (int)profile._id,
notification);
} catch (Exception e) {
//Log.e("CheckGitHubReleasesBroadcastReceiver._doWork", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
}
if (profile._cameraFlash != 0) {
if (Permissions.checkProfileCameraFlash(context, profile, null)) {
switch (profile._cameraFlash) {
case 1:
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_cameraFlash 1");
NoobCameraManager noobCameraManager = NoobCameraManager.getInstance();
if (noobCameraManager != null) {
try {
noobCameraManager.turnOnFlash();
} catch (Exception e) {
PPApplication.recordException(e);
}
}
break;
case 2:
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_cameraFlash 2");
noobCameraManager = NoobCameraManager.getInstance();
if (noobCameraManager != null) {
try {
noobCameraManager.turnOffFlash();
} catch (Exception e) {
PPApplication.recordException(e);
}
}
break;
}
}
}
if (profile._deviceForceStopApplicationChange == 1) {
boolean enabled;
if (Build.VERSION.SDK_INT >= 28)
enabled = PPPExtenderBroadcastReceiver.isEnabled(appContext, PPApplication.VERSION_CODE_EXTENDER_5_1_3_1);
else
enabled = PPPExtenderBroadcastReceiver.isEnabled(appContext, PPApplication.VERSION_CODE_EXTENDER_3_0);
if (enabled) {
// executeForInteractivePreferences() is called from broadcast receiver PPPExtenderBroadcastReceiver
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "executeForForceStopApplications()");
ActivateProfileHelper.executeForForceStopApplications(profile, appContext);
}
}
else {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "executeForInteractivePreferences()");
executeForInteractivePreferences(profile, appContext);
}
}
private static void showNotificationForInteractiveParameters(Context context, String title, String text, Intent intent, int notificationId, String notificationTag) {
Context appContext = context.getApplicationContext();
String nTitle = title;
String nText = text;
if (android.os.Build.VERSION.SDK_INT < 24) {
nTitle = appContext.getString(R.string.ppp_app_name);
nText = title+": "+text;
}
PPApplication.createInformationNotificationChannel(appContext);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext, PPApplication.INFORMATION_NOTIFICATION_CHANNEL)
.setColor(ContextCompat.getColor(appContext, R.color.notificationDecorationColor))
.setSmallIcon(R.drawable.ic_exclamation_notify) // notification icon
.setContentTitle(nTitle) // title for notification
.setContentText(nText) // message for notification
.setAutoCancel(true); // clear notification after click
mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(nText));
PendingIntent pi = PendingIntent.getActivity(appContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pi);
mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
//if (android.os.Build.VERSION.SDK_INT >= 21)
//{
mBuilder.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION);
mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
//}
Notification notification = mBuilder.build();
notification.vibrate = null;
notification.defaults &= ~DEFAULT_VIBRATE;
NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(appContext);
try {
mNotificationManager.notify(notificationTag, notificationId, notification);
} catch (Exception e) {
//Log.e("ActivateProfileHelper.showNotificationForInteractiveParameters", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
}
static void setScreenTimeout(int screenTimeout, Context context) {
//PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "xxx");
Context appContext = context.getApplicationContext();
disableScreenTimeoutInternalChange = true;
//Log.d("ActivateProfileHelper.setScreenTimeout", "current="+Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 0));
switch (screenTimeout) {
case 1:
//removeScreenTimeoutAlwaysOnView(context);
if (/*(PhoneProfilesService.getInstance() != null) &&*/ (PPApplication.lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PPApplication.screenTimeoutBeforeDeviceLock = 15000;
else {
/*if (PPApplication.deviceIsOppo || PPApplication.deviceIsRealme) {
synchronized (PPApplication.rootMutex) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", ""+screenTimeout);
String command1 = "settings put system " + Settings.System.SCREEN_OFF_TIMEOUT + " 15000";
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "command="+command1);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(false, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenTimeout");
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "end - "+screenTimeout);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
} else*/
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 15000);
}
break;
case 2:
//removeScreenTimeoutAlwaysOnView(context);
if (/*(PhoneProfilesService.getInstance() != null) &&*/ (PPApplication.lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PPApplication.screenTimeoutBeforeDeviceLock = 30000;
else {
/*if (PPApplication.deviceIsOppo || PPApplication.deviceIsRealme) {
synchronized (PPApplication.rootMutex) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", ""+screenTimeout);
String command1 = "settings put system " + Settings.System.SCREEN_OFF_TIMEOUT + " 30000";
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "command="+command1);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(false, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenTimeout");
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "end - "+screenTimeout);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
else*/
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000);
}
break;
case 3:
//removeScreenTimeoutAlwaysOnView(context);
if (/*(PhoneProfilesService.getInstance() != null) &&*/ (PPApplication.lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PPApplication.screenTimeoutBeforeDeviceLock = 60000;
else {
/*if (PPApplication.deviceIsOppo || PPApplication.deviceIsRealme) {
synchronized (PPApplication.rootMutex) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", ""+screenTimeout);
String command1 = "settings put system " + Settings.System.SCREEN_OFF_TIMEOUT + " 60000";
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "command="+command1);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(false, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenTimeout");
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "end - "+screenTimeout);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
else*/
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 60000);
}
break;
case 4:
//removeScreenTimeoutAlwaysOnView(context);
if (/*(PhoneProfilesService.getInstance() != null) &&*/ (PPApplication.lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PPApplication.screenTimeoutBeforeDeviceLock = 120000;
else {
/*if (PPApplication.deviceIsOppo || PPApplication.deviceIsRealme) {
synchronized (PPApplication.rootMutex) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", ""+screenTimeout);
String command1 = "settings put system " + Settings.System.SCREEN_OFF_TIMEOUT + " 120000";
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "command="+command1);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(false, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenTimeout");
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "end - "+screenTimeout);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
else*/
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 120000);
}
break;
case 5:
//removeScreenTimeoutAlwaysOnView(context);
if (/*(PhoneProfilesService.getInstance() != null) &&*/ (PPApplication.lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PPApplication.screenTimeoutBeforeDeviceLock = 600000;
else {
/*if (PPApplication.deviceIsOppo || PPApplication.deviceIsRealme) {
synchronized (PPApplication.rootMutex) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", ""+screenTimeout);
String command1 = "settings put system " + Settings.System.SCREEN_OFF_TIMEOUT + " 600000";
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "command="+command1);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(false, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenTimeout");
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "end - "+screenTimeout);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
else*/
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 600000);
}
break;
/*case 6:
//2147483647 = Integer.MAX_VALUE
//18000000 = 5 hours
//86400000 = 24 hours
//43200000 = 12 hours
removeScreenTimeoutAlwaysOnView(context);
if ((PhoneProfilesService.getInstance() != null) && (PhoneProfilesService.getInstance().lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PhoneProfilesService.getInstance().screenTimeoutBeforeDeviceLock = 86400000;
else
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 86400000);
break;*/
case 7:
//removeScreenTimeoutAlwaysOnView(context);
if (/*(PhoneProfilesService.getInstance() != null) &&*/ (PPApplication.lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PPApplication.screenTimeoutBeforeDeviceLock = 300000;
else {
/*if (PPApplication.deviceIsOppo || PPApplication.deviceIsRealme) {
synchronized (PPApplication.rootMutex) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", ""+screenTimeout);
String command1 = "settings put system " + Settings.System.SCREEN_OFF_TIMEOUT + " 300000";
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "command="+command1);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(false, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenTimeout");
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "end - "+screenTimeout);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
else*/
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 300000);
}
break;
/*case 8:
removeScreenTimeoutAlwaysOnView(context);
if ((PhoneProfilesService.getInstance() != null) && (PhoneProfilesService.getInstance().lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PhoneProfilesService.getInstance().screenTimeoutBeforeDeviceLock = 86400000; //1800000;
else
createScreenTimeoutAlwaysOnView(appContext);
break;*/
case 9:
//removeScreenTimeoutAlwaysOnView(context);
if (/*(PhoneProfilesService.getInstance() != null) &&*/ (PPApplication.lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PPApplication.screenTimeoutBeforeDeviceLock = 1800000;
else {
/*if (PPApplication.deviceIsOppo || PPApplication.deviceIsRealme) {
synchronized (PPApplication.rootMutex) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", ""+screenTimeout);
String command1 = "settings put system " + Settings.System.SCREEN_OFF_TIMEOUT + " 1800000";
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "command="+command1);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(false, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenTimeout");
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "end - "+screenTimeout);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
else*/
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 1800000);
}
break;
}
setActivatedProfileScreenTimeout(appContext, 0);
OneTimeWorkRequest disableInternalChangeWorker =
new OneTimeWorkRequest.Builder(DisableScreenTimeoutInternalChangeWorker.class)
.addTag(DisableScreenTimeoutInternalChangeWorker.WORK_TAG)
.setInitialDelay(5, TimeUnit.SECONDS)
.build();
try {
if (PPApplication.getApplicationStarted(true)) {
WorkManager workManager = PPApplication.getWorkManagerInstance();
if (workManager != null) {
// //if (PPApplication.logEnabled()) {
// ListenableFuture<List<WorkInfo>> statuses;
// statuses = workManager.getWorkInfosForUniqueWork(DisableScreenTimeoutInternalChangeWorker.WORK_TAG);
// try {
// List<WorkInfo> workInfoList = statuses.get();
// PPApplication.logE("[TEST BATTERY] ActivateProfileHelper.setScreenTimeout", "for=" + DisableScreenTimeoutInternalChangeWorker.WORK_TAG + " workInfoList.size()=" + workInfoList.size());
// } catch (Exception ignored) {
// }
// //}
// PPApplication.logE("[WORKER_CALL] ActivateProfileHelper.setScreenTimeout", "xxx");
workManager.enqueueUniqueWork(DisableScreenTimeoutInternalChangeWorker.WORK_TAG, ExistingWorkPolicy.REPLACE, disableInternalChangeWorker);
}
}
} catch (Exception e) {
PPApplication.recordException(e);
}
/*PPApplication.startHandlerThreadInternalChangeToFalse();
final Handler handler = new Handler(PPApplication.handlerThreadInternalChangeToFalse.getLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "disable screen timeout internal change");
disableScreenTimeoutInternalChange = false;
}
}, 3000);*/
//PostDelayedBroadcastReceiver.setAlarm(
// PostDelayedBroadcastReceiver.ACTION_DISABLE_SCREEN_TIMEOUT_INTERNAL_CHANGE_TO_FALSE, 3, context);
}
/*private static void createScreenTimeoutAlwaysOnView(Context context)
{
removeScreenTimeoutAlwaysOnView(context);
if (PhoneProfilesService.getInstance() != null) {
final Context appContext = context.getApplicationContext();
// Put 30 minutes screen timeout. Required for SettingsContentObserver.OnChange to call removeScreenTimeoutAlwaysOnView
// when user change system setting.
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 86400000);
WindowManager windowManager = (WindowManager) appContext.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
int type;
//if (android.os.Build.VERSION.SDK_INT < 25)
// type = WindowManager.LayoutParams.TYPE_TOAST;
//else
if (android.os.Build.VERSION.SDK_INT < 26)
type = LayoutParams.TYPE_SYSTEM_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
else
type = LayoutParams.TYPE_APPLICATION_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
type,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, // | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |
PixelFormat.TRANSLUCENT
);
// if (android.os.Build.VERSION.SDK_INT < 17)
// params.gravity = Gravity.RIGHT | Gravity.TOP;
// else
// params.gravity = Gravity.END | Gravity.TOP;
PhoneProfilesService.getInstance().screenTimeoutAlwaysOnView = new BrightnessView(appContext);
try {
windowManager.addView(PhoneProfilesService.getInstance().screenTimeoutAlwaysOnView, params);
} catch (Exception e) {
PhoneProfilesService.getInstance().screenTimeoutAlwaysOnView = null;
}
}
}
}
static void removeScreenTimeoutAlwaysOnView(Context context)
{
if (PhoneProfilesService.getInstance() != null) {
if (PhoneProfilesService.getInstance().screenTimeoutAlwaysOnView != null) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
try {
windowManager.removeView(PhoneProfilesService.getInstance().screenTimeoutAlwaysOnView);
} catch (Exception ignored) {
}
PhoneProfilesService.getInstance().screenTimeoutAlwaysOnView = null;
}
}
}
}
*/
/*
@SuppressLint("RtlHardcoded")
private static void createBrightnessView(Profile profile, Context context)
{
PPApplication.logE("ActivateProfileHelper.createBrightnessView", "xxx");
if (PhoneProfilesService.getInstance() != null) {
final Context appContext = context.getApplicationContext();
WindowManager windowManager = (WindowManager) appContext.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
if (PhoneProfilesService.getInstance().brightnessView != null) {
try {
windowManager.removeView(PhoneProfilesService.getInstance().brightnessView);
} catch (Exception ignored) {
}
PhoneProfilesService.getInstance().brightnessView = null;
}
int type;
//if (android.os.Build.VERSION.SDK_INT < 25)
// type = WindowManager.LayoutParams.TYPE_TOAST;
//else
if (android.os.Build.VERSION.SDK_INT < 26)
type = LayoutParams.TYPE_SYSTEM_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
else
type = LayoutParams.TYPE_APPLICATION_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
type,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, //| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.TRANSLUCENT
);
if (profile.getDeviceBrightnessAutomatic() || (!profile.getDeviceBrightnessChangeLevel()))
params.screenBrightness = LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
else
params.screenBrightness = profile.getDeviceBrightnessManualValue(appContext) / (float) 255;
PhoneProfilesService.getInstance().brightnessView = new BrightnessView(appContext);
try {
windowManager.addView(PhoneProfilesService.getInstance().brightnessView, params);
} catch (Exception e) {
PhoneProfilesService.getInstance().brightnessView = null;
}
final Handler handler = new Handler(appContext.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
PPApplication.logE("ActivateProfileHelper.createBrightnessView", "remove brightness view");
WindowManager windowManager = (WindowManager) appContext.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
if ((PhoneProfilesService.getInstance() != null) && (PhoneProfilesService.getInstance().brightnessView != null)) {
try {
windowManager.removeView(PhoneProfilesService.getInstance().brightnessView);
} catch (Exception ignored) {
}
PhoneProfilesService.getInstance().brightnessView = null;
}
}
}
}, 5000);
// PostDelayedBroadcastReceiver.setAlarm(PostDelayedBroadcastReceiver.ACTION_REMOVE_BRIGHTNESS_VIEW,5, context);
}
}
}
static void removeBrightnessView(Context context) {
if (PhoneProfilesService.getInstance() != null) {
if (PhoneProfilesService.getInstance().brightnessView != null) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
try {
windowManager.removeView(PhoneProfilesService.getInstance().brightnessView);
} catch (Exception ignored) {
}
PhoneProfilesService.getInstance().brightnessView = null;
}
}
}
}
*/
private static void createKeepScreenOnView(Context context) {
//removeKeepScreenOnView();
final Context appContext = context.getApplicationContext();
/*
//if (PhoneProfilesService.getInstance() != null) {
//PhoneProfilesService service = PhoneProfilesService.getInstance();
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
if (powerManager != null) {
try {
Log.e("ActivateProfileHelper.createKeepScreenOnView", "keepScreenOnWakeLock="+PPApplication.keepScreenOnWakeLock);
if (PPApplication.keepScreenOnWakeLock == null)
PPApplication.keepScreenOnWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_createKeepScreenOnView");
} catch(Exception e) {
PPApplication.keepScreenOnWakeLock = null;
Log.e("ActivateProfileHelper.createKeepScreenOnView", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
try {
if ((PPApplication.keepScreenOnWakeLock != null) && (!PPApplication.keepScreenOnWakeLock.isHeld())) {
Log.e("ActivateProfileHelper.createKeepScreenOnView", "acquire");
PPApplication.keepScreenOnWakeLock.acquire();
}
} catch (Exception e) {
Log.e("ActivateProfileHelper.createKeepScreenOnView", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
}
*/
if (PPApplication.keepScreenOnView != null)
removeKeepScreenOnView(context);
WindowManager windowManager = (WindowManager) appContext.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
int type;
//if (android.os.Build.VERSION.SDK_INT < 25)
// type = WindowManager.LayoutParams.TYPE_TOAST;
//else
if (android.os.Build.VERSION.SDK_INT < 26)
type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
else
type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
type,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON/* |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | // deprecated in API level 26
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | // deprecated in API level 27
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON // deprecated in API level 27*/
, PixelFormat.TRANSLUCENT
);
//if (android.os.Build.VERSION.SDK_INT < 17)
// params.gravity = Gravity.RIGHT | Gravity.TOP;
//else
// params.gravity = Gravity.END | Gravity.TOP;
PPApplication.keepScreenOnView = new BrightnessView(appContext);
try {
windowManager.addView(PPApplication.keepScreenOnView, params);
} catch (Exception e) {
PPApplication.keepScreenOnView = null;
}
}
}
static void removeKeepScreenOnView(Context context)
{
final Context appContext = context.getApplicationContext();
//if (PhoneProfilesService.getInstance() != null) {
//final Context appContext = context.getApplicationContext();
//PhoneProfilesService service = PhoneProfilesService.getInstance();
/*try {
Log.e("ActivateProfileHelper.removeKeepScreenOnView", "keepScreenOnWakeLock="+PPApplication.keepScreenOnWakeLock);
if ((PPApplication.keepScreenOnWakeLock != null) && PPApplication.keepScreenOnWakeLock.isHeld())
PPApplication.keepScreenOnWakeLock.release();
} catch (Exception e) {
Log.e("ActivateProfileHelper.removeKeepScreenOnView", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
PPApplication.keepScreenOnWakeLock = null;*/
if (PPApplication.keepScreenOnView != null) {
WindowManager windowManager = (WindowManager) appContext.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
try {
windowManager.removeView(PPApplication.keepScreenOnView);
} catch (Exception ignored) {
}
PPApplication.keepScreenOnView = null;
}
}
//}
}
static boolean isAirplaneMode(Context context)
{
//if (android.os.Build.VERSION.SDK_INT >= 17)
return Settings.Global.getInt(context.getApplicationContext().getContentResolver(), Global.AIRPLANE_MODE_ON, 0) != 0;
//else
// return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
private static void setAirplaneMode(boolean mode)
{
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false))) {
// device is rooted
synchronized (PPApplication.rootMutex) {
String command1;
String command2;
if (mode) {
command1 = "settings put global airplane_mode_on 1";
command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true";
} else {
command1 = "settings put global airplane_mode_on 0";
command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false";
}
//if (PPApplication.isSELinuxEnforcing())
//{
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
// command2 = PPApplication.getSELinuxEnforceCommand(command2, Shell.ShellContext.SYSTEM_APP);
//}
Command command = new Command(0, true, command1, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setAirplaneMode");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setAirplaneMode", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
//PPApplication.logE("ActivateProfileHelper.setAirplaneMode", "done");
}
}
}
static boolean isMobileData(Context context, int simCard)
{
Context appContext = context.getApplicationContext();
/*
if (android.os.Build.VERSION.SDK_INT < 21)
{
ConnectivityManager connectivityManager = null;
try {
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
} catch (Exception ignored) {
// java.lang.NullPointerException: missing IConnectivityManager
// Dual SIM?? Bug in Android ???
}
if (connectivityManager != null) {
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method getMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled");
getMobileDataEnabledMethod.setAccessible(true);
return (Boolean) getMobileDataEnabledMethod.invoke(connectivityManager);
} catch (Exception e) {
return false;
}
}
else
return false;
}
else*/
/*if (android.os.Build.VERSION.SDK_INT < 22)
{
Method getDataEnabledMethod;
Class<?> telephonyManagerClass;
Object ITelephonyStub;
Class<?> ITelephonyClass;
TelephonyManager telephonyManager = (TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
try {
telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");
getITelephonyMethod.setAccessible(true);
ITelephonyStub = getITelephonyMethod.invoke(telephonyManager);
if (ITelephonyStub != null) {
ITelephonyClass = Class.forName(ITelephonyStub.getClass().getName());
getDataEnabledMethod = ITelephonyClass.getDeclaredMethod("getDataEnabled");
getDataEnabledMethod.setAccessible(true);
//noinspection ConstantConditions
return (Boolean) getDataEnabledMethod.invoke(ITelephonyStub);
}
else
return false;
} catch (Exception e) {
return false;
}
}
else
return false;
}
else*/
/*if (android.os.Build.VERSION.SDK_INT < 28)
{
TelephonyManager telephonyManager = (TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
Method getDataEnabledMethod;
Class<?> telephonyManagerClass;
try {
telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
getDataEnabledMethod = telephonyManagerClass.getDeclaredMethod("getDataEnabled");
getDataEnabledMethod.setAccessible(true);
//noinspection ConstantConditions
return (Boolean) getDataEnabledMethod.invoke(telephonyManager);
} catch (Exception e) {
return false;
}
}
else
return false;
}
else*/
return CmdMobileData.isEnabled(appContext, simCard);
}
static boolean canSetMobileData(Context context)
{
Context appContext = context.getApplicationContext();
if (android.os.Build.VERSION.SDK_INT >= 28)
return true;
else
//if (android.os.Build.VERSION.SDK_INT >= 22)
{
Class<?> telephonyManagerClass;
TelephonyManager telephonyManager = (TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
try {
telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
Method getDataEnabledMethod = telephonyManagerClass.getDeclaredMethod("getDataEnabled");
getDataEnabledMethod.setAccessible(true);
return true;
} catch (Exception e) {
return false;
}
}
else
return false;
}
/*else
//if (android.os.Build.VERSION.SDK_INT >= 21)
{
Class<?> telephonyManagerClass;
TelephonyManager telephonyManager = (TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
try {
telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");
getITelephonyMethod.setAccessible(true);
return true;
} catch (Exception e) {
return false;
}
}
else
return false;
}*/
/*else
{
ConnectivityManager connectivityManager = null;
try {
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
} catch (Exception ignored) {
// java.lang.NullPointerException: missing IConnectivityManager
// Dual SIM?? Bug in Android ???
}
if (connectivityManager != null) {
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method getMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled");
getMobileDataEnabledMethod.setAccessible(true);
return true;
} catch (Exception e) {
return false;
}
}
else
return false;
}*/
}
private static void setMobileData(Context context, boolean enable, int simCard)
{
// PPApplication.logE("ActivateProfileHelper.setMobileData", "xxx");
Context appContext = context.getApplicationContext();
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
PPApplication.isRooted(false) &&
PhoneProfilesService.hasSIMCard(appContext, simCard, true))
{
if (Permissions.checkPhone(context.getApplicationContext())) {
//PPApplication.logE("ActivateProfileHelper.setMobileData", "ask for root enabled and is rooted");
if ((Build.VERSION.SDK_INT < 26) || (simCard == 0)) {
// dual sim is supported by TelephonyManager from API 26
synchronized (PPApplication.rootMutex) {
String command1 = "svc data " + (enable ? "enable" : "disable");
//PPApplication.logE("ActivateProfileHelper.setMobileData", "command=" + command1);
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SHELL).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setMobileData");
//PPApplication.logE("ActivateProfileHelper.setMobileData", "after wait");
} catch (Exception e) {
//Log.e("ActivateProfileHelper.setMobileData", Log.getStackTraceString(e));
}
}
} else {
// Get the value of the "TRANSACTION_setDataEnabled" field.
Object serviceManager = PPApplication.getServiceManager("phone");
int transactionCode = -1;
if (serviceManager != null) {
if (Build.VERSION.SDK_INT >= 28)
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setUserDataEnabled");
else
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDataEnabled");
}
int state = enable ? 1 : 0;
if (transactionCode != -1) {
// PPApplication.logE("ActivateProfileHelper.setMobileData", "transactionCode=" + transactionCode);
SubscriptionManager mSubscriptionManager = (SubscriptionManager) appContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
//SubscriptionManager.from(appContext);
if (mSubscriptionManager != null) {
// PPApplication.logE("ActivateProfileHelper.setMobileData", "mSubscriptionManager != null");
List<SubscriptionInfo> subscriptionList = null;
try {
// Loop through the subscription list i.e. SIM list.
subscriptionList = mSubscriptionManager.getActiveSubscriptionInfoList();
// PPApplication.logE("ActivateProfileHelper.setMobileData", "subscriptionList=" + subscriptionList);
} catch (SecurityException e) {
PPApplication.recordException(e);
}
if (subscriptionList != null) {
// PPApplication.logE("ActivateProfileHelper.setMobileData", "subscriptionList.size()=" + subscriptionList.size());
for (int i = 0; i < subscriptionList.size(); i++) {
// Get the active subscription ID for a given SIM card.
SubscriptionInfo subscriptionInfo = subscriptionList.get(i);
// PPApplication.logE("ActivateProfileHelper.setMobileData", "subscriptionInfo=" + subscriptionInfo);
if (subscriptionInfo != null) {
int slotIndex = subscriptionInfo.getSimSlotIndex();
if (simCard == (slotIndex+1)) {
int subscriptionId = subscriptionInfo.getSubscriptionId();
// PPApplication.logE("ActivateProfileHelper.setMobileData", "subscriptionId=" + subscriptionId);
synchronized (PPApplication.rootMutex) {
String command1 = PPApplication.getServiceCommand("phone", transactionCode, subscriptionId, state);
// PPApplication.logE("ActivateProfileHelper.setMobileData", "command1=" + command1);
if (command1 != null) {
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setMobileData");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setMobileData", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
}
}
// else
// PPApplication.logE("ActivateProfileHelper.setMobileData", "subscriptionInfo == null");
}
}
// else
// PPApplication.logE("ActivateProfileHelper.setMobileData", "subscriptionList == null");
}
// else
// PPApplication.logE("ActivateProfileHelper.setMobileData", "mSubscriptionManager == null");
}
// else
// PPApplication.logE("ActivateProfileHelper.setMobileData", "transactionCode == -1");
}
}
}
}
/*
private int getPreferredNetworkType(Context context) {
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot(context)) &&
(PPApplication.isRooted()))
{
try {
// Get the value of the "TRANSACTION_setPreferredNetworkType" field.
String transactionCode = PPApplication.getTransactionCode(context, "TRANSACTION_getPreferredNetworkType");
if (transactionCode != null && transactionCode.length() > 0) {
String command1 = "service call phone " + transactionCode + " i32";
Command command = new Command(0, false, command1) {
@Override
public void commandOutput(int id, String line) {
super.commandOutput(id, line);
String splits[] = line.split(" ");
try {
networkType = Integer.parseInt(splits[2]);
} catch (Exception e) {
networkType = -1;
}
}
@Override
public void commandTerminated(int id, String reason) {
super.commandTerminated(id, reason);
}
@Override
public void commandCompleted(int id, int exitCode) {
super.commandCompleted(id, exitCode);
}
};
try {
roottools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPreferredNetworkType", Log.getStackTraceString(e));
}
}
} catch(Exception e) {
Log.e("ActivateProfileHelper.getPreferredNetworkType", Log.getStackTraceString(e));
}
}
else
networkType = -1;
return networkType;
}
*/
static boolean telephonyServiceExists(String preference) {
try {
int transactionCode = -1;
switch (preference) {
case Profile.PREF_PROFILE_DEVICE_MOBILE_DATA:
case Profile.PREF_PROFILE_DEVICE_MOBILE_DATA_SIM1:
case Profile.PREF_PROFILE_DEVICE_MOBILE_DATA_SIM2:
Object serviceManager = PPApplication.getServiceManager("phone");
if (serviceManager != null) {
if (Build.VERSION.SDK_INT >= 28)
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setUserDataEnabled");
else
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDataEnabled");
}
break;
case Profile.PREF_PROFILE_DEVICE_NETWORK_TYPE:
case Profile.PREF_PROFILE_DEVICE_NETWORK_TYPE_SIM1:
case Profile.PREF_PROFILE_DEVICE_NETWORK_TYPE_SIM2:
serviceManager = PPApplication.getServiceManager("phone");
if (serviceManager != null)
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setPreferredNetworkType");
break;
case Profile.PREF_PROFILE_DEVICE_DEFAULT_SIM_CARDS:
serviceManager = PPApplication.getServiceManager("isub");
if (serviceManager != null) {
// support for only data devices
int transactionCodeVoice = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDefaultVoiceSubId");
int transactionCodeSMS = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDefaultSmsSubId");
int transactionCodeData = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDefaultDataSubId");
if ((transactionCodeVoice != -1) || (transactionCodeSMS != -1) || (transactionCodeData != -1))
transactionCode = 1;
}
break;
case Profile.PREF_PROFILE_DEVICE_ONOFF_SIM1:
case Profile.PREF_PROFILE_DEVICE_ONOFF_SIM2:
serviceManager = PPApplication.getServiceManager("isub");
if (serviceManager != null)
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setSubscriptionEnabled");
break;
}
return transactionCode != -1;
} catch(Exception e) {
return false;
}
}
private static void setPreferredNetworkType(Context context, int networkType, int simCard)
{
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
PPApplication.isRooted(false) &&
PPApplication.serviceBinaryExists(false) &&
PhoneProfilesService.hasSIMCard(context, simCard, true))
{
if (Permissions.checkPhone(context.getApplicationContext())) {
try {
// Get the value of the "TRANSACTION_setPreferredNetworkType" field.
Object serviceManager = PPApplication.getServiceManager("phone");
int transactionCode = -1;
if (serviceManager != null) {
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setPreferredNetworkType");
}
if (transactionCode != -1) {
// Android 5.1?
//if (Build.VERSION.SDK_INT >= 22) {
Context appContext = context.getApplicationContext();
SubscriptionManager mSubscriptionManager = (SubscriptionManager) appContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
//SubscriptionManager.from(context);
if (mSubscriptionManager != null) {
List<SubscriptionInfo> subscriptionList = null;
try {
// Loop through the subscription list i.e. SIM list.
subscriptionList = mSubscriptionManager.getActiveSubscriptionInfoList();
} catch (SecurityException e) {
PPApplication.recordException(e);
}
if (subscriptionList != null) {
for (int i = 0; i < subscriptionList.size();/*mSubscriptionManager.getActiveSubscriptionInfoCountMax();*/ i++) {
// Get the active subscription ID for a given SIM card.
SubscriptionInfo subscriptionInfo = subscriptionList.get(i);
if (subscriptionInfo != null) {
int slotIndex = subscriptionInfo.getSimSlotIndex();
if ((Build.VERSION.SDK_INT < 26) || (simCard == 0) || (simCard == (slotIndex+1))) {
// dual sim is supported by TelephonyManager from API 26
int subscriptionId = subscriptionInfo.getSubscriptionId();
synchronized (PPApplication.rootMutex) {
String command1 = PPApplication.getServiceCommand("phone", transactionCode, subscriptionId, networkType);
if (command1 != null) {
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setPreferredNetworkType");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setPreferredNetworkType", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
}
}
}
}
}
/*} else {
synchronized (PPApplication.rootMutex) {
String command1 = PPApplication.getServiceCommand("phone", transactionCode, networkType);
if (command1 != null) {
Command command = new Command(0, false, command1);
try {
roottools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command);
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setPreferredNetworkType", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
}*/
}
} catch (Exception ee) {
PPApplication.recordException(ee);
}
}
}
}
static boolean wifiServiceExists(/*Context context, */
@SuppressWarnings("SameParameterValue") String preference) {
try {
Object serviceManager = PPApplication.getServiceManager("wifi");
if (serviceManager != null) {
int transactionCode = -1;
if (preference.equals(Profile.PREF_PROFILE_DEVICE_WIFI_AP))
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setWifiApEnabled");
return transactionCode != -1;
}
return false;
} catch(Exception e) {
//Log.e("ActivateProfileHelper.wifiServiceExists",Log.getStackTraceString(e));
PPApplication.recordException(e);
return false;
}
}
private static void setWifiAP(WifiApManager wifiApManager, boolean enable, boolean doNotChangeWifi, Context context) {
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-enable="+enable);
if (Build.VERSION.SDK_INT < 26) {
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-API < 26");
wifiApManager.setWifiApState(enable, doNotChangeWifi);
}
else
if (Build.VERSION.SDK_INT < 28) {
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-API >= 26");
Context appContext = context.getApplicationContext();
if (WifiApManager.canExploitWifiTethering(appContext)) {
if (enable)
wifiApManager.startTethering(doNotChangeWifi);
else
wifiApManager.stopTethering();
}
else
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.serviceBinaryExists(false))) {
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-rooted");
try {
Object serviceManager = PPApplication.getServiceManager("wifi");
int transactionCode = -1;
if (serviceManager != null) {
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setWifiApEnabled");
}
/*if (PPApplication.logEnabled()) {
PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-serviceManager=" + serviceManager);
PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-transactionCode=" + transactionCode);
}*/
if (transactionCode != -1) {
if (enable && (!doNotChangeWifi)) {
WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-wifiManager=" + wifiManager);
if (wifiManager != null) {
int wifiState = wifiManager.getWifiState();
boolean isWifiEnabled = ((wifiState == WifiManager.WIFI_STATE_ENABLED) || (wifiState == WifiManager.WIFI_STATE_ENABLING));
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-isWifiEnabled=" + isWifiEnabled);
if (isWifiEnabled) {
//PPApplication.logE("#### setWifiEnabled", "from ActivateProfileHelper.setWifiAP");
wifiManager.setWifiEnabled(false);
PPApplication.sleep(1000);
}
}
}
synchronized (PPApplication.rootMutex) {
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-start root command");
String command1 = PPApplication.getServiceCommand("wifi", transactionCode, 0, (enable) ? 1 : 0);
if (command1 != null) {
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-command1=" + command1);
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setWifiAP");
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-root command end");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setWifiAP", Log.getStackTraceString(e));
//PPApplication.recordException(e);
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-root command error");
}
}
}
}
} catch (Exception e) {
//Log.e("ActivateProfileHelper.setWifiAP", Log.getStackTraceString(e));
PPApplication.recordException(e);
//PPApplication.logE("$$$ WifiAP", Log.getStackTraceString(e));
}
}
}
else {
if (enable)
wifiApManager.startTethering(doNotChangeWifi);
else
wifiApManager.stopTethering();
}
}
private static void setNFC(Context context, boolean enable)
{
/*
Not working in debug version of application !!!!
Test with release version.
*/
Context appContext = context.getApplicationContext();
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
CmdNfc.setNFC(enable);
}
else
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false))) {
synchronized (PPApplication.rootMutex) {
String command1 = PPApplication.getJavaCommandFile(CmdNfc.class, "nfc", appContext, enable);
if (command1 != null) {
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.NORMAL).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setNFC");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setNFC", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
//String command = PPApplication.getJavaCommandFile(CmdNfc.class, "nfc", context, enable);
//if (command != null)
// RootToolsSmall.runSuCommand(command);
}
}
}
/*
static boolean canExploitGPS(Context context)
{
Context appContext = context.getApplicationContext();
// test exploiting power manager widget
PackageManager pacMan = appContext.getPackageManager();
try {
PackageInfo pacInfo = pacMan.getPackageInfo("com.android.settings", PackageManager.GET_RECEIVERS);
if(pacInfo != null){
for(ActivityInfo actInfo : pacInfo.receivers){
//test if receiver is exported. if so, we can toggle GPS.
if(actInfo.name.equals("com.android.settings.widget.SettingsAppWidgetProvider") && actInfo.exported){
return true;
}
}
}
} catch (Exception e) {
return false; //package not found
}
return false;
}
*/
private static void setGPS(Context context, boolean enable)
{
Context appContext = context.getApplicationContext();
//boolean isEnabled;
//int locationMode = -1;
//if (android.os.Build.VERSION.SDK_INT < 19)
// isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
/*else {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE, -1);
isEnabled = (locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY) ||
(locationMode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY);
}*/
boolean isEnabled = false;
boolean ok = true;
LocationManager locationManager = (LocationManager) appContext.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null)
isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
else
ok = false;
if (!ok)
return;
//PPApplication.logE("ActivateProfileHelper.setGPS", "isEnabled="+isEnabled);
//if(!provider.contains(LocationManager.GPS_PROVIDER) && enable)
if ((!isEnabled) && enable)
{
// adb shell pm grant sk.henrichg.phoneprofilesplus android.permission.WRITE_SECURE_SETTINGS
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
String newSet;
newSet = "+gps";
//noinspection deprecation
Settings.Secure.putString(appContext.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newSet);
}
else
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false)))
{
// device is rooted
//PPApplication.logE("ActivateProfileHelper.setGPS", "rooted");
String command1;
/*
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
PPApplication.logE("ActivateProfileHelper.setGPS", "provider="+provider);
*/
synchronized (PPApplication.rootMutex) {
command1 = "settings put secure location_providers_allowed +gps";
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setGPS (1)");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setGPS", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
/*else
if (canExploitGPS(appContext))
{
//PPApplication.logE("ActivateProfileHelper.setGPS", "exploit");
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
appContext.sendBroadcast(poke);
}*/
}
else
//if(provider.contains(LocationManager.GPS_PROVIDER) && (!enable))
if (isEnabled && (!enable))
{
// adb shell pm grant sk.henrichg.phoneprofilesplus android.permission.WRITE_SECURE_SETTINGS
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
String newSet;// = "";
newSet = "-gps";
//noinspection deprecation
Settings.Secure.putString(appContext.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newSet);
}
else
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false)))
{
// device is rooted
//PPApplication.logE("ActivateProfileHelper.setGPS", "rooted");
String command1;
/*
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
PPApplication.logE("ActivateProfileHelper.setGPS", "provider="+provider);
*/
synchronized (PPApplication.rootMutex) {
command1 = "settings put secure location_providers_allowed -gps";
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setGPS (2)");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setGPS", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
/*else
if (canExploitGPS(appContext))
{
//PPApplication.logE("ActivateProfileHelper.setGPS", "exploit");
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
appContext.sendBroadcast(poke);
}*/
}
}
private static void setLocationMode(Context context, int mode)
{
Context appContext = context.getApplicationContext();
//PPApplication.logE("ActivateProfileHelper.setLocationMode", "mode="+mode);
// adb shell pm grant sk.henrichg.phoneprofilesplus android.permission.WRITE_SECURE_SETTINGS
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
Settings.Secure.putInt(appContext.getContentResolver(), Settings.Secure.LOCATION_MODE, mode);
}
/*else
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false)))
{
// device is rooted - NOT WORKING
PPApplication.logE("ActivateProfileHelper.setLocationMode", "rooted");
String command1;
synchronized (PPApplication.rootMutex) {
command1 = "settings put secure location_mode " + mode;
Command command = new Command(0, false, command1);
try {
roottools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setLocationMode");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setLocationMode", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
}
}*/
}
private static void setPowerSaveMode(final Profile profile, Context context) {
if (profile._devicePowerSaveMode != 0) {
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadProfileActivation();
final Handler handler = new Handler(PPApplication.handlerThreadProfileActivation.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadProfileActivation", "START run - from=ActivateProfileHelper.setPowerSaveMode");
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_POWER_SAVE_MODE, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_setPowerSaveMode");
wakeLock.acquire(10 * 60 * 1000);
}
if (powerManager != null) {
//PowerManager powerManager = (PowerManager) appContext.getSystemService(POWER_SERVICE);
boolean _isPowerSaveMode;
//if (Build.VERSION.SDK_INT >= 21)
_isPowerSaveMode = powerManager.isPowerSaveMode();
boolean _setPowerSaveMode = false;
switch (profile._devicePowerSaveMode) {
case 1:
if (!_isPowerSaveMode) {
_isPowerSaveMode = true;
_setPowerSaveMode = true;
}
break;
case 2:
if (_isPowerSaveMode) {
_isPowerSaveMode = false;
_setPowerSaveMode = true;
}
break;
case 3:
_isPowerSaveMode = !_isPowerSaveMode;
_setPowerSaveMode = true;
break;
}
if (_setPowerSaveMode) {
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
//if (android.os.Build.VERSION.SDK_INT >= 21)
Global.putInt(appContext.getContentResolver(), "low_power", ((_isPowerSaveMode) ? 1 : 0));
} else if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false))) {
synchronized (PPApplication.rootMutex) {
String command1 = "settings put global low_power " + ((_isPowerSaveMode) ? 1 : 0);
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setPowerSaveMode");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setPowerSaveMode", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
}
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
}
});
}
}
private static void lockDevice(final Profile profile, Context context) {
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadProfileActivation();
final Handler handler = new Handler(PPApplication.handlerThreadProfileActivation.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadProfileActivation", "START run - from=ActivateProfileHelper.lockDevice");
//PPApplication.logE("[TEST_BLOCK_PROFILE_EVENTS_ACTIONS] ActivateProfileHelper.lockDevice", "PPApplication.blockProfileEventActions="+PPApplication.blockProfileEventActions);
if (PPApplication.blockProfileEventActions)
// not lock device after boot
return;
/*if (PPApplication.logEnabled()) {
PPApplication.logE("ActivateProfileHelper.lockDevice", "not blocked");
PPApplication.logE("ActivateProfileHelper.lockDevice", "profile._lockDevice=" + profile._lockDevice);
}*/
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_lockDevice");
wakeLock.acquire(10 * 60 * 1000);
}
switch (profile._lockDevice) {
case 1:
if (PhoneProfilesService.getInstance() != null) {
if (Permissions.checkLockDevice(appContext) && (PPApplication.lockDeviceActivity == null)) {
try {
Intent intent = new Intent(appContext, LockDeviceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
appContext.startActivity(intent);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
break;
case 2:
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false))) {
synchronized (PPApplication.rootMutex) {
/*String command1 = "input keyevent 26";
Command command = new Command(0, false, command1);
try {
roottools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (RootDeniedException e) {
PPApplication.rootMutex.rootGranted = false;
Log.e("ActivateProfileHelper.lockDevice", Log.getStackTraceString(e));
} catch (Exception e) {
Log.e("ActivateProfileHelper.lockDevice", Log.getStackTraceString(e));
}*/
String command1 = PPApplication.getJavaCommandFile(CmdGoToSleep.class, "power", appContext, 0);
if (command1 != null) {
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.NORMAL).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.lockDevice");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.lockDevice", Log.getStackTraceString(e));
//CPPApplication.recordException(e);
}
}
}
}
/*if ((!ApplicationPreferences.applicationNeverAskForGrantRoot(context)) &&
(PPApplication.isRooted() && PPApplication.serviceBinaryExists())) {
synchronized (PPApplication.rootMutex) {
try {
// Get the value of the "TRANSACTION_goToSleep" field.
String transactionCode = PPApplication.getTransactionCode("android.os.IPowerManager", "TRANSACTION_goToSleep");
String command1 = "service call power " + transactionCode + " i64 " + SystemClock.uptimeMillis();
Command command = new Command(0, false, command1);
try {
roottools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (RootDeniedException e) {
PPApplication.rootMutex.rootGranted = false;
Log.e("ActivateProfileHelper.lockDevice", Log.getStackTraceString(e));
} catch (Exception e) {
Log.e("ActivateProfileHelper.lockDevice", Log.getStackTraceString(e));
}
} catch(Exception ignored) {
}
}
*/
break;
case 3:
Intent intent = new Intent(PPApplication.ACTION_LOCK_DEVICE);
appContext.sendBroadcast(intent, PPApplication.PPP_EXTENDER_PERMISSION);
break;
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
});
}
private static void setScreenDarkMode(Context appContext, final int value) {
//PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "xxx");
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_SCREEN_DARK_MODE, null, null, false, appContext).allowed
== PreferenceAllowed.PREFERENCE_ALLOWED) {
if (Build.VERSION.SDK_INT >= 29) {
//PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "allowed");
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
//PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "G1 granted");
try {
//PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "value="+value);
// Android Q (Tasker: https://www.reddit.com/r/tasker/comments/d2ngcl/trigger_android_10_dark_theme_with_brightness/)
if (value == 1)
Settings.Secure.putInt(appContext.getContentResolver(), "ui_night_mode", 2);
else
Settings.Secure.putInt(appContext.getContentResolver(), "ui_night_mode", 1);
}
catch (Exception e2) {
//Log.e("ActivateProfileHelper.setScreenDarkMode", Log.getStackTraceString(e2));
PPApplication.recordException(e2);
}
}
else {
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false))) {
//PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "root granted");
synchronized (PPApplication.rootMutex) {
String command1 = "settings put secure ui_night_mode ";
if (value == 1)
command1 = command1 + "2";
else
command1 = command1 + "1";
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenDarkMode");
} catch (Exception ee) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenDarkMode", Log.getStackTraceString(ee));
//PPApplication.recordException(e);
}
}
}
}
// switch car mode on and off is required !!!
// but how when car mode is on by device? Opposite switch?
UiModeManager uiModeManager = (UiModeManager) appContext.getSystemService(Context.UI_MODE_SERVICE);
//PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "uiModeManager=" + uiModeManager);
if (uiModeManager != null) {
if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_NORMAL) {
uiModeManager.enableCarMode(0);
PPApplication.sleep(200);
uiModeManager.disableCarMode(0);
}
else
if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_CAR) {
uiModeManager.disableCarMode(0);
PPApplication.sleep(200);
uiModeManager.enableCarMode(0);
}
}
}
/*if (Build.VERSION.SDK_INT > 26) {
if (Permissions.hasPermission(context, Manifest.permission.WRITE_SECURE_SETTINGS)) {
try {
// Not working in Samsung S8 :-(
// this not change gui to dark, this is blue filter (???)
PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "(G1)");
if (value == 1)
Settings.Global.putInt(context.getContentResolver(), "night_mode_enabled", 1);
else
Settings.Global.putInt(context.getContentResolver(), "night_mode_enabled", 0);
// Android Q (Tasker: https://www.reddit.com/r/tasker/comments/d2ngcl/trigger_android_10_dark_theme_with_brightness/)
if (value == 1)
Settings.Secure.putInt(context.getContentResolver(), "ui_night_mode", 2);
else
Settings.Secure.putInt(context.getContentResolver(), "ui_night_mode", 1);
}
catch (Exception e2) {
PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", Log.getStackTraceString(e2));
}
}
}
else {
UiModeManager uiModeManager = (UiModeManager) context.getSystemService(Context.UI_MODE_SERVICE);
PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "uiModeManager=" + uiModeManager);
if (uiModeManager != null) {
switch (value) {
case 1:
//uiModeManager.enableCarMode(0);
uiModeManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
break;
case 2:
//uiModeManager.enableCarMode(0);
uiModeManager.setNightMode(UiModeManager.MODE_NIGHT_NO);
break;
case 3:
//uiModeManager.disableCarMode(0);
uiModeManager.setNightMode(UiModeManager.MODE_NIGHT_NO);
break;
}
PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "currentModeType=" + uiModeManager.getCurrentModeType());
PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "nightMode=" + uiModeManager.getNightMode());
}
}*/
}
}
private static void setDefaultSimCard(Context context, int subscriptionType, int simCard)
{
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "subscriptionType="+subscriptionType);
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "simCard="+simCard);
Context appContext = context.getApplicationContext();
switch (subscriptionType) {
case SUBSCRIPTRION_VOICE:
switch (simCard) {
case 1: // ask for SIM - currently not supported
simCard = -1;
break;
case 2: // SIM 1
simCard = 1;
break;
case 3: // SIM 2
simCard = 2;
break;
}
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "new simCard="+simCard);
break;
case SUBSCRIPTRION_SMS:
case SUBSCRIPTRION_DATA:
break;
}
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
PPApplication.isRooted(false)) {
if (Permissions.checkPhone(context.getApplicationContext())) {
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "ask for root enabled and is rooted");
if (Build.VERSION.SDK_INT >= 26) {
if (simCard != -1) {
if (PhoneProfilesService.hasSIMCard(appContext, simCard, false)) {
int defaultSubscriptionId = -1;
// Get the value of the "TRANSACTION_setDefaultSimCard" field.
Object serviceManager = PPApplication.getServiceManager("isub");
int transactionCode = -1;
if (serviceManager != null) {
switch (subscriptionType) {
case SUBSCRIPTRION_VOICE:
defaultSubscriptionId = SubscriptionManager.getDefaultVoiceSubscriptionId();
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "getTransactionCode for setDefaultVoiceSubId");
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDefaultVoiceSubId");
break;
case SUBSCRIPTRION_SMS:
defaultSubscriptionId = SubscriptionManager.getDefaultSmsSubscriptionId();
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "getTransactionCode for setDefaultSmsSubId");
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDefaultSmsSubId");
break;
case SUBSCRIPTRION_DATA:
defaultSubscriptionId = SubscriptionManager.getDefaultDataSubscriptionId();
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "getTransactionCode for setDefaultDataSubId");
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDefaultDataSubId");
break;
}
}
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "defaultSubscriptionId=" + defaultSubscriptionId);
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "transactionCode=" + transactionCode);
if (transactionCode != -1) {
SubscriptionManager mSubscriptionManager = (SubscriptionManager) appContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
//SubscriptionManager.from(appContext);
if (mSubscriptionManager != null) {
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "mSubscriptionManager != null");
List<SubscriptionInfo> subscriptionList = null;
try {
// Loop through the subscription list i.e. SIM list.
subscriptionList = mSubscriptionManager.getActiveSubscriptionInfoList();
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "subscriptionList=" + subscriptionList);
} catch (SecurityException e) {
PPApplication.recordException(e);
}
if (subscriptionList != null) {
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "subscriptionList.size()=" + subscriptionList.size());
for (int i = 0; i < subscriptionList.size(); i++) {
// Get the active subscription ID for a given SIM card.
SubscriptionInfo subscriptionInfo = subscriptionList.get(i);
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "subscriptionInfo=" + subscriptionInfo);
if (subscriptionInfo != null) {
int slotIndex = subscriptionInfo.getSimSlotIndex();
if (simCard == (slotIndex+1)) {
int subscriptionId = subscriptionInfo.getSubscriptionId();
if (subscriptionId != defaultSubscriptionId) {
// do not call subscription change, when is aleredy set, this cause FC
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "subscriptionId=" + subscriptionId);
synchronized (PPApplication.rootMutex) {
String command1 = PPApplication.getServiceCommand("isub", transactionCode, subscriptionId);
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "command1=" + command1);
String command2 = "";
switch (subscriptionType) {
case SUBSCRIPTRION_VOICE:
command2 = "settings put global " + Settings.Global.MULTI_SIM_VOICE_CALL_SUBSCRIPTION + " " + subscriptionId;
break;
case SUBSCRIPTRION_SMS:
command2 = "settings put global " + Settings.Global.MULTI_SIM_SMS_SUBSCRIPTION + " " + subscriptionId;
break;
case SUBSCRIPTRION_DATA:
command2 = "settings put global " + Settings.Global.MULTI_SIM_DATA_CALL_SUBSCRIPTION + " " + subscriptionId;
break;
}
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "command2=" + command2);
if ((command1 != null) && (!command2.isEmpty())) {
Command command = new Command(0, false, command2, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setDefaultSimCard");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setDefaultSimCard", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
}
}
}
}
}
else
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "subscriptionInfo == null");
}
}
else
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "subscriptionList == null");
}
else
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "mSubscriptionManager == null");
}
else
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "(transactionCode == -1) || (simCard == -1)");
}
}
else {
synchronized (PPApplication.rootMutex) {
String command1 = "";
switch (subscriptionType) {
case SUBSCRIPTRION_VOICE:
command1 = "settings put global " + Settings.Global.MULTI_SIM_VOICE_CALL_SUBSCRIPTION + " -1";
break;
case SUBSCRIPTRION_SMS:
command1 = "settings put global " + Settings.Global.MULTI_SIM_SMS_SUBSCRIPTION + " -1";
break;
case SUBSCRIPTRION_DATA:
command1 = "settings put global " + Settings.Global.MULTI_SIM_DATA_CALL_SUBSCRIPTION + " -1";
break;
}
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "command1=" + command1);
if (!command1.isEmpty()) {
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setDefaultSimCard");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setDefaultSimCard", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
}
}
}
}
}
}
}
private static void setSIMOnOff(Context context, boolean enable, int simCard)
{
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "xxx");
Context appContext = context.getApplicationContext();
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
PPApplication.isRooted(false) &&
PhoneProfilesService.hasSIMCard(appContext, simCard, true))
{
if (Permissions.checkPhone(context.getApplicationContext())) {
//PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "ask for root enabled and is rooted");
// Get the value of the "TRANSACTION_setDataEnabled" field.
Object serviceManager = PPApplication.getServiceManager("isub");
int transactionCode = -1;
if (serviceManager != null) {
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setSubscriptionEnabled");
}
int state = enable ? 1 : 0;
if (transactionCode != -1) {
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "transactionCode=" + transactionCode);
SubscriptionManager mSubscriptionManager = (SubscriptionManager) appContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
//SubscriptionManager.from(appContext);
if (mSubscriptionManager != null) {
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "mSubscriptionManager != null");
List<SubscriptionInfo> subscriptionList = null;
try {
// Loop through the subscription list i.e. SIM list.
subscriptionList = mSubscriptionManager.getActiveSubscriptionInfoList();
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "subscriptionList=" + subscriptionList);
} catch (SecurityException e) {
PPApplication.recordException(e);
}
if (subscriptionList != null) {
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "subscriptionList.size()=" + subscriptionList.size());
for (int i = 0; i < subscriptionList.size(); i++) {
// Get the active subscription ID for a given SIM card.
SubscriptionInfo subscriptionInfo = subscriptionList.get(i);
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "subscriptionInfo=" + subscriptionInfo);
if (subscriptionInfo != null) {
int slotIndex = subscriptionInfo.getSimSlotIndex();
if (simCard == (slotIndex+1)) {
int subscriptionId = subscriptionInfo.getSubscriptionId();
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "subscriptionId=" + subscriptionId);
synchronized (PPApplication.rootMutex) {
String command1 = PPApplication.getServiceCommand("isub", transactionCode, subscriptionId, state);
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "command1=" + command1);
if (command1 != null) {
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setSIMOnOff");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setSIMOnOff", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
}
}
// else
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "subscriptionInfo == null");
}
}
// else
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "subscriptionList == null");
}
// else
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "mSubscriptionManager == null");
}
// else
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "transactionCode == -1");
}
}
}
static void getRingerVolume(Context context)
{
synchronized (PPApplication.profileActivationMutex) {
ApplicationPreferences.prefRingerVolume = ApplicationPreferences.
getSharedPreferences(context).getInt(PREF_RINGER_VOLUME, -999);
//return prefRingerVolume;
}
}
static void setRingerVolume(Context context, int volume)
{
synchronized (PPApplication.profileActivationMutex) {
final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int systemZenMode = getSystemZenMode(context/*, -1*/);
if (isAudibleSystemRingerMode(audioManager, systemZenMode/*, appContext*/)) {
//PPApplication.logE("ActivateProfileHelper.(s)setRingerVolume","volume="+volume);
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context);
editor.putInt(PREF_RINGER_VOLUME, volume);
editor.apply();
ApplicationPreferences.prefRingerVolume = volume;
}
}
}
static void getNotificationVolume(Context context)
{
synchronized (PPApplication.profileActivationMutex) {
ApplicationPreferences.prefNotificationVolume = ApplicationPreferences.
getSharedPreferences(context).getInt(PREF_NOTIFICATION_VOLUME, -999);
//return prefNotificationVolume;
}
}
static void setNotificationVolume(Context context, int volume)
{
synchronized (PPApplication.profileActivationMutex) {
final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int systemZenMode = getSystemZenMode(context/*, -1*/);
if (isAudibleSystemRingerMode(audioManager, systemZenMode/*, appContext*/)) {
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context);
editor.putInt(PREF_NOTIFICATION_VOLUME, volume);
editor.apply();
ApplicationPreferences.prefNotificationVolume = volume;
}
}
}
// called only from PPApplication.loadProfileActivationData()
static void getRingerMode(Context context)
{
synchronized (PPApplication.profileActivationMutex) {
ApplicationPreferences.prefRingerMode = ApplicationPreferences.
getSharedPreferences(context).getInt(PREF_RINGER_MODE, 0);
//return prefRingerMode;
}
}
static void saveRingerMode(Context context, int mode)
{
synchronized (PPApplication.profileActivationMutex) {
//PPApplication.logE("ActivateProfileHelper.(s)saveRingerMode","mode="+mode);
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context);
editor.putInt(PREF_RINGER_MODE, mode);
editor.apply();
ApplicationPreferences.prefRingerMode = mode;
}
}
// called only from PPApplication.loadProfileActivationData()
static void getZenMode(Context context)
{
synchronized (PPApplication.profileActivationMutex) {
ApplicationPreferences.prefZenMode = ApplicationPreferences.
getSharedPreferences(context).getInt(PREF_ZEN_MODE, 0);
//return prefZenMode;
}
}
static void saveZenMode(Context context, int mode)
{
synchronized (PPApplication.profileActivationMutex) {
//PPApplication.logE("ActivateProfileHelper.(s)saveZenMode","mode="+mode);
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context);
editor.putInt(PREF_ZEN_MODE, mode);
editor.apply();
ApplicationPreferences.prefZenMode = mode;
}
}
static void getLockScreenDisabled(Context context)
{
synchronized (PPApplication.profileActivationMutex) {
ApplicationPreferences.prefLockScreenDisabled = ApplicationPreferences.
getSharedPreferences(context).getBoolean(PREF_LOCKSCREEN_DISABLED, false);
//return prefLockScreenDisabled;
}
}
static void setLockScreenDisabled(Context context, boolean disabled)
{
synchronized (PPApplication.profileActivationMutex) {
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context);
editor.putBoolean(PREF_LOCKSCREEN_DISABLED, disabled);
editor.apply();
ApplicationPreferences.prefLockScreenDisabled = disabled;
}
}
static void getActivatedProfileScreenTimeout(Context context)
{
synchronized (PPApplication.profileActivationMutex) {
ApplicationPreferences.prefActivatedProfileScreenTimeout = ApplicationPreferences.
getSharedPreferences(context).getInt(PREF_ACTIVATED_PROFILE_SCREEN_TIMEOUT, 0);
//return prefActivatedProfileScreenTimeout;
}
}
static void setActivatedProfileScreenTimeout(Context context, int timeout)
{
synchronized (PPApplication.profileActivationMutex) {
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context);
editor.putInt(PREF_ACTIVATED_PROFILE_SCREEN_TIMEOUT, timeout);
editor.apply();
ApplicationPreferences.prefActivatedProfileScreenTimeout = timeout;
}
}
@SuppressWarnings("SameParameterValue")
static void showError(Context context, String profileName, int parameterType) {
if ((context == null) || (profileName == null))
return;
Context appContext = context.getApplicationContext();
String title = appContext.getString(R.string.profile_activation_activation_error_title) + " " + profileName;
String text;
int notificationId;
String notificationTag;
//noinspection SwitchStatementWithTooFewBranches
switch (parameterType) {
case Profile.PARAMETER_TYPE_WIFI:
text = appContext.getString(R.string.profile_activation_activation_error_change_wifi);
notificationId = PPApplication.PROFILE_ACTIVATION_WIFI_ERROR_NOTIFICATION_ID;
notificationTag = PPApplication.PROFILE_ACTIVATION_WIFI_ERROR_NOTIFICATION_TAG;
break;
case Profile.PARAMETER_TYPE_WIFIAP:
text = appContext.getString(R.string.profile_activation_activation_error_change_wifi_ap);
notificationId = PPApplication.PROFILE_ACTIVATION_WIFI_AP_ERROR_NOTIFICATION_ID;
notificationTag = PPApplication.PROFILE_ACTIVATION_WIFI_AP_ERROR_NOTIFICATION_TAG;
break;
case Profile.PARAMETER_CLOSE_ALL_APPLICATION:
text = appContext.getString(R.string.profile_activation_activation_error_close_all_applications);
notificationId = PPApplication.PROFILE_ACTIVATION_CLOSE_ALL_APPLICATIONS_ERROR_NOTIFICATION_ID;
notificationTag = PPApplication.PROFILE_ACTIVATION_CLOSE_ALL_APPLICATIONS_ERROR_NOTIFICATION_TAG;
break;
default:
text = appContext.getString(R.string.profile_activation_activation_error);
notificationId = PPApplication.PROFILE_ACTIVATION_ERROR_NOTIFICATION_ID;
notificationTag = PPApplication.PROFILE_ACTIVATION_ERROR_NOTIFICATION_TAG;
break;
}
String nTitle = title;
String nText = text;
if (android.os.Build.VERSION.SDK_INT < 24) {
nTitle = appContext.getString(R.string.ppp_app_name);
nText = title+": "+text;
}
PPApplication.createInformationNotificationChannel(appContext);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext, PPApplication.EXCLAMATION_NOTIFICATION_CHANNEL)
.setColor(ContextCompat.getColor(appContext, R.color.notificationDecorationColor))
.setSmallIcon(R.drawable.ic_exclamation_notify) // notification icon
.setContentTitle(nTitle) // title for notification
.setContentText(nText) // message for notification
.setAutoCancel(true); // clear notification after click
mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(nText));
//PendingIntent pi = PendingIntent.getActivity(appContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//mBuilder.setContentIntent(pi);
mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
//if (android.os.Build.VERSION.SDK_INT >= 21)
//{
mBuilder.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION);
mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
//}
Notification notification = mBuilder.build();
NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(appContext);
try {
mNotificationManager.notify(notificationTag, notificationId, notification);
} catch (Exception e) {
//Log.e("ActivateProfileHelper.showNotificationForInteractiveParameters", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
}
}
| phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/ActivateProfileHelper.java | package sk.henrichg.phoneprofilesplus;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.UiModeManager;
import android.app.WallpaperManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.provider.Settings.Global;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.IconCompat;
import androidx.work.Data;
import androidx.work.ExistingWorkPolicy;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import com.noob.noobcameraflash.managers.NoobCameraManager;
import com.stericson.rootshell.execution.Command;
import com.stericson.rootshell.execution.Shell;
import com.stericson.roottools.RootTools;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static android.app.Notification.DEFAULT_VIBRATE;
class ActivateProfileHelper {
static boolean disableScreenTimeoutInternalChange = false;
static boolean brightnessDialogInternalChange = false;
// bluetooth calls volume stream
static final int STREAM_BLUETOOTH_SCO = 6;
//static final String ADAPTIVE_BRIGHTNESS_SETTING_NAME = "screen_auto_brightness_adj";
// Setting.Global "zen_mode"
static final int ZENMODE_ALL = 0;
static final int ZENMODE_PRIORITY = 1;
static final int ZENMODE_NONE = 2;
static final int ZENMODE_ALARMS = 3;
@SuppressWarnings("WeakerAccess")
static final int ZENMODE_SILENT = 99;
static final int SUBSCRIPTRION_VOICE = 1;
static final int SUBSCRIPTRION_SMS = 2;
static final int SUBSCRIPTRION_DATA = 3;
//static final String EXTRA_MERGED_PROFILE = "merged_profile";
//static final String EXTRA_FOR_PROFILE_ACTIVATION = "for_profile_activation";
private static final String PREF_RINGER_VOLUME = "ringer_volume";
private static final String PREF_NOTIFICATION_VOLUME = "notification_volume";
private static final String PREF_RINGER_MODE = "ringer_mode";
private static final String PREF_ZEN_MODE = "zen_mode";
private static final String PREF_LOCKSCREEN_DISABLED = "lockscreenDisabled";
private static final String PREF_ACTIVATED_PROFILE_SCREEN_TIMEOUT = "activated_profile_screen_timeout";
static final String PREF_MERGED_RING_NOTIFICATION_VOLUMES = "merged_ring_notification_volumes";
static final String EXTRA_PROFILE_NAME = "profile_name";
@SuppressLint("MissingPermission")
private static void doExecuteForRadios(Context context, Profile profile)
{
/*if (PPApplication.logEnabled()) {
PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "profile=" + profile);
if (profile != null)
PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "profile._name=" + profile._name);
}*/
if (profile == null)
return;
PPApplication.sleep(300);
Context appContext = context.getApplicationContext();
// switch on/off SIM
if (Build.VERSION.SDK_INT >= 26) {
final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
int phoneCount = telephonyManager.getPhoneCount();
if (phoneCount > 1) {
if (profile._deviceOnOffSIM1 != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_ONOFF_SIM1, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM1");
//boolean _isSIM1On = isSIMOn(appContext, 1);
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios","_isSIM1On="+_isSIM1On);
boolean _setSIM1OnOff = false;
switch (profile._deviceOnOffSIM1) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM1 1");
_setSIM1OnOff = true;
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM1 2");
//noinspection DuplicateBranchesInSwitch
_setSIM1OnOff = true;
break;
}
if ( _setSIM1OnOff) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setSIMOnOff()");
//noinspection ConstantConditions
setSIMOnOff(appContext, _setSIM1OnOff, 1);
PPApplication.sleep(200);
}
}
//else
// PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM1 NOT ALLOWED");
}
if (profile._deviceOnOffSIM2 != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_ONOFF_SIM2, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM2");
//boolean _isSIM2On = isSIMOn(appContext, 2);
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios","_isSIM2On="+_isSIM2On);
boolean _setSIM2OnOff = false;
switch (profile._deviceOnOffSIM2) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM2 1");
_setSIM2OnOff = true;
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM2 2");
//noinspection DuplicateBranchesInSwitch
_setSIM2OnOff = true;
break;
}
if ( _setSIM2OnOff) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setSIMOnOff()");
//noinspection ConstantConditions
setSIMOnOff(appContext, _setSIM2OnOff, 2);
PPApplication.sleep(200);
}
}
//else
// PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "_deviceOnOffSIM1 NOT ALLOWED");
}
}
}
}
// change default SIM
if (Build.VERSION.SDK_INT >= 26) {
if (!profile._deviceDefaultSIMCards.equals("0|0|0")) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_DEFAULT_SIM_CARDS, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.doExecuteForRadios", "profile._deviceDefaultSIMCards="+profile._deviceDefaultSIMCards);
String[] splits = profile._deviceDefaultSIMCards.split("\\|");
try {
String voice = splits[0];
if (!voice.equals("0")) {
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.doExecuteForRadios", "voice value="+Integer.parseInt(voice));
setDefaultSimCard(context, SUBSCRIPTRION_VOICE, Integer.parseInt(voice));
}
} catch (Exception e) {
PPApplication.recordException(e);
}
try {
String sms = splits[1];
if (!sms.equals("0")) {
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.doExecuteForRadios", "sms value="+Integer.parseInt(sms));
setDefaultSimCard(context, SUBSCRIPTRION_SMS, Integer.parseInt(sms));
}
} catch (Exception e) {
PPApplication.recordException(e);
}
try {
String data = splits[2];
if (!data.equals("0")) {
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.doExecuteForRadios", "data value="+Integer.parseInt(data));
setDefaultSimCard(context, SUBSCRIPTRION_DATA, Integer.parseInt(data));
}
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
}
// setup network type
// in array.xml, networkTypeGSMValues are 100+ values
if (profile._deviceNetworkType >= 100) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_NETWORK_TYPE, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceNetworkType");
// in array.xml, networkTypeGSMValues are 100+ values
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setPreferredNetworkType()");
setPreferredNetworkType(appContext, profile._deviceNetworkType - 100, 0);
PPApplication.sleep(200);
}
}
if (Build.VERSION.SDK_INT >= 26) {
final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
int phoneCount = telephonyManager.getPhoneCount();
if (phoneCount > 1) {
if (profile._deviceNetworkTypeSIM1 >= 100) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_NETWORK_TYPE_SIM1, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceNetworkType");
// in array.xml, networkTypeGSMValues are 100+ values
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setPreferredNetworkType()");
setPreferredNetworkType(appContext, profile._deviceNetworkTypeSIM1 - 100, 1);
PPApplication.sleep(200);
}
}
if (profile._deviceNetworkTypeSIM2 >= 100) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_NETWORK_TYPE_SIM2, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceNetworkType");
// in array.xml, networkTypeGSMValues are 100+ values
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setPreferredNetworkType()");
setPreferredNetworkType(appContext, profile._deviceNetworkTypeSIM2 - 100, 2);
PPApplication.sleep(200);
}
}
}
}
}
// setup mobile data
if (profile._deviceMobileData != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_MOBILE_DATA, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileData");
boolean _isMobileData = isMobileData(appContext, 0);
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios","_isMobileData="+_isMobileData);
boolean _setMobileData = false;
switch (profile._deviceMobileData) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileData 1");
if (!_isMobileData) {
_isMobileData = true;
_setMobileData = true;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileData 2");
if (_isMobileData) {
_isMobileData = false;
_setMobileData = true;
}
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileData 3");
_isMobileData = !_isMobileData;
_setMobileData = true;
break;
}
if (_setMobileData) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setMobileData()");
setMobileData(appContext, _isMobileData, 0);
PPApplication.sleep(200);
}
}
//else
// PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "_deviceMobileData NOT ALLOWED");
}
if (Build.VERSION.SDK_INT >= 26) {
final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
int phoneCount = telephonyManager.getPhoneCount();
if (phoneCount > 1) {
if (profile._deviceMobileDataSIM1 != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_MOBILE_DATA_SIM1, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM1");
boolean _isMobileData = isMobileData(appContext, 1);
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios","_isMobileData="+_isMobileData);
boolean _setMobileData = false;
switch (profile._deviceMobileDataSIM1) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM1 1");
if (!_isMobileData) {
_isMobileData = true;
_setMobileData = true;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM1 2");
if (_isMobileData) {
_isMobileData = false;
_setMobileData = true;
}
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM1 3");
_isMobileData = !_isMobileData;
_setMobileData = true;
break;
}
if (_setMobileData) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setMobileData()");
setMobileData(appContext, _isMobileData, 1);
PPApplication.sleep(200);
}
}
//else
// PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM1 NOT ALLOWED");
}
if (profile._deviceMobileDataSIM2 != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_MOBILE_DATA_SIM2, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM2");
boolean _isMobileData = isMobileData(appContext, 2);
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios","_isMobileData="+_isMobileData);
boolean _setMobileData = false;
switch (profile._deviceMobileDataSIM2) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM2 1");
if (!_isMobileData) {
_isMobileData = true;
_setMobileData = true;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM2 2");
if (_isMobileData) {
_isMobileData = false;
_setMobileData = true;
}
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM2 3");
_isMobileData = !_isMobileData;
_setMobileData = true;
break;
}
if (_setMobileData) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setMobileData()");
setMobileData(appContext, _isMobileData, 2);
PPApplication.sleep(200);
}
}
//else
// PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "_deviceMobileDataSIM2 NOT ALLOWED");
}
}
}
}
// setup WiFi AP
boolean canChangeWifi = true;
if (profile._deviceWiFiAP != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_WIFI_AP, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFiAP");
if (Build.VERSION.SDK_INT < 28) {
WifiApManager wifiApManager = null;
try {
wifiApManager = new WifiApManager(appContext);
} catch (Exception e) {
PPApplication.recordException(e);
}
if (wifiApManager != null) {
boolean setWifiAPState = false;
boolean doNotChangeWifi = false;
boolean isWifiAPEnabled = wifiApManager.isWifiAPEnabled();
switch (profile._deviceWiFiAP) {
case 1:
case 4:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFiAP 1");
if (!isWifiAPEnabled) {
isWifiAPEnabled = true;
setWifiAPState = true;
doNotChangeWifi = profile._deviceWiFiAP == 4;
canChangeWifi = profile._deviceWiFiAP == 4;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFiAP 2");
if (isWifiAPEnabled) {
isWifiAPEnabled = false;
setWifiAPState = true;
canChangeWifi = true;
}
break;
case 3:
case 5:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFiAP 3");
isWifiAPEnabled = !isWifiAPEnabled;
setWifiAPState = true;
doNotChangeWifi = profile._deviceWiFiAP == 5;
if (doNotChangeWifi)
canChangeWifi = true;
else
canChangeWifi = !isWifiAPEnabled;
break;
}
if (setWifiAPState) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setWifiAP()");
setWifiAP(wifiApManager, isWifiAPEnabled, doNotChangeWifi, appContext);
PPApplication.sleep(3000);
}
}
}
else if (Build.VERSION.SDK_INT < 30) {
// not working in Android 11+
boolean setWifiAPState = false;
boolean doNotChangeWifi = false;
boolean isWifiAPEnabled = CmdWifiAP.isEnabled();
switch (profile._deviceWiFiAP) {
case 1:
case 4:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFiAP 1");
if (!isWifiAPEnabled) {
isWifiAPEnabled = true;
setWifiAPState = true;
doNotChangeWifi = profile._deviceWiFiAP == 4;
canChangeWifi = profile._deviceWiFiAP == 4;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFiAP 2");
if (isWifiAPEnabled) {
isWifiAPEnabled = false;
setWifiAPState = true;
canChangeWifi = true;
}
break;
case 3:
case 5:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFiAP 3");
isWifiAPEnabled = !isWifiAPEnabled;
setWifiAPState = true;
doNotChangeWifi = profile._deviceWiFiAP == 5;
if (doNotChangeWifi)
canChangeWifi = true;
else
canChangeWifi = !isWifiAPEnabled;
break;
}
if (setWifiAPState) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "CmdWifiAP.setWifiAP()");
CmdWifiAP.setWifiAP(isWifiAPEnabled, doNotChangeWifi, context, profile._name);
PPApplication.sleep(1000);
}
}
}
}
if (canChangeWifi) {
// setup Wi-Fi
if (profile._deviceWiFi != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_WIFI, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFi");
boolean isWifiAPEnabled;
if (Build.VERSION.SDK_INT < 28)
isWifiAPEnabled = WifiApManager.isWifiAPEnabled(appContext);
else
isWifiAPEnabled = CmdWifiAP.isEnabled();
// PPApplication.logE("[WIFI] ActivateProfileHelper.doExecuteForRadios", "isWifiAPEnabled="+isWifiAPEnabled);
if ((!isWifiAPEnabled) || (profile._deviceWiFi >= 4)) { // only when wifi AP is not enabled, change wifi
WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null) {
int wifiState = wifiManager.getWifiState();
boolean isWifiEnabled = ((wifiState == WifiManager.WIFI_STATE_ENABLED) || (wifiState == WifiManager.WIFI_STATE_ENABLING));
boolean setWifiState = false;
switch (profile._deviceWiFi) {
case 1:
case 4:
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFi 1,4");
if (!isWifiEnabled) {
isWifiEnabled = true;
setWifiState = true;
}
break;
case 2:
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFi 2");
if (isWifiEnabled) {
isWifiEnabled = false;
setWifiState = true;
}
break;
case 3:
case 5:
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceWiFi 3,5");
isWifiEnabled = !isWifiEnabled;
setWifiState = true;
break;
}
// PPApplication.logE("[WIFI] ActivateProfileHelper.doExecuteForRadios", "isWifiEnabled="+isWifiEnabled);
// PPApplication.logE("[WIFI] ActivateProfileHelper.doExecuteForRadios", "setWifiState="+setWifiState);
if (isWifiEnabled) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setWifiEnabledForScan()");
// when wifi is enabled from profile, no disable wifi after scan
WifiScanWorker.setWifiEnabledForScan(appContext, false);
}
if (setWifiState) {
try {
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setWifiEnabled()");
//PPApplication.logE("#### setWifiEnabled", "from ActivateProfileHelper.doExecuteForRadio");
//if (Build.VERSION.SDK_INT >= 29)
// CmdWifi.setWifi(isWifiEnabled);
//else
wifiManager.setWifiEnabled(isWifiEnabled);
//CmdWifi.setWifiEnabled(isWifiAPEnabled);
} catch (Exception e) {
//WTF?: DOOGEE- X5pro - java.lang.SecurityException: Permission Denial: Enable WiFi requires com.mediatek.permission.CTA_ENABLE_WIFI
//Log.e("ActivateProfileHelper.doExecuteForRadios", Log.getStackTraceString(e));
//PPApplication.recordException(e);;
showError(context, profile._name, Profile.PARAMETER_TYPE_WIFI);
}
PPApplication.sleep(200);
}
}
}
}
}
// connect to SSID
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_CONNECT_TO_SSID, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
if (!profile._deviceConnectToSSID.equals(Profile.CONNECTTOSSID_JUSTANY)) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceConnectToSSID");
if (Permissions.checkLocation(appContext)) {
WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null) {
int wifiState = wifiManager.getWifiState();
if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
// check if wifi is connected
ConnectivityManager connManager = null;
try {
connManager = (ConnectivityManager) appContext.getSystemService(Context.CONNECTIVITY_SERVICE);
} catch (Exception e) {
// java.lang.NullPointerException: missing IConnectivityManager
// Dual SIM?? Bug in Android ???
PPApplication.recordException(e);
}
if (connManager != null) {
boolean wifiConnected = false;
/*if (Build.VERSION.SDK_INT < 28) {
NetworkInfo activeNetwork = connManager.getActiveNetworkInfo();
wifiConnected = (activeNetwork != null) &&
(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) &&
activeNetwork.isConnected();
}
else*/ {
Network[] activeNetworks=connManager.getAllNetworks();
for(Network network : activeNetworks){
try {
//NetworkInfo networkInfo = connManager.getNetworkInfo(network);
//if ((networkInfo != null) && networkInfo.isConnected()) {
NetworkCapabilities networkCapabilities = connManager.getNetworkCapabilities(network);
if ((networkCapabilities != null) && networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
wifiConnected = WifiNetworkCallback.connected;
break;
}
//}
} catch (Exception ee) {
PPApplication.recordException(ee);
}
}
}
WifiInfo wifiInfo = null;
if (wifiConnected)
wifiInfo = wifiManager.getConnectionInfo();
List<WifiConfiguration> list = null;
if (Permissions.hasPermission(appContext, Manifest.permission.ACCESS_FINE_LOCATION))
list = wifiManager.getConfiguredNetworks();
if (list != null) {
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals(profile._deviceConnectToSSID)) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceConnectToSSID wifiConnected="+wifiConnected);
if (wifiConnected) {
if (!wifiInfo.getSSID().equals(i.SSID)) {
if (PhoneProfilesService.getInstance() != null)
PhoneProfilesService.getInstance().connectToSSIDStarted = true;
// connected to another SSID
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
}
} else
wifiManager.enableNetwork(i.networkId, true);
break;
}
}
}
}
}
}
}
}
//else {
// WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
// int wifiState = wifiManager.getWifiState();
// if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
// wifiManager.disconnect();
// wifiManager.reconnect();
// }
//}
if (PhoneProfilesService.getInstance() != null)
PhoneProfilesService.getInstance().connectToSSID = profile._deviceConnectToSSID;
}
}
// setup bluetooth
if (profile._deviceBluetooth != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_BLUETOOTH, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceBluetooth");
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //BluetoothScanWorker.getBluetoothAdapter(context);
if (bluetoothAdapter != null) {
boolean isBluetoothEnabled = bluetoothAdapter.isEnabled();
boolean setBluetoothState = false;
switch (profile._deviceBluetooth) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceBluetooth 1");
if (!isBluetoothEnabled) {
isBluetoothEnabled = true;
setBluetoothState = true;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceBluetooth 2");
if (isBluetoothEnabled) {
isBluetoothEnabled = false;
setBluetoothState = true;
}
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceBluetooth 3");
isBluetoothEnabled = !isBluetoothEnabled;
setBluetoothState = true;
break;
}
/*if (PPApplication.logEnabled()) {
PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "setBluetoothState=" + setBluetoothState);
PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "isBluetoothEnabled=" + isBluetoothEnabled);
}*/
if (isBluetoothEnabled) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "setBluetoothEnabledForScan()");
// when bluetooth is enabled from profile, no disable bluetooth after scan
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "isBluetoothEnabled=true; setBluetoothEnabledForScan=false");
BluetoothScanWorker.setBluetoothEnabledForScan(appContext, false);
}
if (setBluetoothState) {
try {
//if (Build.VERSION.SDK_INT >= 26)
// CmdBluetooth.setBluetooth(isBluetoothEnabled);
//else {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "enable/disable bluetooth adapter");
if (isBluetoothEnabled)
bluetoothAdapter.enable();
else
bluetoothAdapter.disable();
//}
} catch (Exception e) {
// WTF?: DOOGEE - X5pro -> java.lang.SecurityException: Permission Denial: Enable bluetooth requires com.mediatek.permission.CTA_ENABLE_BT
//Log.e("ActivateProfileHelper.doExecuteForRadio", Log.getStackTraceString(e));
//PPApplication.recordException(e);;
}
}
}
}
}
// setup location mode
if (profile._deviceLocationMode != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_LOCATION_MODE, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceLocationMode");
switch (profile._deviceLocationMode) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceLocationMode 1");
setLocationMode(appContext, Settings.Secure.LOCATION_MODE_OFF);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceLocationMode 2");
setLocationMode(appContext, Settings.Secure.LOCATION_MODE_SENSORS_ONLY);
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceLocationMode 3");
setLocationMode(appContext, Settings.Secure.LOCATION_MODE_BATTERY_SAVING);
break;
case 4:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceLocationMode 4");
setLocationMode(appContext, Settings.Secure.LOCATION_MODE_HIGH_ACCURACY);
break;
}
}
}
// setup GPS
if (profile._deviceGPS != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_GPS, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceGPS");
//String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
boolean isEnabled = false;
boolean ok = true;
/*if (android.os.Build.VERSION.SDK_INT < 19)
isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
else {*/
LocationManager locationManager = (LocationManager) appContext.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null)
isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
else
ok = false;
//}
if (ok) {
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "isEnabled=" + isEnabled);
switch (profile._deviceGPS) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceGPS 1");
setGPS(appContext, true);
//setLocationMode(appContext, true);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceGPS 2");
setGPS(appContext, false);
//setLocationMode(appContext, false);
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceGPS 3");
//setLocationMode(appContext, true);
//setLocationMode(appContext, false);
setGPS(appContext, !isEnabled);
break;
}
}
}
}
// setup NFC
if (profile._deviceNFC != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_NFC, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceNFC");
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(appContext);
if (nfcAdapter != null) {
switch (profile._deviceNFC) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceNFC 1");
setNFC(appContext, true);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceNFC 2");
setNFC(appContext, false);
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.doExecuteForRadios", "_deviceNFC 3");
setNFC(appContext, !nfcAdapter.isEnabled());
break;
}
}
}
}
}
private static void executeForRadios(final Profile profile, Context context)
{
/*if (PPApplication.logEnabled()) {
PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "profile=" + profile);
if (profile != null)
PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "profile._name=" + profile._name);
}*/
if (profile == null)
return;
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadRadios();
final Handler handler = new Handler(PPApplication.handlerThreadRadios.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadRadios", "START run - from=ActivateProfileHelper.executeForRadios");
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_executeForRadios");
wakeLock.acquire(10 * 60 * 1000);
}
boolean _isAirplaneMode = false;
boolean _setAirplaneMode = false;
if (profile._deviceAirplaneMode != 0) {
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_AIRPLANE_MODE, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
_isAirplaneMode = isAirplaneMode(appContext);
switch (profile._deviceAirplaneMode) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "_deviceAirplaneMode 1");
if (!_isAirplaneMode) {
_isAirplaneMode = true;
_setAirplaneMode = true;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "_deviceAirplaneMode 2");
if (_isAirplaneMode) {
_isAirplaneMode = false;
_setAirplaneMode = true;
}
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "_deviceAirplaneMode 3");
_isAirplaneMode = !_isAirplaneMode;
_setAirplaneMode = true;
break;
}
}
}
if (_setAirplaneMode /*&& _isAirplaneMode*/) {
// switch ON airplane mode, set it before doExecuteForRadios
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "setAirplaneMode()");
setAirplaneMode(/*context,*/ _isAirplaneMode);
PPApplication.sleep(2500);
//PPApplication.logE("ActivateProfileHelper.executeForRadios", "after sleep");
}
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "doExecuteForRadios()");
doExecuteForRadios(appContext, profile);
/*if (_setAirplaneMode && (!_isAirplaneMode)) {
// 200 milliseconds is in doExecuteForRadios
PPApplication.sleep(1800);
// switch OFF airplane mode, set if after executeForRadios
setAirplaneMode(context, _isAirplaneMode);
}*/
//PPApplication.sleep(500);
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForRadios", "end");
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
});
}
static boolean isAudibleRinging(int ringerMode, int zenMode/*, boolean onlyVibrateSilent*/) {
/*if (onlyVibrateSilent)
return (!((ringerMode == Profile.RINGERMODE_VIBRATE) || (ringerMode == Profile.RINGERMODE_SILENT) ||
((ringerMode == Profile.RINGERMODE_ZENMODE) &&
((zenMode == Profile.ZENMODE_ALL_AND_VIBRATE) || (zenMode == Profile.ZENMODE_PRIORITY_AND_VIBRATE)))
));
else*/
return (!((ringerMode == Profile.RINGERMODE_VIBRATE) || (ringerMode == Profile.RINGERMODE_SILENT) ||
((ringerMode == Profile.RINGERMODE_ZENMODE) &&
((zenMode == Profile.ZENMODE_NONE) || (zenMode == Profile.ZENMODE_ALL_AND_VIBRATE) ||
(zenMode == Profile.ZENMODE_PRIORITY_AND_VIBRATE) || (zenMode == Profile.ZENMODE_ALARMS)))
));
}
private static boolean isVibrateRingerMode(int ringerMode/*, int zenMode*/) {
return (ringerMode == Profile.RINGERMODE_VIBRATE);
}
static boolean isAudibleSystemRingerMode(AudioManager audioManager, int systemZenMode/*, Context context*/) {
/*int ringerMode = audioManager.getRingerMode();
PPApplication.logE("ActivateProfileHelper.isAudibleSystemRingerMode", "ringerMode="+ringerMode);
if (ringerMode != AudioManager.RINGER_MODE_NORMAL) {
if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
int zenMode = getSystemZenMode(context, -1);
return (zenMode == ActivateProfileHelper.ZENMODE_PRIORITY);
}
else
return false;
}
else
return true;*/
int systemRingerMode = audioManager.getRingerMode();
//int systemZenMode = getSystemZenMode(context/*, -1*/);
/*return (audibleRingerMode) ||
((systemZenMode == ActivateProfileHelper.ZENMODE_PRIORITY) &&
(systemRingerMode != AudioManager.RINGER_MODE_VIBRATE));*/
/*if (PPApplication.logEnabled()) {
PPApplication.logE("ActivateProfileHelper.isAudibleSystemRingerMode", "systemRingerMode=" + systemRingerMode);
PPApplication.logE("ActivateProfileHelper.isAudibleSystemRingerMode", "systemZenMode=" + systemZenMode);
}*/
boolean audibleRingerMode;
// In AOSP, when systemZenMode == ActivateProfileHelper.ZENMODE_PRIORITY, systemRingerMode == AudioManager.RINGER_MODE_SILENT :-/
if (systemZenMode == ActivateProfileHelper.ZENMODE_PRIORITY) {
audibleRingerMode = (systemRingerMode == AudioManager.RINGER_MODE_NORMAL) ||
(systemRingerMode == AudioManager.RINGER_MODE_SILENT);
}
else
audibleRingerMode = systemRingerMode == AudioManager.RINGER_MODE_NORMAL;
boolean audibleZenMode = (systemZenMode == -1) ||
(systemZenMode == ActivateProfileHelper.ZENMODE_ALL) ||
(systemZenMode == ActivateProfileHelper.ZENMODE_PRIORITY);
return audibleRingerMode && audibleZenMode;
}
/*
private static void correctVolume0(AudioManager audioManager) {
int ringerMode, zenMode;
ringerMode = PPApplication.getRingerMode(context);
zenMode = PPApplication.getZenMode(context);
if ((ringerMode == 1) || (ringerMode == 2) || (ringerMode == 4) ||
((ringerMode == 5) && ((zenMode == 1) || (zenMode == 2)))) {
// any "nonVIBRATE" ringer mode is selected
if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
// actual system ringer mode = vibrate
// volume changed it to vibrate
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_RING, 1, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
PhoneProfilesService.ringingVolume = 1;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, 1);
}
}
}
*/
static void getMergedRingNotificationVolumes(Context context) {
synchronized (PPApplication.profileActivationMutex) {
ApplicationPreferences.prefMergedRingNotificationVolumes =
ApplicationPreferences.getSharedPreferences(context).getBoolean(PREF_MERGED_RING_NOTIFICATION_VOLUMES, true);
}
}
static boolean getMergedRingNotificationVolumes() {
//PPApplication.logE("ActivateProfileHelper.getMergedRingNotificationVolumes", "force set="+ApplicationPreferences.applicationForceSetMergeRingNotificationVolumes(context));
//PPApplication.logE("ActivateProfileHelper.getMergedRingNotificationVolumes", "merged="+ApplicationPreferences.preferences.getBoolean(PREF_MERGED_RING_NOTIFICATION_VOLUMES, true));
if (ApplicationPreferences.applicationForceSetMergeRingNotificationVolumes > 0)
return ApplicationPreferences.applicationForceSetMergeRingNotificationVolumes == 1;
else
return ApplicationPreferences.prefMergedRingNotificationVolumes;
}
// test if ring and notification volumes are merged
static void setMergedRingNotificationVolumes(Context context/*, boolean force*/) {
synchronized (PPApplication.profileActivationMutex) {
//PPApplication.logE("ActivateProfileHelper.setMergedRingNotificationVolumes", "xxx");
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context);
setMergedRingNotificationVolumes(context, /*force,*/ editor);
editor.apply();
}
}
static void setMergedRingNotificationVolumes(Context context, /*boolean force,*/ SharedPreferences.Editor editor) {
synchronized (PPApplication.profileActivationMutex) {
//PPApplication.logE("ActivateProfileHelper.setMergedRingNotificationVolumes", "xxx");
Context appContext = context.getApplicationContext();
//if (!ApplicationPreferences.getSharedPreferences(appContext).contains(PREF_MERGED_RING_NOTIFICATION_VOLUMES) || force) {
try {
boolean merged;
AudioManager audioManager = (AudioManager) appContext.getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) {
//RingerModeChangeReceiver.internalChange = true;
int ringerMode = audioManager.getRingerMode();
int maximumNotificationValue = audioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);
int oldRingVolume = audioManager.getStreamVolume(AudioManager.STREAM_RING);
int oldNotificationVolume = audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
if (oldRingVolume == oldNotificationVolume) {
int newNotificationVolume;
if (oldNotificationVolume == maximumNotificationValue)
newNotificationVolume = oldNotificationVolume - 1;
else
newNotificationVolume = oldNotificationVolume + 1;
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, newNotificationVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
PPApplication.sleep(2000);
merged = audioManager.getStreamVolume(AudioManager.STREAM_RING) == newNotificationVolume;
} else
merged = false;
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, oldNotificationVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
audioManager.setRingerMode(ringerMode);
//PPApplication.logE("ActivateProfileHelper.setMergedRingNotificationVolumes", "merged=" + merged);
editor.putBoolean(PREF_MERGED_RING_NOTIFICATION_VOLUMES, merged);
ApplicationPreferences.prefMergedRingNotificationVolumes = merged;
}
} catch (Exception e) {
//PPApplication.recordException(e);
}
//}
}
}
@SuppressLint("NewApi")
private static void setVolumes(Context context, Profile profile, AudioManager audioManager, int systemZenMode,
int linkUnlink, boolean forProfileActivation, boolean forRingerMode)
{
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile=" + profile);
if (profile == null)
return;
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile._name=" + profile._name);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "linkUnlink=" + linkUnlink);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "forProfileActivation=" + forProfileActivation);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "forRingerMode=" + forRingerMode);
Context appContext = context.getApplicationContext();
int ringerMode = ApplicationPreferences.prefRingerMode;
//PPApplication.logE("ActivateProfileHelper.setVolumes", "ringerMode=" + ringerMode);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile._volumeMuteSound=" + profile._volumeMuteSound);
if (profile._volumeMuteSound) {
if (isAudibleSystemRingerMode(audioManager, systemZenMode) || (ringerMode == 0)) {
if (!audioManager.isStreamMute(AudioManager.STREAM_RING))
audioManager.adjustStreamVolume(AudioManager.STREAM_RING, AudioManager.ADJUST_MUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (!audioManager.isStreamMute(AudioManager.STREAM_NOTIFICATION))
audioManager.adjustStreamVolume(AudioManager.STREAM_NOTIFICATION, AudioManager.ADJUST_MUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (!audioManager.isStreamMute(AudioManager.STREAM_SYSTEM))
audioManager.adjustStreamVolume(AudioManager.STREAM_SYSTEM, AudioManager.ADJUST_MUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (!audioManager.isStreamMute(AudioManager.STREAM_DTMF))
audioManager.adjustStreamVolume(AudioManager.STREAM_DTMF, AudioManager.ADJUST_MUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
if (!audioManager.isStreamMute(AudioManager.STREAM_MUSIC))
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
else {
if (isAudibleSystemRingerMode(audioManager, systemZenMode) || (ringerMode == 0)) {
if (audioManager.isStreamMute(AudioManager.STREAM_RING))
audioManager.adjustStreamVolume(AudioManager.STREAM_RING, AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (audioManager.isStreamMute(AudioManager.STREAM_NOTIFICATION))
audioManager.adjustStreamVolume(AudioManager.STREAM_NOTIFICATION, AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (audioManager.isStreamMute(AudioManager.STREAM_SYSTEM))
audioManager.adjustStreamVolume(AudioManager.STREAM_SYSTEM, AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (audioManager.isStreamMute(AudioManager.STREAM_DTMF))
audioManager.adjustStreamVolume(AudioManager.STREAM_DTMF, AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
if (audioManager.isStreamMute(AudioManager.STREAM_MUSIC))
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
// get mute state before set of all volumes; system stream may set mute to true
boolean ringMuted = audioManager.isStreamMute(AudioManager.STREAM_RING);
boolean notificationMuted = audioManager.isStreamMute(AudioManager.STREAM_NOTIFICATION);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "ring mute status="+ringMuted);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "notification mute status="+notificationMuted);
boolean systemMuted = audioManager.isStreamMute(AudioManager.STREAM_SYSTEM);
boolean dtmfMuted = audioManager.isStreamMute(AudioManager.STREAM_DTMF);
boolean musicMuted = audioManager.isStreamMute(AudioManager.STREAM_MUSIC);
if (forRingerMode) {
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeRingtoneChange()=" + profile.getVolumeRingtoneChange());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeRingtoneValue()=" + profile.getVolumeRingtoneValue());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeNotificationChange()=" + profile.getVolumeNotificationChange());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeNotificationValue()=" + profile.getVolumeNotificationValue());
if (!profile._volumeMuteSound) {
if (!ringMuted) {
if (profile.getVolumeRingtoneChange()) {
if (forProfileActivation) {
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
setRingerVolume(appContext, profile.getVolumeRingtoneValue());
}
}
}
if (!notificationMuted) {
if (profile.getVolumeNotificationChange()) {
if (forProfileActivation) {
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
setNotificationVolume(appContext, profile.getVolumeNotificationValue());
}
}
}
}
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeAccessibilityChange()=" + profile.getVolumeAccessibilityChange());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeAccessibilityValue()=" + profile.getVolumeAccessibilityValue());
if (forProfileActivation) {
if (Build.VERSION.SDK_INT >= 26) {
if (profile.getVolumeAccessibilityChange()) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_ACCESSIBILITY /* 10 */, profile.getVolumeAccessibilityValue(), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.STREAM_ACCESSIBILITY, profile.getVolumeAccessibilityValue());
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
}
//PPApplication.logE("ActivateProfileHelper.setVolumes", "isAudibleSystemRingerMode=" + isAudibleSystemRingerMode(audioManager, systemZenMode/*, appContext*/));
if (!profile._volumeMuteSound) {
//if (isAudibleRinging(ringerMode, zenMode, true) || (ringerMode == 0)) {
if (isAudibleSystemRingerMode(audioManager, systemZenMode/*, appContext*/) || (ringerMode == 0)) {
// test only system ringer mode
//PPApplication.logE("ActivateProfileHelper.setVolumes", "ringer/notification/system change");
//if (Permissions.checkAccessNotificationPolicy(context)) {
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeDTMFChange()=" + profile.getVolumeDTMFChange());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeDTMFValue()=" + profile.getVolumeDTMFValue());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeSystemChange()=" + profile.getVolumeSystemChange());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "profile.getVolumeSystemValue()=" + profile.getVolumeSystemValue());
if (forProfileActivation) {
if (!dtmfMuted) {
if (profile.getVolumeDTMFChange()) {
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
try {
audioManager.setStreamVolume(AudioManager.STREAM_DTMF /* 8 */, profile.getVolumeDTMFValue(), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_DTMF, profile.getVolumeDTMFValue());
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
if (!systemMuted) {
if (profile.getVolumeSystemChange()) {
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
try {
audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM /* 1 */, profile.getVolumeSystemValue(), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_SYSTEM, profile.getVolumeSystemValue());
//correctVolume0(audioManager);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
}
//PPApplication.logE("ActivateProfileHelper.setVolumes", "ActivateProfileHelper.getMergedRingNotificationVolumes()=" + ActivateProfileHelper.getMergedRingNotificationVolumes());
//PPApplication.logE("ActivateProfileHelper.setVolumes", "ApplicationPreferences.applicationUnlinkRingerNotificationVolumes=" + ApplicationPreferences.applicationUnlinkRingerNotificationVolumes);
boolean volumesSet = false;
//TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (/*(telephony != null) &&*/ ActivateProfileHelper.getMergedRingNotificationVolumes() && ApplicationPreferences.applicationUnlinkRingerNotificationVolumes) {
//PPApplication.logE("ActivateProfileHelper.setVolumes", "do unlink volumes");
if ((!ringMuted) && (!notificationMuted)) {
//PPApplication.logE("ActivateProfileHelper.setVolumes", "linkUnlink=" + linkUnlink);
//int callState = telephony.getCallState();
if ((linkUnlink == PhoneCallBroadcastReceiver.LINKMODE_UNLINK)/* ||
(callState == TelephonyManager.CALL_STATE_RINGING)*/) {
// for separating ringing and notification
// in ringing state ringer volumes must by set
// and notification volumes must not by set
int volume = ApplicationPreferences.prefRingerVolume;
// PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-RINGING-unlink ringer volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING /* 2 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (PhoneProfilesService.getInstance() != null)
PhoneProfilesService.getInstance().ringingVolume = volume;
//PhoneProfilesService.notificationVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION /* 5 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
//correctVolume0(audioManager);
if (!profile.getVolumeNotificationChange())
setNotificationVolume(appContext, volume);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
volumesSet = true;
} else if (linkUnlink == PhoneCallBroadcastReceiver.LINKMODE_LINK) {
// for separating ringing and notification
// in not ringing state ringer and notification volume must by change
int volume = ApplicationPreferences.prefRingerVolume;
// PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING-link ringer volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING /* 2 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (PhoneProfilesService.getInstance() != null)
PhoneProfilesService.getInstance().ringingVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
if (!profile.getVolumeNotificationChange())
setNotificationVolume(appContext, volume);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
volume = ApplicationPreferences.prefNotificationVolume;
// PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING-link notification volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION /* 5 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//PhoneProfilesService.notificationVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
} catch (Exception e) {
PPApplication.recordException(e);
}
}
//correctVolume0(audioManager);
volumesSet = true;
} else if ((linkUnlink == PhoneCallBroadcastReceiver.LINKMODE_NONE)/* ||
(callState == TelephonyManager.CALL_STATE_IDLE)*/) {
int volume = ApplicationPreferences.prefRingerVolume;
// PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING-none ringer volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING /* 2 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (PhoneProfilesService.getInstance() != null)
PhoneProfilesService.getInstance().ringingVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, volume);
//correctVolume0(audioManager);
if (!profile.getVolumeNotificationChange())
setNotificationVolume(appContext, volume);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
volume = ApplicationPreferences.prefNotificationVolume;
// PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING-none notification volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION /* 5 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//PhoneProfilesService.notificationVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, volume);
//correctVolume0(audioManager);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
volumesSet = true;
}
}
}
if (!volumesSet) {
// reverted order for disabled unlink
int volume;
if (!ActivateProfileHelper.getMergedRingNotificationVolumes()) {
if (!notificationMuted) {
volume = ApplicationPreferences.prefNotificationVolume;
//PPApplication.logE("ActivateProfileHelper.setVolumes", "no doUnlink notification volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION /* 5 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//PhoneProfilesService.notificationVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, volume);
//correctVolume0(audioManager);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "notification volume set");
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
}
if (!ringMuted) {
volume = ApplicationPreferences.prefRingerVolume;
//PPApplication.logE("ActivateProfileHelper.setVolumes", "no doUnlink ringer volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING /* 2 */, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
if (PhoneProfilesService.getInstance() != null)
PhoneProfilesService.getInstance().ringingVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, volume);
//correctVolume0(audioManager);
//PPApplication.logE("ActivateProfileHelper.setVolumes", "ringer volume set");
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
}
//}
//else
// PPApplication.logE("ActivateProfileHelper.setVolumes", "not granted");
}
}
}
/*if (PPApplication.logEnabled()) {
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeMediaChange()=" + profile.getVolumeMediaChange());
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeMediaValue()=" + profile.getVolumeMediaValue());
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeAlarmChange()=" + profile.getVolumeAlarmChange());
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeAlarmValue()=" + profile.getVolumeAlarmValue());
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeVoiceChange()=" + profile.getVolumeVoiceChange());
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeVoiceValue()=" + profile.getVolumeVoiceValue());
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeBluetoothSCOChange()=" + profile.getVolumeBluetoothSCOChange());
PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setVolumes", "profile.getVolumeBluetoothSCOValue()=" + profile.getVolumeBluetoothSCOValue());
}*/
if (forProfileActivation) {
if (profile.getVolumeBluetoothSCOChange()) {
try {
audioManager.setStreamVolume(ActivateProfileHelper.STREAM_BLUETOOTH_SCO, profile.getVolumeBluetoothSCOValue(), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_VOICE, profile.getVolumeVoiceValue());
} catch (Exception e) {
PPApplication.recordException(e);
}
}
if (profile.getVolumeVoiceChange()) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL /* 0 */, profile.getVolumeVoiceValue(), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_VOICE, profile.getVolumeVoiceValue());
} catch (Exception e) {
PPApplication.recordException(e);
}
}
if (profile.getVolumeAlarmChange()) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_ALARM /* 4 */, profile.getVolumeAlarmValue(), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_ALARM, profile.getVolumeAlarmValue());
} catch (Exception e) {
PPApplication.recordException(e);
}
}
if (!profile._volumeMuteSound) {
if (!musicMuted) {
if (profile.getVolumeMediaChange()) {
setMediaVolume(appContext, audioManager, profile.getVolumeMediaValue());
}
}
}
}
//int value = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
//PPApplication.logE("[VOL] ActivateProfileHelper.setVolumes", "STREAM_VOICE_CALL="+value);
}
static void setMediaVolume(Context context, AudioManager audioManager, int value) {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "value="+value);
// Fatal Exception: java.lang.SecurityException: Only SystemUI can disable the safe media volume:
// Neither user 10118 nor current process has android.permission.STATUS_BAR_SERVICE.
try {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "set media volume (1)");
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC /* 3 */, value, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_MUSIC, profile.getVolumeMediaValue());
} catch (SecurityException e) {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "set media volume (1) - SecurityException");
//PPApplication.recordException(e);
Context appContext = context.getApplicationContext();
// adb shell pm grant sk.henrichg.phoneprofilesplus android.permission.WRITE_SECURE_SETTINGS
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "WRITE_SECURE_SETTINGS granted");
try {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "disable safe volume without root");
Settings.Global.putInt(appContext.getContentResolver(), "audio_safe_volume_state", 2);
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "set media volume (2)");
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC /* 3 */, value, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
catch (Exception e2) {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "set media volume (2) - Exception");
PPApplication.recordException(e2);
}
}
else {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "WRITE_SECURE_SETTINGS NOT granted");
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false))) {
synchronized (PPApplication.rootMutex) {
String command1 = "settings put global audio_safe_volume_state 2";
Command command = new Command(0, false, command1);
try {
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "disable safe volume with root");
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setMediaVolume");
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "set media volume (3)");
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC /* 3 */, value, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
} catch (Exception ee) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//PPApplication.recordException(e);;
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "set media volume (3) - Exception");
}
}
}
}
} catch (Exception e3) {
PPApplication.recordException(e3);
//PPApplication.logE("[TEST MEDIA VOLUME] ActivateProfileHelper.setMediaVolume", "set media volume (1) - Exception");
}
}
/*
private static void setZenMode(Context context, int zenMode, AudioManager audioManager, int systemZenMode, int ringerMode)
{
//if (android.os.Build.VERSION.SDK_INT >= 21)
//{
//if (PPApplication.logEnabled()) {
// PPApplication.logE("ActivateProfileHelper.setZenMode", "zenMode=" + zenMode);
// PPApplication.logE("ActivateProfileHelper.setZenMode", "ringerMode=" + ringerMode);
//}
Context appContext = context.getApplicationContext();
//int systemZenMode = getSystemZenMode(appContext); //, -1);
//PPApplication.logE("ActivateProfileHelper.setZenMode", "systemZenMode=" + systemZenMode);
//int systemRingerMode = audioManager.getRingerMode();
//PPApplication.logE("ActivateProfileHelper.setZenMode", "systemRingerMode=" + systemRingerMode);
if ((zenMode != ZENMODE_SILENT) && canChangeZenMode(appContext)) {
//PPApplication.logE("ActivateProfileHelper.setZenMode", "not ZENMODE_SILENT and can change zen mode");
try {
if (ringerMode != -1) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
audioManager.setRingerMode(ringerMode);
if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) {
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
}
else {
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
}
//if (!((zenMode == ZENMODE_PRIORITY) && (ringerMode == AudioManager.RINGER_MODE_VIBRATE))) {
PPApplication.sleep(500);
//}
}
if ((zenMode != systemZenMode) || (zenMode == ZENMODE_PRIORITY)) {
//PPApplication.logE("ActivateProfileHelper.setZenMode", "change zen mode");
RingerModeChangeReceiver.notUnlinkVolumes = false;
PPNotificationListenerService.requestInterruptionFilter(appContext, zenMode);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, zenMode);
}
//if (zenMode == ZENMODE_PRIORITY) {
// PPApplication.logE("ActivateProfileHelper.setZenMode", "change ringer mode");
// PPApplication.sleep(1000);
// //audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
// audioManager.setRingerMode(ringerMode);
//}
} catch (Exception e) {
PPApplication.recordException(e);
}
} else {
//PPApplication.logE("ActivateProfileHelper.setZenMode", "ZENMODE_SILENT or not can change zen mode");
try {
//noinspection SwitchStatementWithTooFewBranches
switch (zenMode) {
case ZENMODE_SILENT:
//audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
//PPApplication.sleep(1000);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
if ((systemZenMode != ZENMODE_ALL) && canChangeZenMode(appContext)) {
//PPApplication.logE("ActivateProfileHelper.setZenMode", "change zen mode");
RingerModeChangeReceiver.notUnlinkVolumes = false;
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALL);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALL);
PPApplication.sleep(500);
}
RingerModeChangeReceiver.notUnlinkVolumes = false;
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
break;
default:
RingerModeChangeReceiver.notUnlinkVolumes = false;
audioManager.setRingerMode(ringerMode);
}
} catch (Exception e) {
// may be produced this exception:
//
// java.lang.SecurityException: Not allowed to change Do Not Disturb state
//
// when changed is ringer mode in activated Do not disturb and
// GlobalGUIRoutines.activityActionExists(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS, context) returns false.
PPApplication.recordException(e);
}
}
//}
//else {
// RingerModeChangeReceiver.notUnlinkVolumes = false;
// audioManager.setRingerMode(ringerMode);
//}
}
*/
private static void setVibrateWhenRinging(Context context, Profile profile, int value) {
// if (PPApplication.logEnabled()) {
// PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "profile=" + profile);
// PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "value=" + value);
// }
int lValue = value;
if (profile != null) {
switch (profile._vibrateWhenRinging) {
case 1:
lValue = 1;
break;
case 2:
lValue = 0;
break;
}
}
// PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "lValue="+lValue);
if (lValue != -1) {
Context appContext = context.getApplicationContext();
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_VIBRATE_WHEN_RINGING, null, null, false, appContext).allowed
== PreferenceAllowed.PREFERENCE_ALLOWED) {
if (Permissions.checkVibrateWhenRinging(appContext)) {
/*if (android.os.Build.VERSION.SDK_INT < 23) { // Not working in Android M (exception)
Settings.System.putInt(appContext.getContentResolver(), "vibrate_when_ringing", lValue);
//PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "vibrate when ringing set (API < 23)");
}
else {*/
/*if (PPApplication.romIsMIUI) {
PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging",
"vibrate_in_normal="+Settings.System.getInt(context.getContentResolver(), "vibrate_in_normal",-1));
PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging",
"vibrate_in_silent="+Settings.System.getInt(context.getContentResolver(), "vibrate_in_silent",-1));
}
else*/ {
try {
Settings.System.putInt(appContext.getContentResolver(), Settings.System.VIBRATE_WHEN_RINGING, lValue);
if (PPApplication.deviceIsXiaomi && PPApplication.romIsMIUI) {
//PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "Xiaomi");
Settings.System.putInt(appContext.getContentResolver(), "vibrate_in_normal", lValue);
Settings.System.putInt(appContext.getContentResolver(), "vibrate_in_silent", lValue);
}
//PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "vibrate when ringing set (API >= 23)");
} catch (Exception ee) {
// java.lang.IllegalArgumentException: You cannot change private secure settings.
//Log.e("ActivateProfileHelper.setVibrateWhenRinging", Log.getStackTraceString(ee));
//PPApplication.recordException(ee);
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false))) {
synchronized (PPApplication.rootMutex) {
String command1;
Command command;
if (PPApplication.deviceIsXiaomi && PPApplication.romIsMIUI) {
command1 = "settings put system " + Settings.System.VIBRATE_WHEN_RINGING + " " + lValue;
String command2 = "settings put system " + "vibrate_in_normal" + " " + lValue;
String command3 = "settings put system " + "vibrate_in_silent" + " " + lValue;
command = new Command(0, false, command1, command2, command3);
} else {
command1 = "settings put system " + Settings.System.VIBRATE_WHEN_RINGING + " " + lValue;
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
command = new Command(0, false, command1); //, command2);
}
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setVibrationWhenRinging");
//PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "vibrate when ringing set (API >= 23 with root)");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setVibrateWhenRinging", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
//else
//PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "not rooted");
}
}
//}
}
//else
// PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "not permission granted");
}
//else
// PPApplication.logE("ActivateProfileHelper.setVibrateWhenRinging", "not profile preferences allowed");
}
}
private static boolean setTones(Context context, Profile profile) {
boolean noError = true;
Context appContext = context.getApplicationContext();
if (Permissions.checkProfileRingtones(appContext, profile, null)) {
if (profile._soundRingtoneChange == 1) {
if (!profile._soundRingtone.isEmpty()) {
try {
String[] splits = profile._soundRingtone.split("\\|");
if (!splits[0].isEmpty()) {
//Uri uri = Uri.parse(splits[0]);
Uri uri = getUriOfSavedTone(context, splits[0], RingtoneManager.TYPE_RINGTONE);
//TODO je mozne, ze to Uri z RingtoneManagera je uz grantnute, tak toto nebude treba robit.
try {
ContentResolver contentResolver = context.getContentResolver();
context.grantUriPermission(PPApplication.PACKAGE_NAME, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
//PPApplication.logE("ActivateProfileHelper.setTones", "ring tone granted");
} catch (Exception e) {
// java.lang.SecurityException: UID 10157 does not have permission to
// content://com.android.externalstorage.documents/document/93ED-1CEC%3AMirek%2Fmobil%2F.obr%C3%A1zek%2Fblack.jpg
// [user 0]; you could obtain access using ACTION_OPEN_DOCUMENT or related APIs
//Log.e("ActivateProfileHelper.setTones (1)", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
/*
if (PPApplication.deviceIsSamsung && (uri != null)) {
//Settings.System.putString(context.getContentResolver(), "ringtone_set", "1");
//Settings.System.putString(context.getContentResolver(), "ringtone_2_set", "1");
Log.e("ActivateProfileHelper.setTones", "ringtone Samsung uri="+uri.toString());
try {
uri = ContentProvider.maybeAddUserId(uri, context.getUserId());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone_2", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else
if (PPApplication.deviceIsHuawei && (PPApplication.romIsEMUI) && (uri != null)) {
Log.e("ActivateProfileHelper.setTones", "ringtone Huawei uri="+uri.toString());
try {
uri = ContentProvider.maybeAddUserId(uri, context.getUserId());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone2", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else
if (PPApplication.deviceIsXiaomi && (PPApplication.romIsMIUI) && (uri != null)) {
Log.e("ActivateProfileHelper.setTones", "ringtone Xiaomi uri="+uri.toString());
try {
uri = ContentProvider.maybeAddUserId(uri, context.getUserId());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone_sound_slot_1", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone_sound_use_uniform", "0");
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone_sound_slot_2", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else*/
RingtoneManager.setActualDefaultRingtoneUri(appContext, RingtoneManager.TYPE_RINGTONE, uri);
}
}
catch (IllegalArgumentException e) {
// java.lang.IllegalArgumentException: Invalid column: _data
//Log.e("ActivateProfileHelper.setTones (2)", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
catch (Exception e){
//Log.e("ActivateProfileHelper.setTones (3)", Log.getStackTraceString(e));
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_SET_TONE_RINGTONE, null,
profile._name, profile._icon, 0, "");
noError = false;
/*String[] splits = profile._soundRingtone.split("\\|");
if (!splits[0].isEmpty()) {
try {
boolean found = false;
RingtoneManager manager = new RingtoneManager(context);
Cursor cursor = manager.getCursor();
while (cursor.moveToNext()) {
String _uri = cursor.getString(RingtoneManager.URI_COLUMN_INDEX);
if (_uri.equals(splits[0])) {
// uri exists in RingtoneManager
found = true;
break;
}
}
if (found) {
PPApplication.setCustomKey("ActivateProfileHelper_setTone", splits[0]);
PPApplication.recordException(e);
}
} catch (Exception ee) {
PPApplication.setCustomKey("ActivateProfileHelper_setTone", splits[0]);
PPApplication.recordException(e);
}
} else
PPApplication.recordException(e);*/
}
} else {
// selected is None tone
try {
/*if (PPApplication.deviceIsSamsung) {
Log.e("ActivateProfileHelper.setTones", "ringtone Samsung uri=null");
try {
Settings.System.putString(context.getContentResolver(), "ringtone", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1 - NULL", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone_2", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2 - NULL", Log.getStackTraceString(e));
}
}
else
if (PPApplication.deviceIsHuawei && (PPApplication.romIsEMUI)) {
Log.e("ActivateProfileHelper.setTones", "ringtone Huawei uri=null");
try {
Settings.System.putString(context.getContentResolver(), "ringtone", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1 - NULL", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone2", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2 - NULL", Log.getStackTraceString(e));
}
}
else
if (PPApplication.deviceIsXiaomi && (PPApplication.romIsMIUI)) {
Log.e("ActivateProfileHelper.setTones", "ringtone Xiaomi uri=null");
try {
Settings.System.putString(context.getContentResolver(), "ringtone_sound_slot_1", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone_sound_use_uniform", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "ringtone_sound_slot_2", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else*/
RingtoneManager.setActualDefaultRingtoneUri(appContext, RingtoneManager.TYPE_RINGTONE, null);
}
catch (IllegalArgumentException e) {
// java.lang.IllegalArgumentException: Invalid column: _data
//PPApplication.recordException(e);
}
catch (Exception e){
PPApplication.recordException(e);
noError = false;
}
}
}
if (profile._soundNotificationChange == 1) {
if (!profile._soundNotification.isEmpty()) {
try {
String[] splits = profile._soundNotification.split("\\|");
if (!splits[0].isEmpty()) {
//Uri uri = Uri.parse(splits[0]);
Uri uri = getUriOfSavedTone(context, splits[0], RingtoneManager.TYPE_NOTIFICATION);
//TODO je mozne, ze to Uri z RingtoneManagera je uz grantnute, tak toto nebude treba robit.
try {
ContentResolver contentResolver = context.getContentResolver();
context.grantUriPermission(PPApplication.PACKAGE_NAME, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
//PPApplication.logE("ActivateProfileHelper.setTones", "notification tone granted");
} catch (Exception e) {
// java.lang.SecurityException: UID 10157 does not have permission to
// content://com.android.externalstorage.documents/document/93ED-1CEC%3AMirek%2Fmobil%2F.obr%C3%A1zek%2Fblack.jpg
// [user 0]; you could obtain access using ACTION_OPEN_DOCUMENT or related APIs
//Log.e("BitmapManipulator.resampleBitmapUri", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
/*if (PPApplication.deviceIsSamsung && (uri != null)) {
//Settings.System.putString(context.getContentResolver(), "ringtone_set", "1");
//Settings.System.putString(context.getContentResolver(), "ringtone_2_set", "1");
Log.e("ActivateProfileHelper.setTones", " notification Samsung uri="+uri.toString());
try {
uri = ContentProvider.maybeAddUserId(uri, context.getUserId());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "notification_sound", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "notification_sound_2", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else
if (PPApplication.deviceIsHuawei && (PPApplication.romIsEMUI) && (uri != null)) {
Log.e("ActivateProfileHelper.setTones", "notification Huawei uri="+uri.toString());
// notifikacie ine ako sms - zvlastna katergoria v Huawei
//Settings.System.putString(context.getContentResolver(), "notification_sound", uri.toString());
try {
uri = ContentProvider.maybeAddUserId(uri, context.getUserId());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "message", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "messageSub1", uri.toString());
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else*/
// Xiaomi devices do not has dual sim notifications
RingtoneManager.setActualDefaultRingtoneUri(appContext, RingtoneManager.TYPE_NOTIFICATION, uri);
}
}
catch (IllegalArgumentException e) {
// java.lang.IllegalArgumentException: Invalid column: _data
//PPApplication.recordException(e);
}
catch (Exception e){
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_SET_TONE_NOTIFICATION, null,
profile._name, profile._icon, 0, "");
noError = false;
/*String[] splits = profile._soundNotification.split("\\|");
if (!splits[0].isEmpty()) {
try {
boolean found = false;
RingtoneManager manager = new RingtoneManager(context);
Cursor cursor = manager.getCursor();
while (cursor.moveToNext()) {
String _uri = cursor.getString(RingtoneManager.URI_COLUMN_INDEX);
if (_uri.equals(splits[0])) {
// uri exists in RingtoneManager
found = true;
break;
}
}
if (found) {
PPApplication.setCustomKey("ActivateProfileHelper_setTone", splits[0]);
PPApplication.recordException(e);
}
} catch (Exception ee) {
PPApplication.setCustomKey("ActivateProfileHelper_setTone", splits[0]);
PPApplication.recordException(e);
}
} else
PPApplication.recordException(e);*/
}
} else {
// selected is None tone
try {
/*if (PPApplication.deviceIsSamsung) {
//Settings.System.putString(context.getContentResolver(), "ringtone_set", "1");
//Settings.System.putString(context.getContentResolver(), "ringtone_2_set", "1");
Log.e("ActivateProfileHelper.setTones", " notification Samsung uri=null");
try {
Settings.System.putString(context.getContentResolver(), "notification_sound", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "notification_sound_2", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else
if (PPApplication.deviceIsHuawei && (PPApplication.romIsEMUI)) {
Log.e("ActivateProfileHelper.setTones", "notification Huawei uri=null");
// notifikacie ine ako sms - zvlastna katergoria v Huawei
//Settings.System.putString(context.getContentResolver(), "notification_sound", null);
try {
Settings.System.putString(context.getContentResolver(), "message", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM1", Log.getStackTraceString(e));
}
try {
Settings.System.putString(context.getContentResolver(), "messageSub1", null);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setTones - SIM2", Log.getStackTraceString(e));
}
}
else*/
// Xiaomi devices do not has dual sim notifications
RingtoneManager.setActualDefaultRingtoneUri(appContext, RingtoneManager.TYPE_NOTIFICATION, null);
}
catch (IllegalArgumentException e) {
// java.lang.IllegalArgumentException: Invalid column: _data
//PPApplication.recordException(e);
}
catch (Exception e){
PPApplication.recordException(e);
noError = false;
}
}
}
if (profile._soundAlarmChange == 1) {
if (!profile._soundAlarm.isEmpty()) {
try {
String[] splits = profile._soundAlarm.split("\\|");
if (!splits[0].isEmpty()) {
//Uri uri = Uri.parse(splits[0]);
Uri uri = getUriOfSavedTone(context, splits[0], RingtoneManager.TYPE_ALARM);
//TODO je mozne, ze to Uri z RingtoneManagera je uz grantnute, tak toto nebude treba robit.
try {
ContentResolver contentResolver = context.getContentResolver();
context.grantUriPermission(PPApplication.PACKAGE_NAME, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
//PPApplication.logE("ActivateProfileHelper.setTones", "alarm tone granted");
} catch (Exception e) {
// java.lang.SecurityException: UID 10157 does not have permission to
// content://com.android.externalstorage.documents/document/93ED-1CEC%3AMirek%2Fmobil%2F.obr%C3%A1zek%2Fblack.jpg
// [user 0]; you could obtain access using ACTION_OPEN_DOCUMENT or related APIs
//Log.e("BitmapManipulator.resampleBitmapUri", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
//Settings.System.putString(context.getContentResolver(), Settings.System.RINGTONE, splits[0]);
RingtoneManager.setActualDefaultRingtoneUri(appContext, RingtoneManager.TYPE_ALARM, uri);
}
}
catch (IllegalArgumentException e) {
// java.lang.IllegalArgumentException: Invalid column: _data
//PPApplication.recordException(e);
}
catch (Exception e){
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_SET_TONE_ALARM, null,
profile._name, profile._icon, 0, "");
noError = false;
/*String[] splits = profile._soundAlarm.split("\\|");
if (!splits[0].isEmpty()) {
try {
boolean found = false;
RingtoneManager manager = new RingtoneManager(context);
Cursor cursor = manager.getCursor();
while (cursor.moveToNext()) {
String _uri = cursor.getString(RingtoneManager.URI_COLUMN_INDEX);
if (_uri.equals(splits[0])) {
// uri exists in RingtoneManager
found = true;
break;
}
}
if (found) {
PPApplication.setCustomKey("ActivateProfileHelper_setTone", splits[0]);
PPApplication.recordException(e);
}
} catch (Exception ee) {
PPApplication.setCustomKey("ActivateProfileHelper_setTone", splits[0]);
PPApplication.recordException(e);
}
} else
PPApplication.recordException(e);*/
}
} else {
// selected is None tone
try {
//Settings.System.putString(context.getContentResolver(), Settings.System.ALARM_ALERT, null);
RingtoneManager.setActualDefaultRingtoneUri(appContext, RingtoneManager.TYPE_ALARM, null);
}
catch (IllegalArgumentException e) {
// java.lang.IllegalArgumentException: Invalid column: _data
//PPApplication.recordException(e);
}
catch (Exception e){
PPApplication.recordException(e);
noError = false;
}
}
}
}
return noError;
}
private static Uri getUriOfSavedTone(Context context, String savedTone, int toneType) {
Log.e("ActivateProfileHelper.getUriOfSavedTone", "savedTone="+savedTone);
Uri toneUri;
boolean uriFound = false;
if (savedTone.equals("")) {
toneUri = null;
uriFound = true;
}
else
if (savedTone.equals(Settings.System.DEFAULT_RINGTONE_URI.toString())) {
toneUri = Settings.System.DEFAULT_RINGTONE_URI;
uriFound = true;
}
else
if (savedTone.equals(Settings.System.DEFAULT_NOTIFICATION_URI.toString())) {
toneUri = Settings.System.DEFAULT_NOTIFICATION_URI;
uriFound = true;
}
else
if (savedTone.equals(Settings.System.DEFAULT_ALARM_ALERT_URI.toString())) {
toneUri = Settings.System.DEFAULT_ALARM_ALERT_URI;
uriFound = true;
}
else {
toneUri = null;
RingtoneManager manager = new RingtoneManager(context.getApplicationContext());
manager.setType(toneType);
Cursor ringtoneCursor = manager.getCursor();
while (ringtoneCursor.moveToNext()) {
Uri _toneUri = manager.getRingtoneUri(ringtoneCursor.getPosition());
String _uri = ringtoneCursor.getString(RingtoneManager.URI_COLUMN_INDEX);
String _id = ringtoneCursor.getString(RingtoneManager.ID_COLUMN_INDEX);
String toneFromCursor = _uri + "/" + _id;
if (toneFromCursor.equals(savedTone)) {
toneUri = _toneUri;
uriFound = true;
break;
}
}
}
if (toneUri != null)
Log.e("ActivateProfileHelper.getUriOfSavedTone", "toneUri="+toneUri.toString());
Log.e("ActivateProfileHelper.getUriOfSavedTone", "uriFound="+uriFound);
if (uriFound)
return toneUri;
else
return null;
}
static void executeForVolumes(final Profile profile, final int linkUnlinkVolumes, final boolean forProfileActivation, Context context) {
// if (PPApplication.logEnabled()) {
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "profile=" + profile);
// if (profile != null)
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "profile._name=" + profile._name);
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "linkUnlinkVolumes=" + linkUnlinkVolumes);
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "forProfileActivation=" + forProfileActivation);
// }
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadVolumes();
final Handler handler = new Handler(PPApplication.handlerThreadVolumes.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadVolumes", "START run - from=ActivateProfileHelper.executeForVolumes");
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_executeForVolumes");
wakeLock.acquire(10 * 60 * 1000);
}
int linkUnlink = PhoneCallBroadcastReceiver.LINKMODE_NONE;
if (ActivateProfileHelper.getMergedRingNotificationVolumes() &&
ApplicationPreferences.applicationUnlinkRingerNotificationVolumes) {
if (Permissions.checkPhone(appContext))
linkUnlink = linkUnlinkVolumes;
}
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "linkUnlink=" + linkUnlink);
if (profile != null) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "setTones() 1");
boolean noErrorSetTone = setTones(appContext, profile);
final AudioManager audioManager = (AudioManager) appContext.getSystemService(Context.AUDIO_SERVICE);
if ((profile._volumeRingerMode != 0) ||
profile.getVolumeRingtoneChange() ||
profile.getVolumeNotificationChange() ||
profile.getVolumeSystemChange() ||
profile.getVolumeDTMFChange()) {
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "change ringer mode");
//if (Permissions.checkProfileAccessNotificationPolicy(context, profile, null)) {
if (canChangeZenMode(appContext)) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "can change zen mode");
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "changeRingerModeForVolumeEqual0()");
changeRingerModeForVolumeEqual0(profile, audioManager, appContext);
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "changeNotificationVolumeForVolumeEqual0()");
changeNotificationVolumeForVolumeEqual0(/*context,*/ profile);
RingerModeChangeReceiver.internalChange = true;
//int systemZenMode = getSystemZenMode(appContext/*, -1*/);
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "setRingerMode()");
setRingerMode(appContext, profile, audioManager, /*systemZenMode,*/ forProfileActivation);
// get actual system zen mode (may be changed in setRingerMode())
int systemZenMode = getSystemZenMode(appContext/*, -1*/);
//PPApplication.logE("ActivateProfileHelper.executeForVolumes", "internalChange=" + RingerModeChangeReceiver.internalChange);
PPApplication.sleep(500);
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "setVolumes()");
setVolumes(appContext, profile, audioManager, systemZenMode, linkUnlink, forProfileActivation, true);
//PPApplication.logE("ActivateProfileHelper.executeForVolumes", "internalChange=" + RingerModeChangeReceiver.internalChange);
PPApplication.sleep(500);
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "start internal change work");
DisableInternalChangeWorker.enqueueWork();
/*PPApplication.startHandlerThreadInternalChangeToFalse();
final Handler handler = new Handler(PPApplication.handlerThreadInternalChangeToFalse.getLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "disable ringer mode change internal change");
RingerModeChangeReceiver.internalChange = false;
}
}, 3000);*/
//PostDelayedBroadcastReceiver.setAlarm(
// PostDelayedBroadcastReceiver.ACTION_RINGER_MODE_INTERNAL_CHANGE_TO_FALSE, 3, context);
}
}
else
/*if (profile.getVolumeMediaChange() ||
profile.getVolumeAlarmChange() ||
profile.getVolumeVoiceChange() ||
profile.getVolumeAccessibilityChange() ||
profile.getVolumeBluetoothSCOChange())*/ {
// call setVolume() for "Mute sound"
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "do not change ringer mode");
int systemZenMode = getSystemZenMode(appContext/*, -1*/);
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "setVolumes()");
setVolumes(appContext, profile, audioManager, systemZenMode, linkUnlink, forProfileActivation, false);
}
/*else {
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "ringer mode and volumes are not configured");
}*/
/*
if (profile._volumeSpeakerPhone != 0) {
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "profile._volumeSpeakerPhone="+profile._volumeSpeakerPhone);
boolean savedSpeakerphone = false; audioManager.isSpeakerphoneOn();
boolean changeSpeakerphone = false;
if (savedSpeakerphone && (profile._volumeSpeakerPhone == 2)) // 2=speakerphone off
changeSpeakerphone = true;
if ((!savedSpeakerphone) && (profile._volumeSpeakerPhone == 1)) // 1=speakerphone on
changeSpeakerphone = true;
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "changeSpeakerphone="+changeSpeakerphone);
if (changeSpeakerphone) {
/// activate SpeakerPhone
// not working in EMUI :-/
audioManager.setMode(AudioManager.MODE_IN_CALL);
// Delay 2 seconds mode changed to MODE_IN_CALL
long start = SystemClock.uptimeMillis();
do {
if (audioManager.getMode() != AudioManager.MODE_IN_CALL) {
//if (audioManager.getMode() != AudioManager.MODE_IN_COMMUNICATION) {
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "xxx - audio mode MODE_IN_CALL="+(audioManager.getMode() == AudioManager.MODE_IN_CALL));
//PPApplication.logE("PhoneCallBroadcastReceiver.callAnswered", "xxx - audio mode MODE_IN_COMMUNICATION="+(audioManager.getMode() == AudioManager.MODE_IN_COMMUNICATION));
PPApplication.sleep(500);
}
else
break;
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "SystemClock.uptimeMillis() - start="+(SystemClock.uptimeMillis() - start));
} while (SystemClock.uptimeMillis() - start < (5 * 1000));
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "yyy - audio mode MODE_IN_CALL="+(audioManager.getMode() == AudioManager.MODE_IN_CALL));
//PPApplication.logE("ActivateProfileHelper.executeForVolumes", "yyy - audio mode MODE_IN_COMMUNICATION="+(audioManager.getMode() == AudioManager.MODE_IN_COMMUNICATION));
PPApplication.sleep(500);
audioManager.setSpeakerphoneOn(profile._volumeSpeakerPhone == 1);
//PhoneCallBroadcastReceiver.speakerphoneSelected = true;
PPApplication.logE("ActivateProfileHelper.executeForVolumes", "ACTIVATED SPEAKERPHONE");
}
}
*/
if (noErrorSetTone) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "setTones() 2");
setTones(appContext, profile);
}
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.executeForVolumes", "end");
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
});
}
private static void setNotificationLed(Context context, final int value) {
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadProfileActivation();
final Handler handler = new Handler(PPApplication.handlerThreadProfileActivation.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadProfileActivation", "START run - from=ActivateProfileHelper.setNotificationLed");
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_setNotificationLed");
wakeLock.acquire(10 * 60 * 1000);
}
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_NOTIFICATION_LED, null, null, false, appContext).allowed
== PreferenceAllowed.PREFERENCE_ALLOWED) {
//if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception)
// Settings.System.putInt(appContext.getContentResolver(), "notification_light_pulse"/*Settings.System.NOTIFICATION_LIGHT_PULSE*/, value);
//else {
/* not working (private secure settings) :-/
if (Permissions.hasPermission(context, Manifest.permission.WRITE_SECURE_SETTINGS)) {
Settings.System.putInt(context.getContentResolver(), "notification_light_pulse", value);
}
else*/
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false))) {
synchronized (PPApplication.rootMutex) {
String command1 = "settings put system " + "notification_light_pulse"/*Settings.System.NOTIFICATION_LIGHT_PULSE*/ + " " + value;
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setNotificationLed");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setNotificationLed", Log.getStackTraceString(e));
//PPApplication.recordException(e);;
}
}
}
//}
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
});
}
private static void setHeadsUpNotifications(Context context, final int value) {
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadProfileActivation();
final Handler handler = new Handler(PPApplication.handlerThreadProfileActivation.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadProfileActivation", "START run - from=ActivateProfileHelper.setHeadsUpNotifications");
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_setHeadsUpNotifications");
wakeLock.acquire(10 * 60 * 1000);
}
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_HEADS_UP_NOTIFICATIONS, null, null, false, appContext).allowed
== PreferenceAllowed.PREFERENCE_ALLOWED) {
//if (android.os.Build.VERSION.SDK_INT >= 21) {
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
Global.putInt(appContext.getContentResolver(), "heads_up_notifications_enabled", value);
} else {
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false))) {
synchronized (PPApplication.rootMutex) {
String command1 = "settings put global " + "heads_up_notifications_enabled" + " " + value;
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setHeadsUpNotifications");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setHeadsUpNotifications", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
}
//}
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {
}
}
}
});
}
private static void setAlwaysOnDisplay(Context context, final int value) {
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadProfileActivation();
final Handler handler = new Handler(PPApplication.handlerThreadProfileActivation.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadProfileActivation", "START run - from=ActivateProfileHelper.setAlwaysOnDisplay");
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_setAlwaysOnDisplay");
wakeLock.acquire(10 * 60 * 1000);
}
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_ALWAYS_ON_DISPLAY, null, null, false, appContext).allowed
== PreferenceAllowed.PREFERENCE_ALLOWED) {
/* not working (private secure settings) :-/
if (Permissions.hasPermission(context, Manifest.permission.WRITE_SECURE_SETTINGS)) {
Settings.System.putInt(context.getContentResolver(), "aod_mode", value);
}
else*/
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false))) {
synchronized (PPApplication.rootMutex) {
String command1 = "settings put system " + "aod_mode" + " " + value;
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setAlwaysOnDisplay");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setAlwaysOnDisplay", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
});
}
private static void setScreenOnPermanent(Profile profile, Context context) {
//PPApplication.logE("******** ActivateProfileHelper.setScreenOnPermanent", "profile._screenOnPermanent="+profile._screenOnPermanent);
if (Permissions.checkProfileScreenOnPermanent(context, profile, null)) {
if (profile._screenOnPermanent == 1)
createKeepScreenOnView(context);
else if (profile._screenOnPermanent == 2)
removeKeepScreenOnView(context);
}
}
private static void changeRingerModeForVolumeEqual0(Profile profile, AudioManager audioManager, Context context) {
/*if (PPApplication.logEnabled()) {
PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "volumeRingtoneChange=" + profile.getVolumeRingtoneChange());
PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "volumeRingtoneValue=" + profile.getVolumeRingtoneValue());
}*/
//profile._ringerModeForZenMode = AudioManager.RINGER_MODE_NORMAL;
if (profile.getVolumeRingtoneChange()) {
if (profile.getVolumeRingtoneValue() == 0) {
profile.setVolumeRingtoneValue(1);
if (!profile._volumeMuteSound) {
//profile._ringerModeForZenMode = AudioManager.RINGER_MODE_SILENT;
// for profile ringer/zen mode = "only vibrate" do not change ringer mode to Silent
if (!isVibrateRingerMode(profile._volumeRingerMode/*, profile._volumeZenMode*/)) {
if (isAudibleRinging(profile._volumeRingerMode, profile._volumeZenMode/*, false*/)) {
// change ringer mode to Silent
//PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "changed to silent");
profile._volumeRingerMode = Profile.RINGERMODE_SILENT;
}// else
// PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "not audible ringer mode in profile");
}// else
// PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "vibrate ringer mode in profile");
}
} else {
if (profile._volumeRingerMode == 0) {
// ringer mode is not changed by profile, use system ringer and zen mode
if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
int systemZenMode = getSystemZenMode(context/*, -1*/);
if (!isAudibleSystemRingerMode(audioManager, systemZenMode/*, context*/)) {
// change ringer mode to ringing becaiuse configured is ringing volume
// Priority zen mode is audible. DO NOT DISABLE IT !!!
//PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "system ringer mode is not audible - changed to ringing");
profile._volumeRingerMode = Profile.RINGERMODE_RING;
}
}
}
}
}
}
private static boolean checkAccessNotificationPolicy(Context context) {
Context appContext = context.getApplicationContext();
try {
NotificationManager mNotificationManager = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
boolean granted = false;
if (mNotificationManager != null)
granted = mNotificationManager.isNotificationPolicyAccessGranted();
//if (granted)
// setShowRequestAccessNotificationPolicyPermission(context, true);
return granted;
} catch (Exception e) {
return false;
}
}
static boolean canChangeZenMode(Context context/*, boolean notCheckAccess*/) {
Context appContext = context.getApplicationContext();
//if (android.os.Build.VERSION.SDK_INT >= 23) {
boolean no60 = !Build.VERSION.RELEASE.equals("6.0");
if (no60 && GlobalGUIRoutines.activityActionExists(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS, context)) {
//if (notCheckAccess)
// return true;
//else
return checkAccessNotificationPolicy(appContext);
//return Permissions.checkAccessNotificationPolicy(appContext);
}
else
return PPNotificationListenerService.isNotificationListenerServiceEnabled(appContext, false);
//}
//else
//if (android.os.Build.VERSION.SDK_INT >= 21)
// return PPNotificationListenerService.isNotificationListenerServiceEnabled(appContext);
//return false;
}
private static void changeNotificationVolumeForVolumeEqual0(Profile profile) {
//if (PPApplication.logEnabled()) {
//PPApplication.logE("ActivateProfileHelper.changeNotificationVolumeForVolumeEqual0", "volumeNotificationChange=" + profile.getVolumeNotificationChange());
//PPApplication.logE("ActivateProfileHelper.changeNotificationVolumeForVolumeEqual0", "mergedRingNotificationVolumes=" + getMergedRingNotificationVolumes(context));
//PPApplication.logE("ActivateProfileHelper.changeNotificationVolumeForVolumeEqual0", "volumeNotificationValue=" + profile.getVolumeNotificationValue());
//}
if (profile.getVolumeNotificationChange() && ActivateProfileHelper.getMergedRingNotificationVolumes()) {
if (profile.getVolumeNotificationValue() == 0) {
//PPApplication.logE("ActivateProfileHelper.changeNotificationVolumeForVolumeEqual0", "changed notification value to 1");
profile.setVolumeNotificationValue(1);
}
}
}
@SuppressLint("SwitchIntDef")
static int getSystemZenMode(Context context/*, int defaultValue*/) {
Context appContext = context.getApplicationContext();
//if (android.os.Build.VERSION.SDK_INT >= 23) {
boolean no60 = !Build.VERSION.RELEASE.equals("6.0");
//PPApplication.logE("ActivateProfileHelper.getSystemZenMode", "no60="+no60);
boolean activityExists = GlobalGUIRoutines.activityActionExists(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS, context);
//PPApplication.logE("ActivateProfileHelper.getSystemZenMode", "activityExists="+activityExists);
if (no60 && activityExists) {
NotificationManager mNotificationManager = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
//PPApplication.logE("ActivateProfileHelper.getSystemZenMode", "mNotificationManager="+mNotificationManager);
if (mNotificationManager != null) {
int interruptionFilter = mNotificationManager.getCurrentInterruptionFilter();
//PPApplication.logE("ActivateProfileHelper.getSystemZenMode", "interruptionFilter="+interruptionFilter);
switch (interruptionFilter) {
case NotificationManager.INTERRUPTION_FILTER_ALARMS:
return ActivateProfileHelper.ZENMODE_ALARMS;
case NotificationManager.INTERRUPTION_FILTER_NONE:
return ActivateProfileHelper.ZENMODE_NONE;
case NotificationManager.INTERRUPTION_FILTER_PRIORITY:
return ActivateProfileHelper.ZENMODE_PRIORITY;
case NotificationManager.INTERRUPTION_FILTER_ALL:
case NotificationManager.INTERRUPTION_FILTER_UNKNOWN:
default:
return ActivateProfileHelper.ZENMODE_ALL;
}
}
}
else {
ContentResolver resolver = appContext.getContentResolver();
if (resolver != null) {
int interruptionFilter = Settings.Global.getInt(resolver, "zen_mode", -1);
switch (interruptionFilter) {
case 0:
return ActivateProfileHelper.ZENMODE_ALL;
case 1:
return ActivateProfileHelper.ZENMODE_PRIORITY;
case 2:
return ActivateProfileHelper.ZENMODE_NONE;
case 3:
return ActivateProfileHelper.ZENMODE_ALARMS;
}
}
}
/*}
if (android.os.Build.VERSION.SDK_INT < 23) {
int interruptionFilter = Settings.Global.getInt(appContext.getContentResolver(), "zen_mode", -1);
switch (interruptionFilter) {
case 0:
return ActivateProfileHelper.ZENMODE_ALL;
case 1:
return ActivateProfileHelper.ZENMODE_PRIORITY;
case 2:
return ActivateProfileHelper.ZENMODE_NONE;
case 3:
return ActivateProfileHelper.ZENMODE_ALARMS;
}
}*/
return -1; //defaultValue;
}
/*
static boolean vibrationIsOn(AudioManager audioManager, boolean testRingerMode) {
int ringerMode = -999;
if (testRingerMode)
ringerMode = audioManager.getRingerMode();
int vibrateType = -999;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1)
vibrateType = audioManager.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);
//int vibrateWhenRinging;
//if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception)
// vibrateWhenRinging = Settings.System.getInt(context.getContentResolver(), "vibrate_when_ringing", 0);
//else
// vibrateWhenRinging = Settings.System.getInt(context.getContentResolver(), Settings.System.VIBRATE_WHEN_RINGING, 0);
//if (PPApplication.logEnabled()) {
// PPApplication.logE("PPApplication.vibrationIsOn", "ringerMode=" + ringerMode);
// PPApplication.logE("PPApplication.vibrationIsOn", "vibrateType=" + vibrateType);
//}
//PPApplication.logE("PPApplication.vibrationIsOn", "vibrateWhenRinging="+vibrateWhenRinging);
return (ringerMode == AudioManager.RINGER_MODE_VIBRATE) ||
(vibrateType == AudioManager.VIBRATE_SETTING_ON) ||
(vibrateType == AudioManager.VIBRATE_SETTING_ONLY_SILENT);// ||
//(vibrateWhenRinging == 1);
}
*/
private static void setVibrateSettings(boolean vibrate, AudioManager audioManager) {
if (vibrate) {
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
}
else {
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ee) {
//PPApplication.recordException(ee);
}
}
}
private static void setRingerMode(Context context, Profile profile, AudioManager audioManager, /*int systemZenMode,*/ boolean forProfileActivation)
{
//PPApplication.logE("@@@ ActivateProfileHelper.setRingerMode", "audioM.ringerMode=" + audioManager.getRingerMode());
Context appContext = context.getApplicationContext();
int ringerMode;
int zenMode;
/*if (PPApplication.logEnabled()) {
PPApplication.logE("ActivateProfileHelper.setRingerMode", "profile._volumeRingerMode=" + profile._volumeRingerMode);
PPApplication.logE("ActivateProfileHelper.setRingerMode", "profile._volumeZenMode=" + profile._volumeZenMode);
}*/
if (forProfileActivation) {
if (profile._volumeRingerMode != 0) {
saveRingerMode(appContext, profile._volumeRingerMode);
if ((profile._volumeRingerMode == Profile.RINGERMODE_ZENMODE) && (profile._volumeZenMode != 0))
saveZenMode(appContext, profile._volumeZenMode);
}
}
//if (firstCall)
// return;
ringerMode = ApplicationPreferences.prefRingerMode;
zenMode = ApplicationPreferences.prefZenMode;
/*if (PPApplication.logEnabled()) {
PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringerMode=" + ringerMode);
PPApplication.logE("ActivateProfileHelper.setRingerMode", "zenMode=" + zenMode);
PPApplication.logE("ActivateProfileHelper.setRingerMode", "_ringerModeForZenMode=" + profile._ringerModeForZenMode);
}*/
if (forProfileActivation) {
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringer mode change");
switch (ringerMode) {
case Profile.RINGERMODE_RING:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringer mode=RING");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALL);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALL);
PPApplication.sleep(500);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
setVibrateSettings(false, audioManager);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
//setZenMode(appContext, ZENMODE_ALL, audioManager, systemZenMode, AudioManager.RINGER_MODE_NORMAL);
setVibrateWhenRinging(appContext, profile, -1);
break;
case Profile.RINGERMODE_RING_AND_VIBRATE:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringer mode=RING & VIBRATE");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALL);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALL);
PPApplication.sleep(500);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
setVibrateSettings(true, audioManager);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
//setZenMode(appContext, ZENMODE_ALL, audioManager, systemZenMode, AudioManager.RINGER_MODE_NORMAL);
setVibrateWhenRinging(appContext, null, 1);
break;
case Profile.RINGERMODE_VIBRATE:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringer mode=VIBRATE");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALL);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALL);
PPApplication.sleep(500);
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
setVibrateSettings(true, audioManager);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
//setZenMode(appContext, ZENMODE_ALL, audioManager, systemZenMode, AudioManager.RINGER_MODE_VIBRATE);
setVibrateWhenRinging(appContext, null, 1);
break;
case Profile.RINGERMODE_SILENT:
//setZenMode(appContext, ZENMODE_SILENT, audioManager, systemZenMode, AudioManager.RINGER_MODE_SILENT);
if (PPApplication.deviceIsSamsung || PPApplication.romIsEMUI) {
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALL);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALL);
PPApplication.sleep(500);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
setVibrateSettings(true, audioManager);
}
else {
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
setVibrateSettings(false, audioManager);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALARMS);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALARMS);
}
setVibrateWhenRinging(appContext, profile, -1);
break;
case Profile.RINGERMODE_ZENMODE:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringer mode=ZEN MODE");
switch (zenMode) {
case Profile.ZENMODE_ALL:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "zen mode=ALL");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
setVibrateSettings(false, audioManager);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALL);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALL);
//setZenMode(appContext, ZENMODE_ALL, audioManager, systemZenMode, /*AudioManager.RINGER_MODE_NORMAL*/profile._ringerModeForZenMode);
setVibrateWhenRinging(appContext, profile, -1);
break;
case Profile.ZENMODE_PRIORITY:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "zen mode=PRIORITY");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
setVibrateSettings(false, audioManager);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
//setZenMode(appContext, ZENMODE_PRIORITY, audioManager, systemZenMode, profile._ringerModeForZenMode);
setVibrateWhenRinging(appContext, profile, -1);
break;
case Profile.ZENMODE_NONE:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "zen mode=NONE");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
setVibrateSettings(false, audioManager);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_NONE);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_NONE);
//setZenMode(appContext, ZENMODE_NONE, audioManager, systemZenMode, AudioManager.RINGER_MODE_SILENT);
break;
case Profile.ZENMODE_ALL_AND_VIBRATE:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "zen mode=ALL & VIBRATE");
// this is as Sound mode = Vibrate
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
setVibrateSettings(true, audioManager);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALL);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALL);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
//setZenMode(appContext, ZENMODE_ALL, audioManager, systemZenMode, AudioManager.RINGER_MODE_VIBRATE);
setVibrateWhenRinging(appContext, null, 1);
break;
case Profile.ZENMODE_PRIORITY_AND_VIBRATE:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "zen mode=PRIORITY & VIBRATE");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
if (Build.VERSION.SDK_INT <= 25) {
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
setVibrateSettings(true, audioManager);
//PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
}
else
if (Build.VERSION.SDK_INT <= 28) {
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
//setVibrateSettings(true, audioManager);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
PPApplication.sleep(1000);
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
setVibrateSettings(true, audioManager);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
}
else {
// must be set 2x to keep vibraton
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
setVibrateSettings(true, audioManager);
//PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_PRIORITY);
}
//setZenMode(appContext, ZENMODE_PRIORITY, audioManager, systemZenMode, AudioManager.RINGER_MODE_VIBRATE);
//setZenMode(appContext, ZENMODE_PRIORITY, audioManager, systemZenMode, AudioManager.RINGER_MODE_VIBRATE);
setVibrateWhenRinging(appContext, null, 1);
break;
case Profile.ZENMODE_ALARMS:
//PPApplication.logE("ActivateProfileHelper.setRingerMode", "zen mode=ALARMS");
synchronized (PPApplication.notUnlinkVolumesMutex) {
RingerModeChangeReceiver.notUnlinkVolumes = false;
}
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
setVibrateSettings(false, audioManager);
PPApplication.sleep(500);
PPNotificationListenerService.requestInterruptionFilter(appContext, ZENMODE_ALARMS);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(appContext, ZENMODE_ALARMS);
//setZenMode(appContext, ZENMODE_ALARMS, audioManager, systemZenMode, AudioManager.RINGER_MODE_SILENT);
break;
}
break;
}
}
}
private static void executeForWallpaper(final Profile profile, Context context) {
if (profile._deviceWallpaperChange == 1)
{
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadWallpaper();
final Handler handler = new Handler(PPApplication.handlerThreadWallpaper.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadWallpaper", "START run - from=ActivateProfileHelper.executeForWallpaper");
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_executeForWallpaper");
wakeLock.acquire(10 * 60 * 1000);
}
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager wm = (WindowManager) appContext.getSystemService(Context.WINDOW_SERVICE);
if (wm != null) {
Display display = wm.getDefaultDisplay();
//if (android.os.Build.VERSION.SDK_INT >= 17)
display.getRealMetrics(displayMetrics);
//else
// display.getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
if (appContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
//noinspection SuspiciousNameCombination
height = displayMetrics.widthPixels;
//noinspection SuspiciousNameCombination
width = displayMetrics.heightPixels;
}
//PPApplication.logE("PPApplication.startHandlerThreadWallpaper", "height="+height);
//PPApplication.logE("PPApplication.startHandlerThreadWallpaper", "width="+width);
// for lock screen no double width
if ((Build.VERSION.SDK_INT < 24) || (profile._deviceWallpaperFor != 2))
width = width << 1; // best wallpaper width is twice screen width
//PPApplication.logE("PPApplication.startHandlerThreadWallpaper", "width (2)="+width);
Bitmap decodedSampleBitmap = BitmapManipulator.resampleBitmapUri(profile._deviceWallpaper, width, height, false, true, appContext);
if (decodedSampleBitmap != null) {
// set wallpaper
WallpaperManager wallpaperManager = WallpaperManager.getInstance(appContext);
try {
if (Build.VERSION.SDK_INT >= 24) {
int flags = WallpaperManager.FLAG_SYSTEM | WallpaperManager.FLAG_LOCK;
Rect visibleCropHint = null;
if (profile._deviceWallpaperFor == 1)
flags = WallpaperManager.FLAG_SYSTEM;
if (profile._deviceWallpaperFor == 2) {
flags = WallpaperManager.FLAG_LOCK;
int left = 0;
int right = decodedSampleBitmap.getWidth();
if (decodedSampleBitmap.getWidth() > width) {
left = (decodedSampleBitmap.getWidth() / 2) - (width / 2);
right = (decodedSampleBitmap.getWidth() / 2) + (width / 2);
}
visibleCropHint = new Rect(left, 0, right, decodedSampleBitmap.getHeight());
}
//noinspection WrongConstant
wallpaperManager.setBitmap(decodedSampleBitmap, visibleCropHint, true, flags);
} else
wallpaperManager.setBitmap(decodedSampleBitmap);
} catch (IOException e) {
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_SET_WALLPAPER, null,
profile._name, profile._icon, 0, "");
//Log.e("ActivateProfileHelper.executeForWallpaper", Log.getStackTraceString(e));
PPApplication.recordException(e);
} catch (Exception e) {
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_SET_WALLPAPER, null,
profile._name, profile._icon, 0, "");
//PPApplication.recordException(e);
}
}
else {
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_SET_WALLPAPER, null,
profile._name, profile._icon, 0, "");
}
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
});
}
}
private static void executeForRunApplications(final Profile profile, Context context) {
if (profile._deviceRunApplicationChange == 1)
{
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadRunApplication();
final Handler handler = new Handler(PPApplication.handlerThreadRunApplication.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadRunApplication", "START run - from=ActivateProfileHelper.executeForRunApplications");
if (PPApplication.blockProfileEventActions)
// not start applications after boot
return;
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_executeForRunApplications");
wakeLock.acquire(10 * 60 * 1000);
}
String[] splits = profile._deviceRunApplicationPackageName.split("\\|");
Intent intent;
PackageManager packageManager = appContext.getPackageManager();
//ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//List<ActivityManager.RunningAppProcessInfo> procInfo = activityManager.getRunningAppProcesses();
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","profile._name="+profile._name);
for (String split : splits) {
//Log.d("ActivateProfileHelper.executeForRunApplications","app data="+splits[i]);
int startApplicationDelay = Application.getStartApplicationDelay(split);
if (Application.getStartApplicationDelay(split) > 0) {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","run with delay");
RunApplicationWithDelayBroadcastReceiver.setDelayAlarm(appContext, startApplicationDelay, profile._name, split);
} else {
if (Application.isShortcut(split)) {
long shortcutId = Application.getShortcutId(split);
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","shortcut - shortcutId="+shortcutId);
if (shortcutId > 0) {
//Shortcut shortcut = dataWrapper.getDatabaseHandler().getShortcut(shortcutId);
Shortcut shortcut = DatabaseHandler.getInstance(appContext).getShortcut(shortcutId);
if (shortcut != null) {
try {
intent = Intent.parseUri(shortcut._intent, 0);
if (intent != null) {
//String packageName = intent.getPackage();
//if (!isRunning(procInfo, packageName)) {
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName + ": not running");
//Log.d("ActivateProfileHelper.executeForRunApplications","intent="+intent);
//noinspection TryWithIdenticalCatches
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","shortcut - ERROR (01)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_SHORTCUT, null,
profile._name, profile._icon, 0, "");
} catch (SecurityException e) {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","shortcut - ERROR (02)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_SHORTCUT, null,
profile._name, profile._icon, 0, "");
} catch (Exception e) {
PPApplication.recordException(e);
}
//} else
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName + ": running");
} else {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","shortcut - ERROR (1)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_SHORTCUT, null,
profile._name, profile._icon, 0, "");
}
} catch (Exception ee) {
PPApplication.recordException(ee);
}
} else {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","shortcut - ERROR (2)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_SHORTCUT, null,
profile._name, profile._icon, 0, "");
}
} else {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","shortcut - ERROR (3)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_SHORTCUT, null,
profile._name, profile._icon, 0, "");
}
} else if (Application.isIntent(split)) {
long intentId = Application.getIntentId(split);
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","intent - intentId="+intentId);
if (intentId > 0) {
PPIntent ppIntent = DatabaseHandler.getInstance(appContext).getIntent(intentId);
if (ppIntent != null) {
intent = ApplicationEditorIntentActivityX.createIntent(ppIntent);
if (intent != null) {
if (ppIntent._intentType == 0) {
//noinspection TryWithIdenticalCatches
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","intent - ERROR (01)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_INTENT, null,
profile._name, profile._icon, 0, "");
} catch (SecurityException e) {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","intent - ERROR (02)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_INTENT, null,
profile._name, profile._icon, 0, "");
} catch (Exception e) {
PPApplication.recordException(e);
}
} else {
try {
appContext.sendBroadcast(intent);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
} else {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","intent - ERROR (1)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_INTENT, null,
profile._name, profile._icon, 0, "");
}
} else {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","intent - ERROR (2)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_INTENT, null,
profile._name, profile._icon, 0, "");
}
} else {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","intent - ERROR (3)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_INTENT, null,
profile._name, profile._icon, 0, "");
}
} else {
String packageName = Application.getPackageName(split);
intent = packageManager.getLaunchIntentForPackage(packageName);
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","application - intent="+intent);
if (intent != null) {
//if (!isRunning(procInfo, packageName)) {
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName+": not running");
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","intent="+intent);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
//noinspection TryWithIdenticalCatches
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(intent);
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","application started");
} catch (ActivityNotFoundException e) {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","application - ERROR (01)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_APPLICATION, null,
profile._name, profile._icon, 0, "");
} catch (SecurityException e) {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","application - ERROR (02)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_APPLICATION, null,
profile._name, profile._icon, 0, "");
} catch (Exception e) {
//Log.e("ActivateProfileHelper.executeForRunApplications", Log.getStackTraceString(e));
}
//}
//else
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName+": running");
}
else {
//PPApplication.logE("ActivateProfileHelper.executeForRunApplications","application - ERROR (1)");
PPApplication.addActivityLog(appContext, PPApplication.ALTYPE_PROFILE_ERROR_RUN_APPLICATION_APPLICATION, null,
profile._name, profile._icon, 0, "");
}
}
}
PPApplication.sleep(1000);
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {
}
}
}
});
}
}
//private static int processPID = -1;
private static void executeForForceStopApplications(final Profile profile, Context context) {
if (PPApplication.blockProfileEventActions)
// not force stop applications after boot
return;
Context appContext = context.getApplicationContext();
/*if ((!ApplicationPreferences.applicationNeverAskForGrantRoot(context)) &&
(PPApplication.isRooted(false))) {
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications","do force stop via root");
synchronized (PPApplication.rootMutex) {
processPID = -1;
String command1 = "pidof sk.henrichg.phoneprofilesplus";
Command command = new Command(0, false, command1) {
@Override
public void commandOutput(int id, String line) {
super.commandOutput(id, line);
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications","shell output="+line);
try {
processPID = Integer.parseInt(line);
} catch (Exception e) {
processPID = -1;
}
}
@Override
public void commandTerminated(int id, String reason) {
super.commandTerminated(id, reason);
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications","terminated="+reason);
}
@Override
public void commandCompleted(int id, int exitCode) {
super.commandCompleted(id, exitCode);
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications","completed="+exitCode);
}
};
try {
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications", "force stop application with root");
roottools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command);
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications", "processPID="+processPID);
//if (processPID != -1) {
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications", "call roottools.killProcess");
boolean killed = roottools.killProcess(PPApplication.PACKAGE_NAME);
PPApplication.logE("ActivateProfileHelper.executeForForceStopApplications", "killed="+killed);
//}
} catch (Exception ee) {
Log.e("ActivateProfileHelper.executeForForceStopApplications", Log.getStackTraceString(ee));
}
}
} else {*/
if (profile._lockDevice != 0)
// not force stop if profile has lock device enabled
return;
String applications = profile._deviceForceStopApplicationPackageName;
if (!(applications.isEmpty() || (applications.equals("-")))) {
Intent intent = new Intent(PPApplication.ACTION_FORCE_STOP_APPLICATIONS_START);
intent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);
intent.putExtra(PPApplication.EXTRA_APPLICATIONS, applications);
appContext.sendBroadcast(intent, PPApplication.PPP_EXTENDER_PERMISSION);
}
//}
}
private static void executeRootForAdaptiveBrightness(final Profile profile, Context context) {
/* not working (private secure settings) :-/
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
Settings.System.putFloat(appContext.getContentResolver(), ADAPTIVE_BRIGHTNESS_SETTING_NAME,
profile.getDeviceBrightnessAdaptiveValue(appContext));
}
else {*/
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadProfileActivation();
final Handler handler = new Handler(PPApplication.handlerThreadProfileActivation.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadProfileActivation", "START run - from=ActivateProfileHelper.executeRootForAdaptiveBrightness");
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_executeRootForAdaptiveBrightness");
wakeLock.acquire(10 * 60 * 1000);
}
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false))) {
synchronized (PPApplication.rootMutex) {
String command1 = "settings put system " + Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ + " " +
profile.getDeviceBrightnessAdaptiveValue(appContext);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.executeRootForAdaptiveBrightness");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.executeRootForAdaptiveBrightness", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
});
//}
}
static void executeForInteractivePreferences(final Profile profile, final Context context) {
if (profile == null)
return;
if (PPApplication.blockProfileEventActions)
// not start applications after boot
return;
Context appContext = context.getApplicationContext();
if (profile._deviceRunApplicationChange == 1)
{
executeForRunApplications(profile, appContext);
}
//PowerManager pm = (PowerManager) context.getSystemService(POWER_SERVICE);
KeyguardManager myKM = (KeyguardManager) appContext.getSystemService(Context.KEYGUARD_SERVICE);
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_MOBILE_DATA_PREFS, null, null, true, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED)
{
if (profile._deviceMobileDataPrefs == 1)
{
if (PPApplication.isScreenOn && (myKM != null) && !myKM.isKeyguardLocked()) {
boolean ok = true;
try {
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
appContext.startActivity(intent);
//PPApplication.logE("ActivateProfileHelper.executeForInteractivePreferences", "1. OK");
} catch (Exception e) {
ok = false;
// Xiaomi: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.android.settings/com.android.settings.Settings$DataUsageSummaryActivity}; have you declared this activity in your AndroidManifest.xml?
//Log.e("ActivateProfileHelper.executeForInteractivePreferences", "1. ERROR" + Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
if (!ok) {
ok = true;
try {
final Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
final ComponentName componentName = new ComponentName("com.android.phone", "com.android.phone.Settings");
intent.setComponent(componentName);
appContext.startActivity(intent);
//PPApplication.logE("ActivateProfileHelper.executeForInteractivePreferences", "2. OK");
} catch (Exception e) {
ok = false;
// Xiaomi: java.lang.SecurityException: Permission Denial: starting Intent { act=android.settings.DATA_ROAMING_SETTINGS flg=0x10000000 cmp=com.android.phone/.Settings } from ProcessRecord{215f88f 16252:sk.henrichg.phoneprofilesplus/u0a231} (pid=16252, uid=10231) not exported from uid 1001
//Log.e("ActivateProfileHelper.executeForInteractivePreferences", "2. ERROR" + Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
if (!ok) {
try {
final Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(intent);
//PPApplication.logE("ActivateProfileHelper.executeForInteractivePreferences", "3. OK");
} catch (Exception e) {
//Log.e("ActivateProfileHelper.executeForInteractivePreferences", "3. ERROR" + Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
else {
boolean ok = false;
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
if (GlobalGUIRoutines.activityIntentExists(intent, appContext))
ok = true;
if (!ok) {
intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.setComponent(new ComponentName("com.android.phone", "com.android.phone.Settings"));
if (GlobalGUIRoutines.activityIntentExists(intent, appContext))
ok = true;
}
if (!ok) {
intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
if (GlobalGUIRoutines.activityIntentExists(intent, appContext))
ok = true;
}
if (ok) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String title = appContext.getString(R.string.profile_activation_interactive_preference_notification_title) + " " + profile._name;
String text = appContext.getString(R.string.profile_activation_interactive_preference_notification_text) + " " +
appContext.getString(R.string.profile_preferences_deviceMobileDataPrefs);
showNotificationForInteractiveParameters(appContext, title, text, intent,
PPApplication.PROFILE_ACTIVATION_MOBILE_DATA_PREFS_NOTIFICATION_ID,
PPApplication.PROFILE_ACTIVATION_MOBILE_DATA_PREFS_NOTIFICATION_TAG);
}
}
}
}
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_NETWORK_TYPE_PREFS, null, null, true, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED)
{
if (profile._deviceNetworkTypePrefs == 1)
{
if (PPApplication.isScreenOn && (myKM != null) && !myKM.isKeyguardLocked()) {
try {
final Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(intent);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
else {
Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String title = appContext.getString(R.string.profile_activation_interactive_preference_notification_title) + " " + profile._name;
String text = appContext.getString(R.string.profile_activation_interactive_preference_notification_text) + " " +
appContext.getString(R.string.profile_preferences_deviceNetworkTypePrefs);
showNotificationForInteractiveParameters(appContext, title, text, intent,
PPApplication.PROFILE_ACTIVATION_NETWORK_TYPE_PREFS_NOTIFICATION_ID,
PPApplication.PROFILE_ACTIVATION_NETWORK_TYPE_PREFS_NOTIFICATION_TAG);
}
}
}
//if (PPApplication.hardwareCheck(PPApplication.PREF_PROFILE_DEVICE_GPS, context))
//{ No check only GPS
if (profile._deviceLocationServicePrefs == 1)
{
if (PPApplication.isScreenOn && (myKM != null) && !myKM.isKeyguardLocked()) {
try {
final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(intent);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
else {
final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
if (GlobalGUIRoutines.activityIntentExists(intent, appContext)) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String title = appContext.getString(R.string.profile_activation_interactive_preference_notification_title) + " " + profile._name;
String text = appContext.getString(R.string.profile_activation_interactive_preference_notification_text) + " " +
appContext.getString(R.string.profile_preferences_deviceLocationServicePrefs);
showNotificationForInteractiveParameters(appContext, title, text, intent,
PPApplication.PROFILE_ACTIVATION_LOCATION_PREFS_NOTIFICATION_ID,
PPApplication.PROFILE_ACTIVATION_LOCATION_PREFS_NOTIFICATION_TAG);
}
}
}
//}
if (profile._deviceWiFiAPPrefs == 1) {
if (PPApplication.isScreenOn && (myKM != null) && !myKM.isKeyguardLocked()) {
try {
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.TetherSettings"));
appContext.startActivity(intent);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
else {
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.TetherSettings"));
if (GlobalGUIRoutines.activityIntentExists(intent, appContext)) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String title = appContext.getString(R.string.profile_activation_interactive_preference_notification_title) + " " + profile._name;
String text = appContext.getString(R.string.profile_activation_interactive_preference_notification_text) + " " +
appContext.getString(R.string.profile_preferences_deviceWiFiAPPrefs);
showNotificationForInteractiveParameters(appContext, title, text, intent,
PPApplication.PROFILE_ACTIVATION_WIFI_AP_PREFS_NOTIFICATION_ID,
PPApplication.PROFILE_ACTIVATION_WIFI_AP_PREFS_NOTIFICATION_TAG);
}
}
}
}
static void execute(final Context context, final Profile profile/*, boolean merged, *//*boolean _interactive*/)
{
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "xxx");
final Context appContext = context.getApplicationContext();
// unlink ring and notifications - it is @Hide :-(
//Settings.System.putInt(appContext.getContentResolver(), Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 0);
//final Profile profile = _profile; //Profile.getMappedProfile(_profile, appContext);
// setup volume
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "executeForVolumes()");
ActivateProfileHelper.executeForVolumes(profile, PhoneCallBroadcastReceiver.LINKMODE_NONE,true, appContext);
// set vibration on touch
if (Permissions.checkProfileVibrationOnTouch(appContext, profile, null)) {
switch (profile._vibrationOnTouch) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_vibrationOnTouch 1");
Settings.System.putInt(appContext.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 1);
//Settings.System.putInt(context.getContentResolver(), Settings.Global.CHARGING_SOUNDS_ENABLED, 1);
// Settings.System.DTMF_TONE_WHEN_DIALING - working
// Settings.System.SOUND_EFFECTS_ENABLED - working
// Settings.System.LOCKSCREEN_SOUNDS_ENABLED - private secure settings :-(
// Settings.Global.CHARGING_SOUNDS_ENABLED - java.lang.IllegalArgumentException: You cannot keep your settings in the secure settings. :-/
// (G1) not working :-/
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_vibrationOnTouch 2");
Settings.System.putInt(appContext.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 0);
//Settings.System.putInt(context.getContentResolver(), Settings.Global.CHARGING_SOUNDS_ENABLED, 0);
break;
}
}
// set dtmf tone when dialing
if (Permissions.checkProfileDtmfToneWhenDialing(appContext, profile, null)) {
switch (profile._dtmfToneWhenDialing) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_dtmfToneWhenDialing 1");
Settings.System.putInt(appContext.getContentResolver(), Settings.System.DTMF_TONE_WHEN_DIALING, 1);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_dtmfToneWhenDialing 2");
Settings.System.putInt(appContext.getContentResolver(), Settings.System.DTMF_TONE_WHEN_DIALING, 0);
break;
}
}
// set sound on touch
if (Permissions.checkProfileSoundOnTouch(appContext, profile, null)) {
switch (profile._soundOnTouch) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_soundOnTouch 1");
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SOUND_EFFECTS_ENABLED, 1);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_soundOnTouch 2");
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SOUND_EFFECTS_ENABLED, 0);
break;
}
}
//// setup radio preferences
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "executeForRadios()");
ActivateProfileHelper.executeForRadios(profile, appContext);
// setup auto-sync
try {
boolean _isAutoSync = ContentResolver.getMasterSyncAutomatically();
boolean _setAutoSync = false;
switch (profile._deviceAutoSync) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoSync 1");
if (!_isAutoSync) {
_isAutoSync = true;
_setAutoSync = true;
}
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoSync 2");
if (_isAutoSync) {
_isAutoSync = false;
_setAutoSync = true;
}
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoSync 3");
_isAutoSync = !_isAutoSync;
_setAutoSync = true;
break;
}
if (_setAutoSync)
ContentResolver.setMasterSyncAutomatically(_isAutoSync);
} catch (Exception e) {
PPApplication.recordException(e);
}
// screen on permanent
//if (Permissions.checkProfileScreenTimeout(context, profile, null)) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "setScreenOnPermanent()");
setScreenOnPermanent(profile, appContext);
//}
// screen timeout
if (Permissions.checkProfileScreenTimeout(appContext, profile, null)) {
//PowerManager pm = (PowerManager) context.getSystemService(POWER_SERVICE);
if (PPApplication.isScreenOn) {
//Log.d("ActivateProfileHelper.execute","screen on");
if (PPApplication.screenTimeoutHandler != null) {
PPApplication.screenTimeoutHandler.post(() -> {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "setScreenTimeout()");
setScreenTimeout(profile._deviceScreenTimeout, appContext);
});
}// else
// setScreenTimeout(profile._deviceScreenTimeout);
}
else {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "setActivatedProfileScreenTimeout()");
setActivatedProfileScreenTimeout(appContext, profile._deviceScreenTimeout);
}
}
//else
// PPApplication.setActivatedProfileScreenTimeout(context, 0);
// on/off lock screen
//PPApplication.logE("$$$ ActivateProfileHelper.execute","keyguard");
boolean setLockScreen = false;
switch (profile._deviceKeyguard) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceKeyguard 1");
// enable lock screen
//PPApplication.logE("$$$ ActivateProfileHelper.execute","keyguard=ON");
setLockScreenDisabled(appContext, false);
setLockScreen = true;
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceKeyguard 2");
// disable lock screen
//PPApplication.logE("$$$ ActivateProfileHelper.execute","keyguard=OFF");
setLockScreenDisabled(appContext, true);
setLockScreen = true;
break;
}
if (setLockScreen) {
//boolean isScreenOn;
//PowerManager pm = (PowerManager) context.getSystemService(POWER_SERVICE);
//if (pm != null) {
//PPApplication.logE("$$$ ActivateProfileHelper.execute", "isScreenOn=" + PPApplication.isScreenOn);
boolean keyguardShowing;
KeyguardManager kgMgr = (KeyguardManager) appContext.getSystemService(Context.KEYGUARD_SERVICE);
if (kgMgr != null) {
keyguardShowing = kgMgr.isKeyguardLocked();
//PPApplication.logE("$$$ ActivateProfileHelper.execute", "keyguardShowing=" + keyguardShowing);
if (PPApplication.isScreenOn && !keyguardShowing) {
try {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "switch keyguard");
// start PhoneProfilesService
//PPApplication.firstStartServiceStarted = false;
/*Intent serviceIntent = new Intent(context, PhoneProfilesService.class);
serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);
serviceIntent.putExtra(PhoneProfilesService.EXTRA_SWITCH_KEYGUARD, true);
PPApplication.startPPService(context, serviceIntent);*/
Intent commandIntent = new Intent(PhoneProfilesService.ACTION_COMMAND);
//commandIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);
commandIntent.putExtra(PhoneProfilesService.EXTRA_SWITCH_KEYGUARD, true);
PPApplication.runCommand(appContext, commandIntent);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
//}
}
// setup display brightness
if (Permissions.checkProfileScreenBrightness(appContext, profile, null)) {
if (profile.getDeviceBrightnessChange()) {
/*if (PPApplication.logEnabled()) {
PPApplication.logE("----- ActivateProfileHelper.execute", "set brightness: profile=" + profile._name);
PPApplication.logE("----- ActivateProfileHelper.execute", "set brightness: _deviceBrightness=" + profile._deviceBrightness);
}*/
try {
if (profile.getDeviceBrightnessAutomatic()) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "set automatic brightness");
Settings.System.putInt(appContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
if (profile.getDeviceBrightnessChangeLevel()) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "set brightness 1");
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_ADAPTIVE_BRIGHTNESS, null, null, true, appContext).allowed
== PreferenceAllowed.PREFERENCE_ALLOWED) {
Settings.System.putInt(appContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
profile.getDeviceBrightnessManualValue(appContext));
/*if (android.os.Build.VERSION.SDK_INT < 23) { // Not working in Android M (exception)
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "set adaptive brightness 1");
Settings.System.putFloat(appContext.getContentResolver(),
ADAPTIVE_BRIGHTNESS_SETTING_NAME,
profile.getDeviceBrightnessAdaptiveValue(appContext));
} else*/ {
try {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "set adaptive brightness 2");
Settings.System.putFloat(appContext.getContentResolver(),
Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ,
profile.getDeviceBrightnessAdaptiveValue(appContext));
} catch (Exception ee) {
// run service for execute radios
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "executeRootForAdaptiveBrightness()");
ActivateProfileHelper.executeRootForAdaptiveBrightness(profile, appContext);
}
}
}
}
} else {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "set manual brightness");
Settings.System.putInt(appContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
if (profile.getDeviceBrightnessChangeLevel()) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "set brightness 2");
Settings.System.putInt(appContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
profile.getDeviceBrightnessManualValue(appContext));
}
}
/*
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "start BackgroundBrightnessActivity");
Intent intent = new Intent(appContext, BackgroundBrightnessActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //this is important
float brightnessValue;
//if (profile.getDeviceBrightnessAutomatic() || (!profile.getDeviceBrightnessChangeLevel()))
brightnessValue = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
//else
// brightnessValue= profile.getDeviceBrightnessManualValue(context) / (float) 255;
intent.putExtra(BackgroundBrightnessActivity.EXTRA_BRIGHTNESS_VALUE, brightnessValue);
appContext.startActivity(intent);
*/
/*
if (PPApplication.brightnessHandler != null) {
PPApplication.brightnessHandler.post(new Runnable() {
public void run() {
PPApplication.logE("ActivateProfileHelper.execute", "brightnessHandler");
createBrightnessView(profile, context);
}
});
}// else
// createBrightnessView(context);
*/
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
// setup rotation
if (Permissions.checkProfileAutoRotation(appContext, profile, null)) {
switch (profile._deviceAutoRotate) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoRotate 1");
// set autorotate on
Settings.System.putInt(appContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);
//Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 6:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoRotate 6");
// set autorotate off
Settings.System.putInt(appContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
//Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoRotate 2");
// set autorotate off
// degree 0
Settings.System.putInt(appContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(appContext.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 3:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoRotate 3");
// set autorotate off
// degree 90
Settings.System.putInt(appContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(appContext.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_90);
break;
case 4:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoRotate 4");
// set autorotate off
// degree 180
Settings.System.putInt(appContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(appContext.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_180);
break;
case 5:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_deviceAutoRotate 5");
// set autorotate off
// degree 270
Settings.System.putInt(appContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(appContext.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_270);
break;
}
}
// set notification led
if (profile._notificationLed != 0) {
//if (Permissions.checkProfileNotificationLed(context, profile)) { not needed for Android 6+, because root is required
switch (profile._notificationLed) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_notificationLed 1");
setNotificationLed(appContext, 1);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_notificationLed 2");
setNotificationLed(appContext, 0);
break;
}
//}
}
// setup wallpaper
if (Permissions.checkProfileWallpaper(appContext, profile, null)) {
if (profile._deviceWallpaperChange == 1) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "executeForWallpaper()");
ActivateProfileHelper.executeForWallpaper(profile, appContext);
}
}
// set power save mode
ActivateProfileHelper.setPowerSaveMode(profile, appContext);
if (Permissions.checkProfileLockDevice(appContext, profile, null)) {
if (profile._lockDevice != 0) {
boolean keyguardLocked;
KeyguardManager kgMgr = (KeyguardManager) appContext.getSystemService(Context.KEYGUARD_SERVICE);
if (kgMgr != null) {
keyguardLocked = kgMgr.isKeyguardLocked();
//PPApplication.logE("---$$$ ActivateProfileHelper.execute", "keyguardLocked=" + keyguardLocked);
if (!keyguardLocked) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "lockDevice()");
ActivateProfileHelper.lockDevice(profile, appContext);
}
}
}
}
// enable/disable scanners
if (profile._applicationDisableWifiScanning != 0) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_applicationDisableWifiScanning");
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(appContext);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_WIFI_ENABLE_SCANNING, profile._applicationDisableWifiScanning == 2);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_WIFI_DISABLED_SCANNING_BY_PROFILE, profile._applicationDisableWifiScanning == 1);
editor.apply();
ApplicationPreferences.applicationEventWifiEnableScanning(appContext);
ApplicationPreferences.applicationEventWifiDisabledScannigByProfile(appContext);
//PPApplication.logE("[RJS] ActivateProfileHelper.execute", "_applicationDisableWifiScanning");
PPApplication.restartWifiScanner(appContext);
}
if (profile._applicationDisableBluetoothScanning != 0) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_applicationDisableBluetoothScanning");
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(appContext);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_BLUETOOTH_ENABLE_SCANNING, profile._applicationDisableBluetoothScanning == 2);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_BLUETOOTH_DISABLED_SCANNING_BY_PROFILE, profile._applicationDisableBluetoothScanning == 1);
editor.apply();
ApplicationPreferences.applicationEventBluetoothEnableScanning(appContext);
ApplicationPreferences.applicationEventBluetoothDisabledScannigByProfile(appContext);
//PPApplication.logE("[RJS] ActivateProfileHelper.execute", "_applicationDisableBluetoothScanning");
PPApplication.restartBluetoothScanner(appContext);
}
if (profile._applicationDisableLocationScanning != 0) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_applicationDisableLocationScanning");
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(appContext);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_LOCATION_ENABLE_SCANNING, profile._applicationDisableLocationScanning == 2);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_LOCATION_DISABLED_SCANNING_BY_PROFILE, profile._applicationDisableLocationScanning == 1);
editor.apply();
ApplicationPreferences.applicationEventLocationEnableScanning(appContext);
ApplicationPreferences.applicationEventLocationDisabledScannigByProfile(appContext);
//PPApplication.logE("[RJS] ActivateProfileHelper.execute", "_applicationDisableLocationScanning");
PPApplication.restartGeofenceScanner(appContext);
}
if (profile._applicationDisableMobileCellScanning != 0) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_applicationDisableMobileCellScanning");
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(appContext);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_MOBILE_CELL_ENABLE_SCANNING, profile._applicationDisableMobileCellScanning == 2);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_MOBILE_CELL_DISABLED_SCANNING_BY_PROFILE, profile._applicationDisableMobileCellScanning == 1);
editor.apply();
ApplicationPreferences.applicationEventMobileCellEnableScanning(appContext);
ApplicationPreferences.applicationEventMobileCellDisabledScannigByProfile(appContext);
//PPApplication.logE("[RJS] ActivateProfileHelper.execute", "_applicationDisableMobileCellScanning");
PPApplication.restartPhoneStateScanner(appContext);
}
if (profile._applicationDisableOrientationScanning != 0) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_applicationDisableOrientationScanning");
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(appContext);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_ORIENTATION_ENABLE_SCANNING, profile._applicationDisableOrientationScanning == 2);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_ORIENTATION_DISABLED_SCANNING_BY_PROFILE, profile._applicationDisableOrientationScanning == 1);
editor.apply();
ApplicationPreferences.applicationEventOrientationEnableScanning(appContext);
ApplicationPreferences.applicationEventOrientationDisabledScannigByProfile(appContext);
//PPApplication.logE("[RJS] ActivateProfileHelper.execute", "_applicationDisableOrientationScanning");
PPApplication.restartOrientationScanner(appContext);
}
if (profile._applicationDisableNotificationScanning != 0) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_applicationDisableNotificationScanning");
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(appContext);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_NOTIFICATION_ENABLE_SCANNING, profile._applicationDisableNotificationScanning == 2);
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_NOTIFICATION_DISABLED_SCANNING_BY_PROFILE, profile._applicationDisableNotificationScanning == 1);
editor.apply();
ApplicationPreferences.applicationEventNotificationEnableScanning(appContext);
ApplicationPreferences.applicationEventNotificationDisabledScannigByProfile(appContext);
//PPApplication.logE("[RJS] ActivateProfileHelper.execute", "_applicationDisableNotificationScanning");
PPApplication.restartNotificationScanner(appContext);
}
// set heads-up notifications
if (profile._headsUpNotifications != 0) {
switch (profile._headsUpNotifications) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_headsUpNotifications 1");
setHeadsUpNotifications(appContext, 1);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_headsUpNotifications 2");
setHeadsUpNotifications(appContext, 0);
break;
}
}
// set screen dark mode
if (profile._screenDarkMode != 0) {
setScreenDarkMode(context, profile._screenDarkMode);
}
if (android.os.Build.VERSION.SDK_INT >= 26) {
// set always on display
if (profile._alwaysOnDisplay != 0) {
switch (profile._alwaysOnDisplay) {
case 1:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_alwaysOnDisplay 1");
setAlwaysOnDisplay(appContext, 1);
break;
case 2:
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_alwaysOnDisplay 2");
setAlwaysOnDisplay(appContext, 0);
break;
}
}
}
// close all applications
if (profile._deviceCloseAllApplications == 1) {
if (!PPApplication.blockProfileEventActions) {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "start work for close all applications");
// work for first start events or activate profile on boot
Data workData = new Data.Builder()
.putString(EXTRA_PROFILE_NAME, profile._name)
.build();
OneTimeWorkRequest worker =
new OneTimeWorkRequest.Builder(MainWorker.class)
.addTag(MainWorker.CLOSE_ALL_APPLICATIONS_WORK_TAG)
.setInputData(workData)
.setInitialDelay(1500, TimeUnit.MILLISECONDS)
.build();
try {
if (PPApplication.getApplicationStarted(true)) {
WorkManager workManager = PPApplication.getWorkManagerInstance();
if (workManager != null) {
// //if (PPApplication.logEnabled()) {
// ListenableFuture<List<WorkInfo>> statuses;
// statuses = workManager.getWorkInfosForUniqueWork(MainWorker.CLOSE_ALL_APPLICATIONS_WORK_TAG);
// try {
// List<WorkInfo> workInfoList = statuses.get();
// PPApplication.logE("[TEST BATTERY] ActivateProfileHelper.execute", "for=" + MainWorker.CLOSE_ALL_APPLICATIONS_WORK_TAG + " workInfoList.size()=" + workInfoList.size());
// } catch (Exception ignored) {
// }
// //}
// PPApplication.logE("[WORKER_CALL] ActivateProfileHelper.execute", "xxx");
workManager.enqueueUniqueWork(MainWorker.CLOSE_ALL_APPLICATIONS_WORK_TAG, ExistingWorkPolicy.REPLACE, worker);
}
}
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
if (profile.getGenerateNotificationGenerate()) {
PPApplication.createGeneratedByProfileNotificationChannel(appContext);
NotificationCompat.Builder mBuilder;
Intent _intent;
_intent = new Intent(appContext, EditorProfilesActivity.class);
String nTitle = profile.getGenerateNotificationTitle();
String nText = profile.getGenerateNotificationBody();
if (android.os.Build.VERSION.SDK_INT < 24) {
nTitle = appContext.getString(R.string.ppp_app_name);
nText = profile.getGenerateNotificationTitle() + ": " +
profile.getGenerateNotificationBody();
}
nTitle = nTitle + " (" + profile._name + ")";
mBuilder = new NotificationCompat.Builder(appContext, PPApplication.GENERATED_BY_PROFILE_NOTIFICATION_CHANNEL)
.setColor(ContextCompat.getColor(appContext, R.color.notificationDecorationColor))
.setContentTitle(nTitle) // title for notification
.setContentText(nText)
.setStyle(new NotificationCompat.BigTextStyle().bigText(nText))
.setAutoCancel(true); // clear notification after click
switch (profile.getGenerateNotificationIconType()) {
case 0:
mBuilder.setSmallIcon(R.drawable.ic_information_notify);
break;
case 1:
mBuilder.setSmallIcon(R.drawable.ic_exclamation_notify);
break;
default:
// not supported color profile icons
if (profile.getIsIconResourceID()) {
int iconSmallResource = R.drawable.ic_profile_default_notify;
try {
String iconIdentifier = profile.getIconIdentifier();
if ((iconIdentifier != null) && (!iconIdentifier.isEmpty())) {
Object idx = Profile.profileIconNotifyId.get(iconIdentifier);
if (idx != null)
iconSmallResource = (int) idx;
}
} catch (Exception e) {
PPApplication.recordException(e);
}
mBuilder.setSmallIcon(iconSmallResource);
} else {
profile.generateIconBitmap(appContext, false, 0, false);
if (profile._iconBitmap != null) {
mBuilder.setSmallIcon(IconCompat.createWithBitmap(profile._iconBitmap));
}
else {
int iconSmallResource;
iconSmallResource = R.drawable.ic_profile_default_notify;
mBuilder.setSmallIcon(iconSmallResource);
}
}
break;
}
PendingIntent pi = PendingIntent.getActivity(appContext, 0, _intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pi);
mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
//if (android.os.Build.VERSION.SDK_INT >= 21) {
mBuilder.setCategory(NotificationCompat.CATEGORY_EVENT);
mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
//}
Notification notification = mBuilder.build();
notification.vibrate = null;
notification.defaults &= ~DEFAULT_VIBRATE;
NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(appContext);
try {
mNotificationManager.notify(
PPApplication.GENERATED_BY_PROFILE_NOTIFICATION_TAG,
PPApplication.GENERATED_BY_PROFILE_NOTIFICATION_ID + (int)profile._id,
notification);
} catch (Exception e) {
//Log.e("CheckGitHubReleasesBroadcastReceiver._doWork", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
}
if (profile._cameraFlash != 0) {
if (Permissions.checkProfileCameraFlash(context, profile, null)) {
switch (profile._cameraFlash) {
case 1:
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_cameraFlash 1");
NoobCameraManager noobCameraManager = NoobCameraManager.getInstance();
if (noobCameraManager != null) {
try {
noobCameraManager.turnOnFlash();
} catch (Exception e) {
PPApplication.recordException(e);
}
}
break;
case 2:
// PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "_cameraFlash 2");
noobCameraManager = NoobCameraManager.getInstance();
if (noobCameraManager != null) {
try {
noobCameraManager.turnOffFlash();
} catch (Exception e) {
PPApplication.recordException(e);
}
}
break;
}
}
}
if (profile._deviceForceStopApplicationChange == 1) {
boolean enabled;
if (Build.VERSION.SDK_INT >= 28)
enabled = PPPExtenderBroadcastReceiver.isEnabled(appContext, PPApplication.VERSION_CODE_EXTENDER_5_1_3_1);
else
enabled = PPPExtenderBroadcastReceiver.isEnabled(appContext, PPApplication.VERSION_CODE_EXTENDER_3_0);
if (enabled) {
// executeForInteractivePreferences() is called from broadcast receiver PPPExtenderBroadcastReceiver
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "executeForForceStopApplications()");
ActivateProfileHelper.executeForForceStopApplications(profile, appContext);
}
}
else {
//PPApplication.logE("[ACTIVATOR] ActivateProfileHelper.execute", "executeForInteractivePreferences()");
executeForInteractivePreferences(profile, appContext);
}
}
private static void showNotificationForInteractiveParameters(Context context, String title, String text, Intent intent, int notificationId, String notificationTag) {
Context appContext = context.getApplicationContext();
String nTitle = title;
String nText = text;
if (android.os.Build.VERSION.SDK_INT < 24) {
nTitle = appContext.getString(R.string.ppp_app_name);
nText = title+": "+text;
}
PPApplication.createInformationNotificationChannel(appContext);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext, PPApplication.INFORMATION_NOTIFICATION_CHANNEL)
.setColor(ContextCompat.getColor(appContext, R.color.notificationDecorationColor))
.setSmallIcon(R.drawable.ic_exclamation_notify) // notification icon
.setContentTitle(nTitle) // title for notification
.setContentText(nText) // message for notification
.setAutoCancel(true); // clear notification after click
mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(nText));
PendingIntent pi = PendingIntent.getActivity(appContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pi);
mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
//if (android.os.Build.VERSION.SDK_INT >= 21)
//{
mBuilder.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION);
mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
//}
Notification notification = mBuilder.build();
notification.vibrate = null;
notification.defaults &= ~DEFAULT_VIBRATE;
NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(appContext);
try {
mNotificationManager.notify(notificationTag, notificationId, notification);
} catch (Exception e) {
//Log.e("ActivateProfileHelper.showNotificationForInteractiveParameters", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
}
static void setScreenTimeout(int screenTimeout, Context context) {
//PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "xxx");
Context appContext = context.getApplicationContext();
disableScreenTimeoutInternalChange = true;
//Log.d("ActivateProfileHelper.setScreenTimeout", "current="+Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 0));
switch (screenTimeout) {
case 1:
//removeScreenTimeoutAlwaysOnView(context);
if (/*(PhoneProfilesService.getInstance() != null) &&*/ (PPApplication.lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PPApplication.screenTimeoutBeforeDeviceLock = 15000;
else {
/*if (PPApplication.deviceIsOppo || PPApplication.deviceIsRealme) {
synchronized (PPApplication.rootMutex) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", ""+screenTimeout);
String command1 = "settings put system " + Settings.System.SCREEN_OFF_TIMEOUT + " 15000";
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "command="+command1);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(false, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenTimeout");
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "end - "+screenTimeout);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
} else*/
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 15000);
}
break;
case 2:
//removeScreenTimeoutAlwaysOnView(context);
if (/*(PhoneProfilesService.getInstance() != null) &&*/ (PPApplication.lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PPApplication.screenTimeoutBeforeDeviceLock = 30000;
else {
/*if (PPApplication.deviceIsOppo || PPApplication.deviceIsRealme) {
synchronized (PPApplication.rootMutex) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", ""+screenTimeout);
String command1 = "settings put system " + Settings.System.SCREEN_OFF_TIMEOUT + " 30000";
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "command="+command1);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(false, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenTimeout");
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "end - "+screenTimeout);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
else*/
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000);
}
break;
case 3:
//removeScreenTimeoutAlwaysOnView(context);
if (/*(PhoneProfilesService.getInstance() != null) &&*/ (PPApplication.lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PPApplication.screenTimeoutBeforeDeviceLock = 60000;
else {
/*if (PPApplication.deviceIsOppo || PPApplication.deviceIsRealme) {
synchronized (PPApplication.rootMutex) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", ""+screenTimeout);
String command1 = "settings put system " + Settings.System.SCREEN_OFF_TIMEOUT + " 60000";
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "command="+command1);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(false, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenTimeout");
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "end - "+screenTimeout);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
else*/
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 60000);
}
break;
case 4:
//removeScreenTimeoutAlwaysOnView(context);
if (/*(PhoneProfilesService.getInstance() != null) &&*/ (PPApplication.lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PPApplication.screenTimeoutBeforeDeviceLock = 120000;
else {
/*if (PPApplication.deviceIsOppo || PPApplication.deviceIsRealme) {
synchronized (PPApplication.rootMutex) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", ""+screenTimeout);
String command1 = "settings put system " + Settings.System.SCREEN_OFF_TIMEOUT + " 120000";
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "command="+command1);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(false, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenTimeout");
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "end - "+screenTimeout);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
else*/
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 120000);
}
break;
case 5:
//removeScreenTimeoutAlwaysOnView(context);
if (/*(PhoneProfilesService.getInstance() != null) &&*/ (PPApplication.lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PPApplication.screenTimeoutBeforeDeviceLock = 600000;
else {
/*if (PPApplication.deviceIsOppo || PPApplication.deviceIsRealme) {
synchronized (PPApplication.rootMutex) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", ""+screenTimeout);
String command1 = "settings put system " + Settings.System.SCREEN_OFF_TIMEOUT + " 600000";
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "command="+command1);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(false, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenTimeout");
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "end - "+screenTimeout);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
else*/
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 600000);
}
break;
/*case 6:
//2147483647 = Integer.MAX_VALUE
//18000000 = 5 hours
//86400000 = 24 hours
//43200000 = 12 hours
removeScreenTimeoutAlwaysOnView(context);
if ((PhoneProfilesService.getInstance() != null) && (PhoneProfilesService.getInstance().lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PhoneProfilesService.getInstance().screenTimeoutBeforeDeviceLock = 86400000;
else
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 86400000);
break;*/
case 7:
//removeScreenTimeoutAlwaysOnView(context);
if (/*(PhoneProfilesService.getInstance() != null) &&*/ (PPApplication.lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PPApplication.screenTimeoutBeforeDeviceLock = 300000;
else {
/*if (PPApplication.deviceIsOppo || PPApplication.deviceIsRealme) {
synchronized (PPApplication.rootMutex) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", ""+screenTimeout);
String command1 = "settings put system " + Settings.System.SCREEN_OFF_TIMEOUT + " 300000";
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "command="+command1);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(false, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenTimeout");
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "end - "+screenTimeout);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
else*/
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 300000);
}
break;
/*case 8:
removeScreenTimeoutAlwaysOnView(context);
if ((PhoneProfilesService.getInstance() != null) && (PhoneProfilesService.getInstance().lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PhoneProfilesService.getInstance().screenTimeoutBeforeDeviceLock = 86400000; //1800000;
else
createScreenTimeoutAlwaysOnView(appContext);
break;*/
case 9:
//removeScreenTimeoutAlwaysOnView(context);
if (/*(PhoneProfilesService.getInstance() != null) &&*/ (PPApplication.lockDeviceActivity != null))
// in LockDeviceActivity.onDestroy() will be used this value to revert back system screen timeout
PPApplication.screenTimeoutBeforeDeviceLock = 1800000;
else {
/*if (PPApplication.deviceIsOppo || PPApplication.deviceIsRealme) {
synchronized (PPApplication.rootMutex) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", ""+screenTimeout);
String command1 = "settings put system " + Settings.System.SCREEN_OFF_TIMEOUT + " 1800000";
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "command="+command1);
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(false, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenTimeout");
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "end - "+screenTimeout);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
else*/
Settings.System.putInt(appContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 1800000);
}
break;
}
setActivatedProfileScreenTimeout(appContext, 0);
OneTimeWorkRequest disableInternalChangeWorker =
new OneTimeWorkRequest.Builder(DisableScreenTimeoutInternalChangeWorker.class)
.addTag(DisableScreenTimeoutInternalChangeWorker.WORK_TAG)
.setInitialDelay(5, TimeUnit.SECONDS)
.build();
try {
if (PPApplication.getApplicationStarted(true)) {
WorkManager workManager = PPApplication.getWorkManagerInstance();
if (workManager != null) {
// //if (PPApplication.logEnabled()) {
// ListenableFuture<List<WorkInfo>> statuses;
// statuses = workManager.getWorkInfosForUniqueWork(DisableScreenTimeoutInternalChangeWorker.WORK_TAG);
// try {
// List<WorkInfo> workInfoList = statuses.get();
// PPApplication.logE("[TEST BATTERY] ActivateProfileHelper.setScreenTimeout", "for=" + DisableScreenTimeoutInternalChangeWorker.WORK_TAG + " workInfoList.size()=" + workInfoList.size());
// } catch (Exception ignored) {
// }
// //}
// PPApplication.logE("[WORKER_CALL] ActivateProfileHelper.setScreenTimeout", "xxx");
workManager.enqueueUniqueWork(DisableScreenTimeoutInternalChangeWorker.WORK_TAG, ExistingWorkPolicy.REPLACE, disableInternalChangeWorker);
}
}
} catch (Exception e) {
PPApplication.recordException(e);
}
/*PPApplication.startHandlerThreadInternalChangeToFalse();
final Handler handler = new Handler(PPApplication.handlerThreadInternalChangeToFalse.getLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
PPApplication.logE("ActivateProfileHelper.setScreenTimeout", "disable screen timeout internal change");
disableScreenTimeoutInternalChange = false;
}
}, 3000);*/
//PostDelayedBroadcastReceiver.setAlarm(
// PostDelayedBroadcastReceiver.ACTION_DISABLE_SCREEN_TIMEOUT_INTERNAL_CHANGE_TO_FALSE, 3, context);
}
/*private static void createScreenTimeoutAlwaysOnView(Context context)
{
removeScreenTimeoutAlwaysOnView(context);
if (PhoneProfilesService.getInstance() != null) {
final Context appContext = context.getApplicationContext();
// Put 30 minutes screen timeout. Required for SettingsContentObserver.OnChange to call removeScreenTimeoutAlwaysOnView
// when user change system setting.
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 86400000);
WindowManager windowManager = (WindowManager) appContext.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
int type;
//if (android.os.Build.VERSION.SDK_INT < 25)
// type = WindowManager.LayoutParams.TYPE_TOAST;
//else
if (android.os.Build.VERSION.SDK_INT < 26)
type = LayoutParams.TYPE_SYSTEM_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
else
type = LayoutParams.TYPE_APPLICATION_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
type,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, // | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |
PixelFormat.TRANSLUCENT
);
// if (android.os.Build.VERSION.SDK_INT < 17)
// params.gravity = Gravity.RIGHT | Gravity.TOP;
// else
// params.gravity = Gravity.END | Gravity.TOP;
PhoneProfilesService.getInstance().screenTimeoutAlwaysOnView = new BrightnessView(appContext);
try {
windowManager.addView(PhoneProfilesService.getInstance().screenTimeoutAlwaysOnView, params);
} catch (Exception e) {
PhoneProfilesService.getInstance().screenTimeoutAlwaysOnView = null;
}
}
}
}
static void removeScreenTimeoutAlwaysOnView(Context context)
{
if (PhoneProfilesService.getInstance() != null) {
if (PhoneProfilesService.getInstance().screenTimeoutAlwaysOnView != null) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
try {
windowManager.removeView(PhoneProfilesService.getInstance().screenTimeoutAlwaysOnView);
} catch (Exception ignored) {
}
PhoneProfilesService.getInstance().screenTimeoutAlwaysOnView = null;
}
}
}
}
*/
/*
@SuppressLint("RtlHardcoded")
private static void createBrightnessView(Profile profile, Context context)
{
PPApplication.logE("ActivateProfileHelper.createBrightnessView", "xxx");
if (PhoneProfilesService.getInstance() != null) {
final Context appContext = context.getApplicationContext();
WindowManager windowManager = (WindowManager) appContext.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
if (PhoneProfilesService.getInstance().brightnessView != null) {
try {
windowManager.removeView(PhoneProfilesService.getInstance().brightnessView);
} catch (Exception ignored) {
}
PhoneProfilesService.getInstance().brightnessView = null;
}
int type;
//if (android.os.Build.VERSION.SDK_INT < 25)
// type = WindowManager.LayoutParams.TYPE_TOAST;
//else
if (android.os.Build.VERSION.SDK_INT < 26)
type = LayoutParams.TYPE_SYSTEM_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
else
type = LayoutParams.TYPE_APPLICATION_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
type,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, //| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.TRANSLUCENT
);
if (profile.getDeviceBrightnessAutomatic() || (!profile.getDeviceBrightnessChangeLevel()))
params.screenBrightness = LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
else
params.screenBrightness = profile.getDeviceBrightnessManualValue(appContext) / (float) 255;
PhoneProfilesService.getInstance().brightnessView = new BrightnessView(appContext);
try {
windowManager.addView(PhoneProfilesService.getInstance().brightnessView, params);
} catch (Exception e) {
PhoneProfilesService.getInstance().brightnessView = null;
}
final Handler handler = new Handler(appContext.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
PPApplication.logE("ActivateProfileHelper.createBrightnessView", "remove brightness view");
WindowManager windowManager = (WindowManager) appContext.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
if ((PhoneProfilesService.getInstance() != null) && (PhoneProfilesService.getInstance().brightnessView != null)) {
try {
windowManager.removeView(PhoneProfilesService.getInstance().brightnessView);
} catch (Exception ignored) {
}
PhoneProfilesService.getInstance().brightnessView = null;
}
}
}
}, 5000);
// PostDelayedBroadcastReceiver.setAlarm(PostDelayedBroadcastReceiver.ACTION_REMOVE_BRIGHTNESS_VIEW,5, context);
}
}
}
static void removeBrightnessView(Context context) {
if (PhoneProfilesService.getInstance() != null) {
if (PhoneProfilesService.getInstance().brightnessView != null) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
try {
windowManager.removeView(PhoneProfilesService.getInstance().brightnessView);
} catch (Exception ignored) {
}
PhoneProfilesService.getInstance().brightnessView = null;
}
}
}
}
*/
private static void createKeepScreenOnView(Context context) {
//removeKeepScreenOnView();
final Context appContext = context.getApplicationContext();
/*
//if (PhoneProfilesService.getInstance() != null) {
//PhoneProfilesService service = PhoneProfilesService.getInstance();
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
if (powerManager != null) {
try {
Log.e("ActivateProfileHelper.createKeepScreenOnView", "keepScreenOnWakeLock="+PPApplication.keepScreenOnWakeLock);
if (PPApplication.keepScreenOnWakeLock == null)
PPApplication.keepScreenOnWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_createKeepScreenOnView");
} catch(Exception e) {
PPApplication.keepScreenOnWakeLock = null;
Log.e("ActivateProfileHelper.createKeepScreenOnView", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
try {
if ((PPApplication.keepScreenOnWakeLock != null) && (!PPApplication.keepScreenOnWakeLock.isHeld())) {
Log.e("ActivateProfileHelper.createKeepScreenOnView", "acquire");
PPApplication.keepScreenOnWakeLock.acquire();
}
} catch (Exception e) {
Log.e("ActivateProfileHelper.createKeepScreenOnView", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
}
*/
if (PPApplication.keepScreenOnView != null)
removeKeepScreenOnView(context);
WindowManager windowManager = (WindowManager) appContext.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
int type;
//if (android.os.Build.VERSION.SDK_INT < 25)
// type = WindowManager.LayoutParams.TYPE_TOAST;
//else
if (android.os.Build.VERSION.SDK_INT < 26)
type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
else
type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
type,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON/* |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | // deprecated in API level 26
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | // deprecated in API level 27
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON // deprecated in API level 27*/
, PixelFormat.TRANSLUCENT
);
//if (android.os.Build.VERSION.SDK_INT < 17)
// params.gravity = Gravity.RIGHT | Gravity.TOP;
//else
// params.gravity = Gravity.END | Gravity.TOP;
PPApplication.keepScreenOnView = new BrightnessView(appContext);
try {
windowManager.addView(PPApplication.keepScreenOnView, params);
} catch (Exception e) {
PPApplication.keepScreenOnView = null;
}
}
}
static void removeKeepScreenOnView(Context context)
{
final Context appContext = context.getApplicationContext();
//if (PhoneProfilesService.getInstance() != null) {
//final Context appContext = context.getApplicationContext();
//PhoneProfilesService service = PhoneProfilesService.getInstance();
/*try {
Log.e("ActivateProfileHelper.removeKeepScreenOnView", "keepScreenOnWakeLock="+PPApplication.keepScreenOnWakeLock);
if ((PPApplication.keepScreenOnWakeLock != null) && PPApplication.keepScreenOnWakeLock.isHeld())
PPApplication.keepScreenOnWakeLock.release();
} catch (Exception e) {
Log.e("ActivateProfileHelper.removeKeepScreenOnView", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
PPApplication.keepScreenOnWakeLock = null;*/
if (PPApplication.keepScreenOnView != null) {
WindowManager windowManager = (WindowManager) appContext.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
try {
windowManager.removeView(PPApplication.keepScreenOnView);
} catch (Exception ignored) {
}
PPApplication.keepScreenOnView = null;
}
}
//}
}
static boolean isAirplaneMode(Context context)
{
//if (android.os.Build.VERSION.SDK_INT >= 17)
return Settings.Global.getInt(context.getApplicationContext().getContentResolver(), Global.AIRPLANE_MODE_ON, 0) != 0;
//else
// return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
private static void setAirplaneMode(boolean mode)
{
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false))) {
// device is rooted
synchronized (PPApplication.rootMutex) {
String command1;
String command2;
if (mode) {
command1 = "settings put global airplane_mode_on 1";
command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true";
} else {
command1 = "settings put global airplane_mode_on 0";
command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false";
}
//if (PPApplication.isSELinuxEnforcing())
//{
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
// command2 = PPApplication.getSELinuxEnforceCommand(command2, Shell.ShellContext.SYSTEM_APP);
//}
Command command = new Command(0, true, command1, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setAirplaneMode");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setAirplaneMode", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
//PPApplication.logE("ActivateProfileHelper.setAirplaneMode", "done");
}
}
}
static boolean isMobileData(Context context, int simCard)
{
Context appContext = context.getApplicationContext();
/*
if (android.os.Build.VERSION.SDK_INT < 21)
{
ConnectivityManager connectivityManager = null;
try {
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
} catch (Exception ignored) {
// java.lang.NullPointerException: missing IConnectivityManager
// Dual SIM?? Bug in Android ???
}
if (connectivityManager != null) {
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method getMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled");
getMobileDataEnabledMethod.setAccessible(true);
return (Boolean) getMobileDataEnabledMethod.invoke(connectivityManager);
} catch (Exception e) {
return false;
}
}
else
return false;
}
else*/
/*if (android.os.Build.VERSION.SDK_INT < 22)
{
Method getDataEnabledMethod;
Class<?> telephonyManagerClass;
Object ITelephonyStub;
Class<?> ITelephonyClass;
TelephonyManager telephonyManager = (TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
try {
telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");
getITelephonyMethod.setAccessible(true);
ITelephonyStub = getITelephonyMethod.invoke(telephonyManager);
if (ITelephonyStub != null) {
ITelephonyClass = Class.forName(ITelephonyStub.getClass().getName());
getDataEnabledMethod = ITelephonyClass.getDeclaredMethod("getDataEnabled");
getDataEnabledMethod.setAccessible(true);
//noinspection ConstantConditions
return (Boolean) getDataEnabledMethod.invoke(ITelephonyStub);
}
else
return false;
} catch (Exception e) {
return false;
}
}
else
return false;
}
else*/
/*if (android.os.Build.VERSION.SDK_INT < 28)
{
TelephonyManager telephonyManager = (TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
Method getDataEnabledMethod;
Class<?> telephonyManagerClass;
try {
telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
getDataEnabledMethod = telephonyManagerClass.getDeclaredMethod("getDataEnabled");
getDataEnabledMethod.setAccessible(true);
//noinspection ConstantConditions
return (Boolean) getDataEnabledMethod.invoke(telephonyManager);
} catch (Exception e) {
return false;
}
}
else
return false;
}
else*/
return CmdMobileData.isEnabled(appContext, simCard);
}
static boolean canSetMobileData(Context context)
{
Context appContext = context.getApplicationContext();
if (android.os.Build.VERSION.SDK_INT >= 28)
return true;
else
//if (android.os.Build.VERSION.SDK_INT >= 22)
{
Class<?> telephonyManagerClass;
TelephonyManager telephonyManager = (TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
try {
telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
Method getDataEnabledMethod = telephonyManagerClass.getDeclaredMethod("getDataEnabled");
getDataEnabledMethod.setAccessible(true);
return true;
} catch (Exception e) {
return false;
}
}
else
return false;
}
/*else
//if (android.os.Build.VERSION.SDK_INT >= 21)
{
Class<?> telephonyManagerClass;
TelephonyManager telephonyManager = (TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
try {
telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");
getITelephonyMethod.setAccessible(true);
return true;
} catch (Exception e) {
return false;
}
}
else
return false;
}*/
/*else
{
ConnectivityManager connectivityManager = null;
try {
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
} catch (Exception ignored) {
// java.lang.NullPointerException: missing IConnectivityManager
// Dual SIM?? Bug in Android ???
}
if (connectivityManager != null) {
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method getMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled");
getMobileDataEnabledMethod.setAccessible(true);
return true;
} catch (Exception e) {
return false;
}
}
else
return false;
}*/
}
private static void setMobileData(Context context, boolean enable, int simCard)
{
// PPApplication.logE("ActivateProfileHelper.setMobileData", "xxx");
Context appContext = context.getApplicationContext();
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
PPApplication.isRooted(false) &&
PhoneProfilesService.hasSIMCard(appContext, simCard, true))
{
if (Permissions.checkPhone(context.getApplicationContext())) {
//PPApplication.logE("ActivateProfileHelper.setMobileData", "ask for root enabled and is rooted");
if ((Build.VERSION.SDK_INT < 26) || (simCard == 0)) {
// dual sim is supported by TelephonyManager from API 26
synchronized (PPApplication.rootMutex) {
String command1 = "svc data " + (enable ? "enable" : "disable");
//PPApplication.logE("ActivateProfileHelper.setMobileData", "command=" + command1);
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SHELL).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setMobileData");
//PPApplication.logE("ActivateProfileHelper.setMobileData", "after wait");
} catch (Exception e) {
//Log.e("ActivateProfileHelper.setMobileData", Log.getStackTraceString(e));
}
}
} else {
// Get the value of the "TRANSACTION_setDataEnabled" field.
Object serviceManager = PPApplication.getServiceManager("phone");
int transactionCode = -1;
if (serviceManager != null) {
if (Build.VERSION.SDK_INT >= 28)
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setUserDataEnabled");
else
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDataEnabled");
}
int state = enable ? 1 : 0;
if (transactionCode != -1) {
// PPApplication.logE("ActivateProfileHelper.setMobileData", "transactionCode=" + transactionCode);
SubscriptionManager mSubscriptionManager = (SubscriptionManager) appContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
//SubscriptionManager.from(appContext);
if (mSubscriptionManager != null) {
// PPApplication.logE("ActivateProfileHelper.setMobileData", "mSubscriptionManager != null");
List<SubscriptionInfo> subscriptionList = null;
try {
// Loop through the subscription list i.e. SIM list.
subscriptionList = mSubscriptionManager.getActiveSubscriptionInfoList();
// PPApplication.logE("ActivateProfileHelper.setMobileData", "subscriptionList=" + subscriptionList);
} catch (SecurityException e) {
PPApplication.recordException(e);
}
if (subscriptionList != null) {
// PPApplication.logE("ActivateProfileHelper.setMobileData", "subscriptionList.size()=" + subscriptionList.size());
for (int i = 0; i < subscriptionList.size(); i++) {
// Get the active subscription ID for a given SIM card.
SubscriptionInfo subscriptionInfo = subscriptionList.get(i);
// PPApplication.logE("ActivateProfileHelper.setMobileData", "subscriptionInfo=" + subscriptionInfo);
if (subscriptionInfo != null) {
int slotIndex = subscriptionInfo.getSimSlotIndex();
if (simCard == (slotIndex+1)) {
int subscriptionId = subscriptionInfo.getSubscriptionId();
// PPApplication.logE("ActivateProfileHelper.setMobileData", "subscriptionId=" + subscriptionId);
synchronized (PPApplication.rootMutex) {
String command1 = PPApplication.getServiceCommand("phone", transactionCode, subscriptionId, state);
// PPApplication.logE("ActivateProfileHelper.setMobileData", "command1=" + command1);
if (command1 != null) {
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setMobileData");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setMobileData", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
}
}
// else
// PPApplication.logE("ActivateProfileHelper.setMobileData", "subscriptionInfo == null");
}
}
// else
// PPApplication.logE("ActivateProfileHelper.setMobileData", "subscriptionList == null");
}
// else
// PPApplication.logE("ActivateProfileHelper.setMobileData", "mSubscriptionManager == null");
}
// else
// PPApplication.logE("ActivateProfileHelper.setMobileData", "transactionCode == -1");
}
}
}
}
/*
private int getPreferredNetworkType(Context context) {
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot(context)) &&
(PPApplication.isRooted()))
{
try {
// Get the value of the "TRANSACTION_setPreferredNetworkType" field.
String transactionCode = PPApplication.getTransactionCode(context, "TRANSACTION_getPreferredNetworkType");
if (transactionCode != null && transactionCode.length() > 0) {
String command1 = "service call phone " + transactionCode + " i32";
Command command = new Command(0, false, command1) {
@Override
public void commandOutput(int id, String line) {
super.commandOutput(id, line);
String splits[] = line.split(" ");
try {
networkType = Integer.parseInt(splits[2]);
} catch (Exception e) {
networkType = -1;
}
}
@Override
public void commandTerminated(int id, String reason) {
super.commandTerminated(id, reason);
}
@Override
public void commandCompleted(int id, int exitCode) {
super.commandCompleted(id, exitCode);
}
};
try {
roottools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPreferredNetworkType", Log.getStackTraceString(e));
}
}
} catch(Exception e) {
Log.e("ActivateProfileHelper.getPreferredNetworkType", Log.getStackTraceString(e));
}
}
else
networkType = -1;
return networkType;
}
*/
static boolean telephonyServiceExists(String preference) {
try {
int transactionCode = -1;
switch (preference) {
case Profile.PREF_PROFILE_DEVICE_MOBILE_DATA:
case Profile.PREF_PROFILE_DEVICE_MOBILE_DATA_SIM1:
case Profile.PREF_PROFILE_DEVICE_MOBILE_DATA_SIM2:
Object serviceManager = PPApplication.getServiceManager("phone");
if (serviceManager != null) {
if (Build.VERSION.SDK_INT >= 28)
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setUserDataEnabled");
else
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDataEnabled");
}
break;
case Profile.PREF_PROFILE_DEVICE_NETWORK_TYPE:
case Profile.PREF_PROFILE_DEVICE_NETWORK_TYPE_SIM1:
case Profile.PREF_PROFILE_DEVICE_NETWORK_TYPE_SIM2:
serviceManager = PPApplication.getServiceManager("phone");
if (serviceManager != null)
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setPreferredNetworkType");
break;
case Profile.PREF_PROFILE_DEVICE_DEFAULT_SIM_CARDS:
serviceManager = PPApplication.getServiceManager("isub");
if (serviceManager != null) {
// support for only data devices
int transactionCodeVoice = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDefaultVoiceSubId");
int transactionCodeSMS = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDefaultSmsSubId");
int transactionCodeData = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDefaultDataSubId");
if ((transactionCodeVoice != -1) || (transactionCodeSMS != -1) || (transactionCodeData != -1))
transactionCode = 1;
}
break;
case Profile.PREF_PROFILE_DEVICE_ONOFF_SIM1:
case Profile.PREF_PROFILE_DEVICE_ONOFF_SIM2:
serviceManager = PPApplication.getServiceManager("isub");
if (serviceManager != null)
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setSubscriptionEnabled");
break;
}
return transactionCode != -1;
} catch(Exception e) {
return false;
}
}
private static void setPreferredNetworkType(Context context, int networkType, int simCard)
{
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
PPApplication.isRooted(false) &&
PPApplication.serviceBinaryExists(false) &&
PhoneProfilesService.hasSIMCard(context, simCard, true))
{
if (Permissions.checkPhone(context.getApplicationContext())) {
try {
// Get the value of the "TRANSACTION_setPreferredNetworkType" field.
Object serviceManager = PPApplication.getServiceManager("phone");
int transactionCode = -1;
if (serviceManager != null) {
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setPreferredNetworkType");
}
if (transactionCode != -1) {
// Android 5.1?
//if (Build.VERSION.SDK_INT >= 22) {
Context appContext = context.getApplicationContext();
SubscriptionManager mSubscriptionManager = (SubscriptionManager) appContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
//SubscriptionManager.from(context);
if (mSubscriptionManager != null) {
List<SubscriptionInfo> subscriptionList = null;
try {
// Loop through the subscription list i.e. SIM list.
subscriptionList = mSubscriptionManager.getActiveSubscriptionInfoList();
} catch (SecurityException e) {
PPApplication.recordException(e);
}
if (subscriptionList != null) {
for (int i = 0; i < subscriptionList.size();/*mSubscriptionManager.getActiveSubscriptionInfoCountMax();*/ i++) {
// Get the active subscription ID for a given SIM card.
SubscriptionInfo subscriptionInfo = subscriptionList.get(i);
if (subscriptionInfo != null) {
int slotIndex = subscriptionInfo.getSimSlotIndex();
if ((Build.VERSION.SDK_INT < 26) || (simCard == 0) || (simCard == (slotIndex+1))) {
// dual sim is supported by TelephonyManager from API 26
int subscriptionId = subscriptionInfo.getSubscriptionId();
synchronized (PPApplication.rootMutex) {
String command1 = PPApplication.getServiceCommand("phone", transactionCode, subscriptionId, networkType);
if (command1 != null) {
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setPreferredNetworkType");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setPreferredNetworkType", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
}
}
}
}
}
/*} else {
synchronized (PPApplication.rootMutex) {
String command1 = PPApplication.getServiceCommand("phone", transactionCode, networkType);
if (command1 != null) {
Command command = new Command(0, false, command1);
try {
roottools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command);
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setPreferredNetworkType", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
}*/
}
} catch (Exception ee) {
PPApplication.recordException(ee);
}
}
}
}
static boolean wifiServiceExists(/*Context context, */
@SuppressWarnings("SameParameterValue") String preference) {
try {
Object serviceManager = PPApplication.getServiceManager("wifi");
if (serviceManager != null) {
int transactionCode = -1;
if (preference.equals(Profile.PREF_PROFILE_DEVICE_WIFI_AP))
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setWifiApEnabled");
return transactionCode != -1;
}
return false;
} catch(Exception e) {
//Log.e("ActivateProfileHelper.wifiServiceExists",Log.getStackTraceString(e));
PPApplication.recordException(e);
return false;
}
}
private static void setWifiAP(WifiApManager wifiApManager, boolean enable, boolean doNotChangeWifi, Context context) {
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-enable="+enable);
if (Build.VERSION.SDK_INT < 26) {
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-API < 26");
wifiApManager.setWifiApState(enable, doNotChangeWifi);
}
else
if (Build.VERSION.SDK_INT < 28) {
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-API >= 26");
Context appContext = context.getApplicationContext();
if (WifiApManager.canExploitWifiTethering(appContext)) {
if (enable)
wifiApManager.startTethering(doNotChangeWifi);
else
wifiApManager.stopTethering();
}
else
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.serviceBinaryExists(false))) {
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-rooted");
try {
Object serviceManager = PPApplication.getServiceManager("wifi");
int transactionCode = -1;
if (serviceManager != null) {
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setWifiApEnabled");
}
/*if (PPApplication.logEnabled()) {
PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-serviceManager=" + serviceManager);
PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-transactionCode=" + transactionCode);
}*/
if (transactionCode != -1) {
if (enable && (!doNotChangeWifi)) {
WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-wifiManager=" + wifiManager);
if (wifiManager != null) {
int wifiState = wifiManager.getWifiState();
boolean isWifiEnabled = ((wifiState == WifiManager.WIFI_STATE_ENABLED) || (wifiState == WifiManager.WIFI_STATE_ENABLING));
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-isWifiEnabled=" + isWifiEnabled);
if (isWifiEnabled) {
//PPApplication.logE("#### setWifiEnabled", "from ActivateProfileHelper.setWifiAP");
wifiManager.setWifiEnabled(false);
PPApplication.sleep(1000);
}
}
}
synchronized (PPApplication.rootMutex) {
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-start root command");
String command1 = PPApplication.getServiceCommand("wifi", transactionCode, 0, (enable) ? 1 : 0);
if (command1 != null) {
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-command1=" + command1);
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setWifiAP");
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-root command end");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setWifiAP", Log.getStackTraceString(e));
//PPApplication.recordException(e);
//PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.setWifiAP-root command error");
}
}
}
}
} catch (Exception e) {
//Log.e("ActivateProfileHelper.setWifiAP", Log.getStackTraceString(e));
PPApplication.recordException(e);
//PPApplication.logE("$$$ WifiAP", Log.getStackTraceString(e));
}
}
}
else {
if (enable)
wifiApManager.startTethering(doNotChangeWifi);
else
wifiApManager.stopTethering();
}
}
private static void setNFC(Context context, boolean enable)
{
/*
Not working in debug version of application !!!!
Test with release version.
*/
Context appContext = context.getApplicationContext();
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
CmdNfc.setNFC(enable);
}
else
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false))) {
synchronized (PPApplication.rootMutex) {
String command1 = PPApplication.getJavaCommandFile(CmdNfc.class, "nfc", appContext, enable);
if (command1 != null) {
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.NORMAL).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setNFC");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setNFC", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
//String command = PPApplication.getJavaCommandFile(CmdNfc.class, "nfc", context, enable);
//if (command != null)
// RootToolsSmall.runSuCommand(command);
}
}
}
/*
static boolean canExploitGPS(Context context)
{
Context appContext = context.getApplicationContext();
// test exploiting power manager widget
PackageManager pacMan = appContext.getPackageManager();
try {
PackageInfo pacInfo = pacMan.getPackageInfo("com.android.settings", PackageManager.GET_RECEIVERS);
if(pacInfo != null){
for(ActivityInfo actInfo : pacInfo.receivers){
//test if receiver is exported. if so, we can toggle GPS.
if(actInfo.name.equals("com.android.settings.widget.SettingsAppWidgetProvider") && actInfo.exported){
return true;
}
}
}
} catch (Exception e) {
return false; //package not found
}
return false;
}
*/
private static void setGPS(Context context, boolean enable)
{
Context appContext = context.getApplicationContext();
//boolean isEnabled;
//int locationMode = -1;
//if (android.os.Build.VERSION.SDK_INT < 19)
// isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
/*else {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE, -1);
isEnabled = (locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY) ||
(locationMode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY);
}*/
boolean isEnabled = false;
boolean ok = true;
LocationManager locationManager = (LocationManager) appContext.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null)
isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
else
ok = false;
if (!ok)
return;
//PPApplication.logE("ActivateProfileHelper.setGPS", "isEnabled="+isEnabled);
//if(!provider.contains(LocationManager.GPS_PROVIDER) && enable)
if ((!isEnabled) && enable)
{
// adb shell pm grant sk.henrichg.phoneprofilesplus android.permission.WRITE_SECURE_SETTINGS
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
String newSet;
newSet = "+gps";
//noinspection deprecation
Settings.Secure.putString(appContext.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newSet);
}
else
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false)))
{
// device is rooted
//PPApplication.logE("ActivateProfileHelper.setGPS", "rooted");
String command1;
/*
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
PPApplication.logE("ActivateProfileHelper.setGPS", "provider="+provider);
*/
synchronized (PPApplication.rootMutex) {
command1 = "settings put secure location_providers_allowed +gps";
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setGPS (1)");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setGPS", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
/*else
if (canExploitGPS(appContext))
{
//PPApplication.logE("ActivateProfileHelper.setGPS", "exploit");
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
appContext.sendBroadcast(poke);
}*/
}
else
//if(provider.contains(LocationManager.GPS_PROVIDER) && (!enable))
if (isEnabled && (!enable))
{
// adb shell pm grant sk.henrichg.phoneprofilesplus android.permission.WRITE_SECURE_SETTINGS
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
String newSet;// = "";
newSet = "-gps";
//noinspection deprecation
Settings.Secure.putString(appContext.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newSet);
}
else
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false)))
{
// device is rooted
//PPApplication.logE("ActivateProfileHelper.setGPS", "rooted");
String command1;
/*
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
PPApplication.logE("ActivateProfileHelper.setGPS", "provider="+provider);
*/
synchronized (PPApplication.rootMutex) {
command1 = "settings put secure location_providers_allowed -gps";
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setGPS (2)");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setGPS", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
/*else
if (canExploitGPS(appContext))
{
//PPApplication.logE("ActivateProfileHelper.setGPS", "exploit");
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
appContext.sendBroadcast(poke);
}*/
}
}
private static void setLocationMode(Context context, int mode)
{
Context appContext = context.getApplicationContext();
//PPApplication.logE("ActivateProfileHelper.setLocationMode", "mode="+mode);
// adb shell pm grant sk.henrichg.phoneprofilesplus android.permission.WRITE_SECURE_SETTINGS
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
Settings.Secure.putInt(appContext.getContentResolver(), Settings.Secure.LOCATION_MODE, mode);
}
/*else
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false)))
{
// device is rooted - NOT WORKING
PPApplication.logE("ActivateProfileHelper.setLocationMode", "rooted");
String command1;
synchronized (PPApplication.rootMutex) {
command1 = "settings put secure location_mode " + mode;
Command command = new Command(0, false, command1);
try {
roottools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setLocationMode");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setLocationMode", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
}
}*/
}
private static void setPowerSaveMode(final Profile profile, Context context) {
if (profile._devicePowerSaveMode != 0) {
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadProfileActivation();
final Handler handler = new Handler(PPApplication.handlerThreadProfileActivation.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadProfileActivation", "START run - from=ActivateProfileHelper.setPowerSaveMode");
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_POWER_SAVE_MODE, null, null, false, appContext).allowed == PreferenceAllowed.PREFERENCE_ALLOWED) {
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_setPowerSaveMode");
wakeLock.acquire(10 * 60 * 1000);
}
if (powerManager != null) {
//PowerManager powerManager = (PowerManager) appContext.getSystemService(POWER_SERVICE);
boolean _isPowerSaveMode;
//if (Build.VERSION.SDK_INT >= 21)
_isPowerSaveMode = powerManager.isPowerSaveMode();
boolean _setPowerSaveMode = false;
switch (profile._devicePowerSaveMode) {
case 1:
if (!_isPowerSaveMode) {
_isPowerSaveMode = true;
_setPowerSaveMode = true;
}
break;
case 2:
if (_isPowerSaveMode) {
_isPowerSaveMode = false;
_setPowerSaveMode = true;
}
break;
case 3:
_isPowerSaveMode = !_isPowerSaveMode;
_setPowerSaveMode = true;
break;
}
if (_setPowerSaveMode) {
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
//if (android.os.Build.VERSION.SDK_INT >= 21)
Global.putInt(appContext.getContentResolver(), "low_power", ((_isPowerSaveMode) ? 1 : 0));
} else if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false) && PPApplication.settingsBinaryExists(false))) {
synchronized (PPApplication.rootMutex) {
String command1 = "settings put global low_power " + ((_isPowerSaveMode) ? 1 : 0);
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setPowerSaveMode");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setPowerSaveMode", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
}
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
}
});
}
}
private static void lockDevice(final Profile profile, Context context) {
final Context appContext = context.getApplicationContext();
PPApplication.startHandlerThreadProfileActivation();
final Handler handler = new Handler(PPApplication.handlerThreadProfileActivation.getLooper());
handler.post(() -> {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThreadProfileActivation", "START run - from=ActivateProfileHelper.lockDevice");
//PPApplication.logE("[TEST_BLOCK_PROFILE_EVENTS_ACTIONS] ActivateProfileHelper.lockDevice", "PPApplication.blockProfileEventActions="+PPApplication.blockProfileEventActions);
if (PPApplication.blockProfileEventActions)
// not lock device after boot
return;
/*if (PPApplication.logEnabled()) {
PPApplication.logE("ActivateProfileHelper.lockDevice", "not blocked");
PPApplication.logE("ActivateProfileHelper.lockDevice", "profile._lockDevice=" + profile._lockDevice);
}*/
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActivateProfileHelper_lockDevice");
wakeLock.acquire(10 * 60 * 1000);
}
switch (profile._lockDevice) {
case 1:
if (PhoneProfilesService.getInstance() != null) {
if (Permissions.checkLockDevice(appContext) && (PPApplication.lockDeviceActivity == null)) {
try {
Intent intent = new Intent(appContext, LockDeviceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
appContext.startActivity(intent);
} catch (Exception e) {
PPApplication.recordException(e);
}
}
}
break;
case 2:
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false))) {
synchronized (PPApplication.rootMutex) {
/*String command1 = "input keyevent 26";
Command command = new Command(0, false, command1);
try {
roottools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (RootDeniedException e) {
PPApplication.rootMutex.rootGranted = false;
Log.e("ActivateProfileHelper.lockDevice", Log.getStackTraceString(e));
} catch (Exception e) {
Log.e("ActivateProfileHelper.lockDevice", Log.getStackTraceString(e));
}*/
String command1 = PPApplication.getJavaCommandFile(CmdGoToSleep.class, "power", appContext, 0);
if (command1 != null) {
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.NORMAL).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.lockDevice");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.lockDevice", Log.getStackTraceString(e));
//CPPApplication.recordException(e);
}
}
}
}
/*if ((!ApplicationPreferences.applicationNeverAskForGrantRoot(context)) &&
(PPApplication.isRooted() && PPApplication.serviceBinaryExists())) {
synchronized (PPApplication.rootMutex) {
try {
// Get the value of the "TRANSACTION_goToSleep" field.
String transactionCode = PPApplication.getTransactionCode("android.os.IPowerManager", "TRANSACTION_goToSleep");
String command1 = "service call power " + transactionCode + " i64 " + SystemClock.uptimeMillis();
Command command = new Command(0, false, command1);
try {
roottools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (RootDeniedException e) {
PPApplication.rootMutex.rootGranted = false;
Log.e("ActivateProfileHelper.lockDevice", Log.getStackTraceString(e));
} catch (Exception e) {
Log.e("ActivateProfileHelper.lockDevice", Log.getStackTraceString(e));
}
} catch(Exception ignored) {
}
}
*/
break;
case 3:
Intent intent = new Intent(PPApplication.ACTION_LOCK_DEVICE);
appContext.sendBroadcast(intent, PPApplication.PPP_EXTENDER_PERMISSION);
break;
}
} catch (Exception e) {
// PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
});
}
private static void setScreenDarkMode(Context appContext, final int value) {
//PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "xxx");
if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_SCREEN_DARK_MODE, null, null, false, appContext).allowed
== PreferenceAllowed.PREFERENCE_ALLOWED) {
if (Build.VERSION.SDK_INT >= 29) {
//PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "allowed");
if (Permissions.hasPermission(appContext, Manifest.permission.WRITE_SECURE_SETTINGS)) {
//PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "G1 granted");
try {
//PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "value="+value);
// Android Q (Tasker: https://www.reddit.com/r/tasker/comments/d2ngcl/trigger_android_10_dark_theme_with_brightness/)
if (value == 1)
Settings.Secure.putInt(appContext.getContentResolver(), "ui_night_mode", 2);
else
Settings.Secure.putInt(appContext.getContentResolver(), "ui_night_mode", 1);
}
catch (Exception e2) {
//Log.e("ActivateProfileHelper.setScreenDarkMode", Log.getStackTraceString(e2));
PPApplication.recordException(e2);
}
}
else {
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
(PPApplication.isRooted(false))) {
//PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "root granted");
synchronized (PPApplication.rootMutex) {
String command1 = "settings put secure ui_night_mode ";
if (value == 1)
command1 = command1 + "2";
else
command1 = command1 + "1";
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setScreenDarkMode");
} catch (Exception ee) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setScreenDarkMode", Log.getStackTraceString(ee));
//PPApplication.recordException(e);
}
}
}
}
// switch car mode on and off is required !!!
// but how when car mode is on by device? Opposite switch?
UiModeManager uiModeManager = (UiModeManager) appContext.getSystemService(Context.UI_MODE_SERVICE);
//PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "uiModeManager=" + uiModeManager);
if (uiModeManager != null) {
if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_NORMAL) {
uiModeManager.enableCarMode(0);
PPApplication.sleep(200);
uiModeManager.disableCarMode(0);
}
else
if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_CAR) {
uiModeManager.disableCarMode(0);
PPApplication.sleep(200);
uiModeManager.enableCarMode(0);
}
}
}
/*if (Build.VERSION.SDK_INT > 26) {
if (Permissions.hasPermission(context, Manifest.permission.WRITE_SECURE_SETTINGS)) {
try {
// Not working in Samsung S8 :-(
// this not change gui to dark, this is blue filter (???)
PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "(G1)");
if (value == 1)
Settings.Global.putInt(context.getContentResolver(), "night_mode_enabled", 1);
else
Settings.Global.putInt(context.getContentResolver(), "night_mode_enabled", 0);
// Android Q (Tasker: https://www.reddit.com/r/tasker/comments/d2ngcl/trigger_android_10_dark_theme_with_brightness/)
if (value == 1)
Settings.Secure.putInt(context.getContentResolver(), "ui_night_mode", 2);
else
Settings.Secure.putInt(context.getContentResolver(), "ui_night_mode", 1);
}
catch (Exception e2) {
PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", Log.getStackTraceString(e2));
}
}
}
else {
UiModeManager uiModeManager = (UiModeManager) context.getSystemService(Context.UI_MODE_SERVICE);
PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "uiModeManager=" + uiModeManager);
if (uiModeManager != null) {
switch (value) {
case 1:
//uiModeManager.enableCarMode(0);
uiModeManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
break;
case 2:
//uiModeManager.enableCarMode(0);
uiModeManager.setNightMode(UiModeManager.MODE_NIGHT_NO);
break;
case 3:
//uiModeManager.disableCarMode(0);
uiModeManager.setNightMode(UiModeManager.MODE_NIGHT_NO);
break;
}
PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "currentModeType=" + uiModeManager.getCurrentModeType());
PPApplication.logE("ActivateProfileHelper.setScreenDarkMode", "nightMode=" + uiModeManager.getNightMode());
}
}*/
}
}
private static void setDefaultSimCard(Context context, int subscriptionType, int simCard)
{
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "subscriptionType="+subscriptionType);
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "simCard="+simCard);
Context appContext = context.getApplicationContext();
switch (subscriptionType) {
case SUBSCRIPTRION_VOICE:
switch (simCard) {
case 1: // ask for SIM - currently not supported
simCard = -1;
break;
case 2: // SIM 1
simCard = 1;
break;
case 3: // SIM 2
simCard = 2;
break;
}
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "new simCard="+simCard);
break;
case SUBSCRIPTRION_SMS:
case SUBSCRIPTRION_DATA:
break;
}
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
PPApplication.isRooted(false)) {
if (Permissions.checkPhone(context.getApplicationContext())) {
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "ask for root enabled and is rooted");
if (Build.VERSION.SDK_INT >= 26) {
if (simCard != -1) {
if (PhoneProfilesService.hasSIMCard(appContext, simCard, false)) {
int defaultSubscriptionId = -1;
// Get the value of the "TRANSACTION_setDefaultSimCard" field.
Object serviceManager = PPApplication.getServiceManager("isub");
int transactionCode = -1;
if (serviceManager != null) {
switch (subscriptionType) {
case SUBSCRIPTRION_VOICE:
defaultSubscriptionId = SubscriptionManager.getDefaultVoiceSubscriptionId();
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "getTransactionCode for setDefaultVoiceSubId");
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDefaultVoiceSubId");
break;
case SUBSCRIPTRION_SMS:
defaultSubscriptionId = SubscriptionManager.getDefaultSmsSubscriptionId();
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "getTransactionCode for setDefaultSmsSubId");
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDefaultSmsSubId");
break;
case SUBSCRIPTRION_DATA:
defaultSubscriptionId = SubscriptionManager.getDefaultDataSubscriptionId();
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "getTransactionCode for setDefaultDataSubId");
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setDefaultDataSubId");
break;
}
}
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "defaultSubscriptionId=" + defaultSubscriptionId);
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "transactionCode=" + transactionCode);
if (transactionCode != -1) {
SubscriptionManager mSubscriptionManager = (SubscriptionManager) appContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
//SubscriptionManager.from(appContext);
if (mSubscriptionManager != null) {
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "mSubscriptionManager != null");
List<SubscriptionInfo> subscriptionList = null;
try {
// Loop through the subscription list i.e. SIM list.
subscriptionList = mSubscriptionManager.getActiveSubscriptionInfoList();
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "subscriptionList=" + subscriptionList);
} catch (SecurityException e) {
PPApplication.recordException(e);
}
if (subscriptionList != null) {
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "subscriptionList.size()=" + subscriptionList.size());
for (int i = 0; i < subscriptionList.size(); i++) {
// Get the active subscription ID for a given SIM card.
SubscriptionInfo subscriptionInfo = subscriptionList.get(i);
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "subscriptionInfo=" + subscriptionInfo);
if (subscriptionInfo != null) {
int slotIndex = subscriptionInfo.getSimSlotIndex();
if (simCard == (slotIndex+1)) {
int subscriptionId = subscriptionInfo.getSubscriptionId();
if (subscriptionId != defaultSubscriptionId) {
// do not call subscription change, when is aleredy set, this cause FC
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "subscriptionId=" + subscriptionId);
synchronized (PPApplication.rootMutex) {
String command1 = PPApplication.getServiceCommand("isub", transactionCode, subscriptionId);
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "command1=" + command1);
String command2 = "";
switch (subscriptionType) {
case SUBSCRIPTRION_VOICE:
command2 = "settings put global " + Settings.Global.MULTI_SIM_VOICE_CALL_SUBSCRIPTION + " " + subscriptionId;
break;
case SUBSCRIPTRION_SMS:
command2 = "settings put global " + Settings.Global.MULTI_SIM_SMS_SUBSCRIPTION + " " + subscriptionId;
break;
case SUBSCRIPTRION_DATA:
command2 = "settings put global " + Settings.Global.MULTI_SIM_DATA_CALL_SUBSCRIPTION + " " + subscriptionId;
break;
}
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "command2=" + command2);
if ((command1 != null) && (!command2.isEmpty())) {
Command command = new Command(0, false, command1, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setDefaultSimCard");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setDefaultSimCard", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
}
}
}
}
}
else
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "subscriptionInfo == null");
}
}
else
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "subscriptionList == null");
}
else
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "mSubscriptionManager == null");
}
else
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "(transactionCode == -1) || (simCard == -1)");
}
}
else {
synchronized (PPApplication.rootMutex) {
String command1 = "";
switch (subscriptionType) {
case SUBSCRIPTRION_VOICE:
command1 = "settings put global " + Settings.Global.MULTI_SIM_VOICE_CALL_SUBSCRIPTION + " -1";
break;
case SUBSCRIPTRION_SMS:
command1 = "settings put global " + Settings.Global.MULTI_SIM_SMS_SUBSCRIPTION + " -1";
break;
case SUBSCRIPTRION_DATA:
command1 = "settings put global " + Settings.Global.MULTI_SIM_DATA_CALL_SUBSCRIPTION + " -1";
break;
}
PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "command1=" + command1);
if (!command1.isEmpty()) {
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setDefaultSimCard");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setDefaultSimCard", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
}
}
}
}
}
}
}
private static void setSIMOnOff(Context context, boolean enable, int simCard)
{
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "xxx");
Context appContext = context.getApplicationContext();
if ((!ApplicationPreferences.applicationNeverAskForGrantRoot) &&
PPApplication.isRooted(false) &&
PhoneProfilesService.hasSIMCard(appContext, simCard, true))
{
if (Permissions.checkPhone(context.getApplicationContext())) {
//PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "ask for root enabled and is rooted");
// Get the value of the "TRANSACTION_setDataEnabled" field.
Object serviceManager = PPApplication.getServiceManager("isub");
int transactionCode = -1;
if (serviceManager != null) {
transactionCode = PPApplication.getTransactionCode(String.valueOf(serviceManager), "setSubscriptionEnabled");
}
int state = enable ? 1 : 0;
if (transactionCode != -1) {
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "transactionCode=" + transactionCode);
SubscriptionManager mSubscriptionManager = (SubscriptionManager) appContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
//SubscriptionManager.from(appContext);
if (mSubscriptionManager != null) {
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "mSubscriptionManager != null");
List<SubscriptionInfo> subscriptionList = null;
try {
// Loop through the subscription list i.e. SIM list.
subscriptionList = mSubscriptionManager.getActiveSubscriptionInfoList();
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "subscriptionList=" + subscriptionList);
} catch (SecurityException e) {
PPApplication.recordException(e);
}
if (subscriptionList != null) {
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "subscriptionList.size()=" + subscriptionList.size());
for (int i = 0; i < subscriptionList.size(); i++) {
// Get the active subscription ID for a given SIM card.
SubscriptionInfo subscriptionInfo = subscriptionList.get(i);
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "subscriptionInfo=" + subscriptionInfo);
if (subscriptionInfo != null) {
int slotIndex = subscriptionInfo.getSimSlotIndex();
if (simCard == (slotIndex+1)) {
int subscriptionId = subscriptionInfo.getSubscriptionId();
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "subscriptionId=" + subscriptionId);
synchronized (PPApplication.rootMutex) {
String command1 = PPApplication.getServiceCommand("isub", transactionCode, subscriptionId, state);
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "command1=" + command1);
if (command1 != null) {
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
PPApplication.commandWait(command, "ActivateProfileHelper.setSIMOnOff");
} catch (Exception e) {
// com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied
//Log.e("ActivateProfileHelper.setSIMOnOff", Log.getStackTraceString(e));
//PPApplication.recordException(e);
}
}
}
}
}
// else
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "subscriptionInfo == null");
}
}
// else
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "subscriptionList == null");
}
// else
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "mSubscriptionManager == null");
}
// else
// PPApplication.logE("ActivateProfileHelper.setSIMOnOff", "transactionCode == -1");
}
}
}
static void getRingerVolume(Context context)
{
synchronized (PPApplication.profileActivationMutex) {
ApplicationPreferences.prefRingerVolume = ApplicationPreferences.
getSharedPreferences(context).getInt(PREF_RINGER_VOLUME, -999);
//return prefRingerVolume;
}
}
static void setRingerVolume(Context context, int volume)
{
synchronized (PPApplication.profileActivationMutex) {
final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int systemZenMode = getSystemZenMode(context/*, -1*/);
if (isAudibleSystemRingerMode(audioManager, systemZenMode/*, appContext*/)) {
//PPApplication.logE("ActivateProfileHelper.(s)setRingerVolume","volume="+volume);
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context);
editor.putInt(PREF_RINGER_VOLUME, volume);
editor.apply();
ApplicationPreferences.prefRingerVolume = volume;
}
}
}
static void getNotificationVolume(Context context)
{
synchronized (PPApplication.profileActivationMutex) {
ApplicationPreferences.prefNotificationVolume = ApplicationPreferences.
getSharedPreferences(context).getInt(PREF_NOTIFICATION_VOLUME, -999);
//return prefNotificationVolume;
}
}
static void setNotificationVolume(Context context, int volume)
{
synchronized (PPApplication.profileActivationMutex) {
final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int systemZenMode = getSystemZenMode(context/*, -1*/);
if (isAudibleSystemRingerMode(audioManager, systemZenMode/*, appContext*/)) {
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context);
editor.putInt(PREF_NOTIFICATION_VOLUME, volume);
editor.apply();
ApplicationPreferences.prefNotificationVolume = volume;
}
}
}
// called only from PPApplication.loadProfileActivationData()
static void getRingerMode(Context context)
{
synchronized (PPApplication.profileActivationMutex) {
ApplicationPreferences.prefRingerMode = ApplicationPreferences.
getSharedPreferences(context).getInt(PREF_RINGER_MODE, 0);
//return prefRingerMode;
}
}
static void saveRingerMode(Context context, int mode)
{
synchronized (PPApplication.profileActivationMutex) {
//PPApplication.logE("ActivateProfileHelper.(s)saveRingerMode","mode="+mode);
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context);
editor.putInt(PREF_RINGER_MODE, mode);
editor.apply();
ApplicationPreferences.prefRingerMode = mode;
}
}
// called only from PPApplication.loadProfileActivationData()
static void getZenMode(Context context)
{
synchronized (PPApplication.profileActivationMutex) {
ApplicationPreferences.prefZenMode = ApplicationPreferences.
getSharedPreferences(context).getInt(PREF_ZEN_MODE, 0);
//return prefZenMode;
}
}
static void saveZenMode(Context context, int mode)
{
synchronized (PPApplication.profileActivationMutex) {
//PPApplication.logE("ActivateProfileHelper.(s)saveZenMode","mode="+mode);
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context);
editor.putInt(PREF_ZEN_MODE, mode);
editor.apply();
ApplicationPreferences.prefZenMode = mode;
}
}
static void getLockScreenDisabled(Context context)
{
synchronized (PPApplication.profileActivationMutex) {
ApplicationPreferences.prefLockScreenDisabled = ApplicationPreferences.
getSharedPreferences(context).getBoolean(PREF_LOCKSCREEN_DISABLED, false);
//return prefLockScreenDisabled;
}
}
static void setLockScreenDisabled(Context context, boolean disabled)
{
synchronized (PPApplication.profileActivationMutex) {
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context);
editor.putBoolean(PREF_LOCKSCREEN_DISABLED, disabled);
editor.apply();
ApplicationPreferences.prefLockScreenDisabled = disabled;
}
}
static void getActivatedProfileScreenTimeout(Context context)
{
synchronized (PPApplication.profileActivationMutex) {
ApplicationPreferences.prefActivatedProfileScreenTimeout = ApplicationPreferences.
getSharedPreferences(context).getInt(PREF_ACTIVATED_PROFILE_SCREEN_TIMEOUT, 0);
//return prefActivatedProfileScreenTimeout;
}
}
static void setActivatedProfileScreenTimeout(Context context, int timeout)
{
synchronized (PPApplication.profileActivationMutex) {
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context);
editor.putInt(PREF_ACTIVATED_PROFILE_SCREEN_TIMEOUT, timeout);
editor.apply();
ApplicationPreferences.prefActivatedProfileScreenTimeout = timeout;
}
}
@SuppressWarnings("SameParameterValue")
static void showError(Context context, String profileName, int parameterType) {
if ((context == null) || (profileName == null))
return;
Context appContext = context.getApplicationContext();
String title = appContext.getString(R.string.profile_activation_activation_error_title) + " " + profileName;
String text;
int notificationId;
String notificationTag;
//noinspection SwitchStatementWithTooFewBranches
switch (parameterType) {
case Profile.PARAMETER_TYPE_WIFI:
text = appContext.getString(R.string.profile_activation_activation_error_change_wifi);
notificationId = PPApplication.PROFILE_ACTIVATION_WIFI_ERROR_NOTIFICATION_ID;
notificationTag = PPApplication.PROFILE_ACTIVATION_WIFI_ERROR_NOTIFICATION_TAG;
break;
case Profile.PARAMETER_TYPE_WIFIAP:
text = appContext.getString(R.string.profile_activation_activation_error_change_wifi_ap);
notificationId = PPApplication.PROFILE_ACTIVATION_WIFI_AP_ERROR_NOTIFICATION_ID;
notificationTag = PPApplication.PROFILE_ACTIVATION_WIFI_AP_ERROR_NOTIFICATION_TAG;
break;
case Profile.PARAMETER_CLOSE_ALL_APPLICATION:
text = appContext.getString(R.string.profile_activation_activation_error_close_all_applications);
notificationId = PPApplication.PROFILE_ACTIVATION_CLOSE_ALL_APPLICATIONS_ERROR_NOTIFICATION_ID;
notificationTag = PPApplication.PROFILE_ACTIVATION_CLOSE_ALL_APPLICATIONS_ERROR_NOTIFICATION_TAG;
break;
default:
text = appContext.getString(R.string.profile_activation_activation_error);
notificationId = PPApplication.PROFILE_ACTIVATION_ERROR_NOTIFICATION_ID;
notificationTag = PPApplication.PROFILE_ACTIVATION_ERROR_NOTIFICATION_TAG;
break;
}
String nTitle = title;
String nText = text;
if (android.os.Build.VERSION.SDK_INT < 24) {
nTitle = appContext.getString(R.string.ppp_app_name);
nText = title+": "+text;
}
PPApplication.createInformationNotificationChannel(appContext);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext, PPApplication.EXCLAMATION_NOTIFICATION_CHANNEL)
.setColor(ContextCompat.getColor(appContext, R.color.notificationDecorationColor))
.setSmallIcon(R.drawable.ic_exclamation_notify) // notification icon
.setContentTitle(nTitle) // title for notification
.setContentText(nText) // message for notification
.setAutoCancel(true); // clear notification after click
mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(nText));
//PendingIntent pi = PendingIntent.getActivity(appContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//mBuilder.setContentIntent(pi);
mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
//if (android.os.Build.VERSION.SDK_INT >= 21)
//{
mBuilder.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION);
mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
//}
Notification notification = mBuilder.build();
NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(appContext);
try {
mNotificationManager.notify(notificationTag, notificationId, notification);
} catch (Exception e) {
//Log.e("ActivateProfileHelper.showNotificationForInteractiveParameters", Log.getStackTraceString(e));
PPApplication.recordException(e);
}
}
}
| Test of set default sim card. (11)
| phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/ActivateProfileHelper.java | Test of set default sim card. (11) | <ide><path>honeProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/ActivateProfileHelper.java
<ide> PPApplication.logE("[DEFAULT_SIM] ActivateProfileHelper.setDefaultSimCard", "command2=" + command2);
<ide>
<ide> if ((command1 != null) && (!command2.isEmpty())) {
<del> Command command = new Command(0, false, command1, command2);
<add> Command command = new Command(0, false, command2, command1);
<ide> try {
<ide> RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
<ide> PPApplication.commandWait(command, "ActivateProfileHelper.setDefaultSimCard"); |
|
Java | apache-2.0 | 9809d5d663fc2bdeb3fa9107675a3c857c233e4e | 0 | jivesoftware/amza,bruceadowns/amza,bruceadowns/amza,jivesoftware/amza,bruceadowns/amza,bruceadowns/amza,jivesoftware/amza,jivesoftware/amza | /*
* Copyright 2013 Jive Software, 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.jivesoftware.os.amza.service.storage;
import com.google.common.base.Preconditions;
import com.jivesoftware.os.amza.api.CompareTimestampVersions;
import com.jivesoftware.os.amza.api.TimestampedValue;
import com.jivesoftware.os.amza.api.filer.UIO;
import com.jivesoftware.os.amza.api.partition.PartitionProperties;
import com.jivesoftware.os.amza.api.partition.VersionedPartitionName;
import com.jivesoftware.os.amza.api.scan.RangeScannable;
import com.jivesoftware.os.amza.api.scan.RowStream;
import com.jivesoftware.os.amza.api.scan.RowsChanged;
import com.jivesoftware.os.amza.api.stream.Commitable;
import com.jivesoftware.os.amza.api.stream.KeyContainedStream;
import com.jivesoftware.os.amza.api.stream.KeyValuePointerStream;
import com.jivesoftware.os.amza.api.stream.KeyValueStream;
import com.jivesoftware.os.amza.api.stream.KeyValues;
import com.jivesoftware.os.amza.api.stream.RowType;
import com.jivesoftware.os.amza.api.stream.TxKeyPointerStream;
import com.jivesoftware.os.amza.api.stream.UnprefixedWALKeys;
import com.jivesoftware.os.amza.api.stream.WALKeyPointers;
import com.jivesoftware.os.amza.api.stream.WALMergeKeyPointerStream;
import com.jivesoftware.os.amza.api.wal.KeyedTimestampId;
import com.jivesoftware.os.amza.api.wal.PrimaryRowMarshaller;
import com.jivesoftware.os.amza.api.wal.WALHighwater;
import com.jivesoftware.os.amza.api.wal.WALIndex;
import com.jivesoftware.os.amza.api.wal.WALIndexProvider;
import com.jivesoftware.os.amza.api.wal.WALIndexable;
import com.jivesoftware.os.amza.api.wal.WALKey;
import com.jivesoftware.os.amza.api.wal.WALTimestampId;
import com.jivesoftware.os.amza.api.wal.WALTx;
import com.jivesoftware.os.amza.api.wal.WALValue;
import com.jivesoftware.os.amza.api.wal.WALWriter;
import com.jivesoftware.os.amza.api.wal.WALWriter.IndexableKeys;
import com.jivesoftware.os.amza.api.wal.WALWriter.RawRows;
import com.jivesoftware.os.amza.api.wal.WALWriter.TxKeyPointerFpStream;
import com.jivesoftware.os.amza.service.SickPartitions;
import com.jivesoftware.os.jive.utils.ordered.id.OrderIdProvider;
import com.jivesoftware.os.mlogger.core.MetricLogger;
import com.jivesoftware.os.mlogger.core.MetricLoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.CRC32;
import org.apache.commons.lang.mutable.MutableInt;
import org.apache.commons.lang.mutable.MutableLong;
public class WALStorage<I extends WALIndex> implements RangeScannable {
private static final MetricLogger LOG = MetricLoggerFactory.getLogger();
private static final int numTickleMeElmaphore = 1024; // TODO config
private static final int numKeyHighwaterStripes = 1024; // TODO expose to config
private final VersionedPartitionName versionedPartitionName;
private final OrderIdProvider orderIdProvider;
private final PrimaryRowMarshaller primaryRowMarshaller;
private final HighwaterRowMarshaller<byte[]> highwaterRowMarshaller;
private final WALTx walTx;
private final WALIndexProvider<I> walIndexProvider;
private final SickPartitions sickPartitions;
private final boolean hardFsyncBeforeLeapBoundary;
private volatile long[] stripedKeyHighwaterTimestamps;
private final AtomicReference<I> walIndex = new AtomicReference<>(null);
private final Object oneIndexerAtATimeLock = new Object();
private final Object oneTransactionAtATimeLock = new Object();
private final Semaphore tickleMeElmophore = new Semaphore(numTickleMeElmaphore, true);
private final AtomicLong oldestTimestamp = new AtomicLong(-1);
private final AtomicLong oldestVersion = new AtomicLong(-1);
private final AtomicLong oldestTombstonedTimestamp = new AtomicLong(-1);
private final AtomicLong oldestTombstonedVersion = new AtomicLong(-1);
private final AtomicLong keyCount = new AtomicLong(0);
private final AtomicLong clobberCount = new AtomicLong(0);
private final AtomicLong highestTxId = new AtomicLong(-1);
private final int tombstoneCompactionFactor;
private final ThreadLocal<Integer> reentrant = new ReentrantThreadLocal();
private final AtomicBoolean sick = new AtomicBoolean();
static class ReentrantThreadLocal extends ThreadLocal<Integer> {
@Override
protected Integer initialValue() {
return 0;
}
}
public WALStorage(VersionedPartitionName versionedPartitionName,
OrderIdProvider orderIdProvider,
PrimaryRowMarshaller rowMarshaller,
HighwaterRowMarshaller<byte[]> highwaterRowMarshaller,
WALTx walTx,
WALIndexProvider<I> walIndexProvider,
SickPartitions sickPartitions,
boolean hardFsyncBeforeLeapBoundary,
int tombstoneCompactionFactor) {
this.versionedPartitionName = versionedPartitionName;
this.orderIdProvider = orderIdProvider;
this.primaryRowMarshaller = rowMarshaller;
this.highwaterRowMarshaller = highwaterRowMarshaller;
this.walTx = walTx;
this.walIndexProvider = walIndexProvider;
this.sickPartitions = sickPartitions;
this.hardFsyncBeforeLeapBoundary = hardFsyncBeforeLeapBoundary;
this.tombstoneCompactionFactor = tombstoneCompactionFactor;
this.stripedKeyHighwaterTimestamps = null;
}
public boolean isSick() {
return sick.get();
}
private void acquireOne() {
if (sick.get()) {
throw new IllegalStateException("Partition is sick: " + versionedPartitionName);
}
try {
int enters = reentrant.get();
if (enters == 0) {
tickleMeElmophore.acquire();
}
reentrant.set(enters + 1);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
private void releaseOne() {
int enters = reentrant.get();
if (enters - 1 == 0) {
tickleMeElmophore.release();
}
reentrant.set(enters - 1);
}
private void acquireAll() throws InterruptedException {
if (sick.get()) {
throw new IllegalStateException("Partition is sick: " + versionedPartitionName);
}
tickleMeElmophore.acquire(numTickleMeElmaphore);
}
private void releaseAll() {
tickleMeElmophore.release(numTickleMeElmaphore);
}
public VersionedPartitionName getVersionedPartitionName() {
return versionedPartitionName;
}
public void delete() throws Exception {
acquireAll();
try {
walTx.delete();
I wali = walIndex.get();
if (wali != null) {
wali.delete();
walIndex.set(null);
sickPartitions.recovered(versionedPartitionName);
}
} finally {
releaseAll();
}
}
public boolean compactableTombstone(long tombstoneTimestampId, long tombstoneVersion, long ttlTimestampId, long ttlVersion) throws Exception {
long compactableOldestTombstonedTimestamp = oldestTombstonedTimestamp.get();
long compactableOldestTombstonedVersion = oldestTombstonedVersion.get();
long compactableOldestTimestamp = oldestTimestamp.get();
long compactableOldestVersion = oldestVersion.get();
return (compactableOldestTombstonedTimestamp > -1 && compactableOldestTombstonedTimestamp < tombstoneTimestampId)
|| (compactableOldestTombstonedVersion > -1 && compactableOldestTombstonedVersion < tombstoneVersion)
|| (compactableOldestTimestamp > -1 && compactableOldestTimestamp < ttlTimestampId)
|| (compactableOldestVersion > -1 && compactableOldestVersion < ttlVersion)
|| ((clobberCount.get() + 1) / (keyCount.get() + 1) > tombstoneCompactionFactor);
}
public long compactTombstone(RowType rowType,
long tombstoneTimestampId,
long tombstoneVersion,
long ttlTimestampId,
long ttlVersion,
boolean expectedEndOfMerge) throws Exception {
WALTx.Compacted<I> compact = walTx.compact(rowType,
tombstoneTimestampId,
tombstoneVersion,
ttlTimestampId,
ttlVersion,
walIndex.get());
long[] compactKeyHighwaterTimestamps = findKeyHighwaterTimestamps();
acquireAll();
try {
WALTx.CommittedCompacted<I> compacted;
try {
compacted = compact.commit((!expectedEndOfMerge) ? null
: (raw, highestTxId, oldestTimestamp, oldestVersion, oldestTombstonedTimestamp, oldestTombstonedVersion, keyCount, fpOfLastLeap,
updatesSinceLeap) -> {
long[] oldMarker = loadEndOfMergeMarker(-1, raw);
if (oldMarker == null) {
throw new IllegalStateException("Invalid end of merge marker");
}
long[] marker = buildEndOfMergeMarker(oldMarker[EOM_DELTA_WAL_ID_INDEX],
highestTxId,
oldestTimestamp,
oldestVersion,
oldestTombstonedTimestamp,
oldestTombstonedVersion,
keyCount,
0,
fpOfLastLeap,
updatesSinceLeap,
compactKeyHighwaterTimestamps,
0);
return UIO.longsBytes(marker);
});
} catch (Exception e) {
LOG.inc("failedCompaction");
LOG.error("Failed to compact {}, attempting to reload", new Object[] { versionedPartitionName }, e);
loadInternal(-1, -1, true, false, false);
return -1;
}
walIndex.set(compacted.index);
keyCount.set(compacted.keyCount);
clobberCount.set(0);
LOG.info("Completed compaction: {}", compacted);
return compacted.sizeAfterCompaction;
} finally {
releaseAll();
}
}
public void load(long deltaWALId, long prevDeltaWALId, boolean backwardScan, boolean truncateToEndOfMergeMarker) throws Exception {
acquireAll();
try {
loadInternal(deltaWALId, prevDeltaWALId, false, backwardScan, truncateToEndOfMergeMarker);
} finally {
releaseAll();
}
}
private void loadInternal(long deltaWALId,
long prevDeltaWALId,
boolean recovery,
boolean backwardScan,
boolean truncateToEndOfMergeMarker) throws Exception {
try {
long initialHighestTxId = highestTxId.get();
if (!recovery && initialHighestTxId != -1) {
throw new IllegalStateException("Load should have completed before highestTxId:" + initialHighestTxId + " is modified.");
}
walTx.open(io -> {
long[] lastTxId = { -1 };
long[] fpOfLastLeap = { -1 };
long[] updatesSinceLastMergeMarker = { 0 };
long[] updatesSinceLastLeap = { 0 };
long[] trailingDeltaWALId = { -1 };
long[] loadOldestTimestamp = { -1 };
long[] loadOldestVersion = { -1 };
long[] loadOldestTombstonedTimestamp = { -1 };
long[] loadOldestTombstonedVersion = { -1 };
long[] loadKeyCount = { 0 };
long[] loadClobberCount = { 0 };
//long[][] markerStripedTimestamps = new long[1][];
long[] truncate = { 0 };
primaryRowMarshaller.fromRows(fpRowStream -> {
io.validate(backwardScan,
truncateToEndOfMergeMarker,
(rowFP, rowTxId, rowType, row) -> {
// backward scan
if (rowType == RowType.end_of_merge) {
long[] marker = loadEndOfMergeMarker(deltaWALId, row);
if (marker == null) {
return -1;
}
trailingDeltaWALId[0] = marker[EOM_DELTA_WAL_ID_INDEX];
lastTxId[0] = Math.max(lastTxId[0], marker[EOM_HIGHEST_TX_ID_INDEX]);
loadOldestTimestamp[0] = marker[EOM_OLDEST_TIMESTAMP_INDEX];
loadOldestVersion[0] = marker[EOM_OLDEST_VERSION_INDEX];
loadOldestTombstonedTimestamp[0] = marker[EOM_OLDEST_TOMBSTONED_TIMESTAMP_INDEX];
loadOldestTombstonedVersion[0] = marker[EOM_OLDEST_TOMBSTONED_VERSION_INDEX];
loadKeyCount[0] = marker[EOM_KEY_COUNT_INDEX];
loadClobberCount[0] = marker[EOM_CLOBBER_COUNT_INDEX];
//markerStripedTimestamps[0] = marker;
fpOfLastLeap[0] = marker[EOM_FP_OF_LAST_LEAP_INDEX];
updatesSinceLastLeap[0] = marker[EOM_UPDATES_SINCE_LAST_LEAP_INDEX];
return rowFP;
}
return -1;
},
(rowFP, rowTxId, rowType, row) -> {
// forward scan, only called if backward scan was unsuccessful
if (rowType.isPrimary()) {
lastTxId[0] = Math.max(lastTxId[0], rowTxId);
updatesSinceLastMergeMarker[0]++;
updatesSinceLastLeap[0]++;
try {
Preconditions.checkState(fpRowStream.stream(rowFP, rowType, row), "Validation must accept all primary rows");
} catch (IOException e) {
LOG.error("Encountered I/O exception during forward validation for {}, WAL must be truncated",
new Object[] { versionedPartitionName }, e);
return rowFP;
}
} else if (rowType == RowType.end_of_merge) {
long[] marker = loadEndOfMergeMarker(deltaWALId, row);
if (marker == null) {
LOG.error("Encountered corrupt end of merge marker during forward validation for {}, WAL must be truncated",
versionedPartitionName);
return rowFP;
}
updatesSinceLastMergeMarker[0] = 0;
trailingDeltaWALId[0] = marker[EOM_DELTA_WAL_ID_INDEX];
lastTxId[0] = Math.max(lastTxId[0], marker[EOM_HIGHEST_TX_ID_INDEX]);
loadOldestTimestamp[0] = Math.min(loadOldestTimestamp[0], marker[EOM_OLDEST_TIMESTAMP_INDEX]);
loadOldestVersion[0] = Math.min(loadOldestVersion[0], marker[EOM_OLDEST_VERSION_INDEX]);
loadOldestTombstonedTimestamp[0] = Math.min(loadOldestTombstonedTimestamp[0], marker[EOM_OLDEST_TOMBSTONED_TIMESTAMP_INDEX]);
loadOldestTombstonedVersion[0] = Math.min(loadOldestTombstonedVersion[0], marker[EOM_OLDEST_TOMBSTONED_VERSION_INDEX]);
loadKeyCount[0] = marker[EOM_KEY_COUNT_INDEX];
loadClobberCount[0] = marker[EOM_CLOBBER_COUNT_INDEX];
//markerStripedTimestamps[0] = marker;
if (truncateToEndOfMergeMarker) {
truncate[0] = rowFP;
}
} else if (rowType == RowType.system) {
ByteBuffer buf = ByteBuffer.wrap(row);
byte[] keyBytes = new byte[8];
buf.get(keyBytes);
long key = UIO.bytesLong(keyBytes);
if (key == RowType.LEAP_KEY) {
fpOfLastLeap[0] = rowFP;
updatesSinceLastLeap[0] = 0;
}
}
if (!truncateToEndOfMergeMarker) {
truncate[0] = rowFP;
}
return -(truncate[0] + 1);
},
null);
// TODO!!!! handle the discontinguity of endOfMerge delta ids which prevents us from doing trailingDeltaWALId[0] != prevDeltaWALId
if (truncateToEndOfMergeMarker) {
if (prevDeltaWALId > -1 && trailingDeltaWALId[0] > prevDeltaWALId) {
LOG.error("Inconsistency detected while loading delta:{} prev:{}, encountered tail:{} for {}",
deltaWALId, prevDeltaWALId, trailingDeltaWALId, versionedPartitionName);
throw new IllegalStateException("Delta mismatch, intervention is required");
}
}
return true;
}, (fp, rowType, prefix, key, value, valueTimestamp, valueTombstoned, valueVersion) -> {
loadOldestTimestamp[0] = Math.min(loadOldestTimestamp[0], valueTimestamp);
loadOldestVersion[0] = Math.min(loadOldestVersion[0], valueVersion);
if (valueTombstoned) {
loadOldestTombstonedTimestamp[0] = Math.min(loadOldestTombstonedTimestamp[0], valueTimestamp);
loadOldestTombstonedVersion[0] = Math.min(loadOldestTombstonedVersion[0], valueVersion);
}
mergeStripedKeyHighwaters(prefix, key, valueTimestamp);
return true;
});
highestTxId.set(lastTxId[0]);
oldestTimestamp.set(loadOldestTimestamp[0]);
oldestVersion.set(loadOldestVersion[0]);
oldestTombstonedTimestamp.set(loadOldestTombstonedTimestamp[0]);
oldestTombstonedVersion.set(loadOldestTombstonedVersion[0]);
keyCount.set(loadKeyCount[0] + updatesSinceLastMergeMarker[0]);
clobberCount.set(loadClobberCount[0]);
io.initLeaps(fpOfLastLeap[0], updatesSinceLastLeap[0]);
/*if (markerStripedTimestamps[0] != null) {
for (int i = 0, offset = EOM_HIGHWATER_STRIPES_OFFSET; i < numKeyHighwaterStripes; i++, offset++) {
stripedKeyHighwaterTimestamps[i] = Math.max(stripedKeyHighwaterTimestamps[i], markerStripedTimestamps[0][offset]);
}
}*/
return null;
});
I index = walTx.openIndex(walIndexProvider, versionedPartitionName);
walIndex.compareAndSet(null, index);
} catch (Exception e) {
LOG.error("Partition {} could not be opened, intervention is required, partition will be parked, recovery:{}",
new Object[] { versionedPartitionName, recovery }, e);
sick.set(true);
sickPartitions.sick(versionedPartitionName, e);
}
}
public void flush(boolean fsync) throws Exception {
walTx.flush(fsync);
}
public WALIndex commitIndex(boolean fsync) throws Exception {
WALIndex wali = walIndex.get();
if (wali != null) {
clearKeyHighwaterTimestamp();
wali.commit(fsync);
} else {
LOG.warn("Trying to commit a nonexistent index:{}.", versionedPartitionName);
}
return wali;
}
public void endOfMergeMarker(long deltaWALId, long highestTxId) throws Exception {
long[] keyHighwaterTimestamps = findKeyHighwaterTimestamps();
walTx.tx((io) -> {
long[] marker = buildEndOfMergeMarker(deltaWALId,
highestTxId,
oldestTimestamp.get(),
oldestVersion.get(),
oldestTombstonedTimestamp.get(),
oldestTombstonedVersion.get(),
keyCount.get(),
clobberCount.get(),
io.getFpOfLastLeap(),
io.getUpdatesSinceLeap(),
keyHighwaterTimestamps,
0);
byte[] endOfMergeMarker = UIO.longsBytes(marker);
io.write(-1,
RowType.end_of_merge,
1,
endOfMergeMarker.length,
stream -> stream.stream(endOfMergeMarker),
stream -> true,
(txId, prefix, key, valueTimestamp, valueTombstoned, valueVersion, fp) -> true,
false,
hardFsyncBeforeLeapBoundary);
return null;
});
}
private static final int EOM_VERSION_INDEX = 0;
private static final int EOM_CHECKSUM_INDEX = 1;
private static final int EOM_DELTA_WAL_ID_INDEX = 2;
private static final int EOM_HIGHEST_TX_ID_INDEX = 3;
private static final int EOM_OLDEST_TIMESTAMP_INDEX = 4;
private static final int EOM_OLDEST_VERSION_INDEX = 5;
private static final int EOM_OLDEST_TOMBSTONED_TIMESTAMP_INDEX = 6;
private static final int EOM_OLDEST_TOMBSTONED_VERSION_INDEX = 7;
private static final int EOM_KEY_COUNT_INDEX = 8;
private static final int EOM_CLOBBER_COUNT_INDEX = 9;
private static final int EOM_FP_OF_LAST_LEAP_INDEX = 10;
private static final int EOM_UPDATES_SINCE_LAST_LEAP_INDEX = 11;
private static final int EOM_HIGHWATER_STRIPES_OFFSET = 12;
private static long[] buildEndOfMergeMarker(long deltaWALId,
long highestTxId,
long oldestTimestamp,
long oldestVersion,
long oldestTombstonedTimestamp,
long oldestTombstonedVersion,
long keyCount,
long clobberCount,
long fpOfLastLeap,
long updatesSinceLeap,
long[] stripedKeyHighwaterTimestamps,
int offset) {
final long[] marker = new long[EOM_HIGHWATER_STRIPES_OFFSET + numKeyHighwaterStripes];
marker[EOM_VERSION_INDEX] = 1; // version
marker[EOM_CHECKSUM_INDEX] = 0; // placeholder checksum
marker[EOM_DELTA_WAL_ID_INDEX] = deltaWALId;
marker[EOM_HIGHEST_TX_ID_INDEX] = highestTxId;
marker[EOM_OLDEST_TIMESTAMP_INDEX] = oldestTimestamp;
marker[EOM_OLDEST_VERSION_INDEX] = oldestVersion;
marker[EOM_OLDEST_TOMBSTONED_TIMESTAMP_INDEX] = oldestTombstonedTimestamp;
marker[EOM_OLDEST_TOMBSTONED_VERSION_INDEX] = oldestTombstonedVersion;
marker[EOM_KEY_COUNT_INDEX] = keyCount;
marker[EOM_CLOBBER_COUNT_INDEX] = clobberCount;
marker[EOM_FP_OF_LAST_LEAP_INDEX] = fpOfLastLeap;
marker[EOM_UPDATES_SINCE_LAST_LEAP_INDEX] = updatesSinceLeap;
System.arraycopy(stripedKeyHighwaterTimestamps, offset, marker, EOM_HIGHWATER_STRIPES_OFFSET, numKeyHighwaterStripes);
CRC32 crC32 = new CRC32();
byte[] hintsAsBytes = UIO.longsBytes(marker);
crC32.update(hintsAsBytes, 16, hintsAsBytes.length - 16); // 16 skips the version and checksum
marker[EOM_CHECKSUM_INDEX] = crC32.getValue();
return marker;
}
private long[] loadEndOfMergeMarker(long deltaWALId, byte[] row) {
long[] marker = UIO.bytesLongs(row);
if (marker[EOM_VERSION_INDEX] != 1) {
return null;
}
CRC32 crC32 = new CRC32();
byte[] hintsAsBytes = UIO.longsBytes(marker);
crC32.update(hintsAsBytes, 16, hintsAsBytes.length - 16); // 16 skips the version and checksum
if (marker[EOM_CHECKSUM_INDEX] != crC32.getValue()) {
return null;
}
if (deltaWALId > -1 && marker[EOM_DELTA_WAL_ID_INDEX] >= deltaWALId) {
return null;
}
return marker;
}
public void writeHighwaterMarker(WALWriter rowWriter, WALHighwater highwater) throws Exception {
synchronized (oneTransactionAtATimeLock) {
rowWriter.writeHighwater(highwaterRowMarshaller.toBytes(highwater));
}
}
public RowsChanged update(RowType rowType, long forceTxId, boolean forceApply, byte[] prefix, Commitable updates) throws Exception {
if (!rowType.isPrimary()) {
throw new IllegalArgumentException("rowType:" + rowType + " needs to be of type primary.");
}
Map<WALKey, WALValue> apply = new LinkedHashMap<>();
List<KeyedTimestampId> removes = new ArrayList<>();
List<KeyedTimestampId> clobbers = new ArrayList<>();
List<byte[]> keys = new ArrayList<>();
List<WALValue> values = new ArrayList<>();
WALHighwater[] highwater = new WALHighwater[1];
long updateVersion = orderIdProvider.nextId();
updates.commitable(
(_highwater) -> highwater[0] = _highwater,
(transactionId, key, value, valueTimestamp, valueTombstoned, valueVersion) -> {
WALValue walValue = new WALValue(rowType, value, valueTimestamp, valueTombstoned, valueVersion != -1 ? valueVersion : updateVersion);
if (!forceApply) {
keys.add(key);
values.add(walValue);
} else {
apply.put(new WALKey(prefix, key), walValue);
}
return true;
});
acquireOne();
try {
WALIndex wali = walIndex.get();
if (wali == null) {
throw new IllegalStateException("Attempted to commit against a nonexistent index, it has likely been deleted");
}
RowsChanged rowsChanged;
MutableLong indexCommittedFromTxId = new MutableLong(Long.MAX_VALUE);
MutableLong indexCommittedUpToTxId = new MutableLong();
if (!forceApply) {
MutableInt i = new MutableInt(0);
streamPointers(
stream -> {
for (int k = 0; k < keys.size(); k++) {
WALValue value = values.get(k);
boolean result = stream.stream(rowType,
prefix,
keys.get(k),
value.getValue(),
value.getTimestampId(),
value.getTombstoned(),
value.getVersion());
if (!result) {
return false;
}
}
return true;
},
(_rowType, _prefix, key, value, valueTimestamp, valueTombstone, valueVersion, pointerTimestamp, pointerTombstoned, pointerVersion,
pointerFp) -> {
WALKey walKey = new WALKey(prefix, key);
WALValue walValue = new WALValue(rowType, value, valueTimestamp, valueTombstone, valueVersion);
if (pointerFp == -1) {
apply.put(walKey, walValue);
} else if (CompareTimestampVersions.compare(pointerTimestamp, pointerVersion, valueTimestamp, valueVersion) < 0) {
apply.put(walKey, walValue);
WALTimestampId currentTimestampId = new WALTimestampId(pointerTimestamp, pointerTombstoned);
KeyedTimestampId keyedTimestampId = new KeyedTimestampId(walKey.prefix,
walKey.key,
currentTimestampId.getTimestampId(),
currentTimestampId.getTombstoned());
clobbers.add(keyedTimestampId);
if (valueTombstone && !pointerTombstoned) {
removes.add(keyedTimestampId);
}
}
i.increment();
return true;
});
}
if (apply.isEmpty()) {
rowsChanged = new RowsChanged(versionedPartitionName, apply, removes, clobbers, -1, -1);
} else {
int size = apply.size();
List<WALIndexable> indexables = new ArrayList<>(size);
walTx.tx((io) -> {
int estimatedSizeInBytes = 0;
for (Entry<WALKey, WALValue> row : apply.entrySet()) {
byte[] value = row.getValue().getValue();
estimatedSizeInBytes += primaryRowMarshaller.maximumSizeInBytes(rowType,
row.getKey().sizeOfComposed(),
(value != null ? value.length : 0));
}
flush(rowType,
forceTxId,
size,
estimatedSizeInBytes,
rowStream -> {
for (Entry<WALKey, WALValue> row : apply.entrySet()) {
WALValue value = row.getValue();
if (!rowStream.stream(primaryRowMarshaller.toRow(rowType,
row.getKey().compose(),
value.getValue(),
value.getTimestampId(),
value.getTombstoned(),
value.getVersion()))) {
return false;
}
}
return true;
},
indexableKeyStream -> {
for (Entry<WALKey, WALValue> row : apply.entrySet()) {
WALValue value = row.getValue();
if (!indexableKeyStream.stream(row.getKey().prefix, row.getKey().key,
value.getTimestampId(), value.getTombstoned(), value.getVersion())) {
return false;
}
}
return true;
},
indexCommittedFromTxId,
indexCommittedUpToTxId,
io,
highwater[0],
(rowTxId, _prefix, key, valueTimestamp, valueTombstoned, valueVersion, fp) -> {
oldestTimestamp.set(Math.min(oldestTimestamp.get(), valueTimestamp));
if (valueTombstoned) {
oldestTombstonedTimestamp.set(Math.min(oldestTombstonedTimestamp.get(), valueTimestamp));
}
indexables.add(new WALIndexable(rowTxId, prefix, key, valueTimestamp, valueTombstoned, valueVersion, fp));
return true;
});
return null;
});
synchronized (oneIndexerAtATimeLock) {
wali.merge((TxKeyPointerStream stream) -> {
for (WALIndexable ix : indexables) {
if (!stream.stream(ix.txId, ix.prefix, ix.key, ix.valueTimestamp, ix.valueTombstoned, ix.valueVersion, ix.fp)) {
return false;
}
mergeStripedKeyHighwaters(ix.prefix, ix.key, ix.valueTimestamp);
}
return true;
}, (mode, txId, _prefix, key, timestamp, tombstoned, version, fp) -> {
if (mode == WALMergeKeyPointerStream.added) {
keyCount.incrementAndGet();
} else if (mode == WALMergeKeyPointerStream.clobbered) {
clobberCount.incrementAndGet();
} else {
apply.remove(new WALKey(prefix, key));
}
return true;
});
rowsChanged = new RowsChanged(versionedPartitionName,
apply,
removes,
clobbers,
indexCommittedFromTxId.longValue(),
indexCommittedUpToTxId.longValue());
}
}
return rowsChanged;
} finally {
releaseOne();
}
}
private void flush(RowType rowType,
long txId,
int estimatedNumberOfRows,
int estimatedSizeInBytes,
RawRows rows,
IndexableKeys indexableKeys,
final MutableLong indexCommittedFromTxId,
final MutableLong indexCommitedUpToTxId,
WALWriter rowWriter,
WALHighwater highwater,
TxKeyPointerFpStream stream) throws Exception {
synchronized (oneTransactionAtATimeLock) {
if (txId == -1) {
txId = orderIdProvider.nextId();
}
if (indexCommittedFromTxId.longValue() > txId) {
indexCommittedFromTxId.setValue(txId);
}
try {
if (indexCommitedUpToTxId.longValue() < txId) {
indexCommitedUpToTxId.setValue(txId);
}
} catch (NullPointerException e) {
throw new IllegalStateException("Illogical NPE: " + (indexCommitedUpToTxId == null), e);
}
rowWriter.write(txId, rowType, estimatedNumberOfRows, estimatedSizeInBytes, rows, indexableKeys, stream, false, hardFsyncBeforeLeapBoundary);
if (highwater != null) {
writeHighwaterMarker(rowWriter, highwater);
}
highestTxId.set(indexCommitedUpToTxId.longValue());
}
}
@Override
public boolean rowScan(KeyValueStream keyValueStream) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
return wali == null || wali.rowScan((prefix, key, timestamp, tombstoned, version, fp) -> {
byte[] hydrateRowIndexValue = hydrateRowIndexValue(fp);
RowType rowType = RowType.fromByte(hydrateRowIndexValue[0]);
byte[] value = primaryRowMarshaller.valueFromRow(rowType, hydrateRowIndexValue, 1 + 8);
return keyValueStream.stream(rowType, prefix, key, value, timestamp, tombstoned, version);
});
} finally {
releaseOne();
}
}
@Override
public boolean rangeScan(byte[] fromPrefix, byte[] fromKey, byte[] toPrefix, byte[] toKey, KeyValueStream keyValueStream) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
return wali.rangeScan(fromPrefix,
fromKey,
toPrefix,
toKey,
(prefix, key, timestamp, tombstoned, version, fp) -> {
byte[] hydrateRowIndexValue = hydrateRowIndexValue(fp);
RowType rowType = RowType.fromByte(hydrateRowIndexValue[0]);
byte[] value = primaryRowMarshaller.valueFromRow(rowType, hydrateRowIndexValue, 1 + 8);
return keyValueStream.stream(rowType, prefix, key, value, timestamp, tombstoned, version);
});
} finally {
releaseOne();
}
}
// TODO fix barf
public TimestampedValue getTimestampedValue(byte[] prefix, byte[] key) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
if (wali == null) {
return null;
}
TimestampedValue[] values = new TimestampedValue[1];
wali.getPointer(prefix, key, (_prefix, _key, timestamp, tombstoned, version, fp) -> {
if (fp != -1 && !tombstoned) {
byte[] hydrateRowIndexValue = hydrateRowIndexValue(fp);
RowType rowType = RowType.fromByte(hydrateRowIndexValue[0]);
byte[] value = primaryRowMarshaller.valueFromRow(rowType, hydrateRowIndexValue, 1 + 8);
values[0] = new TimestampedValue(timestamp, version, value);
}
return true;
});
return values[0];
} finally {
releaseOne();
}
}
//
// public WALPointer getPointer(byte[] prefix, byte[] key) throws Exception {
// acquireOne();
// try {
// WALIndex wali = walIndex.get();
// if (wali == null) {
// return null;
// }
// WALPointer[] pointer = new WALPointer[1];
// wali.getPointer(prefix, key, (_prefix, _key, timestamp, tombstoned, version, fp) -> {
// if (fp != -1 && !tombstoned) {
// pointer[0] = new WALPointer(fp, timestamp, tombstoned, version);
// }
// return true;
// });
// return pointer[0];
// } finally {
// releaseOne();
// }
// }
public boolean streamValues(byte[] prefix, UnprefixedWALKeys keys, KeyValueStream keyValueStream) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
return wali == null || wali.getPointers(prefix, keys,
(_prefix, key, pointerTimestamp, pointerTombstoned, pointerVersion, pointerFp) -> {
if (pointerFp != -1) {
RowType rowType = null;
byte[] value = null;
if (!pointerTombstoned) {
byte[] hydrateRowIndexValue = hydrateRowIndexValue(pointerFp);
rowType = RowType.fromByte(hydrateRowIndexValue[0]);
value = primaryRowMarshaller.valueFromRow(rowType, hydrateRowIndexValue, 1 + 8);
}
return keyValueStream.stream(rowType,
prefix,
key,
value,
pointerTimestamp,
pointerTombstoned,
pointerVersion
);
} else {
return keyValueStream.stream(null, prefix, key, null, -1, false, -1);
}
});
} finally {
releaseOne();
}
}
public boolean streamPointers(KeyValues keyValues, KeyValuePointerStream stream) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
long[] keyHighwaterTimestamps = findKeyHighwaterTimestamps();
return wali == null || wali.getPointers(
indexStream -> keyValues.consume(
(rowType, prefix, key, value, valueTimestamp, valueTombstone, valueVersion) -> {
long largestTimestamp = getLargestTimestampForKeyStripe(prefix, key, keyHighwaterTimestamps);
if (valueTimestamp > largestTimestamp) {
return stream.stream(rowType, prefix, key, value, valueTimestamp, valueTombstone, valueVersion, -1, false, -1, -1);
} else {
return indexStream.stream(rowType, prefix, key, value, valueTimestamp, valueTombstone, valueVersion);
}
}),
stream);
} finally {
releaseOne();
}
}
public boolean containsKeys(byte[] prefix, UnprefixedWALKeys keys, KeyContainedStream stream) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
return wali != null && wali.containsKeys(prefix, keys, stream);
} finally {
releaseOne();
}
}
private long[] findKeyHighwaterTimestamps() throws Exception {
if (stripedKeyHighwaterTimestamps == null) {
synchronized (this) {
if (stripedKeyHighwaterTimestamps == null) {
if (versionedPartitionName.getPartitionName().isSystemPartition()) {
stripedKeyHighwaterTimestamps = new long[numKeyHighwaterStripes];
} else {
long[] compactKeyHighwaterTimestamps = new long[numKeyHighwaterStripes];
walTx.tx(io -> {
int[] total = { 0 };
io.reverseScan((rowFP, rowTxId, rowType1, row) -> {
if (rowType1 == RowType.end_of_merge) {
long[] marker = loadEndOfMergeMarker(-1, row);
if (marker == null) {
throw new IllegalStateException("Invalid end of merge marker");
}
System.arraycopy(marker, EOM_HIGHWATER_STRIPES_OFFSET, compactKeyHighwaterTimestamps, 0, numKeyHighwaterStripes);
return false;
} else if (!rowType1.isPrimary()) {
total[0]++;
LOG.warn("Expected end of merge marker but found type {} (total:{})", rowType1, total[0]);
return true;
} else {
//System.out.println("Expected EOM but found " + rowType1);
throw new IllegalStateException("Expected end of merge marker but found type " + rowType1);
}
});
return null;
});
stripedKeyHighwaterTimestamps = compactKeyHighwaterTimestamps;
}
}
}
}
return stripedKeyHighwaterTimestamps;
}
private void clearKeyHighwaterTimestamp() {
if (!versionedPartitionName.getPartitionName().isSystemPartition()) {
stripedKeyHighwaterTimestamps = null;
}
}
private void mergeStripedKeyHighwaters(byte[] prefix, byte[] key, long valueTimestamp) {
if (stripedKeyHighwaterTimestamps != null) {
int highwaterTimestampIndex = Math.abs((Arrays.hashCode(prefix) ^ Arrays.hashCode(key)) % stripedKeyHighwaterTimestamps.length);
stripedKeyHighwaterTimestamps[highwaterTimestampIndex] = Math.max(stripedKeyHighwaterTimestamps[highwaterTimestampIndex], valueTimestamp);
}
}
private long getLargestTimestampForKeyStripe(byte[] prefix, byte[] key, long[] keyHighwaterTimestamps) {
int highwaterTimestampIndex = Math.abs((Arrays.hashCode(prefix) ^ Arrays.hashCode(key)) % keyHighwaterTimestamps.length);
return keyHighwaterTimestamps[highwaterTimestampIndex];
}
//TODO replace with stream!
private byte[] hydrateRowIndexValue(long indexFP) {
try {
return walTx.tx((io) -> io.readTypeByteTxIdAndRow(indexFP));
} catch (Exception x) {
long length;
try {
length = walTx.length();
} catch (Exception e) {
length = -1;
}
throw new RuntimeException(
"Failed to hydrate for " + versionedPartitionName + " versionedPartitionName=" + versionedPartitionName + " size=" + length + " fp=" + indexFP,
x);
}
}
public boolean takeRowUpdatesSince(final long sinceTransactionId, final RowStream rowStream) throws Exception {
if (sinceTransactionId >= highestTxId.get()) {
return true;
}
acquireOne();
try {
long[] takeMetrics = new long[1];
boolean readFromTransactionId = walIndex.get() == null || walTx.readFromTransactionId(sinceTransactionId,
(offset, reader) -> reader.scan(offset,
false,
(rowPointer, rowTxId, rowType, row) -> {
if (rowType != RowType.system && rowTxId > sinceTransactionId) {
return rowStream.row(rowPointer, rowTxId, rowType, row);
} else {
takeMetrics[0]++;
}
return true;
}));
LOG.inc("excessTakes", takeMetrics[0]);
return readFromTransactionId;
} finally {
releaseOne();
}
}
public boolean takeRowUpdatesSince(byte[] prefix, long sinceTransactionId, RowStream rowStream) throws Exception {
if (sinceTransactionId >= highestTxId.get()) {
return true;
}
acquireOne();
try {
long[] takeMetrics = new long[1];
WALIndex wali = walIndex.get();
boolean readFromTransactionId = wali == null || walTx.tx(
io -> io.read(
fpStream -> wali.takePrefixUpdatesSince(prefix, sinceTransactionId, (txId, fp) -> fpStream.stream(fp)),
(rowPointer, rowTxId, rowType, row) -> {
if (rowType != RowType.system && rowTxId > sinceTransactionId) {
return rowStream.row(rowPointer, rowTxId, rowType, row);
} else {
takeMetrics[0]++;
}
return true;
}));
LOG.inc("excessTakes", takeMetrics[0]);
return readFromTransactionId;
} finally {
releaseOne();
}
}
public boolean takeAllRows(final RowStream rowStream) throws Exception {
acquireOne();
try {
return walIndex.get() == null || walTx.readFromTransactionId(0, (offset, reader) -> reader.scan(offset, false, rowStream::row));
} finally {
releaseOne();
}
}
public void updatedProperties(PartitionProperties partitionProperties) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
if (wali != null) {
wali.updatedProperties(partitionProperties.indexProperties);
}
} finally {
releaseOne();
}
}
public long count(WALKeyPointers keyPointers) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
return wali == null ? 0 : wali.deltaCount(keyPointers) + keyCount.get();
} finally {
releaseOne();
}
}
public long highestTxId() {
return highestTxId.get();
}
}
| amza-service/src/main/java/com/jivesoftware/os/amza/service/storage/WALStorage.java | /*
* Copyright 2013 Jive Software, 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.jivesoftware.os.amza.service.storage;
import com.google.common.base.Preconditions;
import com.jivesoftware.os.amza.api.CompareTimestampVersions;
import com.jivesoftware.os.amza.api.TimestampedValue;
import com.jivesoftware.os.amza.api.filer.UIO;
import com.jivesoftware.os.amza.api.partition.PartitionProperties;
import com.jivesoftware.os.amza.api.partition.VersionedPartitionName;
import com.jivesoftware.os.amza.api.scan.RangeScannable;
import com.jivesoftware.os.amza.api.scan.RowStream;
import com.jivesoftware.os.amza.api.scan.RowsChanged;
import com.jivesoftware.os.amza.api.stream.Commitable;
import com.jivesoftware.os.amza.api.stream.KeyContainedStream;
import com.jivesoftware.os.amza.api.stream.KeyValuePointerStream;
import com.jivesoftware.os.amza.api.stream.KeyValueStream;
import com.jivesoftware.os.amza.api.stream.KeyValues;
import com.jivesoftware.os.amza.api.stream.RowType;
import com.jivesoftware.os.amza.api.stream.TxKeyPointerStream;
import com.jivesoftware.os.amza.api.stream.UnprefixedWALKeys;
import com.jivesoftware.os.amza.api.stream.WALKeyPointers;
import com.jivesoftware.os.amza.api.stream.WALMergeKeyPointerStream;
import com.jivesoftware.os.amza.api.wal.KeyedTimestampId;
import com.jivesoftware.os.amza.api.wal.PrimaryRowMarshaller;
import com.jivesoftware.os.amza.api.wal.WALHighwater;
import com.jivesoftware.os.amza.api.wal.WALIndex;
import com.jivesoftware.os.amza.api.wal.WALIndexProvider;
import com.jivesoftware.os.amza.api.wal.WALIndexable;
import com.jivesoftware.os.amza.api.wal.WALKey;
import com.jivesoftware.os.amza.api.wal.WALTimestampId;
import com.jivesoftware.os.amza.api.wal.WALTx;
import com.jivesoftware.os.amza.api.wal.WALValue;
import com.jivesoftware.os.amza.api.wal.WALWriter;
import com.jivesoftware.os.amza.api.wal.WALWriter.IndexableKeys;
import com.jivesoftware.os.amza.api.wal.WALWriter.RawRows;
import com.jivesoftware.os.amza.api.wal.WALWriter.TxKeyPointerFpStream;
import com.jivesoftware.os.amza.service.SickPartitions;
import com.jivesoftware.os.jive.utils.ordered.id.OrderIdProvider;
import com.jivesoftware.os.mlogger.core.MetricLogger;
import com.jivesoftware.os.mlogger.core.MetricLoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.CRC32;
import org.apache.commons.lang.mutable.MutableInt;
import org.apache.commons.lang.mutable.MutableLong;
public class WALStorage<I extends WALIndex> implements RangeScannable {
private static final MetricLogger LOG = MetricLoggerFactory.getLogger();
private static final int numTickleMeElmaphore = 1024; // TODO config
private static final int numKeyHighwaterStripes = 1024; // TODO expose to config
private final VersionedPartitionName versionedPartitionName;
private final OrderIdProvider orderIdProvider;
private final PrimaryRowMarshaller primaryRowMarshaller;
private final HighwaterRowMarshaller<byte[]> highwaterRowMarshaller;
private final WALTx walTx;
private final WALIndexProvider<I> walIndexProvider;
private final SickPartitions sickPartitions;
private final boolean hardFsyncBeforeLeapBoundary;
private volatile long[] stripedKeyHighwaterTimestamps;
private final AtomicReference<I> walIndex = new AtomicReference<>(null);
private final Object oneIndexerAtATimeLock = new Object();
private final Object oneTransactionAtATimeLock = new Object();
private final Semaphore tickleMeElmophore = new Semaphore(numTickleMeElmaphore, true);
private final AtomicLong oldestTimestamp = new AtomicLong(-1);
private final AtomicLong oldestVersion = new AtomicLong(-1);
private final AtomicLong oldestTombstonedTimestamp = new AtomicLong(-1);
private final AtomicLong oldestTombstonedVersion = new AtomicLong(-1);
private final AtomicLong keyCount = new AtomicLong(0);
private final AtomicLong clobberCount = new AtomicLong(0);
private final AtomicLong highestTxId = new AtomicLong(-1);
private final int tombstoneCompactionFactor;
private final ThreadLocal<Integer> reentrant = new ReentrantThreadLocal();
private final AtomicBoolean sick = new AtomicBoolean();
static class ReentrantThreadLocal extends ThreadLocal<Integer> {
@Override
protected Integer initialValue() {
return 0;
}
}
public WALStorage(VersionedPartitionName versionedPartitionName,
OrderIdProvider orderIdProvider,
PrimaryRowMarshaller rowMarshaller,
HighwaterRowMarshaller<byte[]> highwaterRowMarshaller,
WALTx walTx,
WALIndexProvider<I> walIndexProvider,
SickPartitions sickPartitions,
boolean hardFsyncBeforeLeapBoundary,
int tombstoneCompactionFactor) {
this.versionedPartitionName = versionedPartitionName;
this.orderIdProvider = orderIdProvider;
this.primaryRowMarshaller = rowMarshaller;
this.highwaterRowMarshaller = highwaterRowMarshaller;
this.walTx = walTx;
this.walIndexProvider = walIndexProvider;
this.sickPartitions = sickPartitions;
this.hardFsyncBeforeLeapBoundary = hardFsyncBeforeLeapBoundary;
this.tombstoneCompactionFactor = tombstoneCompactionFactor;
this.stripedKeyHighwaterTimestamps = null;
}
public boolean isSick() {
return sick.get();
}
private void acquireOne() {
if (sick.get()) {
throw new IllegalStateException("Partition is sick: " + versionedPartitionName);
}
try {
int enters = reentrant.get();
if (enters == 0) {
tickleMeElmophore.acquire();
}
reentrant.set(enters + 1);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
private void releaseOne() {
int enters = reentrant.get();
if (enters - 1 == 0) {
tickleMeElmophore.release();
}
reentrant.set(enters - 1);
}
private void acquireAll() throws InterruptedException {
if (sick.get()) {
throw new IllegalStateException("Partition is sick: " + versionedPartitionName);
}
tickleMeElmophore.acquire(numTickleMeElmaphore);
}
private void releaseAll() {
tickleMeElmophore.release(numTickleMeElmaphore);
}
public VersionedPartitionName getVersionedPartitionName() {
return versionedPartitionName;
}
public void delete() throws Exception {
acquireAll();
try {
walTx.delete();
I wali = walIndex.get();
if (wali != null) {
wali.delete();
walIndex.set(null);
sickPartitions.recovered(versionedPartitionName);
}
} finally {
releaseAll();
}
}
public boolean compactableTombstone(long tombstoneTimestampId, long tombstoneVersion, long ttlTimestampId, long ttlVersion) throws Exception {
long compactableOldestTombstonedTimestamp = oldestTombstonedTimestamp.get();
long compactableOldestTombstonedVersion = oldestTombstonedVersion.get();
long compactableOldestTimestamp = oldestTimestamp.get();
long compactableOldestVersion = oldestVersion.get();
return (compactableOldestTombstonedTimestamp > -1 && compactableOldestTombstonedTimestamp < tombstoneTimestampId)
|| (compactableOldestTombstonedVersion > -1 && compactableOldestTombstonedVersion < tombstoneVersion)
|| (compactableOldestTimestamp > -1 && compactableOldestTimestamp < ttlTimestampId)
|| (compactableOldestVersion > -1 && compactableOldestVersion < ttlVersion)
|| ((clobberCount.get() + 1) / (keyCount.get() + 1) > tombstoneCompactionFactor);
}
public long compactTombstone(RowType rowType,
long tombstoneTimestampId,
long tombstoneVersion,
long ttlTimestampId,
long ttlVersion,
boolean expectedEndOfMerge) throws Exception {
WALTx.Compacted<I> compact = walTx.compact(rowType,
tombstoneTimestampId,
tombstoneVersion,
ttlTimestampId,
ttlVersion,
walIndex.get());
long[] compactKeyHighwaterTimestamps = findKeyHighwaterTimestamps();
acquireAll();
try {
WALTx.CommittedCompacted<I> compacted;
try {
compacted = compact.commit((!expectedEndOfMerge) ? null
: (raw, highestTxId, oldestTimestamp, oldestVersion, oldestTombstonedTimestamp, oldestTombstonedVersion, keyCount, fpOfLastLeap,
updatesSinceLeap) -> {
long[] oldMarker = loadEndOfMergeMarker(-1, raw);
if (oldMarker == null) {
throw new IllegalStateException("Invalid end of merge marker");
}
long[] marker = buildEndOfMergeMarker(oldMarker[EOM_DELTA_WAL_ID_INDEX],
highestTxId,
oldestTimestamp,
oldestVersion,
oldestTombstonedTimestamp,
oldestTombstonedVersion,
keyCount,
0,
fpOfLastLeap,
updatesSinceLeap,
compactKeyHighwaterTimestamps,
0);
return UIO.longsBytes(marker);
});
} catch (Exception e) {
LOG.inc("failedCompaction");
LOG.error("Failed to compact {}, attempting to reload", new Object[] { versionedPartitionName }, e);
loadInternal(-1, -1, true, false, false);
return -1;
}
walIndex.set(compacted.index);
keyCount.set(compacted.keyCount);
clobberCount.set(0);
LOG.info("Completed compaction: {}", compacted);
return compacted.sizeAfterCompaction;
} finally {
releaseAll();
}
}
public void load(long deltaWALId, long prevDeltaWALId, boolean backwardScan, boolean truncateToEndOfMergeMarker) throws Exception {
acquireAll();
try {
loadInternal(deltaWALId, prevDeltaWALId, false, backwardScan, truncateToEndOfMergeMarker);
} finally {
releaseAll();
}
}
private void loadInternal(long deltaWALId,
long prevDeltaWALId,
boolean recovery,
boolean backwardScan,
boolean truncateToEndOfMergeMarker) throws Exception {
try {
long initialHighestTxId = highestTxId.get();
if (!recovery && initialHighestTxId != -1) {
throw new IllegalStateException("Load should have completed before highestTxId:" + initialHighestTxId + " is modified.");
}
walTx.open(io -> {
long[] lastTxId = { -1 };
long[] fpOfLastLeap = { -1 };
long[] updatesSinceLastMergeMarker = { 0 };
long[] updatesSinceLastLeap = { 0 };
long[] trailingDeltaWALId = { -1 };
long[] loadOldestTimestamp = { -1 };
long[] loadOldestVersion = { -1 };
long[] loadOldestTombstonedTimestamp = { -1 };
long[] loadOldestTombstonedVersion = { -1 };
long[] loadKeyCount = { 0 };
long[] loadClobberCount = { 0 };
//long[][] markerStripedTimestamps = new long[1][];
long[] truncate = { 0 };
primaryRowMarshaller.fromRows(fpRowStream -> {
io.validate(backwardScan,
truncateToEndOfMergeMarker,
(rowFP, rowTxId, rowType, row) -> {
// backward scan
if (rowType == RowType.end_of_merge) {
long[] marker = loadEndOfMergeMarker(deltaWALId, row);
if (marker == null) {
return -1;
}
trailingDeltaWALId[0] = marker[EOM_DELTA_WAL_ID_INDEX];
lastTxId[0] = Math.max(lastTxId[0], marker[EOM_HIGHEST_TX_ID_INDEX]);
loadOldestTimestamp[0] = marker[EOM_OLDEST_TIMESTAMP_INDEX];
loadOldestVersion[0] = marker[EOM_OLDEST_VERSION_INDEX];
loadOldestTombstonedTimestamp[0] = marker[EOM_OLDEST_TOMBSTONED_TIMESTAMP_INDEX];
loadOldestTombstonedVersion[0] = marker[EOM_OLDEST_TOMBSTONED_VERSION_INDEX];
loadKeyCount[0] = marker[EOM_KEY_COUNT_INDEX];
loadClobberCount[0] = marker[EOM_CLOBBER_COUNT_INDEX];
//markerStripedTimestamps[0] = marker;
fpOfLastLeap[0] = marker[EOM_FP_OF_LAST_LEAP_INDEX];
updatesSinceLastLeap[0] = marker[EOM_UPDATES_SINCE_LAST_LEAP_INDEX];
return rowFP;
}
return -1;
},
(rowFP, rowTxId, rowType, row) -> {
// forward scan, only called if backward scan was unsuccessful
if (rowType.isPrimary()) {
lastTxId[0] = Math.max(lastTxId[0], rowTxId);
updatesSinceLastMergeMarker[0]++;
updatesSinceLastLeap[0]++;
try {
Preconditions.checkState(fpRowStream.stream(rowFP, rowType, row), "Validation must accept all primary rows");
} catch (IOException e) {
LOG.error("Encountered I/O exception during forward validation for {}, WAL must be truncated",
new Object[] { versionedPartitionName }, e);
return rowFP;
}
} else if (rowType == RowType.end_of_merge) {
long[] marker = loadEndOfMergeMarker(deltaWALId, row);
if (marker == null) {
LOG.error("Encountered corrupt end of merge marker during forward validation for {}, WAL must be truncated",
versionedPartitionName);
return rowFP;
}
updatesSinceLastMergeMarker[0] = 0;
trailingDeltaWALId[0] = marker[EOM_DELTA_WAL_ID_INDEX];
lastTxId[0] = Math.max(lastTxId[0], marker[EOM_HIGHEST_TX_ID_INDEX]);
loadOldestTimestamp[0] = Math.min(loadOldestTimestamp[0], marker[EOM_OLDEST_TIMESTAMP_INDEX]);
loadOldestVersion[0] = Math.min(loadOldestVersion[0], marker[EOM_OLDEST_VERSION_INDEX]);
loadOldestTombstonedTimestamp[0] = Math.min(loadOldestTombstonedTimestamp[0], marker[EOM_OLDEST_TOMBSTONED_TIMESTAMP_INDEX]);
loadOldestTombstonedVersion[0] = Math.min(loadOldestTombstonedVersion[0], marker[EOM_OLDEST_TOMBSTONED_VERSION_INDEX]);
loadKeyCount[0] = marker[EOM_KEY_COUNT_INDEX];
loadClobberCount[0] = marker[EOM_CLOBBER_COUNT_INDEX];
//markerStripedTimestamps[0] = marker;
if (truncateToEndOfMergeMarker) {
truncate[0] = rowFP;
}
} else if (rowType == RowType.system) {
ByteBuffer buf = ByteBuffer.wrap(row);
byte[] keyBytes = new byte[8];
buf.get(keyBytes);
long key = UIO.bytesLong(keyBytes);
if (key == RowType.LEAP_KEY) {
fpOfLastLeap[0] = rowFP;
updatesSinceLastLeap[0] = 0;
}
}
if (!truncateToEndOfMergeMarker) {
truncate[0] = rowFP;
}
return -(truncate[0] + 1);
},
null);
// TODO!!!! handle the discontinguity of endOfMerge delta ids which prevents us from doing trailingDeltaWALId[0] != prevDeltaWALId
if (truncateToEndOfMergeMarker) {
if (prevDeltaWALId > -1 && trailingDeltaWALId[0] > prevDeltaWALId) {
LOG.error("Inconsistency detected while loading delta:{} prev:{}, encountered tail:{} for {}",
deltaWALId, prevDeltaWALId, trailingDeltaWALId, versionedPartitionName);
throw new IllegalStateException("Delta mismatch, intervention is required");
}
}
return true;
}, (fp, rowType, prefix, key, value, valueTimestamp, valueTombstoned, valueVersion) -> {
loadOldestTimestamp[0] = Math.min(loadOldestTimestamp[0], valueTimestamp);
loadOldestVersion[0] = Math.min(loadOldestVersion[0], valueVersion);
if (valueTombstoned) {
loadOldestTombstonedTimestamp[0] = Math.min(loadOldestTombstonedTimestamp[0], valueTimestamp);
loadOldestTombstonedVersion[0] = Math.min(loadOldestTombstonedVersion[0], valueVersion);
}
mergeStripedKeyHighwaters(prefix, key, valueTimestamp);
return true;
});
highestTxId.set(lastTxId[0]);
oldestTimestamp.set(loadOldestTimestamp[0]);
oldestVersion.set(loadOldestVersion[0]);
oldestTombstonedTimestamp.set(loadOldestTombstonedTimestamp[0]);
oldestTombstonedVersion.set(loadOldestTombstonedVersion[0]);
keyCount.set(loadKeyCount[0] + updatesSinceLastMergeMarker[0]);
clobberCount.set(loadClobberCount[0]);
io.initLeaps(fpOfLastLeap[0], updatesSinceLastLeap[0]);
/*if (markerStripedTimestamps[0] != null) {
for (int i = 0, offset = EOM_HIGHWATER_STRIPES_OFFSET; i < numKeyHighwaterStripes; i++, offset++) {
stripedKeyHighwaterTimestamps[i] = Math.max(stripedKeyHighwaterTimestamps[i], markerStripedTimestamps[0][offset]);
}
}*/
return null;
});
I index = walTx.openIndex(walIndexProvider, versionedPartitionName);
walIndex.compareAndSet(null, index);
} catch (Exception e) {
LOG.error("Partition {} could not be opened, intervention is required, partition will be parked, recovery:{}",
new Object[] { versionedPartitionName, recovery }, e);
sick.set(true);
sickPartitions.sick(versionedPartitionName, e);
}
}
public void flush(boolean fsync) throws Exception {
walTx.flush(fsync);
}
public WALIndex commitIndex(boolean fsync) throws Exception {
WALIndex wali = walIndex.get();
if (wali != null) {
clearKeyHighwaterTimestamp();
wali.commit(fsync);
} else {
LOG.warn("Trying to commit a nonexistent index:{}.", versionedPartitionName);
}
return wali;
}
public void endOfMergeMarker(long deltaWALId, long highestTxId) throws Exception {
long[] keyHighwaterTimestamps = findKeyHighwaterTimestamps();
walTx.tx((io) -> {
long[] marker = buildEndOfMergeMarker(deltaWALId,
highestTxId,
oldestTimestamp.get(),
oldestVersion.get(),
oldestTombstonedTimestamp.get(),
oldestTombstonedVersion.get(),
keyCount.get(),
clobberCount.get(),
io.getFpOfLastLeap(),
io.getUpdatesSinceLeap(),
keyHighwaterTimestamps,
0);
byte[] endOfMergeMarker = UIO.longsBytes(marker);
io.write(-1,
RowType.end_of_merge,
1,
endOfMergeMarker.length,
stream -> stream.stream(endOfMergeMarker),
stream -> true,
(txId, prefix, key, valueTimestamp, valueTombstoned, valueVersion, fp) -> true,
false,
hardFsyncBeforeLeapBoundary);
return null;
});
}
private static final int EOM_VERSION_INDEX = 0;
private static final int EOM_CHECKSUM_INDEX = 1;
private static final int EOM_DELTA_WAL_ID_INDEX = 2;
private static final int EOM_HIGHEST_TX_ID_INDEX = 3;
private static final int EOM_OLDEST_TIMESTAMP_INDEX = 4;
private static final int EOM_OLDEST_VERSION_INDEX = 5;
private static final int EOM_OLDEST_TOMBSTONED_TIMESTAMP_INDEX = 6;
private static final int EOM_OLDEST_TOMBSTONED_VERSION_INDEX = 7;
private static final int EOM_KEY_COUNT_INDEX = 8;
private static final int EOM_CLOBBER_COUNT_INDEX = 9;
private static final int EOM_FP_OF_LAST_LEAP_INDEX = 10;
private static final int EOM_UPDATES_SINCE_LAST_LEAP_INDEX = 11;
private static final int EOM_HIGHWATER_STRIPES_OFFSET = 12;
private static long[] buildEndOfMergeMarker(long deltaWALId,
long highestTxId,
long oldestTimestamp,
long oldestVersion,
long oldestTombstonedTimestamp,
long oldestTombstonedVersion,
long keyCount,
long clobberCount,
long fpOfLastLeap,
long updatesSinceLeap,
long[] stripedKeyHighwaterTimestamps,
int offset) {
final long[] marker = new long[EOM_HIGHWATER_STRIPES_OFFSET + numKeyHighwaterStripes];
marker[EOM_VERSION_INDEX] = 1; // version
marker[EOM_CHECKSUM_INDEX] = 0; // placeholder checksum
marker[EOM_DELTA_WAL_ID_INDEX] = deltaWALId;
marker[EOM_HIGHEST_TX_ID_INDEX] = highestTxId;
marker[EOM_OLDEST_TIMESTAMP_INDEX] = oldestTimestamp;
marker[EOM_OLDEST_VERSION_INDEX] = oldestVersion;
marker[EOM_OLDEST_TOMBSTONED_TIMESTAMP_INDEX] = oldestTombstonedTimestamp;
marker[EOM_OLDEST_TOMBSTONED_VERSION_INDEX] = oldestTombstonedVersion;
marker[EOM_KEY_COUNT_INDEX] = keyCount;
marker[EOM_CLOBBER_COUNT_INDEX] = clobberCount;
marker[EOM_FP_OF_LAST_LEAP_INDEX] = fpOfLastLeap;
marker[EOM_UPDATES_SINCE_LAST_LEAP_INDEX] = updatesSinceLeap;
System.arraycopy(stripedKeyHighwaterTimestamps, offset, marker, EOM_HIGHWATER_STRIPES_OFFSET, numKeyHighwaterStripes);
CRC32 crC32 = new CRC32();
byte[] hintsAsBytes = UIO.longsBytes(marker);
crC32.update(hintsAsBytes, 16, hintsAsBytes.length - 16); // 16 skips the version and checksum
marker[EOM_CHECKSUM_INDEX] = crC32.getValue();
return marker;
}
private long[] loadEndOfMergeMarker(long deltaWALId, byte[] row) {
long[] marker = UIO.bytesLongs(row);
if (marker[EOM_VERSION_INDEX] != 1) {
return null;
}
CRC32 crC32 = new CRC32();
byte[] hintsAsBytes = UIO.longsBytes(marker);
crC32.update(hintsAsBytes, 16, hintsAsBytes.length - 16); // 16 skips the version and checksum
if (marker[EOM_CHECKSUM_INDEX] != crC32.getValue()) {
return null;
}
if (deltaWALId > -1 && marker[EOM_DELTA_WAL_ID_INDEX] >= deltaWALId) {
return null;
}
return marker;
}
public void writeHighwaterMarker(WALWriter rowWriter, WALHighwater highwater) throws Exception {
synchronized (oneTransactionAtATimeLock) {
rowWriter.writeHighwater(highwaterRowMarshaller.toBytes(highwater));
}
}
public RowsChanged update(RowType rowType, long forceTxId, boolean forceApply, byte[] prefix, Commitable updates) throws Exception {
if (!rowType.isPrimary()) {
throw new IllegalArgumentException("rowType:" + rowType + " needs to be of type primary.");
}
Map<WALKey, WALValue> apply = new LinkedHashMap<>();
List<KeyedTimestampId> removes = new ArrayList<>();
List<KeyedTimestampId> clobbers = new ArrayList<>();
List<byte[]> keys = new ArrayList<>();
List<WALValue> values = new ArrayList<>();
WALHighwater[] highwater = new WALHighwater[1];
long updateVersion = orderIdProvider.nextId();
updates.commitable(
(_highwater) -> highwater[0] = _highwater,
(transactionId, key, value, valueTimestamp, valueTombstoned, valueVersion) -> {
WALValue walValue = new WALValue(rowType, value, valueTimestamp, valueTombstoned, valueVersion != -1 ? valueVersion : updateVersion);
if (!forceApply) {
keys.add(key);
values.add(walValue);
} else {
apply.put(new WALKey(prefix, key), walValue);
}
return true;
});
acquireOne();
try {
WALIndex wali = walIndex.get();
if (wali == null) {
throw new IllegalStateException("Attempted to commit against a nonexistent index, it has likely been deleted");
}
RowsChanged rowsChanged;
MutableLong indexCommittedFromTxId = new MutableLong(Long.MAX_VALUE);
MutableLong indexCommittedUpToTxId = new MutableLong();
if (!forceApply) {
MutableInt i = new MutableInt(0);
streamPointers(
stream -> {
for (int k = 0; k < keys.size(); k++) {
WALValue value = values.get(k);
boolean result = stream.stream(rowType,
prefix,
keys.get(k),
value.getValue(),
value.getTimestampId(),
value.getTombstoned(),
value.getVersion());
if (!result) {
return false;
}
}
return true;
},
(_rowType, _prefix, key, value, valueTimestamp, valueTombstone, valueVersion, pointerTimestamp, pointerTombstoned, pointerVersion,
pointerFp) -> {
WALKey walKey = new WALKey(prefix, key);
WALValue walValue = new WALValue(rowType, value, valueTimestamp, valueTombstone, valueVersion);
if (pointerFp == -1) {
apply.put(walKey, walValue);
} else if (CompareTimestampVersions.compare(pointerTimestamp, pointerVersion, valueTimestamp, valueVersion) < 0) {
apply.put(walKey, walValue);
WALTimestampId currentTimestampId = new WALTimestampId(pointerTimestamp, pointerTombstoned);
KeyedTimestampId keyedTimestampId = new KeyedTimestampId(walKey.prefix,
walKey.key,
currentTimestampId.getTimestampId(),
currentTimestampId.getTombstoned());
clobbers.add(keyedTimestampId);
if (valueTombstone && !pointerTombstoned) {
removes.add(keyedTimestampId);
}
}
i.increment();
return true;
});
}
if (apply.isEmpty()) {
rowsChanged = new RowsChanged(versionedPartitionName, apply, removes, clobbers, -1, -1);
} else {
int size = apply.size();
List<WALIndexable> indexables = new ArrayList<>(size);
walTx.tx((io) -> {
int estimatedSizeInBytes = 0;
for (Entry<WALKey, WALValue> row : apply.entrySet()) {
byte[] value = row.getValue().getValue();
estimatedSizeInBytes += primaryRowMarshaller.maximumSizeInBytes(rowType,
row.getKey().sizeOfComposed(),
(value != null ? value.length : 0));
}
flush(rowType,
forceTxId,
size,
estimatedSizeInBytes,
rowStream -> {
for (Entry<WALKey, WALValue> row : apply.entrySet()) {
WALValue value = row.getValue();
if (!rowStream.stream(primaryRowMarshaller.toRow(rowType,
row.getKey().compose(),
value.getValue(),
value.getTimestampId(),
value.getTombstoned(),
value.getVersion()))) {
return false;
}
}
return true;
},
indexableKeyStream -> {
for (Entry<WALKey, WALValue> row : apply.entrySet()) {
WALValue value = row.getValue();
if (!indexableKeyStream.stream(row.getKey().prefix, row.getKey().key,
value.getTimestampId(), value.getTombstoned(), value.getVersion())) {
return false;
}
}
return true;
},
indexCommittedFromTxId,
indexCommittedUpToTxId,
io,
highwater[0],
(rowTxId, _prefix, key, valueTimestamp, valueTombstoned, valueVersion, fp) -> {
oldestTimestamp.set(Math.min(oldestTimestamp.get(), valueTimestamp));
if (valueTombstoned) {
oldestTombstonedTimestamp.set(Math.min(oldestTombstonedTimestamp.get(), valueTimestamp));
}
indexables.add(new WALIndexable(rowTxId, prefix, key, valueTimestamp, valueTombstoned, valueVersion, fp));
return true;
});
return null;
});
synchronized (oneIndexerAtATimeLock) {
wali.merge((TxKeyPointerStream stream) -> {
for (WALIndexable ix : indexables) {
if (!stream.stream(ix.txId, ix.prefix, ix.key, ix.valueTimestamp, ix.valueTombstoned, ix.valueVersion, ix.fp)) {
return false;
}
mergeStripedKeyHighwaters(ix.prefix, ix.key, ix.valueTimestamp);
}
return true;
}, (mode, txId, _prefix, key, timestamp, tombstoned, version, fp) -> {
if (mode == WALMergeKeyPointerStream.added) {
keyCount.incrementAndGet();
} else if (mode == WALMergeKeyPointerStream.clobbered) {
clobberCount.incrementAndGet();
} else {
apply.remove(new WALKey(prefix, key));
}
return true;
});
rowsChanged = new RowsChanged(versionedPartitionName,
apply,
removes,
clobbers,
indexCommittedFromTxId.longValue(),
indexCommittedUpToTxId.longValue());
}
}
return rowsChanged;
} finally {
releaseOne();
}
}
private void flush(RowType rowType,
long txId,
int estimatedNumberOfRows,
int estimatedSizeInBytes,
RawRows rows,
IndexableKeys indexableKeys,
final MutableLong indexCommittedFromTxId,
final MutableLong indexCommitedUpToTxId,
WALWriter rowWriter,
WALHighwater highwater,
TxKeyPointerFpStream stream) throws Exception {
synchronized (oneTransactionAtATimeLock) {
if (txId == -1) {
txId = orderIdProvider.nextId();
}
if (indexCommittedFromTxId.longValue() > txId) {
indexCommittedFromTxId.setValue(txId);
}
try {
if (indexCommitedUpToTxId.longValue() < txId) {
indexCommitedUpToTxId.setValue(txId);
}
} catch (NullPointerException e) {
throw new IllegalStateException("Illogical NPE: " + (indexCommitedUpToTxId == null), e);
}
rowWriter.write(txId, rowType, estimatedNumberOfRows, estimatedSizeInBytes, rows, indexableKeys, stream, false, hardFsyncBeforeLeapBoundary);
if (highwater != null) {
writeHighwaterMarker(rowWriter, highwater);
}
highestTxId.set(indexCommitedUpToTxId.longValue());
}
}
@Override
public boolean rowScan(KeyValueStream keyValueStream) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
return wali == null || wali.rowScan((prefix, key, timestamp, tombstoned, version, fp) -> {
byte[] hydrateRowIndexValue = hydrateRowIndexValue(fp);
RowType rowType = RowType.fromByte(hydrateRowIndexValue[0]);
byte[] value = primaryRowMarshaller.valueFromRow(rowType, hydrateRowIndexValue, 1 + 8);
return keyValueStream.stream(rowType, prefix, key, value, timestamp, tombstoned, version);
});
} finally {
releaseOne();
}
}
@Override
public boolean rangeScan(byte[] fromPrefix, byte[] fromKey, byte[] toPrefix, byte[] toKey, KeyValueStream keyValueStream) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
return wali.rangeScan(fromPrefix,
fromKey,
toPrefix,
toKey,
(prefix, key, timestamp, tombstoned, version, fp) -> {
byte[] hydrateRowIndexValue = hydrateRowIndexValue(fp);
RowType rowType = RowType.fromByte(hydrateRowIndexValue[0]);
byte[] value = primaryRowMarshaller.valueFromRow(rowType, hydrateRowIndexValue, 1 + 8);
return keyValueStream.stream(rowType, prefix, key, value, timestamp, tombstoned, version);
});
} finally {
releaseOne();
}
}
// TODO fix barf
public TimestampedValue getTimestampedValue(byte[] prefix, byte[] key) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
if (wali == null) {
return null;
}
TimestampedValue[] values = new TimestampedValue[1];
wali.getPointer(prefix, key, (_prefix, _key, timestamp, tombstoned, version, fp) -> {
if (fp != -1 && !tombstoned) {
byte[] hydrateRowIndexValue = hydrateRowIndexValue(fp);
RowType rowType = RowType.fromByte(hydrateRowIndexValue[0]);
byte[] value = primaryRowMarshaller.valueFromRow(rowType, hydrateRowIndexValue, 1 + 8);
values[0] = new TimestampedValue(timestamp, version, value);
}
return true;
});
return values[0];
} finally {
releaseOne();
}
}
//
// public WALPointer getPointer(byte[] prefix, byte[] key) throws Exception {
// acquireOne();
// try {
// WALIndex wali = walIndex.get();
// if (wali == null) {
// return null;
// }
// WALPointer[] pointer = new WALPointer[1];
// wali.getPointer(prefix, key, (_prefix, _key, timestamp, tombstoned, version, fp) -> {
// if (fp != -1 && !tombstoned) {
// pointer[0] = new WALPointer(fp, timestamp, tombstoned, version);
// }
// return true;
// });
// return pointer[0];
// } finally {
// releaseOne();
// }
// }
public boolean streamValues(byte[] prefix, UnprefixedWALKeys keys, KeyValueStream keyValueStream) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
return wali == null || wali.getPointers(prefix, keys,
(_prefix, key, pointerTimestamp, pointerTombstoned, pointerVersion, pointerFp) -> {
if (pointerFp != -1) {
RowType rowType = null;
byte[] value = null;
if (!pointerTombstoned) {
byte[] hydrateRowIndexValue = hydrateRowIndexValue(pointerFp);
rowType = RowType.fromByte(hydrateRowIndexValue[0]);
value = primaryRowMarshaller.valueFromRow(rowType, hydrateRowIndexValue, 1 + 8);
}
return keyValueStream.stream(rowType,
prefix,
key,
value,
pointerTimestamp,
pointerTombstoned,
pointerVersion
);
} else {
return keyValueStream.stream(null, prefix, key, null, -1, false, -1);
}
});
} finally {
releaseOne();
}
}
public boolean streamPointers(KeyValues keyValues, KeyValuePointerStream stream) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
long[] keyHighwaterTimestamps = findKeyHighwaterTimestamps();
return wali == null || wali.getPointers(
indexStream -> keyValues.consume(
(rowType, prefix, key, value, valueTimestamp, valueTombstone, valueVersion) -> {
long largestTimestamp = getLargestTimestampForKeyStripe(prefix, key, keyHighwaterTimestamps);
if (valueTimestamp > largestTimestamp) {
return stream.stream(rowType, prefix, key, value, valueTimestamp, valueTombstone, valueVersion, -1, false, -1, -1);
} else {
return indexStream.stream(rowType, prefix, key, value, valueTimestamp, valueTombstone, valueVersion);
}
}),
stream);
} finally {
releaseOne();
}
}
public boolean containsKeys(byte[] prefix, UnprefixedWALKeys keys, KeyContainedStream stream) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
return wali != null && wali.containsKeys(prefix, keys, stream);
} finally {
releaseOne();
}
}
private long[] findKeyHighwaterTimestamps() throws Exception {
if (stripedKeyHighwaterTimestamps == null) {
synchronized (this) {
if (stripedKeyHighwaterTimestamps == null) {
if (versionedPartitionName.getPartitionName().isSystemPartition()) {
stripedKeyHighwaterTimestamps = new long[numKeyHighwaterStripes];
} else {
long[] compactKeyHighwaterTimestamps = new long[numKeyHighwaterStripes];
walTx.tx(io -> {
io.reverseScan((rowFP, rowTxId, rowType1, row) -> {
if (rowType1 == RowType.end_of_merge) {
long[] marker = loadEndOfMergeMarker(-1, row);
if (marker == null) {
throw new IllegalStateException("Invalid end of merge marker");
}
System.arraycopy(marker, EOM_HIGHWATER_STRIPES_OFFSET, compactKeyHighwaterTimestamps, 0, numKeyHighwaterStripes);
} else {
//System.out.println("Expected EOM but found " + rowType1);
throw new IllegalStateException("Missing end of merge marker");
}
return false;
});
return null;
});
stripedKeyHighwaterTimestamps = compactKeyHighwaterTimestamps;
}
}
}
}
return stripedKeyHighwaterTimestamps;
}
private void clearKeyHighwaterTimestamp() {
if (!versionedPartitionName.getPartitionName().isSystemPartition()) {
stripedKeyHighwaterTimestamps = null;
}
}
private void mergeStripedKeyHighwaters(byte[] prefix, byte[] key, long valueTimestamp) {
if (stripedKeyHighwaterTimestamps != null) {
int highwaterTimestampIndex = Math.abs((Arrays.hashCode(prefix) ^ Arrays.hashCode(key)) % stripedKeyHighwaterTimestamps.length);
stripedKeyHighwaterTimestamps[highwaterTimestampIndex] = Math.max(stripedKeyHighwaterTimestamps[highwaterTimestampIndex], valueTimestamp);
}
}
private long getLargestTimestampForKeyStripe(byte[] prefix, byte[] key, long[] keyHighwaterTimestamps) {
int highwaterTimestampIndex = Math.abs((Arrays.hashCode(prefix) ^ Arrays.hashCode(key)) % keyHighwaterTimestamps.length);
return keyHighwaterTimestamps[highwaterTimestampIndex];
}
//TODO replace with stream!
private byte[] hydrateRowIndexValue(long indexFP) {
try {
return walTx.tx((io) -> io.readTypeByteTxIdAndRow(indexFP));
} catch (Exception x) {
long length;
try {
length = walTx.length();
} catch (Exception e) {
length = -1;
}
throw new RuntimeException(
"Failed to hydrate for " + versionedPartitionName + " versionedPartitionName=" + versionedPartitionName + " size=" + length + " fp=" + indexFP,
x);
}
}
public boolean takeRowUpdatesSince(final long sinceTransactionId, final RowStream rowStream) throws Exception {
if (sinceTransactionId >= highestTxId.get()) {
return true;
}
acquireOne();
try {
long[] takeMetrics = new long[1];
boolean readFromTransactionId = walIndex.get() == null || walTx.readFromTransactionId(sinceTransactionId,
(offset, reader) -> reader.scan(offset,
false,
(rowPointer, rowTxId, rowType, row) -> {
if (rowType != RowType.system && rowTxId > sinceTransactionId) {
return rowStream.row(rowPointer, rowTxId, rowType, row);
} else {
takeMetrics[0]++;
}
return true;
}));
LOG.inc("excessTakes", takeMetrics[0]);
return readFromTransactionId;
} finally {
releaseOne();
}
}
public boolean takeRowUpdatesSince(byte[] prefix, long sinceTransactionId, RowStream rowStream) throws Exception {
if (sinceTransactionId >= highestTxId.get()) {
return true;
}
acquireOne();
try {
long[] takeMetrics = new long[1];
WALIndex wali = walIndex.get();
boolean readFromTransactionId = wali == null || walTx.tx(
io -> io.read(
fpStream -> wali.takePrefixUpdatesSince(prefix, sinceTransactionId, (txId, fp) -> fpStream.stream(fp)),
(rowPointer, rowTxId, rowType, row) -> {
if (rowType != RowType.system && rowTxId > sinceTransactionId) {
return rowStream.row(rowPointer, rowTxId, rowType, row);
} else {
takeMetrics[0]++;
}
return true;
}));
LOG.inc("excessTakes", takeMetrics[0]);
return readFromTransactionId;
} finally {
releaseOne();
}
}
public boolean takeAllRows(final RowStream rowStream) throws Exception {
acquireOne();
try {
return walIndex.get() == null || walTx.readFromTransactionId(0, (offset, reader) -> reader.scan(offset, false, rowStream::row));
} finally {
releaseOne();
}
}
public void updatedProperties(PartitionProperties partitionProperties) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
if (wali != null) {
wali.updatedProperties(partitionProperties.indexProperties);
}
} finally {
releaseOne();
}
}
public long count(WALKeyPointers keyPointers) throws Exception {
acquireOne();
try {
WALIndex wali = walIndex.get();
return wali == null ? 0 : wali.deltaCount(keyPointers) + keyCount.get();
} finally {
releaseOne();
}
}
public long highestTxId() {
return highestTxId.get();
}
}
| logging around EOM marker inconsistency
| amza-service/src/main/java/com/jivesoftware/os/amza/service/storage/WALStorage.java | logging around EOM marker inconsistency | <ide><path>mza-service/src/main/java/com/jivesoftware/os/amza/service/storage/WALStorage.java
<ide> } else {
<ide> long[] compactKeyHighwaterTimestamps = new long[numKeyHighwaterStripes];
<ide> walTx.tx(io -> {
<add> int[] total = { 0 };
<ide> io.reverseScan((rowFP, rowTxId, rowType1, row) -> {
<ide> if (rowType1 == RowType.end_of_merge) {
<ide> long[] marker = loadEndOfMergeMarker(-1, row);
<ide> throw new IllegalStateException("Invalid end of merge marker");
<ide> }
<ide> System.arraycopy(marker, EOM_HIGHWATER_STRIPES_OFFSET, compactKeyHighwaterTimestamps, 0, numKeyHighwaterStripes);
<add> return false;
<add> } else if (!rowType1.isPrimary()) {
<add> total[0]++;
<add> LOG.warn("Expected end of merge marker but found type {} (total:{})", rowType1, total[0]);
<add> return true;
<ide> } else {
<ide> //System.out.println("Expected EOM but found " + rowType1);
<del> throw new IllegalStateException("Missing end of merge marker");
<add> throw new IllegalStateException("Expected end of merge marker but found type " + rowType1);
<ide> }
<del> return false;
<ide> });
<ide> return null;
<ide> }); |
|
Java | apache-2.0 | ac13f7462e676bec84528dbd3899427aaf923042 | 0 | sajeetharan/pentaho-kettle,CapeSepias/pentaho-kettle,graimundo/pentaho-kettle,rfellows/pentaho-kettle,rfellows/pentaho-kettle,mbatchelor/pentaho-kettle,wseyler/pentaho-kettle,graimundo/pentaho-kettle,nicoben/pentaho-kettle,mkambol/pentaho-kettle,ddiroma/pentaho-kettle,andrei-viaryshka/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,ViswesvarSekar/pentaho-kettle,stevewillcock/pentaho-kettle,EcoleKeine/pentaho-kettle,nantunes/pentaho-kettle,HiromuHota/pentaho-kettle,SergeyTravin/pentaho-kettle,pminutillo/pentaho-kettle,CapeSepias/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,nicoben/pentaho-kettle,ViswesvarSekar/pentaho-kettle,akhayrutdinov/pentaho-kettle,EcoleKeine/pentaho-kettle,birdtsai/pentaho-kettle,ccaspanello/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,roboguy/pentaho-kettle,mattyb149/pentaho-kettle,DFieldFL/pentaho-kettle,skofra0/pentaho-kettle,Advent51/pentaho-kettle,ddiroma/pentaho-kettle,wseyler/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,marcoslarsen/pentaho-kettle,tkafalas/pentaho-kettle,brosander/pentaho-kettle,wseyler/pentaho-kettle,pymjer/pentaho-kettle,sajeetharan/pentaho-kettle,bmorrise/pentaho-kettle,rmansoor/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,birdtsai/pentaho-kettle,pavel-sakun/pentaho-kettle,Advent51/pentaho-kettle,pavel-sakun/pentaho-kettle,mattyb149/pentaho-kettle,ivanpogodin/pentaho-kettle,matrix-stone/pentaho-kettle,airy-ict/pentaho-kettle,yshakhau/pentaho-kettle,hudak/pentaho-kettle,stevewillcock/pentaho-kettle,matrix-stone/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,MikhailHubanau/pentaho-kettle,gretchiemoran/pentaho-kettle,dkincade/pentaho-kettle,hudak/pentaho-kettle,skofra0/pentaho-kettle,mkambol/pentaho-kettle,marcoslarsen/pentaho-kettle,e-cuellar/pentaho-kettle,eayoungs/pentaho-kettle,stevewillcock/pentaho-kettle,matthewtckr/pentaho-kettle,andrei-viaryshka/pentaho-kettle,tmcsantos/pentaho-kettle,yshakhau/pentaho-kettle,lgrill-pentaho/pentaho-kettle,mkambol/pentaho-kettle,pymjer/pentaho-kettle,kurtwalker/pentaho-kettle,zlcnju/kettle,ViswesvarSekar/pentaho-kettle,hudak/pentaho-kettle,bmorrise/pentaho-kettle,emartin-pentaho/pentaho-kettle,DFieldFL/pentaho-kettle,ddiroma/pentaho-kettle,lgrill-pentaho/pentaho-kettle,brosander/pentaho-kettle,GauravAshara/pentaho-kettle,GauravAshara/pentaho-kettle,zlcnju/kettle,alina-ipatina/pentaho-kettle,akhayrutdinov/pentaho-kettle,birdtsai/pentaho-kettle,tmcsantos/pentaho-kettle,bmorrise/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,matrix-stone/pentaho-kettle,matthewtckr/pentaho-kettle,YuryBY/pentaho-kettle,akhayrutdinov/pentaho-kettle,cjsonger/pentaho-kettle,akhayrutdinov/pentaho-kettle,MikhailHubanau/pentaho-kettle,e-cuellar/pentaho-kettle,Advent51/pentaho-kettle,GauravAshara/pentaho-kettle,eayoungs/pentaho-kettle,zlcnju/kettle,mdamour1976/pentaho-kettle,sajeetharan/pentaho-kettle,pminutillo/pentaho-kettle,mattyb149/pentaho-kettle,alina-ipatina/pentaho-kettle,tkafalas/pentaho-kettle,flbrino/pentaho-kettle,pedrofvteixeira/pentaho-kettle,roboguy/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,EcoleKeine/pentaho-kettle,flbrino/pentaho-kettle,yshakhau/pentaho-kettle,matthewtckr/pentaho-kettle,pentaho/pentaho-kettle,ccaspanello/pentaho-kettle,drndos/pentaho-kettle,MikhailHubanau/pentaho-kettle,dkincade/pentaho-kettle,rmansoor/pentaho-kettle,jbrant/pentaho-kettle,aminmkhan/pentaho-kettle,alina-ipatina/pentaho-kettle,GauravAshara/pentaho-kettle,SergeyTravin/pentaho-kettle,tkafalas/pentaho-kettle,marcoslarsen/pentaho-kettle,marcoslarsen/pentaho-kettle,ivanpogodin/pentaho-kettle,pentaho/pentaho-kettle,lgrill-pentaho/pentaho-kettle,cjsonger/pentaho-kettle,nanata1115/pentaho-kettle,pymjer/pentaho-kettle,brosander/pentaho-kettle,pavel-sakun/pentaho-kettle,ddiroma/pentaho-kettle,airy-ict/pentaho-kettle,ViswesvarSekar/pentaho-kettle,cjsonger/pentaho-kettle,graimundo/pentaho-kettle,denisprotopopov/pentaho-kettle,sajeetharan/pentaho-kettle,drndos/pentaho-kettle,SergeyTravin/pentaho-kettle,tmcsantos/pentaho-kettle,emartin-pentaho/pentaho-kettle,emartin-pentaho/pentaho-kettle,airy-ict/pentaho-kettle,denisprotopopov/pentaho-kettle,DFieldFL/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,dkincade/pentaho-kettle,denisprotopopov/pentaho-kettle,HiromuHota/pentaho-kettle,kurtwalker/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,nicoben/pentaho-kettle,rfellows/pentaho-kettle,eayoungs/pentaho-kettle,kurtwalker/pentaho-kettle,ma459006574/pentaho-kettle,brosander/pentaho-kettle,DFieldFL/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,hudak/pentaho-kettle,stepanovdg/pentaho-kettle,emartin-pentaho/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,pedrofvteixeira/pentaho-kettle,mdamour1976/pentaho-kettle,stevewillcock/pentaho-kettle,EcoleKeine/pentaho-kettle,ma459006574/pentaho-kettle,mdamour1976/pentaho-kettle,zlcnju/kettle,TatsianaKasiankova/pentaho-kettle,HiromuHota/pentaho-kettle,codek/pentaho-kettle,nanata1115/pentaho-kettle,YuryBY/pentaho-kettle,e-cuellar/pentaho-kettle,ivanpogodin/pentaho-kettle,skofra0/pentaho-kettle,YuryBY/pentaho-kettle,nicoben/pentaho-kettle,ma459006574/pentaho-kettle,ccaspanello/pentaho-kettle,mattyb149/pentaho-kettle,Advent51/pentaho-kettle,HiromuHota/pentaho-kettle,eayoungs/pentaho-kettle,mdamour1976/pentaho-kettle,gretchiemoran/pentaho-kettle,roboguy/pentaho-kettle,drndos/pentaho-kettle,jbrant/pentaho-kettle,YuryBY/pentaho-kettle,skofra0/pentaho-kettle,lgrill-pentaho/pentaho-kettle,birdtsai/pentaho-kettle,roboguy/pentaho-kettle,codek/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,pavel-sakun/pentaho-kettle,ccaspanello/pentaho-kettle,mkambol/pentaho-kettle,andrei-viaryshka/pentaho-kettle,flbrino/pentaho-kettle,flbrino/pentaho-kettle,jbrant/pentaho-kettle,pedrofvteixeira/pentaho-kettle,pminutillo/pentaho-kettle,CapeSepias/pentaho-kettle,tkafalas/pentaho-kettle,stepanovdg/pentaho-kettle,pentaho/pentaho-kettle,dkincade/pentaho-kettle,alina-ipatina/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,aminmkhan/pentaho-kettle,aminmkhan/pentaho-kettle,graimundo/pentaho-kettle,nantunes/pentaho-kettle,mbatchelor/pentaho-kettle,matthewtckr/pentaho-kettle,aminmkhan/pentaho-kettle,gretchiemoran/pentaho-kettle,bmorrise/pentaho-kettle,rmansoor/pentaho-kettle,pymjer/pentaho-kettle,rmansoor/pentaho-kettle,stepanovdg/pentaho-kettle,cjsonger/pentaho-kettle,nanata1115/pentaho-kettle,yshakhau/pentaho-kettle,mbatchelor/pentaho-kettle,CapeSepias/pentaho-kettle,nanata1115/pentaho-kettle,wseyler/pentaho-kettle,pentaho/pentaho-kettle,SergeyTravin/pentaho-kettle,matrix-stone/pentaho-kettle,codek/pentaho-kettle,gretchiemoran/pentaho-kettle,codek/pentaho-kettle,stepanovdg/pentaho-kettle,pminutillo/pentaho-kettle,nantunes/pentaho-kettle,drndos/pentaho-kettle,airy-ict/pentaho-kettle,denisprotopopov/pentaho-kettle,ivanpogodin/pentaho-kettle,kurtwalker/pentaho-kettle,mbatchelor/pentaho-kettle,nantunes/pentaho-kettle,jbrant/pentaho-kettle,ma459006574/pentaho-kettle,pedrofvteixeira/pentaho-kettle,e-cuellar/pentaho-kettle,tmcsantos/pentaho-kettle | /**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.core.value;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import org.w3c.dom.Node;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.XMLInterface;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleEOFException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleFileException;
import be.ibridge.kettle.core.exception.KettleValueException;
import be.ibridge.kettle.repository.Repository;
/**
* This class is one of the core classes of the Kettle framework.
* It contains everything you need to manipulate atomic data (Values/Fields/...)
* and to describe it in the form of meta-data. (name, length, precision, etc.)
*
* @author Matt
* @since Beginning 2003
*/
public class Value implements Cloneable, XMLInterface, Serializable
{
private static final long serialVersionUID = -6310073485210258622L;
/**
* Value type indicating that the value has no type set.
*/
public static final int VALUE_TYPE_NONE = 0;
/**
* Value type indicating that the value contains a floating point double precision number.
*/
public static final int VALUE_TYPE_NUMBER = 1;
/**
* Value type indicating that the value contains a text String.
*/
public static final int VALUE_TYPE_STRING = 2;
/**
* Value type indicating that the value contains a Date.
*/
public static final int VALUE_TYPE_DATE = 3;
/**
* Value type indicating that the value contains a boolean.
*/
public static final int VALUE_TYPE_BOOLEAN = 4;
/**
* Value type indicating that the value contains a long integer.
*/
public static final int VALUE_TYPE_INTEGER = 5;
/**
* Value type indicating that the value contains a floating point precision number with arbitrary precision.
*/
public static final int VALUE_TYPE_BIGNUMBER = 6;
/**
* Value type indicating that the value contains an Object.
*/
public static final int VALUE_TYPE_SERIALIZABLE= 7;
/**
* Value type indicating that the value contains binary data:
* BLOB, CLOB, ...
*/
public static final int VALUE_TYPE_BINARY = 8;
/**
* The descriptions of the value types.
*/
private static final String valueTypeCode[]=
{
"-", // $NON-NLS-1$
"Number", "String", "Date", "Boolean", "Integer", "BigNumber", "Serializable", "Binary" // $NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$ $NON-NLS-4$ $NON-NLS-5$ $NON-NLS-6$ $NON-NLS-7$
};
private ValueInterface value;
private String name;
private String origin;
private boolean NULL;
/**
* Constructs a new Value of type EMPTY
*
*/
public Value()
{
clearValue();
}
/**
* Constructs a new Value with a name.
*
* @param name Sets the name of the Value
*/
public Value(String name)
{
clearValue();
setName(name);
}
/**
* Constructs a new Value with a name and a type.
*
* @param name Sets the name of the Value
* @param val_type Sets the type of the Value (Value.VALUE_TYPE_*)
*/
public Value(String name, int val_type)
{
clearValue();
newValue(val_type);
setName(name);
}
/**
* This method allocates a new value of the appropriate type..
* @param val_type The new type of value
*/
private void newValue(int val_type)
{
switch(val_type)
{
case VALUE_TYPE_INTEGER : value = new ValueInteger(); break;
case VALUE_TYPE_STRING : value = new ValueString(); break;
case VALUE_TYPE_DATE : value = new ValueDate(); break;
case VALUE_TYPE_NUMBER : value = new ValueNumber(); break;
case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(); break;
case VALUE_TYPE_BIGNUMBER: value = new ValueBigNumber(); break;
case VALUE_TYPE_BINARY : value = new ValueBinary(); break;
default: value = null;
}
}
/**
* Convert the value to another type. This only works if a value has been set previously.
* That is the reason this method is private. Rather, use the public method setType(int type).
*
* @param valType The type to convert to.
*/
private void convertTo(int valType)
{
if (value!=null)
{
switch(valType)
{
case VALUE_TYPE_NUMBER : value = new ValueNumber(value.getNumber()); break;
case VALUE_TYPE_STRING : value = new ValueString(value.getString()); break;
case VALUE_TYPE_DATE : value = new ValueDate(value.getDate()); break;
case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(value.getBoolean()); break;
case VALUE_TYPE_INTEGER : value = new ValueInteger(value.getInteger()); break;
case VALUE_TYPE_BIGNUMBER : value = new ValueBigNumber(value.getBigNumber()); break;
case VALUE_TYPE_BINARY : value = new ValueBinary(value.getBytes()); break;
default: value = null;
}
}
}
/**
* Constructs a new Value with a name, a type, length and precision.
*
* @param name Sets the name of the Value
* @param valType Sets the type of the Value (Value.VALUE_TYPE_*)
* @param length The length of the value
* @param precision The precision of the value
*/
public Value(String name, int valType, int length, int precision)
{
this(name, valType);
setLength(length, precision);
}
/**
* Constructs a new Value of Type VALUE_TYPE_BIGNUMBER, with a name, containing a BigDecimal number
*
* @param name Sets the name of the Value
* @param bignum The number to store in this Value
*/
public Value(String name, BigDecimal bignum)
{
clearValue();
setValue(bignum);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_NUMBER, with a name, containing a number
*
* @param name Sets the name of the Value
* @param num The number to store in this Value
*/
public Value(String name, double num)
{
clearValue();
setValue(num);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String
*
* @param name Sets the name of the Value
* @param str The text to store in this Value
*/
public Value(String name, StringBuffer str)
{
this(name, str.toString());
}
/**
* Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String
*
* @param name Sets the name of the Value
* @param str The text to store in this Value
*/
public Value(String name, String str)
{
clearValue();
setValue(str);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_DATE, with a name, containing a Date
*
* @param name Sets the name of the Value
* @param dat The date to store in this Value
*/
public Value(String name, Date dat)
{
clearValue();
setValue(dat);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_BOOLEAN, with a name, containing a boolean value
*
* @param name Sets the name of the Value
* @param bool The boolean to store in this Value
*/
public Value(String name, boolean bool)
{
clearValue();
setValue(bool);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_INTEGER, with a name, containing an integer number
*
* @param name Sets the name of the Value
* @param l The integer to store in this Value
*/
public Value(String name, long l)
{
clearValue();
setValue(l);
setName(name);
}
/**
* Constructs a new Value as a copy of another value and renames it...
*
* @param name The new name of the copied Value
* @param v The value to be copied
*/
public Value(String name, Value v)
{
this(v);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_BINARY, with a name, containing a bytes value
*
* @param name Sets the name of the Value
* @param b The bytes to store in this Value
*/
public Value(String name, byte[] b)
{
clearValue();
setValue(b);
setName(name);
}
/**
* Constructs a new Value as a copy of another value
*
* @param v The Value to be copied
*/
public Value(Value v)
{
if (v!=null)
{
setType(v.getType());
value = v.getValueCopy();
setName(v.getName());
setLength(v.getLength(), v.getPrecision());
setNull(v.isNull());
setOrigin(v.origin);
}
else
{
clearValue();
setNull(true);
}
}
public Object clone()
{
Value retval = null;
try
{
retval = (Value)super.clone();
if (value!=null) retval.value = (ValueInterface) value.clone();
}
catch(CloneNotSupportedException e)
{
retval=null;
}
return retval;
}
/**
* Build a copy of this Value
* @return a copy of another value
*
*/
public Value Clone()
{
Value v = new Value(this);
return v;
}
/**
* Clears the content and name of a Value
*/
public void clearValue()
{
value = null;
name = null;
NULL = false;
origin = null;
}
private ValueInterface getValueCopy()
{
if (value==null) return null;
return (ValueInterface)value.clone();
}
/**
* Sets the name of a Value
*
* @param name The new name of the value
*/
public void setName(String name)
{
this.name = name;
}
/**
* Obtain the name of a Value
*
* @return The name of the Value
*/
public String getName()
{
return name;
}
/**
* This method allows you to set the origin of the Value by means of the name of the originating step.
*
* @param step_of_origin The step of origin.
*/
public void setOrigin(String step_of_origin)
{
origin = step_of_origin;
}
/**
* Obtain the origin of the step.
*
* @return The name of the originating step
*/
public String getOrigin()
{
return origin;
}
/**
* Sets the value to a BigDecimal number value.
* @param num The number value to set the value to
*/
public void setValue(BigDecimal num)
{
if (value==null || value.getType()!=VALUE_TYPE_BIGNUMBER) value = new ValueBigNumber(num);
else value.setBigNumber(num);
setNull(false);
}
/**
* Sets the value to a double Number value.
* @param num The number value to set the value to
*/
public void setValue(double num)
{
if (value==null || value.getType()!=VALUE_TYPE_NUMBER) value = new ValueNumber(num);
else value.setNumber(num);
setNull(false);
}
/**
* Sets the Value to a String text
* @param str The StringBuffer to get the text from
*/
public void setValue(StringBuffer str)
{
if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str.toString());
else value.setString(str.toString());
setNull(str==null);
}
/**
* Sets the Value to a String text
* @param str The String to get the text from
*/
public void setValue(String str)
{
if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str);
else value.setString(str);
setNull(str==null);
}
public void setSerializedValue(Serializable ser) {
if (value==null || value.getType()!=VALUE_TYPE_SERIALIZABLE) value = new ValueSerializable(ser);
else value.setSerializable(ser);
setNull(ser==null);
}
/**
* Sets the Value to a Date
* @param dat The Date to set the Value to
*/
public void setValue(Date dat)
{
if (value==null || value.getType()!=VALUE_TYPE_DATE) value = new ValueDate(dat);
else value.setDate(dat);
setNull(dat==null);
}
/**
* Sets the Value to a boolean
* @param bool The boolean to set the Value to
*/
public void setValue(boolean bool)
{
if (value==null || value.getType()!=VALUE_TYPE_BOOLEAN) value = new ValueBoolean(bool);
else value.setBoolean(bool);
setNull(false);
}
/**
* Sets the Value to a long integer
* @param b The byte to convert to a long integer to which the Value is set.
*/
public void setValue(byte b)
{
setValue((long)b);
}
/**
* Sets the Value to a long integer
* @param i The integer to convert to a long integer to which the Value is set.
*/
public void setValue(int i)
{
setValue((long)i);
}
/**
* Sets the Value to a long integer
* @param l The long integer to which the Value is set.
*/
public void setValue(long l)
{
if (value==null || value.getType()!=VALUE_TYPE_INTEGER) value = new ValueInteger(l);
else value.setInteger(l);
setNull(false);
}
/**
* Sets the Value to a byte array
* @param b The byte array to which the Value has to be set.
*/
public void setValue(byte[] b)
{
if (value==null || value.getType()!=VALUE_TYPE_BINARY) value = new ValueBinary(b);
else value.setBytes(b);
if ( b == null )
setNull(true);
else
setNull(false);
}
/**
* Copy the Value from another Value.
* It doesn't copy the name.
* @param v The Value to copy the settings and value from
*/
public void setValue(Value v)
{
if (v!=null)
{
value = v.getValueCopy();
setNull(v.isNull());
setOrigin(v.origin);
}
else
{
clearValue();
}
}
/**
* Get the BigDecimal number of this Value.
* If the value is not of type BIG_NUMBER, a conversion is done first.
* @return the double precision floating point number of this Value.
*/
public BigDecimal getBigNumber()
{
if (value==null || isNull()) return null;
return value.getBigNumber();
}
/**
* Get the double precision floating point number of this Value.
* If the value is not of type NUMBER, a conversion is done first.
* @return the double precision floating point number of this Value.
*/
public double getNumber()
{
if (value==null || isNull()) return 0.0;
return value.getNumber();
}
/**
* Get the String text representing this value.
* If the value is not of type STRING, a conversion if done first.
* @return the String text representing this value.
*/
public String getString()
{
if (value==null || isNull()) return null;
return value.getString();
}
/**
* Get the length of the String representing this value.
* @return the length of the String representing this value.
*/
public int getStringLength()
{
String s = getString();
if (s==null) return 0;
return s.length();
}
/**
* Get the Date of this Value.
* If the Value is not of type DATE, a conversion is done first.
* @return the Date of this Value.
*/
public Date getDate()
{
if (value==null || isNull()) return null;
return value.getDate();
}
/**
* Get the Serializable of this Value.
* If the Value is not of type Serializable, it returns null.
* @return the Serializable of this Value.
*/
public Serializable getSerializable()
{
if (value==null || isNull() || value.getType() != VALUE_TYPE_SERIALIZABLE) return null;
return value.getSerializable();
}
/**
* Get the boolean value of this Value.
* If the Value is not of type BOOLEAN, it will be converted.
* <p>Strings: "YES", "Y", "TRUE" (case insensitive) to true, the rest false
* <p>Number: 0.0 is false, the rest is true.
* <p>Integer: 0 is false, the rest is true.
* <p>Date: always false.
* @return the boolean representation of this Value.
*/
public boolean getBoolean()
{
if (value==null || isNull()) return false;
return value.getBoolean();
}
/**
* Get the long integer representation of this value.
* If the Value is not of type INTEGER, it will be converted:
* <p>String: try to convert to a long value, 0L if it didn't work.
* <p>Number: round the double value and return the resulting long integer.
* <p>Date: return the number of miliseconds after <code>1970:01:01 00:00:00</code>
* <p>Date: always false.
*
* @return the long integer representation of this value.
*/
public long getInteger()
{
if (value==null || isNull()) return 0L;
return value.getInteger();
}
public byte[] getBytes()
{
if (value==null || isNull()) return null;
return value.getBytes();
}
/**
* Set the type of this Value
* @param val_type The type to which the Value will be set.
*/
public void setType(int val_type)
{
if (value==null) newValue(val_type);
else // Convert the value to the appropriate type...
{
convertTo(val_type);
}
}
/**
* Returns the type of this Value
* @return the type of this Value
*/
public int getType()
{
if (value==null) return VALUE_TYPE_NONE;
return value.getType();
}
/**
* Checks whether or not this Value is empty.
* A value is empty if it has the type VALUE_TYPE_EMPTY
* @return true if the value is empty.
*/
public boolean isEmpty()
{
if (value==null) return true;
return false;
}
/**
* Checks wheter or not the value is a String.
* @return true if the value is a String.
*/
public boolean isString()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_STRING;
}
/**
* Checks whether or not this value is a Date
* @return true if the value is a Date
*/
public boolean isDate()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_DATE;
}
/**
* Checks whether or not the value is a Big Number
* @return true is this value is a big number
*/
public boolean isBigNumber()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_BIGNUMBER;
}
/**
* Checks whether or not the value is a Number
* @return true is this value is a number
*/
public boolean isNumber()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_NUMBER;
}
/**
* Checks whether or not this value is a boolean
* @return true if this value has type boolean.
*/
public boolean isBoolean()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_BOOLEAN;
}
/**
* Checks whether or not this value is of type Serializable
* @return true if this value has type Serializable
*/
public boolean isSerializableType() {
if(value == null) {
return false;
}
return value.getType() == VALUE_TYPE_SERIALIZABLE;
}
/**
* Checks whether or not this value is of type Binary
* @return true if this value has type Binary
*/
public boolean isBinary() {
// Serializable is not included here as it used for
// internal purposes only.
if(value == null) {
return false;
}
return value.getType() == VALUE_TYPE_BINARY;
}
/**
* Checks whether or not this value is an Integer
* @return true if this value is an integer
*/
public boolean isInteger()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_INTEGER;
}
/**
* Checks whether or not this Value is Numeric
* A Value is numeric if it is either of type Number or Integer
* @return true if the value is either of type Number or Integer
*/
public boolean isNumeric()
{
return isInteger() || isNumber() || isBigNumber();
}
/**
* Checks whether or not the specified type is either Integer or Number
* @param t the type to check
* @return true if the type is Integer or Number
*/
public static final boolean isNumeric(int t)
{
return t==VALUE_TYPE_INTEGER || t==VALUE_TYPE_NUMBER || t==VALUE_TYPE_BIGNUMBER;
}
/**
* Returns a padded to length String text representation of this Value
* @return a padded to length String text representation of this Value
*/
public String toString()
{
return toString(true);
}
/**
* a String text representation of this Value, optionally padded to the specified length
* @param pad true if you want to pad the resulting String
* @return a String text representation of this Value, optionally padded to the specified length
*/
public String toString(boolean pad)
{
String retval;
switch(getType())
{
case VALUE_TYPE_STRING : retval=toStringString(pad); break;
case VALUE_TYPE_INTEGER: retval=toStringInteger(pad); break;
case VALUE_TYPE_NUMBER : retval=toStringNumber(pad); break;
case VALUE_TYPE_DATE : retval=toStringDate(); break;
case VALUE_TYPE_BOOLEAN: retval=toStringBoolean(); break;
case VALUE_TYPE_BIGNUMBER: retval=toStringBigNumber(pad); break;
case VALUE_TYPE_BINARY : retval=toStringBinary(pad); break;
default: retval=""; break;
}
return retval;
}
/**
* a String text representation of this Value, optionally padded to the specified length
* @return a String text representation of this Value, optionally padded to the specified length
*/
public String toStringMeta()
{
// We (Sven Boden) did explicit performance testing for this
// part. The original version used Strings instead of StringBuffers,
// performance between the 2 does not differ that much. A few milliseconds
// on 100000 iterations in the advantage of StringBuffers. The
// lessened creation of objects may be worth it in the long run.
StringBuffer retval=new StringBuffer(getTypeDesc());
switch(getType())
{
case VALUE_TYPE_STRING :
if (getLength()>0) retval.append('(').append(getLength()).append(')');
break;
case VALUE_TYPE_NUMBER :
case VALUE_TYPE_BIGNUMBER :
if (getLength()>0)
{
retval.append('(').append(getLength());
if (getPrecision()>0)
{
retval.append(", ").append(getPrecision());
}
retval.append(')');
}
break;
case VALUE_TYPE_INTEGER:
if (getLength()>0)
{
retval.append('(').append(getLength()).append(')');
}
break;
default: break;
}
return retval.toString();
}
/**
* Converts a String Value to String optionally padded to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringString(boolean pad)
{
String retval=null;
if (value==null) return null;
if (value.getLength()<=0) // No length specified!
{
if (isNull() || value.getString()==null)
retval = Const.NULL_STRING;
else
retval = value.getString();
}
else
{
if (pad)
{
StringBuffer ret;
if (isNull() || value.getString()==null) ret=new StringBuffer(Const.NULL_STRING);
else ret=new StringBuffer(value.getString());
int length = value.getLength();
if (length>16384) length=16384; // otherwise we get OUT OF MEMORY errors for CLOBS.
Const.rightPad(ret, length);
retval=ret.toString();
}
else
{
if (isNull() || value.getString()==null)
{
retval=Const.NULL_STRING;
}
else
{
retval = value.getString();
}
}
}
return retval;
}
/**
* Converts a Number value to a String, optionally padding the result to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringNumber(boolean pad)
{
String retval;
if (value==null) return null;
if (pad)
{
if (value.getLength()<1)
{
if (isNull()) retval=Const.NULL_NUMBER;
else
{
DecimalFormat form= new DecimalFormat();
form.applyPattern(" ##########0.0########;-#########0.0########");
// System.out.println("local.pattern = ["+form.toLocalizedPattern()+"]");
retval=form.format(value.getNumber());
}
}
else
{
if (isNull())
{
StringBuffer ret=new StringBuffer(Const.NULL_NUMBER);
Const.rightPad(ret, value.getLength());
retval=ret.toString();
}
else
{
StringBuffer fmt=new StringBuffer();
int i;
DecimalFormat form;
if (value.getNumber()>=0) fmt.append(' '); // to compensate for minus sign.
if (value.getPrecision()<0) // Default: two decimals
{
for (i=0;i<value.getLength();i++) fmt.append('0');
fmt.append(".00"); // for the .00
}
else // Floating point format 00001234,56 --> (12,2)
{
for (i=0;i<=value.getLength();i++) fmt.append('0'); // all zeroes.
int pos = value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0);
if (pos>=0 && pos <fmt.length())
{
fmt.setCharAt(value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0), '.'); // one 'comma'
}
}
form= new DecimalFormat(fmt.toString());
retval=form.format(value.getNumber());
}
}
}
else
{
if (isNull()) retval=Const.NULL_NUMBER;
else retval=Double.toString(value.getNumber());
}
return retval;
}
/**
* Converts a Date value to a String.
* The date has format: <code>yyyy/MM/dd HH:mm:ss.SSS</code>
* @return a String representing the Date Value.
*/
private String toStringDate()
{
String retval;
if (value==null) return null;
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS", Locale.US);
if (isNull() || value.getDate()==null) retval=Const.NULL_DATE;
else
{
retval=df.format(value.getDate()).toString();
}
/*
This code was removed as TYPE_VALUE_DATE does not know "length", so this
could never be called anyway
else
{
StringBuffer ret;
if (isNull() || value.getDate()==null)
ret=new StringBuffer(Const.NULL_DATE);
else ret=new StringBuffer(df.format(value.getDate()).toString());
Const.rightPad(ret, getLength()<=10?10:getLength());
retval=ret.toString();
}
*/
return retval;
}
/**
* Returns a String representing the boolean value.
* It will be either "true" or "false".
*
* @return a String representing the boolean value.
*/
private String toStringBoolean()
{
// Code was removed from this method as ValueBoolean
// did not store length, so some parts could never be
// called.
String retval;
if (value==null) return null;
if (isNull())
{
retval=Const.NULL_BOOLEAN;
}
else
{
retval=value.getBoolean()?"true":"false";
}
return retval;
}
/**
* Converts an Integer value to a String, optionally padding the result to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringInteger(boolean pad)
{
String retval;
if (value==null) return null;
if (getLength()<1)
{
if (isNull()) retval=Const.NULL_INTEGER;
else
{
DecimalFormat form= new DecimalFormat(" ###############0;-###############0");
retval=form.format(value.getInteger());
}
}
else
{
if (isNull())
{
StringBuffer ret=new StringBuffer(Const.NULL_INTEGER);
Const.rightPad(ret, getLength());
retval=ret.toString();
}
else
{
if (pad)
{
StringBuffer fmt=new StringBuffer();
int i;
DecimalFormat form;
if (value.getInteger()>=0) fmt.append(' '); // to compensate for minus sign.
int len = getLength();
for (i=0;i<len;i++) fmt.append('0'); // all zeroes.
form= new DecimalFormat(fmt.toString());
retval=form.format(value.getInteger());
}
else
{
retval = Long.toString(value.getInteger());
}
}
}
return retval;
}
/**
* Converts a BigNumber value to a String, optionally padding the result to the specified length. // TODO: BigNumber padding
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringBigNumber(boolean pad)
{
if (value.getBigNumber()==null) return null;
String retval = value.getString();
// Localise . to ,
if (Const.DEFAULT_DECIMAL_SEPARATOR!='.')
{
retval = retval.replace('.', Const.DEFAULT_DECIMAL_SEPARATOR);
}
return retval;
}
/**
* Returns a String representing the binary value.
*
* @return a String representing the binary value.
*/
private String toStringBinary(boolean pad)
{
String retval;
if (value==null) return null;
if (isNull() || value.getBytes() == null)
{
retval=Const.NULL_BINARY;
}
else
{
retval = new String(value.getBytes());
}
return retval;
}
/**
* Sets the length of the Number, Integer or String to the specified length
* Note: no truncation of the value takes place, this is meta-data only!
* @param l the length to which you want to set the Value.
*/
public void setLength(int l)
{
if (value==null) return;
value.setLength(l);
}
/**
* Sets the length and the precision of the Number, Integer or String to the specified length & precision
* Note: no truncation of the value takes place, this is meta-data only!
* @param l the length to which you want to set the Value.
* @param p the precision to which you want to set this Value
*/
public void setLength(int l, int p)
{
if (value==null) return;
value.setLength(l,p);
}
/**
* Get the length of this Value.
* @return the length of this Value.
*/
public int getLength()
{
if (value==null) return -1;
return value.getLength();
}
/**
* get the precision of this Value
* @return the precision of this Value.
*/
public int getPrecision()
{
if (value==null) return -1;
return value.getPrecision();
}
/**
* Sets the precision of this Value
* Note: no rounding or truncation takes place, this is meta-data only!
* @param p the precision to which you want to set this Value.
*/
public void setPrecision(int p)
{
if (value==null) return;
value.setPrecision(p);
}
/**
* Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ...
* @return A String describing the type of value.
*/
public String getTypeDesc()
{
if (value==null) return "Unknown";
return value.getTypeDesc();
}
/**
* Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ... given a certain integer type
* @param t the type to convert to text.
* @return A String describing the type of a certain value.
*/
public static final String getTypeDesc(int t)
{
return valueTypeCode[t];
}
/**
* Convert the String description of a type to an integer type.
* @param desc The description of the type to convert
* @return The integer type of the given String. (Value.VALUE_TYPE_...)
*/
public static final int getType(String desc)
{
int i;
for (i=1;i<valueTypeCode.length;i++)
{
if (valueTypeCode[i].equalsIgnoreCase(desc))
{
return i;
}
}
return VALUE_TYPE_NONE;
}
/**
* get an array of String describing the possible types a Value can have.
* @return an array of String describing the possible types a Value can have.
*/
public static final String[] getTypes()
{
String retval[] = new String[valueTypeCode.length-1];
System.arraycopy(valueTypeCode, 1, retval, 0, valueTypeCode.length-1);
return retval;
}
/**
* Get an array of String describing the possible types a Value can have.
* @return an array of String describing the possible types a Value can have.
*/
public static final String[] getAllTypes()
{
String retval[] = new String[valueTypeCode.length];
System.arraycopy(valueTypeCode, 0, retval, 0, valueTypeCode.length);
return retval;
}
/**
* Sets the Value to null, no type is being changed.
*
*/
public void setNull()
{
setNull(true);
}
/**
* Sets or unsets a value to null, no type is being changed.
* @param n true if you want the value to be null, false if you don't want this to be the case.
*/
public void setNull(boolean n)
{
NULL=n;
}
/**
* Checks wheter or not a value is null.
* @return true if the Value is null.
*/
public boolean isNull()
{
return NULL;
}
/**
* Write the object to an ObjectOutputStream
* @param out
* @throws IOException
*/
private void writeObject(java.io.ObjectOutputStream out) throws IOException
{
writeObj(new DataOutputStream(out));
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
{
readObj(new DataInputStream(in));
}
public void writeObj(DataOutputStream dos) throws IOException
{
int type=getType();
// Handle type
dos.writeInt(getType());
// Handle name-length
dos.writeInt(name.length());
// Write name
dos.writeChars(name);
// length & precision
dos.writeInt(getLength());
dos.writeInt(getPrecision());
// NULL?
dos.writeBoolean(isNull());
// Handle Content -- only when not NULL
if (!isNull())
{
switch(type)
{
case VALUE_TYPE_STRING :
case VALUE_TYPE_BIGNUMBER:
if (getString()!=null && getString().getBytes().length>0)
{
dos.writeInt(getString().getBytes("UTF-8").length);
dos.writeUTF(getString());
}
else
{
dos.writeInt(0);
}
break;
case VALUE_TYPE_DATE :
dos.writeBoolean(getDate()!=null);
if (getDate()!=null)
{
dos.writeLong(getDate().getTime());
}
break;
case VALUE_TYPE_NUMBER :
dos.writeDouble(getNumber());
break;
case VALUE_TYPE_BOOLEAN:
dos.writeBoolean(getBoolean());
break;
case VALUE_TYPE_INTEGER:
dos.writeLong(getInteger());
break;
default: break; // nothing
}
}
}
/**
* Write the value, including the meta-data to a DataOutputStream
* @param outputStream the OutputStream to write to .
* @throws KettleFileException if something goes wrong.
*/
public void write(OutputStream outputStream) throws KettleFileException
{
try
{
writeObj(new DataOutputStream(outputStream));
}
catch(Exception e)
{
throw new KettleFileException("Unable to write value to output stream", e);
}
}
public void readObj(DataInputStream dis) throws IOException
{
// type
int theType = dis.readInt();
newValue(theType);
// name-length
int nameLength=dis.readInt();
// name
StringBuffer nameBuffer=new StringBuffer();
for (int i=0;i<nameLength;i++) nameBuffer.append(dis.readChar());
setName(new String(nameBuffer));
// length & precision
setLength(dis.readInt(), dis.readInt());
// Null?
setNull(dis.readBoolean());
// Read the values
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING:
case VALUE_TYPE_BIGNUMBER:
// Handle lengths
int dataLength=dis.readInt();
if (dataLength>0)
{
String string = dis.readUTF();
setValue(string);
}
if (theType==VALUE_TYPE_BIGNUMBER)
{
try
{
convertString(theType);
}
catch(KettleValueException e)
{
throw new IOException("Unable to convert String to BigNumber while reading from data input stream ["+getString()+"]");
}
}
break;
case VALUE_TYPE_DATE:
if (dis.readBoolean())
{
setValue(new Date(dis.readLong()));
}
break;
case VALUE_TYPE_NUMBER:
setValue(dis.readDouble());
break;
case VALUE_TYPE_INTEGER:
setValue(dis.readLong());
break;
case VALUE_TYPE_BOOLEAN:
setValue(dis.readBoolean());
break;
default: break;
}
}
}
/**
* Read the Value, including meta-data from a DataInputStream
* @param is The InputStream to read the value from
* @throws KettleFileException when the Value couldn't be created by reading it from the DataInputStream.
*/
public Value(InputStream is) throws KettleFileException
{
try
{
readObj(new DataInputStream(is));
}
catch(EOFException e)
{
throw new KettleEOFException("End of file reached", e);
}
catch(Exception e)
{
throw new KettleFileException("Error reading from data input stream", e);
}
}
/**
* Write the data of this Value, without the meta-data to a DataOutputStream
* @param dos The DataOutputStream to write the data to
* @return true if all went well, false if something went wrong.
*/
public boolean writeData(DataOutputStream dos) throws KettleFileException
{
try
{
// Is the value NULL?
dos.writeBoolean(isNull());
// Handle Content -- only when not NULL
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING :
case VALUE_TYPE_BIGNUMBER:
if (getString()!=null && getString().getBytes().length>0)
{
dos.writeInt(getString().getBytes().length);
dos.writeUTF(getString());
}
else
{
dos.writeInt(0);
}
break;
case VALUE_TYPE_DATE :
dos.writeBoolean(getDate()!=null);
if (getDate()!=null)
{
dos.writeLong(getDate().getTime());
}
break;
case VALUE_TYPE_NUMBER :
dos.writeDouble(getNumber());
break;
case VALUE_TYPE_BOOLEAN:
dos.writeBoolean(getBoolean());
break;
case VALUE_TYPE_INTEGER:
dos.writeLong(getInteger());
break;
default: break; // nothing
}
}
}
catch(IOException e)
{
throw new KettleFileException("Unable to write value data to output stream", e);
}
return true;
}
/**
* Read the data of a Value from a DataInputStream, the meta-data of the value has to be set before calling this method!
* @param dis the DataInputStream to read from
* @throws KettleFileException when the value couldn't be read from the DataInputStream
*/
public Value(Value metaData, DataInputStream dis) throws KettleFileException
{
setValue(metaData);
setName(metaData.getName());
try
{
// Is the value NULL?
setNull(dis.readBoolean());
// Read the values
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING:
case VALUE_TYPE_BIGNUMBER:
// Handle lengths
int dataLength=dis.readInt();
if (dataLength>0)
{
String string = dis.readUTF();
setValue(string);
if (metaData.isBigNumber()) convertString(metaData.getType());
}
break;
case VALUE_TYPE_DATE:
if (dis.readBoolean())
{
setValue(new Date(dis.readLong()));
}
break;
case VALUE_TYPE_NUMBER:
setValue(dis.readDouble());
break;
case VALUE_TYPE_INTEGER:
setValue(dis.readLong());
break;
case VALUE_TYPE_BOOLEAN:
setValue(dis.readBoolean());
break;
default: break;
}
}
}
catch(EOFException e)
{
throw new KettleEOFException("End of file reached", e);
}
catch(Exception e)
{
throw new KettleEOFException("Error reading value data from stream", e);
}
}
/**
* Compare 2 values of the same or different type!
* The comparison of Strings is case insensitive
* @param v the value to compare with.
* @return -1 if The value was smaller, 1 bigger and 0 if both values are equal.
*/
public int compare(Value v)
{
return compare(v, true);
}
/**
* Compare 2 values of the same or different type!
* @param v the value to compare with.
* @param caseInsensitive True if you want the comparison to be case insensitive
* @return -1 if The value was smaller, 1 bigger and 0 if both values are equal.
*/
public int compare(Value v, boolean caseInsensitive)
{
boolean n1 = isNull() || (isString() && (getString()==null || getString().length()==0)) || (isDate() && getDate()==null) || (isBigNumber() && getBigNumber()==null);
boolean n2 = v.isNull() || (v.isString() && (v.getString()==null || v.getString().length()==0)) || (v.isDate() && v.getDate()==null) || (v.isBigNumber() && v.getBigNumber()==null);
// null is always smaller!
if ( n1 && !n2) return -1;
if (!n1 && n2) return 1;
if ( n1 && n2) return 0;
switch(getType())
{
case VALUE_TYPE_STRING:
{
String one = Const.rtrim(getString());
String two = Const.rtrim(v.getString());
int cmp=0;
if (caseInsensitive)
{
cmp = one.compareToIgnoreCase(two);
}
else
{
cmp = one.compareTo(two);
}
return cmp;
}
case VALUE_TYPE_INTEGER:
{
return Double.compare(getNumber(), v.getNumber());
}
case VALUE_TYPE_DATE :
{
return Double.compare(getNumber(), v.getNumber());
}
case VALUE_TYPE_BOOLEAN:
{
if (getBoolean() && v.getBoolean() ||
!getBoolean() && !v.getBoolean()) return 0; // true == true, false == false
if (getBoolean() && !v.getBoolean()) return 1; // true > false
return -1; // false < true
}
case VALUE_TYPE_NUMBER :
{
return Double.compare(getNumber(), v.getNumber());
}
case VALUE_TYPE_BIGNUMBER:
{
return getBigNumber().compareTo(v.getBigNumber());
}
}
// Still here? Not possible! But hey, give back 0, mkay?
return 0;
}
public boolean equals(Object v)
{
if (compare((Value)v)==0)
return true;
else
return false;
}
/**
* Check whether this value is equal to the String supplied.
* @param string The string to check for equality
* @return true if the String representation of the value is equal to string. (ignoring case)
*/
public boolean isEqualTo(String string)
{
return getString().equalsIgnoreCase(string);
}
/**
* Check whether this value is equal to the BigDecimal supplied.
* @param number The BigDecimal to check for equality
* @return true if the BigDecimal representation of the value is equal to number.
*/
public boolean isEqualTo(BigDecimal number)
{
return getBigNumber().equals(number);
}
/**
* Check whether this value is equal to the Number supplied.
* @param number The Number to check for equality
* @return true if the Number representation of the value is equal to number.
*/
public boolean isEqualTo(double number)
{
return getNumber() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(long number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(int number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(byte number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Date supplied.
* @param date The Date to check for equality
* @return true if the Date representation of the value is equal to date.
*/
public boolean isEqualTo(Date date)
{
return getDate() == date;
}
public int hashCode()
{
int hash=0; // name.hashCode(); -> Name shouldn't be part of hashCode()!
if (isNull())
{
switch(getType())
{
case VALUE_TYPE_BOOLEAN : hash^= 1; break;
case VALUE_TYPE_DATE : hash^= 2; break;
case VALUE_TYPE_NUMBER : hash^= 4; break;
case VALUE_TYPE_STRING : hash^= 8; break;
case VALUE_TYPE_INTEGER : hash^=16; break;
case VALUE_TYPE_BIGNUMBER : hash^=32; break;
case VALUE_TYPE_NONE : break;
default: break;
}
}
else
{
switch(getType())
{
case VALUE_TYPE_BOOLEAN : hash^=Boolean.valueOf(getBoolean()).hashCode(); break;
case VALUE_TYPE_DATE : if (getDate()!=null) hash^=getDate().hashCode(); break;
case VALUE_TYPE_INTEGER :
case VALUE_TYPE_NUMBER : hash^=(new Double(getNumber())).hashCode(); break;
case VALUE_TYPE_STRING : if (getString()!=null) hash^=getString().hashCode(); break;
case VALUE_TYPE_BIGNUMBER : if (getBigNumber()!=null) hash^=getBigNumber().hashCode(); break;
case VALUE_TYPE_NONE : break;
default: break;
}
}
return hash;
}
// OPERATORS & COMPARATORS
public Value and(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 & n2;
setValue(res);
return this;
}
public Value xor(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 ^ n2;
setValue(res);
return this;
}
public Value or(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 | n2;
setValue(res);
return this;
}
public Value bool_and(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1 && b2;
setValue(res);
return this;
}
public Value bool_or(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1 || b2;
setValue(res);
return this;
}
public Value bool_xor(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1&&b2 ? false : !b1&&!b2 ? false : true;
setValue(res);
return this;
}
public Value bool_not()
{
value.setBoolean(!getBoolean());
return this;
}
public Value greater_equal(Value v)
{
if (compare(v)>=0) setValue(true); else setValue(false);
return this;
}
public Value smaller_equal(Value v)
{
if (compare(v)<=0) setValue(true); else setValue(false);
return this;
}
public Value different(Value v)
{
if (compare(v)!=0) setValue(true); else setValue(false);
return this;
}
public Value equal(Value v)
{
if (compare(v)==0) setValue(true); else setValue(false);
return this;
}
public Value like(Value v)
{
String cmp=v.getString();
// Is cmp part of look?
int idx=getString().indexOf(cmp);
if (idx<0) setValue(false); else setValue(true);
return this;
}
public Value greater(Value v)
{
if (compare(v)>0) setValue(true); else setValue(false);
return this;
}
public Value smaller(Value v)
{
if (compare(v)<0) setValue(true); else setValue(false);
return this;
}
public Value minus(BigDecimal v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(double v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(long v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(int v) throws KettleValueException { return minus(new Value("tmp", (long)v)); }
public Value minus(byte v) throws KettleValueException { return minus(new Value("tmp", (long)v)); }
public Value minus(Value v) throws KettleValueException
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : value.setBigNumber(getBigNumber().subtract(v.getBigNumber())); break;
case VALUE_TYPE_NUMBER : value.setNumber(getNumber()-v.getNumber()); break;
case VALUE_TYPE_INTEGER : value.setInteger(getInteger()-v.getInteger()); break;
case VALUE_TYPE_BOOLEAN :
case VALUE_TYPE_STRING :
default:
throw new KettleValueException("Subtraction can only be done with numbers!");
}
return this;
}
public Value plus(BigDecimal v) { return plus(new Value("tmp", v)); }
public Value plus(double v) { return plus(new Value("tmp", v)); }
public Value plus(long v) { return plus(new Value("tmp", v)); }
public Value plus(int v) { return plus(new Value("tmp", (long)v)); }
public Value plus(byte v) { return plus(new Value("tmp", (long)v)); }
public Value plus(Value v)
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().add(v.getBigNumber())); break;
case VALUE_TYPE_NUMBER : setValue(getNumber()+v.getNumber()); break;
case VALUE_TYPE_INTEGER : setValue(getInteger()+v.getInteger()); break;
case VALUE_TYPE_BOOLEAN : setValue(getBoolean()|v.getBoolean()); break;
case VALUE_TYPE_STRING : setValue(getString()+v.getString()); break;
default: break;
}
return this;
}
public Value divide(BigDecimal v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(double v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(long v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(int v) throws KettleValueException { return divide(new Value("tmp", (long)v)); }
public Value divide(byte v) throws KettleValueException { return divide(new Value("tmp", (long)v)); }
public Value divide(Value v) throws KettleValueException
{
if (isNull() || v.isNull())
{
setNull();
}
else
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().divide(v.getBigNumber(), BigDecimal.ROUND_UP)); break;
case VALUE_TYPE_NUMBER : setValue(getNumber()/v.getNumber()); break;
case VALUE_TYPE_INTEGER : setValue(getInteger()/v.getInteger()); break;
case VALUE_TYPE_BOOLEAN :
case VALUE_TYPE_STRING :
default:
throw new KettleValueException("Division can only be done with numeric data!");
}
}
return this;
}
public Value multiply(BigDecimal v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(double v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(long v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(int v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); }
public Value multiply(byte v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); }
public Value multiply(Value v) throws KettleValueException
{
// a number and a string!
if (isNull() || v.isNull())
{
setNull();
return this;
}
if ((v.isString() && isNumeric()) || (v.isNumeric() && isString()))
{
StringBuffer s;
String append="";
int n;
if (v.isString())
{
s=new StringBuffer(v.getString());
append=v.getString();
n=(int)getInteger();
}
else
{
s=new StringBuffer(getString());
append=getString();
n=(int)v.getInteger();
}
if (n==0) s.setLength(0);
else
for (int i=1;i<n;i++) s.append(append);
setValue(s);
}
else
// big numbers
if (isBigNumber() || v.isBigNumber())
{
setValue(getBigNumber().multiply(v.getBigNumber()));
}
else
// numbers
if (isNumber() || v.isNumber())
{
setValue(getNumber()*v.getNumber());
}
else
// integers
if (isInteger() || v.isInteger())
{
setValue(getInteger()*v.getInteger());
}
else
{
throw new KettleValueException("Multiplication can only be done with numbers or a number and a string!");
}
return this;
}
// FUNCTIONS!!
// implement the ABS function, arguments in args[]
public Value abs() throws KettleValueException
{
if (isNull()) return this;
if (isBigNumber())
{
setValue(getBigNumber().abs());
}
else
if (isNumber())
{
setValue(Math.abs(getNumber()));
}
else
if (isInteger())
{
setValue(Math.abs(getInteger()));
}
else
{
throw new KettleValueException("Function ABS only works with a number");
}
return this;
}
// implement the ACOS function, arguments in args[]
public Value acos() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.acos(getNumber()));
}
else
{
throw new KettleValueException("Function ACOS only works with numeric data");
}
return this;
}
// implement the ASIN function, arguments in args[]
public Value asin() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.asin(getNumber()));
}
else
{
throw new KettleValueException("Function ASIN only works with numeric data");
}
return this;
}
// implement the ATAN function, arguments in args[]
public Value atan() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.atan(getNumber()));
}
else
{
throw new KettleValueException("Function ATAN only works with numeric data");
}
return this;
}
// implement the ATAN2 function, arguments in args[]
public Value atan2(Value arg0) throws KettleValueException { return atan2(arg0.getNumber()); }
public Value atan2(double arg0) throws KettleValueException
{
if (isNull())
{
return this;
}
if (isNumeric())
{
setValue(Math.atan2(getNumber(), arg0));
}
else
{
throw new
KettleValueException("Function ATAN2 only works with numbers");
}
return this;
}
// implement the CEIL function, arguments in args[]
public Value ceil() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.ceil(getNumber()));
}
else
{
throw new KettleValueException("Function CEIL only works with a number");
}
return this;
}
// implement the COS function, arguments in args[]
public Value cos() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.cos(getNumber()));
}
else
{
throw new KettleValueException("Function COS only works with a number");
}
return this;
}
// implement the EXP function, arguments in args[]
public Value exp() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.exp(getNumber()));
}
else
{
throw new KettleValueException("Function EXP only works with a number");
}
return this;
}
// implement the FLOOR function, arguments in args[]
public Value floor() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.floor(getNumber()));
}
else
{
throw new KettleValueException("Function FLOOR only works with a number");
}
return this;
}
// implement the INITCAP function, arguments in args[]
public Value initcap()
{
if (isNull()) return this;
if (getString()==null)
{
setNull();
}
else
{
setValue( Const.initCap(getString()) );
}
return this;
}
// implement the LENGTH function, arguments in args[]
public Value length() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_INTEGER);
setValue(0L);
return this;
}
if (getType()==VALUE_TYPE_STRING)
{
setValue((double)getString().length());
}
else
{
throw new KettleValueException("Function LENGTH only works with a string");
}
return this;
}
// implement the LOG function, arguments in args[]
public Value log() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.log(getNumber()));
}
else
{
throw new KettleValueException("Function LOG only works with a number");
}
return this;
}
// implement the LOWER function, arguments in args[]
public Value lower()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
setValue( getString().toLowerCase() );
}
return this;
}
// implement the LPAD function: left pad strings or numbers...
public Value lpad(Value len) { return lpad((int)len.getNumber(), " "); }
public Value lpad(Value len, Value padstr) { return lpad((int)len.getNumber(), padstr.getString()); }
public Value lpad(int len) { return lpad(len, " "); }
public Value lpad(int len, String padstr)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()!=VALUE_TYPE_STRING) // also lpad other types!
{
setValue(getString());
}
if (getString()!=null)
{
StringBuffer result = new StringBuffer(getString());
int pad=len;
int l= ( pad-result.length() ) / padstr.length() + 1;
int i;
for (i=0;i<l;i++) result.insert(0, padstr);
// Maybe we added one or two too many!
i=result.length();
while (i>pad && pad>0)
{
result.deleteCharAt(0);
i--;
}
setValue(result.toString());
}
else
{
setNull();
}
}
setLength(len);
return this;
}
// implement the LTRIM function
public Value ltrim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getString()!=null)
{
StringBuffer s;
if (getType()==VALUE_TYPE_STRING)
{
s = new StringBuffer(getString());
}
else
{
s = new StringBuffer(toString());
}
// Left trim
while (s.length()>0 && s.charAt(0)==' ') s.deleteCharAt(0);
setValue(s);
}
else
{
setNull();
}
}
return this;
}
// implement the MOD function, arguments in args[]
public Value mod(Value arg) throws KettleValueException { return mod(arg.getNumber()); }
public Value mod(BigDecimal arg) throws KettleValueException { return mod(arg.doubleValue()); }
public Value mod(long arg) throws KettleValueException { return mod((double)arg); }
public Value mod(int arg) throws KettleValueException { return mod((double)arg); }
public Value mod(byte arg) throws KettleValueException { return mod((double)arg); }
public Value mod(double arg0) throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
double n1=getNumber();
double n2=arg0;
setValue( n1 - (n2 * Math.floor(n1 /n2 )) );
}
else
{
throw new KettleValueException("Function MOD only works with numeric data");
}
return this;
}
// implement the NVL function, arguments in args[]
public Value nvl(Value alt)
{
if (isNull()) setValue(alt);
return this;
}
// implement the POWER function, arguments in args[]
public Value power(BigDecimal arg) throws KettleValueException{ return power(new Value("tmp", arg)); }
public Value power(double arg) throws KettleValueException{ return power(new Value("tmp", arg)); }
public Value power(Value v) throws KettleValueException
{
if (isNull()) return this;
else if (isNumeric())
{
setValue( Math.pow(getNumber(), v.getNumber()) );
}
else
{
throw new KettleValueException("Function POWER only works with numeric data");
}
return this;
}
// implement the REPLACE function, arguments in args[]
public Value replace(Value repl, Value with) { return replace(repl.getString(), with.getString()); }
public Value replace(String repl, String with)
{
if (isNull()) return this;
if (getString()==null)
{
setNull();
}
else
{
setValue( Const.replace(getString(), repl, with) );
}
return this;
}
/**
* Rounds off to the nearest integer.<p>
* See also: java.lang.Math.round()
*
* @return The rounded Number value.
*/
public Value round() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( (double)Math.round(getNumber()) );
}
else
{
throw new KettleValueException("Function ROUND only works with a number");
}
return this;
}
/**
* Rounds the Number value to a certain number decimal places.
* @param decimalPlaces
* @return The rounded Number Value
* @throws KettleValueException in case it's not a number (or other problem).
*/
public Value round(int decimalPlaces) throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
if (isBigNumber())
{
// Multiply by 10^decimalPlaces
// For example 123.458343938437, Decimalplaces = 2
//
BigDecimal bigDec = getBigNumber();
// System.out.println("ROUND decimalPlaces : "+decimalPlaces+", bigNumber = "+bigDec);
bigDec = bigDec.setScale(decimalPlaces, BigDecimal.ROUND_HALF_EVEN);
// System.out.println("ROUND finished result : "+bigDec);
setValue( bigDec );
}
else
{
setValue( (double)Const.round(getNumber(), decimalPlaces) );
}
}
else
{
throw new KettleValueException("Function ROUND only works with a number");
}
return this;
}
// implement the RPAD function, arguments in args[]
public Value rpad(Value len) { return rpad((int)len.getNumber(), " "); }
public Value rpad(Value len, Value padstr) { return rpad((int)len.getNumber(), padstr.getString()); }
public Value rpad(int len) { return rpad(len, " "); }
public Value rpad(int len, String padstr)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()!=VALUE_TYPE_STRING) // also rpad other types!
{
setValue(getString());
}
if (getString()!=null)
{
StringBuffer result = new StringBuffer(getString());
int pad=len;
int l= ( pad-result.length() ) / padstr.length() + 1;
int i;
for (i=0;i<l;i++) result.append(padstr);
// Maybe we added one or two too many!
i=result.length();
while (i>pad && pad>0)
{
result.deleteCharAt(i-1);
i--;
}
setValue(result.toString());
}
else
{
setNull();
}
}
setLength(len);
return this;
}
// implement the RTRIM function, arguments in args[]
public Value rtrim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
StringBuffer s;
if (getType()==VALUE_TYPE_STRING)
{
s = new StringBuffer(getString());
}
else
{
s = new StringBuffer(toString());
}
// Right trim
while (s.length()>0 && s.charAt(s.length()-1)==' ') s.deleteCharAt(s.length()-1);
setValue(s);
}
return this;
}
// implement the SIGN function, arguments in args[]
public Value sign() throws KettleValueException
{
if (isNull()) return this;
if (isNumber())
{
int cmp = getBigNumber().compareTo(new BigDecimal(0L));
if (cmp>0) value.setBigNumber(new BigDecimal(1L));
else if (cmp<0) value.setBigNumber(new BigDecimal(-1L));
else value.setBigNumber(new BigDecimal(0L));
}
else
if (isNumber())
{
if (getNumber()>0) value.setNumber(1.0);
else if (getNumber()<0) value.setNumber(-1.0);
else value.setNumber(0.0);
}
else
if (isInteger())
{
if (getInteger()>0) value.setInteger(1);
else if (getInteger()<0) value.setInteger(-1);
else value.setInteger(0);
}
else
{
throw new KettleValueException("Function SIGN only works with a number");
}
return this;
}
// implement the SIN function, arguments in args[]
public Value sin() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.sin(getNumber()) );
}
else
{
throw new KettleValueException("Function SIN only works with a number");
}
return this;
}
// implement the SQRT function, arguments in args[]
public Value sqrt() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.sqrt(getNumber()) );
}
else
{
throw new KettleValueException("Function SQRT only works with a number");
}
return this;
}
// implement the SUBSTR function, arguments in args[]
public Value substr(Value from, Value to) { return substr((int)from.getNumber(), (int)to.getNumber()); }
public Value substr(Value from) { return substr((int)from.getNumber(), -1); }
public Value substr(int from) { return substr(from, -1); }
public Value substr(int from, int to)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
if (getString()!=null)
{
if (to<0 && from>=0)
{
setValue( getString().substring(from) );
}
else if (to>=0 && from>=0)
{
setValue( getString().substring(from, to) );
}
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
// implement the RIGHTSTR function, arguments in args[]
public Value rightstr(Value len) { return rightstr((int)len.getNumber()); }
public Value rightstr(int len)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
int tot_len = getString()!=null?getString().length():0;
if (tot_len>0)
{
int totlen = getString().length();
int f = totlen-len;
if (f<0) f=0;
setValue( getString().substring(f) );
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
// implement the LEFTSTR function, arguments in args[]
public Value leftstr(Value len)
{
return leftstr((int)len.getNumber());
}
public Value leftstr(int len)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
int tot_len = getString()!=null?getString().length():0;
if (tot_len>0)
{
int totlen = getString().length();
int f = totlen-len;
if (f>0)
{
setValue( getString().substring(0,len) );
}
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
public Value startsWith(Value string)
{
return startsWith(string.getString());
}
public Value startsWith(String string)
{
if (isNull())
{
setType(VALUE_TYPE_BOOLEAN);
return this;
}
if (string==null)
{
setValue(false);
setNull();
return this;
}
setValue( getString().startsWith(string) );
return this;
}
// implement the SYSDATE function, arguments in args[]
public Value sysdate()
{
setValue( Calendar.getInstance().getTime() );
return this;
}
// implement the TAN function, arguments in args[]
public Value tan() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.tan(getNumber()) );
}
else
{
throw new KettleValueException("Function TAN only works on a number");
}
return this;
}
// implement the TO_CHAR function, arguments in args[]
// number: NUM2STR( 123.456 ) : default format
// number: NUM2STR( 123.456, '###,##0.000') : format
// number: NUM2STR( 123.456, '###,##0.000', '.') : grouping
// number: NUM2STR( 123.456, '###,##0.000', '.', ',') : decimal
// number: NUM2STR( 123.456, '###,##0.000', '.', ',', '?') : currency
public Value num2str() throws KettleValueException { return num2str(null, null, null, null); }
public Value num2str(String format) throws KettleValueException { return num2str(format, null, null, null); }
public Value num2str(String format, String decimalSymbol) throws KettleValueException { return num2str(format, decimalSymbol, null, null); }
public Value num2str(String format, String decimalSymbol, String groupingSymbol) throws KettleValueException { return num2str(format, decimalSymbol, groupingSymbol, null); }
public Value num2str(String format, String decimalSymbol, String groupingSymbol, String currencySymbol) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
// Number to String conversion...
if (getType()==VALUE_TYPE_NUMBER || getType()==VALUE_TYPE_INTEGER)
{
NumberFormat nf = NumberFormat.getInstance();
DecimalFormat df = (DecimalFormat)nf;
DecimalFormatSymbols dfs =new DecimalFormatSymbols();
if (currencySymbol!=null && currencySymbol.length()>0) dfs.setCurrencySymbol( currencySymbol );
if (groupingSymbol!=null && groupingSymbol.length()>0) dfs.setGroupingSeparator( groupingSymbol.charAt(0) );
if (decimalSymbol!=null && decimalSymbol.length()>0) dfs.setDecimalSeparator( decimalSymbol.charAt(0) );
df.setDecimalFormatSymbols(dfs); // in case of 4, 3 or 2
if (format!=null && format.length()>0) df.applyPattern(format);
try
{
setValue( nf.format(getNumber()) );
}
catch(Exception e)
{
setType(VALUE_TYPE_STRING);
setNull();
throw new KettleValueException("Couldn't convert Number to String "+e.toString());
}
}
else
{
throw new KettleValueException("Function NUM2STR only works on Numbers and Integers");
}
}
return this;
}
// date: TO_CHAR( <date> , 'yyyy/mm/dd HH:mm:ss'
public Value dat2str() throws KettleValueException { return dat2str(null, null); }
public Value dat2str(String arg0) throws KettleValueException { return dat2str(arg0, null); }
public Value dat2str(String arg0, String arg1) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()==VALUE_TYPE_DATE)
{
SimpleDateFormat df = new SimpleDateFormat();
DateFormatSymbols dfs = new DateFormatSymbols();
if (arg1!=null) dfs.setLocalPatternChars(arg1);
if (arg0!=null) df.applyPattern(arg0);
try
{
setValue( df.format(getDate()) );
}
catch(Exception e)
{
setType(VALUE_TYPE_STRING);
setNull();
throw new KettleValueException("TO_CHAR Couldn't convert Date to String "+e.toString());
}
}
else
{
throw new KettleValueException("Function DAT2STR only works on a date");
}
}
return this;
}
// implement the TO_DATE function, arguments in args[]
public Value num2dat() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_DATE);
}
else
{
if (isNumeric())
{
setValue(new Date(getInteger()));
setLength(-1,-1);
}
else
{
throw new KettleValueException("Function NUM2DAT only works on a number");
}
}
return this;
}
public Value str2dat(String arg0) throws KettleValueException { return str2dat(arg0, null); }
public Value str2dat(String arg0, String arg1) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_DATE);
}
else
{
// System.out.println("Convert string ["+string+"] to date using pattern '"+arg0+"'");
SimpleDateFormat df = new SimpleDateFormat();
DateFormatSymbols dfs = new DateFormatSymbols();
if (arg1!=null) dfs.setLocalPatternChars(arg1);
if (arg0!=null) df.applyPattern(arg0);
try
{
value.setDate( df.parse(getString()) );
setType(VALUE_TYPE_DATE);
setLength(-1,-1);
}
catch(Exception e)
{
setType(VALUE_TYPE_DATE);
setNull();
throw new KettleValueException("TO_DATE Couldn't convert String to Date"+e.toString());
}
}
return this;
}
// implement the TO_NUMBER function, arguments in args[]
public Value str2num() throws KettleValueException { return str2num(null, null, null, null); }
public Value str2num(String pattern) throws KettleValueException { return str2num(pattern, null, null, null); }
public Value str2num(String pattern, String decimal) throws KettleValueException { return str2num(pattern, decimal, null, null); }
public Value str2num(String pattern, String decimal, String grouping) throws KettleValueException { return str2num(pattern, decimal, grouping, null); }
public Value str2num(String pattern, String decimal, String grouping, String currency) throws KettleValueException
{
// 0 : pattern
// 1 : Decimal separator
// 2 : Grouping separator
// 3 : Currency symbol
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()==VALUE_TYPE_STRING)
{
if (getString()==null)
{
setNull();
setValue(0.0);
}
else
{
NumberFormat nf = NumberFormat.getInstance();
DecimalFormat df = (DecimalFormat)nf;
DecimalFormatSymbols dfs =new DecimalFormatSymbols();
if ( !Const.isEmpty(pattern ) ) df.applyPattern( pattern );
if ( !Const.isEmpty(decimal ) ) dfs.setDecimalSeparator( decimal.charAt(0) );
if ( !Const.isEmpty(grouping) ) dfs.setGroupingSeparator( grouping.charAt(0) );
if ( !Const.isEmpty(currency) ) dfs.setCurrencySymbol( currency );
try
{
df.setDecimalFormatSymbols(dfs);
setValue( df.parse(getString()).doubleValue() );
}
catch(Exception e)
{
String message = "Couldn't convert string to number "+e.toString();
if ( !Const.isEmpty(pattern ) ) message+=" pattern="+pattern;
if ( !Const.isEmpty(decimal ) ) message+=" decimal="+decimal;
if ( !Const.isEmpty(grouping) ) message+=" grouping="+grouping.charAt(0);
if ( !Const.isEmpty(currency) ) message+=" currency="+currency;
throw new KettleValueException(message);
}
}
}
else
{
throw new KettleValueException("Function STR2NUM works only on strings");
}
}
return this;
}
public Value dat2num() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_INTEGER);
return this;
}
if (getType()==VALUE_TYPE_DATE)
{
if (getString()==null)
{
setNull();
setValue(0L);
}
else
{
setValue(getInteger());
}
}
else
{
throw new KettleValueException("Function DAT2NUM works only on dates");
}
return this;
}
/**
* Performs a right and left trim of spaces in the string.
* If the value is not a string a conversion to String is performed first.
*
* @return The trimmed string value.
*/
public Value trim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
String str = Const.trim(getString());
setValue(str);
return this;
}
// implement the UPPER function, arguments in args[]
public Value upper()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString().toUpperCase() );
return this;
}
// implement the E function, arguments in args[]
public Value e()
{
setValue(Math.E);
return this;
}
// implement the PI function, arguments in args[]
public Value pi()
{
setValue(Math.PI);
return this;
}
// implement the DECODE function, arguments in args[]
public Value v_decode(Value args[]) throws KettleValueException
{
int i;
boolean found;
// Decode takes as input the first argument...
// The next pair
// Limit to 3, 5, 7, 9, ... arguments
if (args.length>=3 && (args.length%2)==1)
{
i=0;
found=false;
while (i<args.length-1 && !found)
{
if (this.equals(args[i]))
{
setValue(args[i+1]);
found=true;
}
i+=2;
}
if (!found) setValue(args[args.length-1]);
}
else
{
// ERROR with nr of arguments
throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!");
}
return this;
}
// implement the IF function, arguments in args[]
// IF( <condition>, <then value>, <else value>)
public Value v_if(Value args[]) throws KettleValueException
{
if (getType()==VALUE_TYPE_BOOLEAN)
{
if (args.length==1)
{
if (getBoolean()) setValue(args[0]); else setNull();
}
else
if (args.length==2)
{
if (getBoolean()) setValue(args[0]); else setValue(args[1]);
}
}
else
{
throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!");
}
return this;
}
// implement the ADD_MONTHS function, one argument
public Value add_months(int months) throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
if (!isNull() && getDate()!=null)
{
Calendar cal = Calendar.getInstance();
cal.setTime(getDate());
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
month+=months;
int newyear = year+(int)Math.floor(month/12);
int newmonth = month%12;
cal.set(newyear, newmonth, 1);
int newday = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
if (newday<day) cal.set(Calendar.DAY_OF_MONTH, newday);
else cal.set(Calendar.DAY_OF_MONTH, day);
setValue( cal.getTime() );
}
}
else
{
throw new KettleValueException("Function add_months only works on a date!");
}
return this;
}
/**
* Add a number of days to a Date value.
*
* @param days The number of days to add to the current date value
* @return The resulting value
* @throws KettleValueException
*/
public Value add_days(long days) throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
if (!isNull() && getDate()!=null)
{
Calendar cal = Calendar.getInstance();
cal.setTime(getDate());
cal.add(Calendar.DAY_OF_YEAR, (int)days);
setValue( cal.getTime() );
}
}
else
{
throw new KettleValueException("Function add_days only works on a date!");
}
return this;
}
// implement the LAST_DAY function, arguments in args[]
public Value last_day() throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
int last_day = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, last_day);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function last_day only works on a date");
}
return this;
}
public Value first_day() throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
cal.set(Calendar.DAY_OF_MONTH, 1);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function first_day only works on a date");
}
return this;
}
// implement the TRUNC function, version without arguments
public Value trunc() throws KettleValueException
{
if (isNull()) return this; // don't do anything, leave it at NULL!
if (isBigNumber())
{
getBigNumber().setScale(0, BigDecimal.ROUND_FLOOR);
}
else
if (isNumber())
{
setValue( Math.floor(getNumber()) );
}
else
if (isInteger())
{
// Nothing
}
else
if (isDate())
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.HOUR_OF_DAY, 0);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function TRUNC only works on numbers and dates");
}
return this;
}
// implement the TRUNC function, arguments in args[]
public Value trunc(double level) throws KettleValueException { return trunc((int)level); }
public Value trunc(int level) throws KettleValueException
{
if (isNull()) return this; // don't do anything, leave it at NULL!
if (isBigNumber())
{
getBigNumber().setScale(level, BigDecimal.ROUND_FLOOR);
}
else
if (isNumber())
{
double pow=Math.pow(10, level);
setValue( Math.floor( getNumber() * pow ) / pow );
}
else
if (isInteger())
{
// Nothing!
}
else
if (isDate())
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
switch((int)level)
{
// MONTHS
case 5: cal.set(Calendar.MONTH, 1);
// DAYS
case 4: cal.set(Calendar.DAY_OF_MONTH, 1);
// HOURS
case 3: cal.set(Calendar.HOUR_OF_DAY, 0);
// MINUTES
case 2: cal.set(Calendar.MINUTE, 0);
// SECONDS
case 1: cal.set(Calendar.SECOND, 0);
// MILI-SECONDS
case 0: cal.set(Calendar.MILLISECOND, 0); break;
default:
throw new KettleValueException("Argument of TRUNC of date has to be between 0 and 5");
}
}
else
{
throw new KettleValueException("Function TRUNC only works with numbers and dates");
}
return this;
}
/**
* Change a string into its hexadecimal representation. E.g. if Value
* contains string "a" afterwards it would contain value "61".
*
* Note that transformations happen in groups of 2 hex characters, so
* the value of a characters is always in the range 0-255.
*
* @return Value itself
* @throws KettleValueException
*/
public Value byteToHexEncode()
{
final char hexDigits[] =
{ '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
setType(VALUE_TYPE_STRING);
if (isNull())
{
return this;
}
String hex = getString();
char[] s = hex.toCharArray();
StringBuffer hexString = new StringBuffer(2 * s.length);
for (int i = 0; i < s.length; i++)
{
hexString.append(hexDigits[(s[i] & 0x00F0) >> 4]); // hi nibble
hexString.append(hexDigits[s[i] & 0x000F]); // lo nibble
}
setValue( hexString );
return this;
}
/**
* Change a hexadecimal string into normal ASCII representation. E.g. if Value
* contains string "61" afterwards it would contain value "a". If the
* hexadecimal string is of odd length a leading zero will be used.
*
* Note that only the low byte of a character will be processed, this
* is for binary transformations.
*
* @return Value itself
* @throws KettleValueException
*/
public Value hexToByteDecode() throws KettleValueException
{
setType(VALUE_TYPE_STRING);
if (isNull())
{
return this;
}
setValue( getString() );
String hexString = getString();
int len = hexString.length();
char chArray[] = new char[(len + 1) / 2];
boolean evenByte = true;
int nextByte = 0;
// we assume a leading 0 if the length is not even.
if ((len % 2) == 1)
evenByte = false;
int nibble;
int i, j;
for (i = 0, j = 0; i < len; i++)
{
char c = hexString.charAt(i);
if ((c >= '0') && (c <= '9'))
nibble = c - '0';
else if ((c >= 'A') && (c <= 'F'))
nibble = c - 'A' + 0x0A;
else if ((c >= 'a') && (c <= 'f'))
nibble = c - 'a' + 0x0A;
else
throw new KettleValueException("invalid hex digit '" + c + "'.");
if (evenByte)
{
nextByte = (nibble << 4);
}
else
{
nextByte += nibble;
chArray[j] = (char)nextByte;
j++;
}
evenByte = ! evenByte;
}
setValue(new String(chArray));
return this;
}
/**
* Change a string into its hexadecimal representation. E.g. if Value
* contains string "a" afterwards it would contain value "0061".
*
* Note that transformations happen in groups of 4 hex characters, so
* the value of a characters is always in the range 0-65535.
*
* @return Value itself
* @throws KettleValueException
*/
public Value charToHexEncode()
{
final char hexDigits[] =
{ '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
setType(VALUE_TYPE_STRING);
if (isNull())
{
return this;
}
String hex = getString();
char[] s = hex.toCharArray();
StringBuffer hexString = new StringBuffer(2 * s.length);
for (int i = 0; i < s.length; i++)
{
hexString.append(hexDigits[(s[i] & 0xF000) >> 12]); // hex 1
hexString.append(hexDigits[(s[i] & 0x0F00) >> 8]); // hex 2
hexString.append(hexDigits[(s[i] & 0x00F0) >> 4]); // hex 3
hexString.append(hexDigits[s[i] & 0x000F]); // hex 4
}
setValue( hexString );
return this;
}
/**
* Change a hexadecimal string into normal ASCII representation. E.g. if Value
* contains string "61" afterwards it would contain value "a". If the
* hexadecimal string is of a wrong length leading zeroes will be used.
*
* Note that transformations happen in groups of 4 hex characters, so
* the value of a characters is always in the range 0-65535.
*
* @return Value itself
* @throws KettleValueException
*/
public Value hexToCharDecode() throws KettleValueException
{
setType(VALUE_TYPE_STRING);
if (isNull())
{
return this;
}
setValue( getString() );
String hexString = getString();
int len = hexString.length();
char chArray[] = new char[(len + 3) / 4];
int charNr;
int nextChar = 0;
// we assume a leading 0s if the length is not right.
charNr = (len % 4);
if ( charNr == 0 ) charNr = 4;
int nibble;
int i, j;
for (i = 0, j = 0; i < len; i++)
{
char c = hexString.charAt(i);
if ((c >= '0') && (c <= '9'))
nibble = c - '0';
else if ((c >= 'A') && (c <= 'F'))
nibble = c - 'A' + 0x0A;
else if ((c >= 'a') && (c <= 'f'))
nibble = c - 'a' + 0x0A;
else
throw new KettleValueException("invalid hex digit '" + c + "'.");
if (charNr == 4)
{
nextChar = (nibble << 12);
charNr--;
}
else if (charNr == 3)
{
nextChar += (nibble << 8);
charNr--;
}
else if (charNr == 2)
{
nextChar += (nibble << 4);
charNr--;
}
else // charNr == 1
{
nextChar += nibble;
chArray[j] = (char)nextChar;
charNr = 4;
j++;
}
}
setValue(new String(chArray));
return this;
}
/*
* Some javascript extensions...
*/
public static final Value getInstance() { return new Value(); }
public String getClassName() { return "Value"; }
public void jsConstructor()
{
}
public void jsConstructor(String name)
{
setName(name);
}
public void jsConstructor(String name, String value)
{
setName(name);
setValue(value);
}
/**
* Produce the XML representation of this value.
* @return a String containing the XML to represent this Value.
*/
public String getXML()
{
StringBuffer retval = new StringBuffer(128);
retval.append(XMLHandler.addTagValue("name", getName(), false));
retval.append(XMLHandler.addTagValue("type", getTypeDesc(), false));
retval.append(XMLHandler.addTagValue("text", toString(false), false));
retval.append(XMLHandler.addTagValue("length", getLength(), false));
retval.append(XMLHandler.addTagValue("precision", getPrecision(), false));
retval.append(XMLHandler.addTagValue("isnull", isNull(), false));
return retval.toString();
}
/**
* Construct a new Value and read the data from XML
* @param valnode The XML Node to read from.
*/
public Value(Node valnode)
{
this();
loadXML(valnode);
}
/**
* Read the data for this Value from an XML Node
* @param valnode The XML Node to read from
* @return true if all went well, false if something went wrong.
*/
public boolean loadXML(Node valnode)
{
try
{
String valname = XMLHandler.getTagValue(valnode, "name");
int valtype = getType( XMLHandler.getTagValue(valnode, "type") );
String text = XMLHandler.getTagValue(valnode, "text");
boolean isnull = "Y".equalsIgnoreCase(XMLHandler.getTagValue(valnode, "isnull"));
int len = Const.toInt(XMLHandler.getTagValue(valnode, "length"), -1);
int prec = Const.toInt(XMLHandler.getTagValue(valnode, "precision"), -1);
setName(valname);
setValue(text);
setLength(len, prec);
if (valtype!=VALUE_TYPE_STRING)
{
trim();
convertString(valtype);
}
if (isnull) setNull();
}
catch(Exception e)
{
setNull();
return false;
}
return true;
}
/**
* Convert this Value from type String to another type
* @param newtype The Value type to convert to.
*/
public void convertString(int newtype) throws KettleValueException
{
switch(newtype)
{
case VALUE_TYPE_STRING : break;
case VALUE_TYPE_NUMBER : setValue( getNumber() ); break;
case VALUE_TYPE_DATE : setValue( getDate() ); break;
case VALUE_TYPE_BOOLEAN : setValue( getBoolean() ); break;
case VALUE_TYPE_INTEGER : setValue( getInteger() ); break;
case VALUE_TYPE_BIGNUMBER : setValue( getBigNumber() ); break;
default:
throw new KettleValueException("Please specify the type to convert to from String type.");
}
}
public Value(Repository rep, long id_value)
throws KettleException
{
try
{
Row r = rep.getValue(id_value);
if (r!=null)
{
name = r.getString("NAME", null);
String valstr = r.getString("VALUE_STR", null);
setValue( valstr );
int valtype = getType( r.getString("VALUE_TYPE", null) );
setType(valtype);
setNull( r.getBoolean("IS_NULL", false) );
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to load Value from repository with id_value="+id_value, dbe);
}
}
/**
* Returns whether "types" of the values are exactly the same: type,
* name, length, precision.
*
* @param v Value to compare type against.
*
* @return == true when types are the same
* == false when the types differ
*/
public boolean equalValueType(Value v)
{
if (v == null)
return false;
if (getType() != v.getType())
return false;
if ((getName() == null && v.getName() != null) ||
(getName() != null && v.getName() == null) ||
!(getName().equals(v.getName())))
return false;
if (getLength() != v.getLength())
return false;
if (getPrecision() != v.getPrecision())
return false;
return true;
}
}
| src/be/ibridge/kettle/core/value/Value.java | /**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.core.value;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import org.w3c.dom.Node;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.XMLInterface;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleEOFException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleFileException;
import be.ibridge.kettle.core.exception.KettleValueException;
import be.ibridge.kettle.repository.Repository;
/**
* This class is one of the core classes of the Kettle framework.
* It contains everything you need to manipulate atomic data (Values/Fields/...)
* and to describe it in the form of meta-data. (name, length, precision, etc.)
*
* @author Matt
* @since Beginning 2003
*/
public class Value implements Cloneable, XMLInterface, Serializable
{
private static final long serialVersionUID = -6310073485210258622L;
/**
* Value type indicating that the value has no type set.
*/
public static final int VALUE_TYPE_NONE = 0;
/**
* Value type indicating that the value contains a floating point double precision number.
*/
public static final int VALUE_TYPE_NUMBER = 1;
/**
* Value type indicating that the value contains a text String.
*/
public static final int VALUE_TYPE_STRING = 2;
/**
* Value type indicating that the value contains a Date.
*/
public static final int VALUE_TYPE_DATE = 3;
/**
* Value type indicating that the value contains a boolean.
*/
public static final int VALUE_TYPE_BOOLEAN = 4;
/**
* Value type indicating that the value contains a long integer.
*/
public static final int VALUE_TYPE_INTEGER = 5;
/**
* Value type indicating that the value contains a floating point precision number with arbitrary precision.
*/
public static final int VALUE_TYPE_BIGNUMBER = 6;
/**
* Value type indicating that the value contains an Object.
*/
public static final int VALUE_TYPE_SERIALIZABLE= 7;
/**
* Value type indicating that the value contains binary data:
* BLOB, CLOB, ...
*/
public static final int VALUE_TYPE_BINARY = 8;
/**
* The descriptions of the value types.
*/
private static final String valueTypeCode[]=
{
"-", // $NON-NLS-1$
"Number", "String", "Date", "Boolean", "Integer", "BigNumber", "Serializable", "Binary" // $NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$ $NON-NLS-4$ $NON-NLS-5$ $NON-NLS-6$ $NON-NLS-7$
};
private ValueInterface value;
private String name;
private String origin;
private boolean NULL;
/**
* Constructs a new Value of type EMPTY
*
*/
public Value()
{
clearValue();
}
/**
* Constructs a new Value with a name.
*
* @param name Sets the name of the Value
*/
public Value(String name)
{
clearValue();
setName(name);
}
/**
* Constructs a new Value with a name and a type.
*
* @param name Sets the name of the Value
* @param val_type Sets the type of the Value (Value.VALUE_TYPE_*)
*/
public Value(String name, int val_type)
{
clearValue();
newValue(val_type);
setName(name);
}
/**
* This method allocates a new value of the appropriate type..
* @param val_type The new type of value
*/
private void newValue(int val_type)
{
switch(val_type)
{
case VALUE_TYPE_INTEGER : value = new ValueInteger(); break;
case VALUE_TYPE_STRING : value = new ValueString(); break;
case VALUE_TYPE_DATE : value = new ValueDate(); break;
case VALUE_TYPE_NUMBER : value = new ValueNumber(); break;
case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(); break;
case VALUE_TYPE_BIGNUMBER: value = new ValueBigNumber(); break;
case VALUE_TYPE_BINARY : value = new ValueBinary(); break;
default: value = null;
}
}
/**
* Convert the value to another type. This only works if a value has been set previously.
* That is the reason this method is private. Rather, use the public method setType(int type).
*
* @param valType The type to convert to.
*/
private void convertTo(int valType)
{
if (value!=null)
{
switch(valType)
{
case VALUE_TYPE_NUMBER : value = new ValueNumber(value.getNumber()); break;
case VALUE_TYPE_STRING : value = new ValueString(value.getString()); break;
case VALUE_TYPE_DATE : value = new ValueDate(value.getDate()); break;
case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(value.getBoolean()); break;
case VALUE_TYPE_INTEGER : value = new ValueInteger(value.getInteger()); break;
case VALUE_TYPE_BIGNUMBER : value = new ValueBigNumber(value.getBigNumber()); break;
case VALUE_TYPE_BINARY : value = new ValueBinary(value.getBytes()); break;
default: value = null;
}
}
}
/**
* Constructs a new Value with a name, a type, length and precision.
*
* @param name Sets the name of the Value
* @param valType Sets the type of the Value (Value.VALUE_TYPE_*)
* @param length The length of the value
* @param precision The precision of the value
*/
public Value(String name, int valType, int length, int precision)
{
this(name, valType);
setLength(length, precision);
}
/**
* Constructs a new Value of Type VALUE_TYPE_BIGNUMBER, with a name, containing a BigDecimal number
*
* @param name Sets the name of the Value
* @param bignum The number to store in this Value
*/
public Value(String name, BigDecimal bignum)
{
clearValue();
setValue(bignum);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_NUMBER, with a name, containing a number
*
* @param name Sets the name of the Value
* @param num The number to store in this Value
*/
public Value(String name, double num)
{
clearValue();
setValue(num);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String
*
* @param name Sets the name of the Value
* @param str The text to store in this Value
*/
public Value(String name, StringBuffer str)
{
this(name, str.toString());
}
/**
* Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String
*
* @param name Sets the name of the Value
* @param str The text to store in this Value
*/
public Value(String name, String str)
{
clearValue();
setValue(str);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_DATE, with a name, containing a Date
*
* @param name Sets the name of the Value
* @param dat The date to store in this Value
*/
public Value(String name, Date dat)
{
clearValue();
setValue(dat);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_BOOLEAN, with a name, containing a boolean value
*
* @param name Sets the name of the Value
* @param bool The boolean to store in this Value
*/
public Value(String name, boolean bool)
{
clearValue();
setValue(bool);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_INTEGER, with a name, containing an integer number
*
* @param name Sets the name of the Value
* @param l The integer to store in this Value
*/
public Value(String name, long l)
{
clearValue();
setValue(l);
setName(name);
}
/**
* Constructs a new Value as a copy of another value and renames it...
*
* @param name The new name of the copied Value
* @param v The value to be copied
*/
public Value(String name, Value v)
{
this(v);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_BINARY, with a name, containing a bytes value
*
* @param name Sets the name of the Value
* @param b The bytes to store in this Value
*/
public Value(String name, byte[] b)
{
clearValue();
setValue(b);
setName(name);
}
/**
* Constructs a new Value as a copy of another value
*
* @param v The Value to be copied
*/
public Value(Value v)
{
if (v!=null)
{
setType(v.getType());
value = v.getValueCopy();
setName(v.getName());
setLength(v.getLength(), v.getPrecision());
setNull(v.isNull());
setOrigin(v.origin);
}
else
{
clearValue();
setNull(true);
}
}
public Object clone()
{
Value retval = null;
try
{
retval = (Value)super.clone();
if (value!=null) retval.value = (ValueInterface) value.clone();
}
catch(CloneNotSupportedException e)
{
retval=null;
}
return retval;
}
/**
* Build a copy of this Value
* @return a copy of another value
*
*/
public Value Clone()
{
Value v = new Value(this);
return v;
}
/**
* Clears the content and name of a Value
*/
public void clearValue()
{
value = null;
name = null;
NULL = false;
origin = null;
}
private ValueInterface getValueCopy()
{
if (value==null) return null;
return (ValueInterface)value.clone();
}
/**
* Sets the name of a Value
*
* @param name The new name of the value
*/
public void setName(String name)
{
this.name = name;
}
/**
* Obtain the name of a Value
*
* @return The name of the Value
*/
public String getName()
{
return name;
}
/**
* This method allows you to set the origin of the Value by means of the name of the originating step.
*
* @param step_of_origin The step of origin.
*/
public void setOrigin(String step_of_origin)
{
origin = step_of_origin;
}
/**
* Obtain the origin of the step.
*
* @return The name of the originating step
*/
public String getOrigin()
{
return origin;
}
/**
* Sets the value to a BigDecimal number value.
* @param num The number value to set the value to
*/
public void setValue(BigDecimal num)
{
if (value==null || value.getType()!=VALUE_TYPE_BIGNUMBER) value = new ValueBigNumber(num);
else value.setBigNumber(num);
setNull(false);
}
/**
* Sets the value to a double Number value.
* @param num The number value to set the value to
*/
public void setValue(double num)
{
if (value==null || value.getType()!=VALUE_TYPE_NUMBER) value = new ValueNumber(num);
else value.setNumber(num);
setNull(false);
}
/**
* Sets the Value to a String text
* @param str The StringBuffer to get the text from
*/
public void setValue(StringBuffer str)
{
if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str.toString());
else value.setString(str.toString());
setNull(str==null);
}
/**
* Sets the Value to a String text
* @param str The String to get the text from
*/
public void setValue(String str)
{
if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str);
else value.setString(str);
setNull(str==null);
}
public void setSerializedValue(Serializable ser) {
if (value==null || value.getType()!=VALUE_TYPE_SERIALIZABLE) value = new ValueSerializable(ser);
else value.setSerializable(ser);
setNull(ser==null);
}
/**
* Sets the Value to a Date
* @param dat The Date to set the Value to
*/
public void setValue(Date dat)
{
if (value==null || value.getType()!=VALUE_TYPE_DATE) value = new ValueDate(dat);
else value.setDate(dat);
setNull(dat==null);
}
/**
* Sets the Value to a boolean
* @param bool The boolean to set the Value to
*/
public void setValue(boolean bool)
{
if (value==null || value.getType()!=VALUE_TYPE_BOOLEAN) value = new ValueBoolean(bool);
else value.setBoolean(bool);
setNull(false);
}
/**
* Sets the Value to a long integer
* @param b The byte to convert to a long integer to which the Value is set.
*/
public void setValue(byte b)
{
setValue((long)b);
}
/**
* Sets the Value to a long integer
* @param i The integer to convert to a long integer to which the Value is set.
*/
public void setValue(int i)
{
setValue((long)i);
}
/**
* Sets the Value to a long integer
* @param l The long integer to which the Value is set.
*/
public void setValue(long l)
{
if (value==null || value.getType()!=VALUE_TYPE_INTEGER) value = new ValueInteger(l);
else value.setInteger(l);
setNull(false);
}
/**
* Sets the Value to a byte array
* @param b The byte array to which the Value has to be set.
*/
public void setValue(byte[] b)
{
if (value==null || value.getType()!=VALUE_TYPE_BINARY) value = new ValueBinary(b);
else value.setBytes(b);
if ( b == null )
setNull(true);
else
setNull(false);
}
/**
* Copy the Value from another Value.
* It doesn't copy the name.
* @param v The Value to copy the settings and value from
*/
public void setValue(Value v)
{
if (v!=null)
{
value = v.getValueCopy();
setNull(v.isNull());
setOrigin(v.origin);
}
else
{
clearValue();
}
}
/**
* Get the BigDecimal number of this Value.
* If the value is not of type BIG_NUMBER, a conversion is done first.
* @return the double precision floating point number of this Value.
*/
public BigDecimal getBigNumber()
{
if (value==null || isNull()) return null;
return value.getBigNumber();
}
/**
* Get the double precision floating point number of this Value.
* If the value is not of type NUMBER, a conversion is done first.
* @return the double precision floating point number of this Value.
*/
public double getNumber()
{
if (value==null || isNull()) return 0.0;
return value.getNumber();
}
/**
* Get the String text representing this value.
* If the value is not of type STRING, a conversion if done first.
* @return the String text representing this value.
*/
public String getString()
{
if (value==null || isNull()) return null;
return value.getString();
}
/**
* Get the length of the String representing this value.
* @return the length of the String representing this value.
*/
public int getStringLength()
{
String s = getString();
if (s==null) return 0;
return s.length();
}
/**
* Get the Date of this Value.
* If the Value is not of type DATE, a conversion is done first.
* @return the Date of this Value.
*/
public Date getDate()
{
if (value==null || isNull()) return null;
return value.getDate();
}
/**
* Get the Serializable of this Value.
* If the Value is not of type Serializable, it returns null.
* @return the Serializable of this Value.
*/
public Serializable getSerializable()
{
if (value==null || isNull() || value.getType() != VALUE_TYPE_SERIALIZABLE) return null;
return value.getSerializable();
}
/**
* Get the boolean value of this Value.
* If the Value is not of type BOOLEAN, it will be converted.
* <p>Strings: "YES", "Y", "TRUE" (case insensitive) to true, the rest false
* <p>Number: 0.0 is false, the rest is true.
* <p>Integer: 0 is false, the rest is true.
* <p>Date: always false.
* @return the boolean representation of this Value.
*/
public boolean getBoolean()
{
if (value==null || isNull()) return false;
return value.getBoolean();
}
/**
* Get the long integer representation of this value.
* If the Value is not of type INTEGER, it will be converted:
* <p>String: try to convert to a long value, 0L if it didn't work.
* <p>Number: round the double value and return the resulting long integer.
* <p>Date: return the number of miliseconds after <code>1970:01:01 00:00:00</code>
* <p>Date: always false.
*
* @return the long integer representation of this value.
*/
public long getInteger()
{
if (value==null || isNull()) return 0L;
return value.getInteger();
}
public byte[] getBytes()
{
if (value==null || isNull()) return null;
return value.getBytes();
}
/**
* Set the type of this Value
* @param val_type The type to which the Value will be set.
*/
public void setType(int val_type)
{
if (value==null) newValue(val_type);
else // Convert the value to the appropriate type...
{
convertTo(val_type);
}
}
/**
* Returns the type of this Value
* @return the type of this Value
*/
public int getType()
{
if (value==null) return VALUE_TYPE_NONE;
return value.getType();
}
/**
* Checks whether or not this Value is empty.
* A value is empty if it has the type VALUE_TYPE_EMPTY
* @return true if the value is empty.
*/
public boolean isEmpty()
{
if (value==null) return true;
return false;
}
/**
* Checks wheter or not the value is a String.
* @return true if the value is a String.
*/
public boolean isString()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_STRING;
}
/**
* Checks whether or not this value is a Date
* @return true if the value is a Date
*/
public boolean isDate()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_DATE;
}
/**
* Checks whether or not the value is a Big Number
* @return true is this value is a big number
*/
public boolean isBigNumber()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_BIGNUMBER;
}
/**
* Checks whether or not the value is a Number
* @return true is this value is a number
*/
public boolean isNumber()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_NUMBER;
}
/**
* Checks whether or not this value is a boolean
* @return true if this value has type boolean.
*/
public boolean isBoolean()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_BOOLEAN;
}
/**
* Checks whether or not this value is of type Serializable
* @return true if this value has type Serializable
*/
public boolean isSerializableType() {
if(value == null) {
return false;
}
return value.getType() == VALUE_TYPE_SERIALIZABLE;
}
/**
* Checks whether or not this value is of type Binary
* @return true if this value has type Binary
*/
public boolean isBinary() {
// Serializable is not included here as it used for
// internal purposes only.
if(value == null) {
return false;
}
return value.getType() == VALUE_TYPE_BINARY;
}
/**
* Checks whether or not this value is an Integer
* @return true if this value is an integer
*/
public boolean isInteger()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_INTEGER;
}
/**
* Checks whether or not this Value is Numeric
* A Value is numeric if it is either of type Number or Integer
* @return true if the value is either of type Number or Integer
*/
public boolean isNumeric()
{
return isInteger() || isNumber() || isBigNumber();
}
/**
* Checks whether or not the specified type is either Integer or Number
* @param t the type to check
* @return true if the type is Integer or Number
*/
public static final boolean isNumeric(int t)
{
return t==VALUE_TYPE_INTEGER || t==VALUE_TYPE_NUMBER || t==VALUE_TYPE_BIGNUMBER;
}
/**
* Returns a padded to length String text representation of this Value
* @return a padded to length String text representation of this Value
*/
public String toString()
{
return toString(true);
}
/**
* a String text representation of this Value, optionally padded to the specified length
* @param pad true if you want to pad the resulting String
* @return a String text representation of this Value, optionally padded to the specified length
*/
public String toString(boolean pad)
{
String retval;
switch(getType())
{
case VALUE_TYPE_STRING : retval=toStringString(pad); break;
case VALUE_TYPE_INTEGER: retval=toStringInteger(pad); break;
case VALUE_TYPE_NUMBER : retval=toStringNumber(pad); break;
case VALUE_TYPE_DATE : retval=toStringDate(); break;
case VALUE_TYPE_BOOLEAN: retval=toStringBoolean(); break;
case VALUE_TYPE_BIGNUMBER: retval=toStringBigNumber(pad); break;
case VALUE_TYPE_BINARY : retval=toStringBinary(pad); break;
default: retval=""; break;
}
return retval;
}
/**
* a String text representation of this Value, optionally padded to the specified length
* @return a String text representation of this Value, optionally padded to the specified length
*/
public String toStringMeta()
{
// We (Sven Boden) did explicit performance testing for this
// part. The original version used Strings instead of StringBuffers,
// performance between the 2 does not differ that much. A few milliseconds
// on 100000 iterations in the advantage of StringBuffers. The
// lessened creation of objects may be worth it in the long run.
StringBuffer retval=new StringBuffer(getTypeDesc());
switch(getType())
{
case VALUE_TYPE_STRING :
if (getLength()>0) retval.append('(').append(getLength()).append(')');
break;
case VALUE_TYPE_NUMBER :
case VALUE_TYPE_BIGNUMBER :
if (getLength()>0)
{
retval.append('(').append(getLength());
if (getPrecision()>0)
{
retval.append(", ").append(getPrecision());
}
retval.append(')');
}
break;
case VALUE_TYPE_INTEGER:
if (getLength()>0)
{
retval.append('(').append(getLength()).append(')');
}
break;
default: break;
}
return retval.toString();
}
/**
* Converts a String Value to String optionally padded to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringString(boolean pad)
{
String retval=null;
if (value==null) return null;
if (value.getLength()<=0) // No length specified!
{
if (isNull() || value.getString()==null)
retval = Const.NULL_STRING;
else
retval = value.getString();
}
else
{
StringBuffer ret;
if (isNull() || value.getString()==null) ret=new StringBuffer(Const.NULL_STRING);
else ret=new StringBuffer(value.getString());
if (pad)
{
int length = value.getLength();
if (length>16384) length=16384; // otherwise we get OUT OF MEMORY errors for CLOBS.
Const.rightPad(ret, length);
}
retval=ret.toString();
}
return retval;
}
/**
* Converts a Number value to a String, optionally padding the result to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringNumber(boolean pad)
{
String retval;
if (value==null) return null;
if (pad)
{
if (value.getLength()<1)
{
if (isNull()) retval=Const.NULL_NUMBER;
else
{
DecimalFormat form= new DecimalFormat();
form.applyPattern(" ##########0.0########;-#########0.0########");
// System.out.println("local.pattern = ["+form.toLocalizedPattern()+"]");
retval=form.format(value.getNumber());
}
}
else
{
if (isNull())
{
StringBuffer ret=new StringBuffer(Const.NULL_NUMBER);
Const.rightPad(ret, value.getLength());
retval=ret.toString();
}
else
{
StringBuffer fmt=new StringBuffer();
int i;
DecimalFormat form;
if (value.getNumber()>=0) fmt.append(' '); // to compensate for minus sign.
if (value.getPrecision()<0) // Default: two decimals
{
for (i=0;i<value.getLength();i++) fmt.append('0');
fmt.append(".00"); // for the .00
}
else // Floating point format 00001234,56 --> (12,2)
{
for (i=0;i<=value.getLength();i++) fmt.append('0'); // all zeroes.
int pos = value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0);
if (pos>=0 && pos <fmt.length())
{
fmt.setCharAt(value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0), '.'); // one 'comma'
}
}
form= new DecimalFormat(fmt.toString());
retval=form.format(value.getNumber());
}
}
}
else
{
if (isNull()) retval=Const.NULL_NUMBER;
else retval=Double.toString(value.getNumber());
}
return retval;
}
/**
* Converts a Date value to a String.
* The date has format: <code>yyyy/MM/dd HH:mm:ss.SSS</code>
* @return a String representing the Date Value.
*/
private String toStringDate()
{
String retval;
if (value==null) return null;
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS", Locale.US);
if (isNull() || value.getDate()==null) retval=Const.NULL_DATE;
else
{
retval=df.format(value.getDate()).toString();
}
/*
This code was removed as TYPE_VALUE_DATE does not know "length", so this
could never be called anyway
else
{
StringBuffer ret;
if (isNull() || value.getDate()==null)
ret=new StringBuffer(Const.NULL_DATE);
else ret=new StringBuffer(df.format(value.getDate()).toString());
Const.rightPad(ret, getLength()<=10?10:getLength());
retval=ret.toString();
}
*/
return retval;
}
/**
* Returns a String representing the boolean value.
* It will be either "true" or "false".
*
* @return a String representing the boolean value.
*/
private String toStringBoolean()
{
// Code was removed from this method as ValueBoolean
// did not store length, so some parts could never be
// called.
String retval;
if (value==null) return null;
if (isNull())
{
retval=Const.NULL_BOOLEAN;
}
else
{
retval=value.getBoolean()?"true":"false";
}
return retval;
}
/**
* Converts an Integer value to a String, optionally padding the result to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringInteger(boolean pad)
{
String retval;
if (value==null) return null;
if (getLength()<1)
{
if (isNull()) retval=Const.NULL_INTEGER;
else
{
DecimalFormat form= new DecimalFormat(" ###############0;-###############0");
retval=form.format(value.getInteger());
}
}
else
{
if (isNull())
{
StringBuffer ret=new StringBuffer(Const.NULL_INTEGER);
Const.rightPad(ret, getLength());
retval=ret.toString();
}
else
{
if (pad)
{
StringBuffer fmt=new StringBuffer();
int i;
DecimalFormat form;
if (value.getInteger()>=0) fmt.append(' '); // to compensate for minus sign.
int len = getLength();
for (i=0;i<len;i++) fmt.append('0'); // all zeroes.
form= new DecimalFormat(fmt.toString());
retval=form.format(value.getInteger());
}
else
{
retval = Long.toString(value.getInteger());
}
}
}
return retval;
}
/**
* Converts a BigNumber value to a String, optionally padding the result to the specified length. // TODO: BigNumber padding
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringBigNumber(boolean pad)
{
if (value.getBigNumber()==null) return null;
String retval = value.getString();
// Localise . to ,
if (Const.DEFAULT_DECIMAL_SEPARATOR!='.')
{
retval = retval.replace('.', Const.DEFAULT_DECIMAL_SEPARATOR);
}
return retval;
}
/**
* Returns a String representing the binary value.
*
* @return a String representing the binary value.
*/
private String toStringBinary(boolean pad)
{
String retval;
if (value==null) return null;
if (isNull() || value.getBytes() == null)
{
retval=Const.NULL_BINARY;
}
else
{
retval = new String(value.getBytes());
}
return retval;
}
/**
* Sets the length of the Number, Integer or String to the specified length
* Note: no truncation of the value takes place, this is meta-data only!
* @param l the length to which you want to set the Value.
*/
public void setLength(int l)
{
if (value==null) return;
value.setLength(l);
}
/**
* Sets the length and the precision of the Number, Integer or String to the specified length & precision
* Note: no truncation of the value takes place, this is meta-data only!
* @param l the length to which you want to set the Value.
* @param p the precision to which you want to set this Value
*/
public void setLength(int l, int p)
{
if (value==null) return;
value.setLength(l,p);
}
/**
* Get the length of this Value.
* @return the length of this Value.
*/
public int getLength()
{
if (value==null) return -1;
return value.getLength();
}
/**
* get the precision of this Value
* @return the precision of this Value.
*/
public int getPrecision()
{
if (value==null) return -1;
return value.getPrecision();
}
/**
* Sets the precision of this Value
* Note: no rounding or truncation takes place, this is meta-data only!
* @param p the precision to which you want to set this Value.
*/
public void setPrecision(int p)
{
if (value==null) return;
value.setPrecision(p);
}
/**
* Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ...
* @return A String describing the type of value.
*/
public String getTypeDesc()
{
if (value==null) return "Unknown";
return value.getTypeDesc();
}
/**
* Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ... given a certain integer type
* @param t the type to convert to text.
* @return A String describing the type of a certain value.
*/
public static final String getTypeDesc(int t)
{
return valueTypeCode[t];
}
/**
* Convert the String description of a type to an integer type.
* @param desc The description of the type to convert
* @return The integer type of the given String. (Value.VALUE_TYPE_...)
*/
public static final int getType(String desc)
{
int i;
for (i=1;i<valueTypeCode.length;i++)
{
if (valueTypeCode[i].equalsIgnoreCase(desc))
{
return i;
}
}
return VALUE_TYPE_NONE;
}
/**
* get an array of String describing the possible types a Value can have.
* @return an array of String describing the possible types a Value can have.
*/
public static final String[] getTypes()
{
String retval[] = new String[valueTypeCode.length-1];
System.arraycopy(valueTypeCode, 1, retval, 0, valueTypeCode.length-1);
return retval;
}
/**
* Get an array of String describing the possible types a Value can have.
* @return an array of String describing the possible types a Value can have.
*/
public static final String[] getAllTypes()
{
String retval[] = new String[valueTypeCode.length];
System.arraycopy(valueTypeCode, 0, retval, 0, valueTypeCode.length);
return retval;
}
/**
* Sets the Value to null, no type is being changed.
*
*/
public void setNull()
{
setNull(true);
}
/**
* Sets or unsets a value to null, no type is being changed.
* @param n true if you want the value to be null, false if you don't want this to be the case.
*/
public void setNull(boolean n)
{
NULL=n;
}
/**
* Checks wheter or not a value is null.
* @return true if the Value is null.
*/
public boolean isNull()
{
return NULL;
}
/**
* Write the object to an ObjectOutputStream
* @param out
* @throws IOException
*/
private void writeObject(java.io.ObjectOutputStream out) throws IOException
{
writeObj(new DataOutputStream(out));
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
{
readObj(new DataInputStream(in));
}
public void writeObj(DataOutputStream dos) throws IOException
{
int type=getType();
// Handle type
dos.writeInt(getType());
// Handle name-length
dos.writeInt(name.length());
// Write name
dos.writeChars(name);
// length & precision
dos.writeInt(getLength());
dos.writeInt(getPrecision());
// NULL?
dos.writeBoolean(isNull());
// Handle Content -- only when not NULL
if (!isNull())
{
switch(type)
{
case VALUE_TYPE_STRING :
case VALUE_TYPE_BIGNUMBER:
if (getString()!=null && getString().getBytes().length>0)
{
dos.writeInt(getString().getBytes("UTF-8").length);
dos.writeUTF(getString());
}
else
{
dos.writeInt(0);
}
break;
case VALUE_TYPE_DATE :
dos.writeBoolean(getDate()!=null);
if (getDate()!=null)
{
dos.writeLong(getDate().getTime());
}
break;
case VALUE_TYPE_NUMBER :
dos.writeDouble(getNumber());
break;
case VALUE_TYPE_BOOLEAN:
dos.writeBoolean(getBoolean());
break;
case VALUE_TYPE_INTEGER:
dos.writeLong(getInteger());
break;
default: break; // nothing
}
}
}
/**
* Write the value, including the meta-data to a DataOutputStream
* @param outputStream the OutputStream to write to .
* @throws KettleFileException if something goes wrong.
*/
public void write(OutputStream outputStream) throws KettleFileException
{
try
{
writeObj(new DataOutputStream(outputStream));
}
catch(Exception e)
{
throw new KettleFileException("Unable to write value to output stream", e);
}
}
public void readObj(DataInputStream dis) throws IOException
{
// type
int theType = dis.readInt();
newValue(theType);
// name-length
int nameLength=dis.readInt();
// name
StringBuffer nameBuffer=new StringBuffer();
for (int i=0;i<nameLength;i++) nameBuffer.append(dis.readChar());
setName(new String(nameBuffer));
// length & precision
setLength(dis.readInt(), dis.readInt());
// Null?
setNull(dis.readBoolean());
// Read the values
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING:
case VALUE_TYPE_BIGNUMBER:
// Handle lengths
int dataLength=dis.readInt();
if (dataLength>0)
{
String string = dis.readUTF();
setValue(string);
}
if (theType==VALUE_TYPE_BIGNUMBER)
{
try
{
convertString(theType);
}
catch(KettleValueException e)
{
throw new IOException("Unable to convert String to BigNumber while reading from data input stream ["+getString()+"]");
}
}
break;
case VALUE_TYPE_DATE:
if (dis.readBoolean())
{
setValue(new Date(dis.readLong()));
}
break;
case VALUE_TYPE_NUMBER:
setValue(dis.readDouble());
break;
case VALUE_TYPE_INTEGER:
setValue(dis.readLong());
break;
case VALUE_TYPE_BOOLEAN:
setValue(dis.readBoolean());
break;
default: break;
}
}
}
/**
* Read the Value, including meta-data from a DataInputStream
* @param is The InputStream to read the value from
* @throws KettleFileException when the Value couldn't be created by reading it from the DataInputStream.
*/
public Value(InputStream is) throws KettleFileException
{
try
{
readObj(new DataInputStream(is));
}
catch(EOFException e)
{
throw new KettleEOFException("End of file reached", e);
}
catch(Exception e)
{
throw new KettleFileException("Error reading from data input stream", e);
}
}
/**
* Write the data of this Value, without the meta-data to a DataOutputStream
* @param dos The DataOutputStream to write the data to
* @return true if all went well, false if something went wrong.
*/
public boolean writeData(DataOutputStream dos) throws KettleFileException
{
try
{
// Is the value NULL?
dos.writeBoolean(isNull());
// Handle Content -- only when not NULL
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING :
case VALUE_TYPE_BIGNUMBER:
if (getString()!=null && getString().getBytes().length>0)
{
dos.writeInt(getString().getBytes().length);
dos.writeUTF(getString());
}
else
{
dos.writeInt(0);
}
break;
case VALUE_TYPE_DATE :
dos.writeBoolean(getDate()!=null);
if (getDate()!=null)
{
dos.writeLong(getDate().getTime());
}
break;
case VALUE_TYPE_NUMBER :
dos.writeDouble(getNumber());
break;
case VALUE_TYPE_BOOLEAN:
dos.writeBoolean(getBoolean());
break;
case VALUE_TYPE_INTEGER:
dos.writeLong(getInteger());
break;
default: break; // nothing
}
}
}
catch(IOException e)
{
throw new KettleFileException("Unable to write value data to output stream", e);
}
return true;
}
/**
* Read the data of a Value from a DataInputStream, the meta-data of the value has to be set before calling this method!
* @param dis the DataInputStream to read from
* @throws KettleFileException when the value couldn't be read from the DataInputStream
*/
public Value(Value metaData, DataInputStream dis) throws KettleFileException
{
setValue(metaData);
setName(metaData.getName());
try
{
// Is the value NULL?
setNull(dis.readBoolean());
// Read the values
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING:
case VALUE_TYPE_BIGNUMBER:
// Handle lengths
int dataLength=dis.readInt();
if (dataLength>0)
{
String string = dis.readUTF();
setValue(string);
if (metaData.isBigNumber()) convertString(metaData.getType());
}
break;
case VALUE_TYPE_DATE:
if (dis.readBoolean())
{
setValue(new Date(dis.readLong()));
}
break;
case VALUE_TYPE_NUMBER:
setValue(dis.readDouble());
break;
case VALUE_TYPE_INTEGER:
setValue(dis.readLong());
break;
case VALUE_TYPE_BOOLEAN:
setValue(dis.readBoolean());
break;
default: break;
}
}
}
catch(EOFException e)
{
throw new KettleEOFException("End of file reached", e);
}
catch(Exception e)
{
throw new KettleEOFException("Error reading value data from stream", e);
}
}
/**
* Compare 2 values of the same or different type!
* The comparison of Strings is case insensitive
* @param v the value to compare with.
* @return -1 if The value was smaller, 1 bigger and 0 if both values are equal.
*/
public int compare(Value v)
{
return compare(v, true);
}
/**
* Compare 2 values of the same or different type!
* @param v the value to compare with.
* @param caseInsensitive True if you want the comparison to be case insensitive
* @return -1 if The value was smaller, 1 bigger and 0 if both values are equal.
*/
public int compare(Value v, boolean caseInsensitive)
{
boolean n1 = isNull() || (isString() && (getString()==null || getString().length()==0)) || (isDate() && getDate()==null) || (isBigNumber() && getBigNumber()==null);
boolean n2 = v.isNull() || (v.isString() && (v.getString()==null || v.getString().length()==0)) || (v.isDate() && v.getDate()==null) || (v.isBigNumber() && v.getBigNumber()==null);
// null is always smaller!
if ( n1 && !n2) return -1;
if (!n1 && n2) return 1;
if ( n1 && n2) return 0;
switch(getType())
{
case VALUE_TYPE_STRING:
{
String one = Const.rtrim(getString());
String two = Const.rtrim(v.getString());
int cmp=0;
if (caseInsensitive)
{
cmp = one.compareToIgnoreCase(two);
}
else
{
cmp = one.compareTo(two);
}
return cmp;
}
case VALUE_TYPE_INTEGER:
{
return Double.compare(getNumber(), v.getNumber());
}
case VALUE_TYPE_DATE :
{
return Double.compare(getNumber(), v.getNumber());
}
case VALUE_TYPE_BOOLEAN:
{
if (getBoolean() && v.getBoolean() ||
!getBoolean() && !v.getBoolean()) return 0; // true == true, false == false
if (getBoolean() && !v.getBoolean()) return 1; // true > false
return -1; // false < true
}
case VALUE_TYPE_NUMBER :
{
return Double.compare(getNumber(), v.getNumber());
}
case VALUE_TYPE_BIGNUMBER:
{
return getBigNumber().compareTo(v.getBigNumber());
}
}
// Still here? Not possible! But hey, give back 0, mkay?
return 0;
}
public boolean equals(Object v)
{
if (compare((Value)v)==0)
return true;
else
return false;
}
/**
* Check whether this value is equal to the String supplied.
* @param string The string to check for equality
* @return true if the String representation of the value is equal to string. (ignoring case)
*/
public boolean isEqualTo(String string)
{
return getString().equalsIgnoreCase(string);
}
/**
* Check whether this value is equal to the BigDecimal supplied.
* @param number The BigDecimal to check for equality
* @return true if the BigDecimal representation of the value is equal to number.
*/
public boolean isEqualTo(BigDecimal number)
{
return getBigNumber().equals(number);
}
/**
* Check whether this value is equal to the Number supplied.
* @param number The Number to check for equality
* @return true if the Number representation of the value is equal to number.
*/
public boolean isEqualTo(double number)
{
return getNumber() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(long number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(int number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(byte number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Date supplied.
* @param date The Date to check for equality
* @return true if the Date representation of the value is equal to date.
*/
public boolean isEqualTo(Date date)
{
return getDate() == date;
}
public int hashCode()
{
int hash=0; // name.hashCode(); -> Name shouldn't be part of hashCode()!
if (isNull())
{
switch(getType())
{
case VALUE_TYPE_BOOLEAN : hash^= 1; break;
case VALUE_TYPE_DATE : hash^= 2; break;
case VALUE_TYPE_NUMBER : hash^= 4; break;
case VALUE_TYPE_STRING : hash^= 8; break;
case VALUE_TYPE_INTEGER : hash^=16; break;
case VALUE_TYPE_BIGNUMBER : hash^=32; break;
case VALUE_TYPE_NONE : break;
default: break;
}
}
else
{
switch(getType())
{
case VALUE_TYPE_BOOLEAN : hash^=Boolean.valueOf(getBoolean()).hashCode(); break;
case VALUE_TYPE_DATE : if (getDate()!=null) hash^=getDate().hashCode(); break;
case VALUE_TYPE_INTEGER :
case VALUE_TYPE_NUMBER : hash^=(new Double(getNumber())).hashCode(); break;
case VALUE_TYPE_STRING : if (getString()!=null) hash^=getString().hashCode(); break;
case VALUE_TYPE_BIGNUMBER : if (getBigNumber()!=null) hash^=getBigNumber().hashCode(); break;
case VALUE_TYPE_NONE : break;
default: break;
}
}
return hash;
}
// OPERATORS & COMPARATORS
public Value and(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 & n2;
setValue(res);
return this;
}
public Value xor(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 ^ n2;
setValue(res);
return this;
}
public Value or(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 | n2;
setValue(res);
return this;
}
public Value bool_and(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1 && b2;
setValue(res);
return this;
}
public Value bool_or(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1 || b2;
setValue(res);
return this;
}
public Value bool_xor(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1&&b2 ? false : !b1&&!b2 ? false : true;
setValue(res);
return this;
}
public Value bool_not()
{
value.setBoolean(!getBoolean());
return this;
}
public Value greater_equal(Value v)
{
if (compare(v)>=0) setValue(true); else setValue(false);
return this;
}
public Value smaller_equal(Value v)
{
if (compare(v)<=0) setValue(true); else setValue(false);
return this;
}
public Value different(Value v)
{
if (compare(v)!=0) setValue(true); else setValue(false);
return this;
}
public Value equal(Value v)
{
if (compare(v)==0) setValue(true); else setValue(false);
return this;
}
public Value like(Value v)
{
String cmp=v.getString();
// Is cmp part of look?
int idx=getString().indexOf(cmp);
if (idx<0) setValue(false); else setValue(true);
return this;
}
public Value greater(Value v)
{
if (compare(v)>0) setValue(true); else setValue(false);
return this;
}
public Value smaller(Value v)
{
if (compare(v)<0) setValue(true); else setValue(false);
return this;
}
public Value minus(BigDecimal v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(double v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(long v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(int v) throws KettleValueException { return minus(new Value("tmp", (long)v)); }
public Value minus(byte v) throws KettleValueException { return minus(new Value("tmp", (long)v)); }
public Value minus(Value v) throws KettleValueException
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : value.setBigNumber(getBigNumber().subtract(v.getBigNumber())); break;
case VALUE_TYPE_NUMBER : value.setNumber(getNumber()-v.getNumber()); break;
case VALUE_TYPE_INTEGER : value.setInteger(getInteger()-v.getInteger()); break;
case VALUE_TYPE_BOOLEAN :
case VALUE_TYPE_STRING :
default:
throw new KettleValueException("Subtraction can only be done with numbers!");
}
return this;
}
public Value plus(BigDecimal v) { return plus(new Value("tmp", v)); }
public Value plus(double v) { return plus(new Value("tmp", v)); }
public Value plus(long v) { return plus(new Value("tmp", v)); }
public Value plus(int v) { return plus(new Value("tmp", (long)v)); }
public Value plus(byte v) { return plus(new Value("tmp", (long)v)); }
public Value plus(Value v)
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().add(v.getBigNumber())); break;
case VALUE_TYPE_NUMBER : setValue(getNumber()+v.getNumber()); break;
case VALUE_TYPE_INTEGER : setValue(getInteger()+v.getInteger()); break;
case VALUE_TYPE_BOOLEAN : setValue(getBoolean()|v.getBoolean()); break;
case VALUE_TYPE_STRING : setValue(getString()+v.getString()); break;
default: break;
}
return this;
}
public Value divide(BigDecimal v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(double v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(long v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(int v) throws KettleValueException { return divide(new Value("tmp", (long)v)); }
public Value divide(byte v) throws KettleValueException { return divide(new Value("tmp", (long)v)); }
public Value divide(Value v) throws KettleValueException
{
if (isNull() || v.isNull())
{
setNull();
}
else
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().divide(v.getBigNumber(), BigDecimal.ROUND_UP)); break;
case VALUE_TYPE_NUMBER : setValue(getNumber()/v.getNumber()); break;
case VALUE_TYPE_INTEGER : setValue(getInteger()/v.getInteger()); break;
case VALUE_TYPE_BOOLEAN :
case VALUE_TYPE_STRING :
default:
throw new KettleValueException("Division can only be done with numeric data!");
}
}
return this;
}
public Value multiply(BigDecimal v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(double v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(long v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(int v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); }
public Value multiply(byte v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); }
public Value multiply(Value v) throws KettleValueException
{
// a number and a string!
if (isNull() || v.isNull())
{
setNull();
return this;
}
if ((v.isString() && isNumeric()) || (v.isNumeric() && isString()))
{
StringBuffer s;
String append="";
int n;
if (v.isString())
{
s=new StringBuffer(v.getString());
append=v.getString();
n=(int)getInteger();
}
else
{
s=new StringBuffer(getString());
append=getString();
n=(int)v.getInteger();
}
if (n==0) s.setLength(0);
else
for (int i=1;i<n;i++) s.append(append);
setValue(s);
}
else
// big numbers
if (isBigNumber() || v.isBigNumber())
{
setValue(getBigNumber().multiply(v.getBigNumber()));
}
else
// numbers
if (isNumber() || v.isNumber())
{
setValue(getNumber()*v.getNumber());
}
else
// integers
if (isInteger() || v.isInteger())
{
setValue(getInteger()*v.getInteger());
}
else
{
throw new KettleValueException("Multiplication can only be done with numbers or a number and a string!");
}
return this;
}
// FUNCTIONS!!
// implement the ABS function, arguments in args[]
public Value abs() throws KettleValueException
{
if (isNull()) return this;
if (isBigNumber())
{
setValue(getBigNumber().abs());
}
else
if (isNumber())
{
setValue(Math.abs(getNumber()));
}
else
if (isInteger())
{
setValue(Math.abs(getInteger()));
}
else
{
throw new KettleValueException("Function ABS only works with a number");
}
return this;
}
// implement the ACOS function, arguments in args[]
public Value acos() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.acos(getNumber()));
}
else
{
throw new KettleValueException("Function ACOS only works with numeric data");
}
return this;
}
// implement the ASIN function, arguments in args[]
public Value asin() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.asin(getNumber()));
}
else
{
throw new KettleValueException("Function ASIN only works with numeric data");
}
return this;
}
// implement the ATAN function, arguments in args[]
public Value atan() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.atan(getNumber()));
}
else
{
throw new KettleValueException("Function ATAN only works with numeric data");
}
return this;
}
// implement the ATAN2 function, arguments in args[]
public Value atan2(Value arg0) throws KettleValueException { return atan2(arg0.getNumber()); }
public Value atan2(double arg0) throws KettleValueException
{
if (isNull())
{
return this;
}
if (isNumeric())
{
setValue(Math.atan2(getNumber(), arg0));
}
else
{
throw new
KettleValueException("Function ATAN2 only works with numbers");
}
return this;
}
// implement the CEIL function, arguments in args[]
public Value ceil() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.ceil(getNumber()));
}
else
{
throw new KettleValueException("Function CEIL only works with a number");
}
return this;
}
// implement the COS function, arguments in args[]
public Value cos() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.cos(getNumber()));
}
else
{
throw new KettleValueException("Function COS only works with a number");
}
return this;
}
// implement the EXP function, arguments in args[]
public Value exp() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.exp(getNumber()));
}
else
{
throw new KettleValueException("Function EXP only works with a number");
}
return this;
}
// implement the FLOOR function, arguments in args[]
public Value floor() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.floor(getNumber()));
}
else
{
throw new KettleValueException("Function FLOOR only works with a number");
}
return this;
}
// implement the INITCAP function, arguments in args[]
public Value initcap()
{
if (isNull()) return this;
if (getString()==null)
{
setNull();
}
else
{
setValue( Const.initCap(getString()) );
}
return this;
}
// implement the LENGTH function, arguments in args[]
public Value length() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_INTEGER);
setValue(0L);
return this;
}
if (getType()==VALUE_TYPE_STRING)
{
setValue((double)getString().length());
}
else
{
throw new KettleValueException("Function LENGTH only works with a string");
}
return this;
}
// implement the LOG function, arguments in args[]
public Value log() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.log(getNumber()));
}
else
{
throw new KettleValueException("Function LOG only works with a number");
}
return this;
}
// implement the LOWER function, arguments in args[]
public Value lower()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
setValue( getString().toLowerCase() );
}
return this;
}
// implement the LPAD function: left pad strings or numbers...
public Value lpad(Value len) { return lpad((int)len.getNumber(), " "); }
public Value lpad(Value len, Value padstr) { return lpad((int)len.getNumber(), padstr.getString()); }
public Value lpad(int len) { return lpad(len, " "); }
public Value lpad(int len, String padstr)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()!=VALUE_TYPE_STRING) // also lpad other types!
{
setValue(getString());
}
if (getString()!=null)
{
StringBuffer result = new StringBuffer(getString());
int pad=len;
int l= ( pad-result.length() ) / padstr.length() + 1;
int i;
for (i=0;i<l;i++) result.insert(0, padstr);
// Maybe we added one or two too many!
i=result.length();
while (i>pad && pad>0)
{
result.deleteCharAt(0);
i--;
}
setValue(result.toString());
}
else
{
setNull();
}
}
setLength(len);
return this;
}
// implement the LTRIM function
public Value ltrim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getString()!=null)
{
StringBuffer s;
if (getType()==VALUE_TYPE_STRING)
{
s = new StringBuffer(getString());
}
else
{
s = new StringBuffer(toString());
}
// Left trim
while (s.length()>0 && s.charAt(0)==' ') s.deleteCharAt(0);
setValue(s);
}
else
{
setNull();
}
}
return this;
}
// implement the MOD function, arguments in args[]
public Value mod(Value arg) throws KettleValueException { return mod(arg.getNumber()); }
public Value mod(BigDecimal arg) throws KettleValueException { return mod(arg.doubleValue()); }
public Value mod(long arg) throws KettleValueException { return mod((double)arg); }
public Value mod(int arg) throws KettleValueException { return mod((double)arg); }
public Value mod(byte arg) throws KettleValueException { return mod((double)arg); }
public Value mod(double arg0) throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
double n1=getNumber();
double n2=arg0;
setValue( n1 - (n2 * Math.floor(n1 /n2 )) );
}
else
{
throw new KettleValueException("Function MOD only works with numeric data");
}
return this;
}
// implement the NVL function, arguments in args[]
public Value nvl(Value alt)
{
if (isNull()) setValue(alt);
return this;
}
// implement the POWER function, arguments in args[]
public Value power(BigDecimal arg) throws KettleValueException{ return power(new Value("tmp", arg)); }
public Value power(double arg) throws KettleValueException{ return power(new Value("tmp", arg)); }
public Value power(Value v) throws KettleValueException
{
if (isNull()) return this;
else if (isNumeric())
{
setValue( Math.pow(getNumber(), v.getNumber()) );
}
else
{
throw new KettleValueException("Function POWER only works with numeric data");
}
return this;
}
// implement the REPLACE function, arguments in args[]
public Value replace(Value repl, Value with) { return replace(repl.getString(), with.getString()); }
public Value replace(String repl, String with)
{
if (isNull()) return this;
if (getString()==null)
{
setNull();
}
else
{
setValue( Const.replace(getString(), repl, with) );
}
return this;
}
/**
* Rounds off to the nearest integer.<p>
* See also: java.lang.Math.round()
*
* @return The rounded Number value.
*/
public Value round() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( (double)Math.round(getNumber()) );
}
else
{
throw new KettleValueException("Function ROUND only works with a number");
}
return this;
}
/**
* Rounds the Number value to a certain number decimal places.
* @param decimalPlaces
* @return The rounded Number Value
* @throws KettleValueException in case it's not a number (or other problem).
*/
public Value round(int decimalPlaces) throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
if (isBigNumber())
{
// Multiply by 10^decimalPlaces
// For example 123.458343938437, Decimalplaces = 2
//
BigDecimal bigDec = getBigNumber();
// System.out.println("ROUND decimalPlaces : "+decimalPlaces+", bigNumber = "+bigDec);
bigDec = bigDec.setScale(decimalPlaces, BigDecimal.ROUND_HALF_EVEN);
// System.out.println("ROUND finished result : "+bigDec);
setValue( bigDec );
}
else
{
setValue( (double)Const.round(getNumber(), decimalPlaces) );
}
}
else
{
throw new KettleValueException("Function ROUND only works with a number");
}
return this;
}
// implement the RPAD function, arguments in args[]
public Value rpad(Value len) { return rpad((int)len.getNumber(), " "); }
public Value rpad(Value len, Value padstr) { return rpad((int)len.getNumber(), padstr.getString()); }
public Value rpad(int len) { return rpad(len, " "); }
public Value rpad(int len, String padstr)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()!=VALUE_TYPE_STRING) // also rpad other types!
{
setValue(getString());
}
if (getString()!=null)
{
StringBuffer result = new StringBuffer(getString());
int pad=len;
int l= ( pad-result.length() ) / padstr.length() + 1;
int i;
for (i=0;i<l;i++) result.append(padstr);
// Maybe we added one or two too many!
i=result.length();
while (i>pad && pad>0)
{
result.deleteCharAt(i-1);
i--;
}
setValue(result.toString());
}
else
{
setNull();
}
}
setLength(len);
return this;
}
// implement the RTRIM function, arguments in args[]
public Value rtrim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
StringBuffer s;
if (getType()==VALUE_TYPE_STRING)
{
s = new StringBuffer(getString());
}
else
{
s = new StringBuffer(toString());
}
// Right trim
while (s.length()>0 && s.charAt(s.length()-1)==' ') s.deleteCharAt(s.length()-1);
setValue(s);
}
return this;
}
// implement the SIGN function, arguments in args[]
public Value sign() throws KettleValueException
{
if (isNull()) return this;
if (isNumber())
{
int cmp = getBigNumber().compareTo(new BigDecimal(0L));
if (cmp>0) value.setBigNumber(new BigDecimal(1L));
else if (cmp<0) value.setBigNumber(new BigDecimal(-1L));
else value.setBigNumber(new BigDecimal(0L));
}
else
if (isNumber())
{
if (getNumber()>0) value.setNumber(1.0);
else if (getNumber()<0) value.setNumber(-1.0);
else value.setNumber(0.0);
}
else
if (isInteger())
{
if (getInteger()>0) value.setInteger(1);
else if (getInteger()<0) value.setInteger(-1);
else value.setInteger(0);
}
else
{
throw new KettleValueException("Function SIGN only works with a number");
}
return this;
}
// implement the SIN function, arguments in args[]
public Value sin() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.sin(getNumber()) );
}
else
{
throw new KettleValueException("Function SIN only works with a number");
}
return this;
}
// implement the SQRT function, arguments in args[]
public Value sqrt() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.sqrt(getNumber()) );
}
else
{
throw new KettleValueException("Function SQRT only works with a number");
}
return this;
}
// implement the SUBSTR function, arguments in args[]
public Value substr(Value from, Value to) { return substr((int)from.getNumber(), (int)to.getNumber()); }
public Value substr(Value from) { return substr((int)from.getNumber(), -1); }
public Value substr(int from) { return substr(from, -1); }
public Value substr(int from, int to)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
if (getString()!=null)
{
if (to<0 && from>=0)
{
setValue( getString().substring(from) );
}
else if (to>=0 && from>=0)
{
setValue( getString().substring(from, to) );
}
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
// implement the RIGHTSTR function, arguments in args[]
public Value rightstr(Value len) { return rightstr((int)len.getNumber()); }
public Value rightstr(int len)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
int tot_len = getString()!=null?getString().length():0;
if (tot_len>0)
{
int totlen = getString().length();
int f = totlen-len;
if (f<0) f=0;
setValue( getString().substring(f) );
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
// implement the LEFTSTR function, arguments in args[]
public Value leftstr(Value len)
{
return leftstr((int)len.getNumber());
}
public Value leftstr(int len)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
int tot_len = getString()!=null?getString().length():0;
if (tot_len>0)
{
int totlen = getString().length();
int f = totlen-len;
if (f>0)
{
setValue( getString().substring(0,len) );
}
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
public Value startsWith(Value string)
{
return startsWith(string.getString());
}
public Value startsWith(String string)
{
if (isNull())
{
setType(VALUE_TYPE_BOOLEAN);
return this;
}
if (string==null)
{
setValue(false);
setNull();
return this;
}
setValue( getString().startsWith(string) );
return this;
}
// implement the SYSDATE function, arguments in args[]
public Value sysdate()
{
setValue( Calendar.getInstance().getTime() );
return this;
}
// implement the TAN function, arguments in args[]
public Value tan() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.tan(getNumber()) );
}
else
{
throw new KettleValueException("Function TAN only works on a number");
}
return this;
}
// implement the TO_CHAR function, arguments in args[]
// number: NUM2STR( 123.456 ) : default format
// number: NUM2STR( 123.456, '###,##0.000') : format
// number: NUM2STR( 123.456, '###,##0.000', '.') : grouping
// number: NUM2STR( 123.456, '###,##0.000', '.', ',') : decimal
// number: NUM2STR( 123.456, '###,##0.000', '.', ',', '?') : currency
public Value num2str() throws KettleValueException { return num2str(null, null, null, null); }
public Value num2str(String format) throws KettleValueException { return num2str(format, null, null, null); }
public Value num2str(String format, String decimalSymbol) throws KettleValueException { return num2str(format, decimalSymbol, null, null); }
public Value num2str(String format, String decimalSymbol, String groupingSymbol) throws KettleValueException { return num2str(format, decimalSymbol, groupingSymbol, null); }
public Value num2str(String format, String decimalSymbol, String groupingSymbol, String currencySymbol) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
// Number to String conversion...
if (getType()==VALUE_TYPE_NUMBER || getType()==VALUE_TYPE_INTEGER)
{
NumberFormat nf = NumberFormat.getInstance();
DecimalFormat df = (DecimalFormat)nf;
DecimalFormatSymbols dfs =new DecimalFormatSymbols();
if (currencySymbol!=null && currencySymbol.length()>0) dfs.setCurrencySymbol( currencySymbol );
if (groupingSymbol!=null && groupingSymbol.length()>0) dfs.setGroupingSeparator( groupingSymbol.charAt(0) );
if (decimalSymbol!=null && decimalSymbol.length()>0) dfs.setDecimalSeparator( decimalSymbol.charAt(0) );
df.setDecimalFormatSymbols(dfs); // in case of 4, 3 or 2
if (format!=null && format.length()>0) df.applyPattern(format);
try
{
setValue( nf.format(getNumber()) );
}
catch(Exception e)
{
setType(VALUE_TYPE_STRING);
setNull();
throw new KettleValueException("Couldn't convert Number to String "+e.toString());
}
}
else
{
throw new KettleValueException("Function NUM2STR only works on Numbers and Integers");
}
}
return this;
}
// date: TO_CHAR( <date> , 'yyyy/mm/dd HH:mm:ss'
public Value dat2str() throws KettleValueException { return dat2str(null, null); }
public Value dat2str(String arg0) throws KettleValueException { return dat2str(arg0, null); }
public Value dat2str(String arg0, String arg1) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()==VALUE_TYPE_DATE)
{
SimpleDateFormat df = new SimpleDateFormat();
DateFormatSymbols dfs = new DateFormatSymbols();
if (arg1!=null) dfs.setLocalPatternChars(arg1);
if (arg0!=null) df.applyPattern(arg0);
try
{
setValue( df.format(getDate()) );
}
catch(Exception e)
{
setType(VALUE_TYPE_STRING);
setNull();
throw new KettleValueException("TO_CHAR Couldn't convert Date to String "+e.toString());
}
}
else
{
throw new KettleValueException("Function DAT2STR only works on a date");
}
}
return this;
}
// implement the TO_DATE function, arguments in args[]
public Value num2dat() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_DATE);
}
else
{
if (isNumeric())
{
setValue(new Date(getInteger()));
setLength(-1,-1);
}
else
{
throw new KettleValueException("Function NUM2DAT only works on a number");
}
}
return this;
}
public Value str2dat(String arg0) throws KettleValueException { return str2dat(arg0, null); }
public Value str2dat(String arg0, String arg1) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_DATE);
}
else
{
// System.out.println("Convert string ["+string+"] to date using pattern '"+arg0+"'");
SimpleDateFormat df = new SimpleDateFormat();
DateFormatSymbols dfs = new DateFormatSymbols();
if (arg1!=null) dfs.setLocalPatternChars(arg1);
if (arg0!=null) df.applyPattern(arg0);
try
{
value.setDate( df.parse(getString()) );
setType(VALUE_TYPE_DATE);
setLength(-1,-1);
}
catch(Exception e)
{
setType(VALUE_TYPE_DATE);
setNull();
throw new KettleValueException("TO_DATE Couldn't convert String to Date"+e.toString());
}
}
return this;
}
// implement the TO_NUMBER function, arguments in args[]
public Value str2num() throws KettleValueException { return str2num(null, null, null, null); }
public Value str2num(String pattern) throws KettleValueException { return str2num(pattern, null, null, null); }
public Value str2num(String pattern, String decimal) throws KettleValueException { return str2num(pattern, decimal, null, null); }
public Value str2num(String pattern, String decimal, String grouping) throws KettleValueException { return str2num(pattern, decimal, grouping, null); }
public Value str2num(String pattern, String decimal, String grouping, String currency) throws KettleValueException
{
// 0 : pattern
// 1 : Decimal separator
// 2 : Grouping separator
// 3 : Currency symbol
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()==VALUE_TYPE_STRING)
{
if (getString()==null)
{
setNull();
setValue(0.0);
}
else
{
NumberFormat nf = NumberFormat.getInstance();
DecimalFormat df = (DecimalFormat)nf;
DecimalFormatSymbols dfs =new DecimalFormatSymbols();
if ( !Const.isEmpty(pattern ) ) df.applyPattern( pattern );
if ( !Const.isEmpty(decimal ) ) dfs.setDecimalSeparator( decimal.charAt(0) );
if ( !Const.isEmpty(grouping) ) dfs.setGroupingSeparator( grouping.charAt(0) );
if ( !Const.isEmpty(currency) ) dfs.setCurrencySymbol( currency );
try
{
df.setDecimalFormatSymbols(dfs);
setValue( df.parse(getString()).doubleValue() );
}
catch(Exception e)
{
String message = "Couldn't convert string to number "+e.toString();
if ( !Const.isEmpty(pattern ) ) message+=" pattern="+pattern;
if ( !Const.isEmpty(decimal ) ) message+=" decimal="+decimal;
if ( !Const.isEmpty(grouping) ) message+=" grouping="+grouping.charAt(0);
if ( !Const.isEmpty(currency) ) message+=" currency="+currency;
throw new KettleValueException(message);
}
}
}
else
{
throw new KettleValueException("Function STR2NUM works only on strings");
}
}
return this;
}
public Value dat2num() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_INTEGER);
return this;
}
if (getType()==VALUE_TYPE_DATE)
{
if (getString()==null)
{
setNull();
setValue(0L);
}
else
{
setValue(getInteger());
}
}
else
{
throw new KettleValueException("Function DAT2NUM works only on dates");
}
return this;
}
/**
* Performs a right and left trim of spaces in the string.
* If the value is not a string a conversion to String is performed first.
*
* @return The trimmed string value.
*/
public Value trim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
String str = Const.trim(getString());
setValue(str);
return this;
}
// implement the UPPER function, arguments in args[]
public Value upper()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString().toUpperCase() );
return this;
}
// implement the E function, arguments in args[]
public Value e()
{
setValue(Math.E);
return this;
}
// implement the PI function, arguments in args[]
public Value pi()
{
setValue(Math.PI);
return this;
}
// implement the DECODE function, arguments in args[]
public Value v_decode(Value args[]) throws KettleValueException
{
int i;
boolean found;
// Decode takes as input the first argument...
// The next pair
// Limit to 3, 5, 7, 9, ... arguments
if (args.length>=3 && (args.length%2)==1)
{
i=0;
found=false;
while (i<args.length-1 && !found)
{
if (this.equals(args[i]))
{
setValue(args[i+1]);
found=true;
}
i+=2;
}
if (!found) setValue(args[args.length-1]);
}
else
{
// ERROR with nr of arguments
throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!");
}
return this;
}
// implement the IF function, arguments in args[]
// IF( <condition>, <then value>, <else value>)
public Value v_if(Value args[]) throws KettleValueException
{
if (getType()==VALUE_TYPE_BOOLEAN)
{
if (args.length==1)
{
if (getBoolean()) setValue(args[0]); else setNull();
}
else
if (args.length==2)
{
if (getBoolean()) setValue(args[0]); else setValue(args[1]);
}
}
else
{
throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!");
}
return this;
}
// implement the ADD_MONTHS function, one argument
public Value add_months(int months) throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
if (!isNull() && getDate()!=null)
{
Calendar cal = Calendar.getInstance();
cal.setTime(getDate());
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
month+=months;
int newyear = year+(int)Math.floor(month/12);
int newmonth = month%12;
cal.set(newyear, newmonth, 1);
int newday = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
if (newday<day) cal.set(Calendar.DAY_OF_MONTH, newday);
else cal.set(Calendar.DAY_OF_MONTH, day);
setValue( cal.getTime() );
}
}
else
{
throw new KettleValueException("Function add_months only works on a date!");
}
return this;
}
/**
* Add a number of days to a Date value.
*
* @param days The number of days to add to the current date value
* @return The resulting value
* @throws KettleValueException
*/
public Value add_days(long days) throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
if (!isNull() && getDate()!=null)
{
Calendar cal = Calendar.getInstance();
cal.setTime(getDate());
cal.add(Calendar.DAY_OF_YEAR, (int)days);
setValue( cal.getTime() );
}
}
else
{
throw new KettleValueException("Function add_days only works on a date!");
}
return this;
}
// implement the LAST_DAY function, arguments in args[]
public Value last_day() throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
int last_day = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, last_day);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function last_day only works on a date");
}
return this;
}
public Value first_day() throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
cal.set(Calendar.DAY_OF_MONTH, 1);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function first_day only works on a date");
}
return this;
}
// implement the TRUNC function, version without arguments
public Value trunc() throws KettleValueException
{
if (isNull()) return this; // don't do anything, leave it at NULL!
if (isBigNumber())
{
getBigNumber().setScale(0, BigDecimal.ROUND_FLOOR);
}
else
if (isNumber())
{
setValue( Math.floor(getNumber()) );
}
else
if (isInteger())
{
// Nothing
}
else
if (isDate())
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.HOUR_OF_DAY, 0);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function TRUNC only works on numbers and dates");
}
return this;
}
// implement the TRUNC function, arguments in args[]
public Value trunc(double level) throws KettleValueException { return trunc((int)level); }
public Value trunc(int level) throws KettleValueException
{
if (isNull()) return this; // don't do anything, leave it at NULL!
if (isBigNumber())
{
getBigNumber().setScale(level, BigDecimal.ROUND_FLOOR);
}
else
if (isNumber())
{
double pow=Math.pow(10, level);
setValue( Math.floor( getNumber() * pow ) / pow );
}
else
if (isInteger())
{
// Nothing!
}
else
if (isDate())
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
switch((int)level)
{
// MONTHS
case 5: cal.set(Calendar.MONTH, 1);
// DAYS
case 4: cal.set(Calendar.DAY_OF_MONTH, 1);
// HOURS
case 3: cal.set(Calendar.HOUR_OF_DAY, 0);
// MINUTES
case 2: cal.set(Calendar.MINUTE, 0);
// SECONDS
case 1: cal.set(Calendar.SECOND, 0);
// MILI-SECONDS
case 0: cal.set(Calendar.MILLISECOND, 0); break;
default:
throw new KettleValueException("Argument of TRUNC of date has to be between 0 and 5");
}
}
else
{
throw new KettleValueException("Function TRUNC only works with numbers and dates");
}
return this;
}
/**
* Change a string into its hexadecimal representation. E.g. if Value
* contains string "a" afterwards it would contain value "61".
*
* Note that transformations happen in groups of 2 hex characters, so
* the value of a characters is always in the range 0-255.
*
* @return Value itself
* @throws KettleValueException
*/
public Value byteToHexEncode()
{
final char hexDigits[] =
{ '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
setType(VALUE_TYPE_STRING);
if (isNull())
{
return this;
}
String hex = getString();
char[] s = hex.toCharArray();
StringBuffer hexString = new StringBuffer(2 * s.length);
for (int i = 0; i < s.length; i++)
{
hexString.append(hexDigits[(s[i] & 0x00F0) >> 4]); // hi nibble
hexString.append(hexDigits[s[i] & 0x000F]); // lo nibble
}
setValue( hexString );
return this;
}
/**
* Change a hexadecimal string into normal ASCII representation. E.g. if Value
* contains string "61" afterwards it would contain value "a". If the
* hexadecimal string is of odd length a leading zero will be used.
*
* Note that only the low byte of a character will be processed, this
* is for binary transformations.
*
* @return Value itself
* @throws KettleValueException
*/
public Value hexToByteDecode() throws KettleValueException
{
setType(VALUE_TYPE_STRING);
if (isNull())
{
return this;
}
setValue( getString() );
String hexString = getString();
int len = hexString.length();
char chArray[] = new char[(len + 1) / 2];
boolean evenByte = true;
int nextByte = 0;
// we assume a leading 0 if the length is not even.
if ((len % 2) == 1)
evenByte = false;
int nibble;
int i, j;
for (i = 0, j = 0; i < len; i++)
{
char c = hexString.charAt(i);
if ((c >= '0') && (c <= '9'))
nibble = c - '0';
else if ((c >= 'A') && (c <= 'F'))
nibble = c - 'A' + 0x0A;
else if ((c >= 'a') && (c <= 'f'))
nibble = c - 'a' + 0x0A;
else
throw new KettleValueException("invalid hex digit '" + c + "'.");
if (evenByte)
{
nextByte = (nibble << 4);
}
else
{
nextByte += nibble;
chArray[j] = (char)nextByte;
j++;
}
evenByte = ! evenByte;
}
setValue(new String(chArray));
return this;
}
/**
* Change a string into its hexadecimal representation. E.g. if Value
* contains string "a" afterwards it would contain value "0061".
*
* Note that transformations happen in groups of 4 hex characters, so
* the value of a characters is always in the range 0-65535.
*
* @return Value itself
* @throws KettleValueException
*/
public Value charToHexEncode()
{
final char hexDigits[] =
{ '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
setType(VALUE_TYPE_STRING);
if (isNull())
{
return this;
}
String hex = getString();
char[] s = hex.toCharArray();
StringBuffer hexString = new StringBuffer(2 * s.length);
for (int i = 0; i < s.length; i++)
{
hexString.append(hexDigits[(s[i] & 0xF000) >> 12]); // hex 1
hexString.append(hexDigits[(s[i] & 0x0F00) >> 8]); // hex 2
hexString.append(hexDigits[(s[i] & 0x00F0) >> 4]); // hex 3
hexString.append(hexDigits[s[i] & 0x000F]); // hex 4
}
setValue( hexString );
return this;
}
/**
* Change a hexadecimal string into normal ASCII representation. E.g. if Value
* contains string "61" afterwards it would contain value "a". If the
* hexadecimal string is of a wrong length leading zeroes will be used.
*
* Note that transformations happen in groups of 4 hex characters, so
* the value of a characters is always in the range 0-65535.
*
* @return Value itself
* @throws KettleValueException
*/
public Value hexToCharDecode() throws KettleValueException
{
setType(VALUE_TYPE_STRING);
if (isNull())
{
return this;
}
setValue( getString() );
String hexString = getString();
int len = hexString.length();
char chArray[] = new char[(len + 3) / 4];
int charNr;
int nextChar = 0;
// we assume a leading 0s if the length is not right.
charNr = (len % 4);
if ( charNr == 0 ) charNr = 4;
int nibble;
int i, j;
for (i = 0, j = 0; i < len; i++)
{
char c = hexString.charAt(i);
if ((c >= '0') && (c <= '9'))
nibble = c - '0';
else if ((c >= 'A') && (c <= 'F'))
nibble = c - 'A' + 0x0A;
else if ((c >= 'a') && (c <= 'f'))
nibble = c - 'a' + 0x0A;
else
throw new KettleValueException("invalid hex digit '" + c + "'.");
if (charNr == 4)
{
nextChar = (nibble << 12);
charNr--;
}
else if (charNr == 3)
{
nextChar += (nibble << 8);
charNr--;
}
else if (charNr == 2)
{
nextChar += (nibble << 4);
charNr--;
}
else // charNr == 1
{
nextChar += nibble;
chArray[j] = (char)nextChar;
charNr = 4;
j++;
}
}
setValue(new String(chArray));
return this;
}
/*
* Some javascript extensions...
*/
public static final Value getInstance() { return new Value(); }
public String getClassName() { return "Value"; }
public void jsConstructor()
{
}
public void jsConstructor(String name)
{
setName(name);
}
public void jsConstructor(String name, String value)
{
setName(name);
setValue(value);
}
/**
* Produce the XML representation of this value.
* @return a String containing the XML to represent this Value.
*/
public String getXML()
{
StringBuffer retval = new StringBuffer(128);
retval.append(XMLHandler.addTagValue("name", getName(), false));
retval.append(XMLHandler.addTagValue("type", getTypeDesc(), false));
retval.append(XMLHandler.addTagValue("text", toString(false), false));
retval.append(XMLHandler.addTagValue("length", getLength(), false));
retval.append(XMLHandler.addTagValue("precision", getPrecision(), false));
retval.append(XMLHandler.addTagValue("isnull", isNull(), false));
return retval.toString();
}
/**
* Construct a new Value and read the data from XML
* @param valnode The XML Node to read from.
*/
public Value(Node valnode)
{
this();
loadXML(valnode);
}
/**
* Read the data for this Value from an XML Node
* @param valnode The XML Node to read from
* @return true if all went well, false if something went wrong.
*/
public boolean loadXML(Node valnode)
{
try
{
String valname = XMLHandler.getTagValue(valnode, "name");
int valtype = getType( XMLHandler.getTagValue(valnode, "type") );
String text = XMLHandler.getTagValue(valnode, "text");
boolean isnull = "Y".equalsIgnoreCase(XMLHandler.getTagValue(valnode, "isnull"));
int len = Const.toInt(XMLHandler.getTagValue(valnode, "length"), -1);
int prec = Const.toInt(XMLHandler.getTagValue(valnode, "precision"), -1);
setName(valname);
setValue(text);
setLength(len, prec);
if (valtype!=VALUE_TYPE_STRING)
{
trim();
convertString(valtype);
}
if (isnull) setNull();
}
catch(Exception e)
{
setNull();
return false;
}
return true;
}
/**
* Convert this Value from type String to another type
* @param newtype The Value type to convert to.
*/
public void convertString(int newtype) throws KettleValueException
{
switch(newtype)
{
case VALUE_TYPE_STRING : break;
case VALUE_TYPE_NUMBER : setValue( getNumber() ); break;
case VALUE_TYPE_DATE : setValue( getDate() ); break;
case VALUE_TYPE_BOOLEAN : setValue( getBoolean() ); break;
case VALUE_TYPE_INTEGER : setValue( getInteger() ); break;
case VALUE_TYPE_BIGNUMBER : setValue( getBigNumber() ); break;
default:
throw new KettleValueException("Please specify the type to convert to from String type.");
}
}
public Value(Repository rep, long id_value)
throws KettleException
{
try
{
Row r = rep.getValue(id_value);
if (r!=null)
{
name = r.getString("NAME", null);
String valstr = r.getString("VALUE_STR", null);
setValue( valstr );
int valtype = getType( r.getString("VALUE_TYPE", null) );
setType(valtype);
setNull( r.getBoolean("IS_NULL", false) );
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to load Value from repository with id_value="+id_value, dbe);
}
}
/**
* Returns whether "types" of the values are exactly the same: type,
* name, length, precision.
*
* @param v Value to compare type against.
*
* @return == true when types are the same
* == false when the types differ
*/
public boolean equalValueType(Value v)
{
if (v == null)
return false;
if (getType() != v.getType())
return false;
if ((getName() == null && v.getName() != null) ||
(getName() != null && v.getName() == null) ||
!(getName().equals(v.getName())))
return false;
if (getLength() != v.getLength())
return false;
if (getPrecision() != v.getPrecision())
return false;
return true;
}
}
| Small performance fix for non-padded string exports
git-svn-id: 9499f031eb5c9fb9d11553a06c92651e5446d292@1970 5fb7f6ec-07c1-534a-b4ca-9155e429e800
| src/be/ibridge/kettle/core/value/Value.java | Small performance fix for non-padded string exports | <ide><path>rc/be/ibridge/kettle/core/value/Value.java
<ide> }
<ide> else
<ide> {
<del> StringBuffer ret;
<del>
<del> if (isNull() || value.getString()==null) ret=new StringBuffer(Const.NULL_STRING);
<del> else ret=new StringBuffer(value.getString());
<del>
<del> if (pad)
<del> {
<del> int length = value.getLength();
<del> if (length>16384) length=16384; // otherwise we get OUT OF MEMORY errors for CLOBS.
<del> Const.rightPad(ret, length);
<del> }
<del>
<del> retval=ret.toString();
<add> if (pad)
<add> {
<add> StringBuffer ret;
<add>
<add> if (isNull() || value.getString()==null) ret=new StringBuffer(Const.NULL_STRING);
<add> else ret=new StringBuffer(value.getString());
<add>
<add> int length = value.getLength();
<add> if (length>16384) length=16384; // otherwise we get OUT OF MEMORY errors for CLOBS.
<add> Const.rightPad(ret, length);
<add>
<add> retval=ret.toString();
<add> }
<add> else
<add> {
<add> if (isNull() || value.getString()==null)
<add> {
<add> retval=Const.NULL_STRING;
<add> }
<add> else
<add> {
<add> retval = value.getString();
<add> }
<add> }
<ide> }
<ide> return retval;
<ide> } |
|
JavaScript | mit | f58f95c1bd3402c98b9720431cc77e128ba30519 | 0 | NAPWebProductionEditTeam/MagTool2,NAPWebProductionEditTeam/MagTool2,NAPWebProductionEditTeam/MagTool2 | /* globals magazineBuilder */
(function(window, $, app) {
function NewElement() {
// Add the new element to the DOM
var addToDom = function($element) {
var $selectable = app.Page.getContent();
// If a slug exists, add the new element after the slug, else add it to the top of the page
var $slug = app.Slug.findSlug();
if ($slug.length) {
$slug.after($element);
} else {
$element.prependTo(app.Page.getContent());
}
// Deselect all other elements
app.ContentEditor.deselectAll();
// If the new element is text or CTA make it editable
app.ContentEditor.applyEdit($element);
// Select the new Element
app.ContentEditor.select($element);
};
// Create New Text Element
this.newText = function() {
var $newDiv = $('<div/>', {
class: 'span-12 textAlignCenter push-down-18 push-right-18 editable resizable draggable ui-selectee'
});
$newDiv.text('NEW EMPTY TEXT ELEMENT');
addToDom($newDiv);
};
// Create New Image Element
this.newImage = function() {
var $newDiv = $('<div/>', {
class: 'span-12 textAlignCenter push-down-18 push-right-18 resizable draggable ui-selectee'
});
$newDiv.append('<img src="http://lorempixel.com/image_output/cats-q-c-200-200-9.jpg" alt="net-a-porter" data-img-src@2x="http://lorempixel.com/image_output/cats-q-c-200-200-9.jpg" />');
console.log("img = " + $newDiv);
addToDom($newDiv);
};
// Create New CTA Element
this.newCTA = function() {
var $newDiv = $('<div/>', {
class: 'btnShopThe span-12 textAlignCenter push-down-18 push-right-18 editable resizable draggable ui-selectee'
});
$newDiv.append('<a data-magtool="ntk" href="${CtaLinkXML[\'ntk\'].@url}">SHOP THE SELECTION</a>');
addToDom($newDiv);
};
}
app.modules.NewElement = NewElement;
})(window, jQuery, MagTool);
| src/js/Application/NewElement.js | /* globals magazineBuilder */
(function(window, $, app) {
function NewElement() {
// Add the new element to the DOM
var addToDom = function($element) {
var $selectable = app.Page.getContent();
// If a slug exists, add the new element after the slug, else add it to the top of the page
var $slug = app.Slug.findSlug();
if ($slug.length) {
$slug.after($element);
} else {
$element.prependTo(app.Page.getContent());
}
// Deselect all other elements
app.ContentEditor.deselectAll();
// If the new element is text or CTA make it editable
if ($element.hasClass('editable') || $element.hasClass('btnShopThe')) {
app.ContentEditor.applyEdit($element);
}
// Select the new Element
app.ContentEditor.select($element);
};
// Create New Text Element
this.newText = function() {
var $newDiv = $('<div/>', {
class: 'span-12 textAlignCenter push-down-18 push-right-18 editable resizable draggable ui-selectee'
});
$newDiv.text('NEW EMPTY TEXT ELEMENT');
addToDom($newDiv);
};
// Create New Image Element
this.newImage = function() {
var $newDiv = $('<div/>', {
class: 'span-12 textAlignCenter push-down-18 push-right-18 resizable draggable ui-selectee'
});
$newDiv.append('<img src="http://lorempixel.com/image_output/cats-q-c-200-200-9.jpg" alt="net-a-porter" data-img-src@2x="http://lorempixel.com/image_output/cats-q-c-200-200-9.jpg" />');
console.log("img = " + $newDiv);
addToDom($newDiv);
};
// Create New CTA Element
this.newCTA = function() {
var $newDiv = $('<div/>', {
class: 'btnShopThe span-12 textAlignCenter push-down-18 push-right-18 editable resizable draggable ui-selectee'
});
$newDiv.append('<a data-magtool="ntk" href="${CtaLinkXML[\'ntk\'].@url}">SHOP THE SELECTION</a>');
addToDom($newDiv);
};
}
app.modules.NewElement = NewElement;
})(window, jQuery, MagTool);
| NewElement make images editable.
| src/js/Application/NewElement.js | NewElement make images editable. | <ide><path>rc/js/Application/NewElement.js
<ide> app.ContentEditor.deselectAll();
<ide>
<ide> // If the new element is text or CTA make it editable
<del> if ($element.hasClass('editable') || $element.hasClass('btnShopThe')) {
<del> app.ContentEditor.applyEdit($element);
<del> }
<add> app.ContentEditor.applyEdit($element);
<ide>
<ide> // Select the new Element
<ide> app.ContentEditor.select($element); |
|
Java | apache-2.0 | 9dd4ae51cc386e95c5999bf6a5d5233918f35687 | 0 | pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus | /**
* Copyright 2007-2020 University Of Southern California
*
* <p>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
*
* <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 edu.isi.pegasus.planner.catalog.transformation.classes;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.node.TextNode;
import edu.isi.pegasus.planner.catalog.CatalogException;
import edu.isi.pegasus.planner.catalog.classes.CatalogEntryJsonDeserializer;
import edu.isi.pegasus.planner.catalog.classes.Profiles;
import edu.isi.pegasus.planner.catalog.classes.SysInfo;
import edu.isi.pegasus.planner.catalog.transformation.TransformationCatalogEntry;
import edu.isi.pegasus.planner.catalog.transformation.impl.Abstract;
import edu.isi.pegasus.planner.classes.Notifications;
import edu.isi.pegasus.planner.classes.Profile;
import edu.isi.pegasus.planner.namespace.Metadata;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* A convenience class for yaml serialization / deserialization of transformation catalog. Should
* not be used for anything else
*
* @author Karan Vahi
*/
@JsonDeserialize(using = TransformationDeserializer.class)
public class Transformation {
private TransformationCatalogEntry mBaseEntry;
private List<TransformationCatalogEntry> mSiteEntries;
public Transformation() {
mSiteEntries = new LinkedList();
}
public void setBaseTCEntry(TransformationCatalogEntry entry) {
mBaseEntry = entry;
}
public void addSiteTCEntry(TransformationCatalogEntry entry) {
this.mSiteEntries.add(entry);
}
public List<TransformationCatalogEntry> getTransformationCatalogEntries() {
List<TransformationCatalogEntry> entries = new LinkedList();
if (this.mSiteEntries.isEmpty()) {
entries.add(mBaseEntry);
return entries;
}
for (TransformationCatalogEntry siteEntry : mSiteEntries) {
entries.add(this.addSiteInformation(mBaseEntry, siteEntry));
}
return entries;
}
/**
* Adds site specific information from to the base tx, and returns a new merged tx
*
* @param base
* @param from
* @return
*/
protected TransformationCatalogEntry addSiteInformation(
TransformationCatalogEntry base, TransformationCatalogEntry from) {
TransformationCatalogEntry entry = (TransformationCatalogEntry) base.clone();
SysInfo sysInfo = new SysInfo();
entry.setResourceId(from.getResourceId());
entry.setSysInfo(from.getSysInfo());
entry.setType(from.getType());
entry.addProfiles(from.getProfiles());
entry.setPhysicalTransformation(from.getPhysicalTransformation());
entry.setForBypassStaging(from.bypassStaging());
entry.setContainer(from.getContainer());
return entry;
}
}
/**
* Custom deserializer for YAML representation of Transformation
*
* @author Karan Vahi
*/
class TransformationDeserializer extends CatalogEntryJsonDeserializer<Transformation> {
/**
* Deserializes a Transformation YAML description of the type
*
* <pre>
* namespace: "example"
* name: "keg"
* version: "1.0"
* profiles:
* env:
* APP_HOME: "/tmp/myscratch"
* JAVA_HOME: "/opt/java/1.6"
* pegasus:
* clusters.num: "1"
* checksum:
* sha256: abc123
* metadata:
* owner: vahi
* size: 1024
* requires:
* - anotherTr
* sites:
* name: "isi"
* type: "installed"
* pfn: "/path/to/keg"
* arch: "x86_64"
* os.type: "linux"
* os.release: "fc"
* os.version: "1.0"
* profiles:
* env:
* Hello: World
* JAVA_HOME: /bin/java.1.6
* condor:
* FOO: bar
* container: centos-pegasus
* </pre>
*
* @param parser
* @param dc
* @return
* @throws IOException
* @throws JsonProcessingException
*/
@Override
public Transformation deserialize(JsonParser parser, DeserializationContext dc)
throws IOException, JsonProcessingException {
ObjectCodec oc = parser.getCodec();
JsonNode node = oc.readTree(parser);
Transformation tx = new Transformation();
TransformationCatalogEntry base = new TransformationCatalogEntry();
Metadata checksum = null;
for (Iterator<Map.Entry<String, JsonNode>> it = node.fields(); it.hasNext(); ) {
Map.Entry<String, JsonNode> e = it.next();
String key = e.getKey();
TransformationCatalogKeywords reservedKey =
TransformationCatalogKeywords.getReservedKey(key);
if (reservedKey == null) {
this.complainForIllegalKey(
TransformationCatalogKeywords.TRANSFORMATIONS.getReservedName(), key, node);
}
switch (reservedKey) {
case NAMESPACE:
base.setLogicalNamespace(node.get(key).asText());
break;
case NAME:
base.setLogicalName(node.get(key).asText());
break;
case VERSION:
base.setLogicalVersion(node.get(key).asText());
break;
case METADATA:
base.addProfiles(this.createMetadata(node.get(key)));
break;
case CHECKSUM:
checksum =
this.createChecksum(
node.get(key),
TransformationCatalogKeywords.TRANSFORMATIONS
.getReservedName());
break;
case PROFILES:
JsonNode profilesNode = node.get(key);
if (profilesNode != null) {
parser = profilesNode.traverse(oc);
Profiles profiles = parser.readValueAs(Profiles.class);
base.addProfiles(profiles);
}
break;
case HOOKS:
JsonNode hooksNode = node.get(key);
if (hooksNode != null) {
parser = hooksNode.traverse(oc);
Notifications n = parser.readValueAs(Notifications.class);
base.addNotifications(n);
}
break;
case REQUIRES:
JsonNode requiresNode =
node.get(TransformationCatalogKeywords.REQUIRES.getReservedName());
if (requiresNode.isArray()) {
for (JsonNode dependentNode : requiresNode) {
base.addDependantTransformation(dependentNode.asText());
}
} else {
throw new CatalogException("requires: value should be of type array ");
}
break;
case SITES:
JsonNode sitesNode = node.get(key);
if (sitesNode.isArray()) {
for (JsonNode siteNode : sitesNode) {
TransformationCatalogEntry entry =
getSiteSpecificEntry(parser, siteNode, base);
tx.addSiteTCEntry(entry);
}
} else {
throw new CatalogException("sites: value should be of type array ");
}
break;
default:
this.complainForUnsupportedKey(
TransformationCatalogKeywords.TRANSFORMATIONS.getReservedName(),
key,
node);
}
}
if (checksum != null) {
// PM-1617 merge metadata profiles to include checksum
Metadata m = (Metadata) base.getProfilesNamepsace(Profiles.NAMESPACES.metadata);
if (m == null) {
// no metadata in the base, add checksum information into the base
for (Iterator<String> it = checksum.getProfileKeyIterator(); it.hasNext(); ) {
String key = it.next();
base.addProfile(
new Profile(checksum.namespaceName(), key, (String) checksum.get(key)));
}
} else {
// merge with existing metadata
m.merge(checksum);
}
}
tx.setBaseTCEntry(base);
return tx;
}
/**
* Parses site information from JsonNode and adds it to the transformation catalog entry.
*
* <pre>
* name: "isi"
* type: "installed"
* pfn: "/path/to/keg"
* bypass: true
* arch: "x86_64"
* os.type: "linux"
* os.release: "fc"
* os.version: "1.0"
* profiles:
* env:
* Hello: World
* JAVA_HOME: /bin/java.1.6
* condor:
* FOO: bar
* container: centos-pegasus
* </pre>
*
* @param parser
* @param node
* @param base
*/
protected TransformationCatalogEntry getSiteSpecificEntry(
JsonParser parser, JsonNode node, TransformationCatalogEntry base) throws IOException {
TransformationCatalogEntry entry = new TransformationCatalogEntry();
SysInfo sysInfo = new SysInfo();
ObjectCodec oc = parser.getCodec();
for (Iterator<Map.Entry<String, JsonNode>> it = node.fields(); it.hasNext(); ) {
Map.Entry<String, JsonNode> e = it.next();
String key = e.getKey();
TransformationCatalogKeywords reservedKey =
TransformationCatalogKeywords.getReservedKey(key);
switch (reservedKey) {
case NAME:
String siteName = node.get(key).asText();
entry.setResourceId(siteName);
break;
case BYPASS:
entry.setForBypassStaging(node.get(key).asBoolean());
break;
case SITE_ARCHITECTURE:
String architecture = node.get(key).asText();
sysInfo.setArchitecture(SysInfo.Architecture.valueOf(architecture));
break;
case SITE_OS:
String os = node.get(key).asText();
sysInfo.setOS(SysInfo.OS.valueOf(os));
break;
case SITE_OS_RELEASE:
String release = node.get(key).asText();
sysInfo.setOSRelease(release);
break;
case SITE_OS_VERSION:
String osVersion = node.get(key).asText();
sysInfo.setOSVersion(String.valueOf(osVersion));
break;
case TYPE:
String type = node.get(key).asText();
entry.setType(TCType.valueOf(type.toUpperCase()));
break;
case PROFILES:
JsonNode profilesNode = node.get(key);
if (profilesNode != null) {
parser = profilesNode.traverse(oc);
Profiles profiles = parser.readValueAs(Profiles.class);
entry.addProfiles(profiles);
}
break;
case METADATA:
entry.addProfiles(this.createMetadata(node.get(key)));
break;
case SITE_PFN:
String pfn = node.get(key).asText();
entry.setPhysicalTransformation(pfn);
break;
case SITE_CONTAINER_NAME:
JsonNode containerNode = node.get(key);
if (!(containerNode instanceof TextNode)) {
throw new CatalogException(
"Container node is fully defined in the tx "
+ base.getLogicalTransformation()
+ " instead of being a reference "
+ node);
}
String containerName = containerNode.asText();
entry.setContainer(new Container(containerName));
break;
default:
break;
}
}
entry.setSysInfo(sysInfo);
Abstract.modifyForFileURLS(entry);
return entry;
}
}
| src/edu/isi/pegasus/planner/catalog/transformation/classes/Transformation.java | /**
* Copyright 2007-2020 University Of Southern California
*
* <p>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
*
* <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 edu.isi.pegasus.planner.catalog.transformation.classes;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.node.TextNode;
import edu.isi.pegasus.planner.catalog.CatalogException;
import edu.isi.pegasus.planner.catalog.classes.CatalogEntryJsonDeserializer;
import edu.isi.pegasus.planner.catalog.classes.Profiles;
import edu.isi.pegasus.planner.catalog.classes.SysInfo;
import edu.isi.pegasus.planner.catalog.transformation.TransformationCatalogEntry;
import edu.isi.pegasus.planner.catalog.transformation.impl.Abstract;
import edu.isi.pegasus.planner.classes.Notifications;
import edu.isi.pegasus.planner.classes.Profile;
import edu.isi.pegasus.planner.namespace.Metadata;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* A convenience class for yaml serialization / deserialization of transformation catalog. Should
* not be used for anything else
*
* @author Karan Vahi
*/
@JsonDeserialize(using = TransformationDeserializer.class)
public class Transformation {
private TransformationCatalogEntry mBaseEntry;
private List<TransformationCatalogEntry> mSiteEntries;
public Transformation() {
mSiteEntries = new LinkedList();
}
public void setBaseTCEntry(TransformationCatalogEntry entry) {
mBaseEntry = entry;
}
public void addSiteTCEntry(TransformationCatalogEntry entry) {
this.mSiteEntries.add(entry);
}
public List<TransformationCatalogEntry> getTransformationCatalogEntries() {
List<TransformationCatalogEntry> entries = new LinkedList();
if (this.mSiteEntries.isEmpty()) {
entries.add(mBaseEntry);
return entries;
}
for (TransformationCatalogEntry siteEntry : mSiteEntries) {
entries.add(this.addSiteInformation(mBaseEntry, siteEntry));
}
return entries;
}
/**
* Adds site specific information from to the base tx, and returns a new merged tx
*
* @param base
* @param from
* @return
*/
protected TransformationCatalogEntry addSiteInformation(
TransformationCatalogEntry base, TransformationCatalogEntry from) {
TransformationCatalogEntry entry = (TransformationCatalogEntry) base.clone();
SysInfo sysInfo = new SysInfo();
entry.setResourceId(from.getResourceId());
entry.setSysInfo(from.getSysInfo());
entry.setType(from.getType());
entry.addProfiles(from.getProfiles());
entry.setPhysicalTransformation(from.getPhysicalTransformation());
entry.setForBypassStaging(from.bypassStaging());
entry.setContainer(from.getContainer());
return entry;
}
}
/**
* Custom deserializer for YAML representation of Transformation
*
* @author Karan Vahi
*/
class TransformationDeserializer extends CatalogEntryJsonDeserializer<Transformation> {
/**
* Deserializes a Transformation YAML description of the type
*
* <pre>
* namespace: "example"
* name: "keg"
* version: "1.0"
* profiles:
* env:
* APP_HOME: "/tmp/myscratch"
* JAVA_HOME: "/opt/java/1.6"
* pegasus:
* clusters.num: "1"
* checksum:
* sha256: abc123
* metadata:
* owner: vahi
* size: 1024
* requires:
* - anotherTr
* sites:
* name: "isi"
* type: "installed"
* pfn: "/path/to/keg"
* arch: "x86_64"
* os.type: "linux"
* os.release: "fc"
* os.version: "1.0"
* profiles:
* env:
* Hello: World
* JAVA_HOME: /bin/java.1.6
* condor:
* FOO: bar
* container: centos-pegasus
* </pre>
*
* @param parser
* @param dc
* @return
* @throws IOException
* @throws JsonProcessingException
*/
@Override
public Transformation deserialize(JsonParser parser, DeserializationContext dc)
throws IOException, JsonProcessingException {
ObjectCodec oc = parser.getCodec();
JsonNode node = oc.readTree(parser);
Transformation tx = new Transformation();
TransformationCatalogEntry base = new TransformationCatalogEntry();
Metadata checksum = null;
for (Iterator<Map.Entry<String, JsonNode>> it = node.fields(); it.hasNext(); ) {
Map.Entry<String, JsonNode> e = it.next();
String key = e.getKey();
TransformationCatalogKeywords reservedKey =
TransformationCatalogKeywords.getReservedKey(key);
if (reservedKey == null) {
this.complainForIllegalKey(
TransformationCatalogKeywords.TRANSFORMATIONS.getReservedName(), key, node);
}
switch (reservedKey) {
case NAMESPACE:
base.setLogicalNamespace(node.get(key).asText());
break;
case NAME:
base.setLogicalName(node.get(key).asText());
break;
case VERSION:
base.setLogicalVersion(node.get(key).asText());
break;
case METADATA:
base.addProfiles(this.createMetadata(node.get(key)));
break;
case CHECKSUM:
checksum =
this.createChecksum(
node.get(key),
TransformationCatalogKeywords.TRANSFORMATIONS
.getReservedName());
break;
case PROFILES:
JsonNode profilesNode = node.get(key);
if (profilesNode != null) {
parser = profilesNode.traverse(oc);
Profiles profiles = parser.readValueAs(Profiles.class);
base.addProfiles(profiles);
}
break;
case HOOKS:
JsonNode hooksNode = node.get(key);
if (hooksNode != null) {
parser = hooksNode.traverse(oc);
Notifications n = parser.readValueAs(Notifications.class);
base.addNotifications(n);
}
break;
case REQUIRES:
JsonNode requiresNode =
node.get(TransformationCatalogKeywords.REQUIRES.getReservedName());
if (requiresNode.isArray()) {
for (JsonNode dependentNode : requiresNode) {
base.addDependantTransformation(dependentNode.asText());
}
} else {
throw new CatalogException("requires: value should be of type array ");
}
break;
case SITES:
JsonNode sitesNode = node.get(key);
if (sitesNode.isArray()) {
for (JsonNode siteNode : sitesNode) {
TransformationCatalogEntry entry =
getSiteSpecificEntry(parser, siteNode, base);
tx.addSiteTCEntry(entry);
}
} else {
throw new CatalogException("sites: value should be of type array ");
}
break;
default:
this.complainForUnsupportedKey(
TransformationCatalogKeywords.TRANSFORMATIONS.getReservedName(),
key,
node);
}
}
if (checksum != null) {
// PM-1617 merge metadata profiles to include checksum
Metadata m = (Metadata) base.getProfilesNamepsace(Profiles.NAMESPACES.metadata);
if (m == null) {
// no metadata in the base, add checksum information into the base
for (Iterator<String> it = checksum.getProfileKeyIterator(); it.hasNext(); ) {
String key = it.next();
base.addProfile(
new Profile(checksum.namespaceName(), key, (String) checksum.get(key)));
}
} else {
// merge with existing metadata
m.merge(checksum);
}
}
tx.setBaseTCEntry(base);
return tx;
}
/**
* Parses site information from JsonNode and adds it to the transformation catalog entry.
*
* <pre>
* name: "isi"
* type: "installed"
* pfn: "/path/to/keg"
* bypass: true
* arch: "x86_64"
* os.type: "linux"
* os.release: "fc"
* os.version: "1.0"
* profiles:
* env:
* Hello: World
* JAVA_HOME: /bin/java.1.6
* condor:
* FOO: bar
* container: centos-pegasus
* </pre>
*
* @param parser
* @param node
* @param base
*/
protected TransformationCatalogEntry getSiteSpecificEntry(
JsonParser parser, JsonNode node, TransformationCatalogEntry base) throws IOException {
TransformationCatalogEntry entry = new TransformationCatalogEntry();
SysInfo sysInfo = new SysInfo();
ObjectCodec oc = parser.getCodec();
for (Iterator<Map.Entry<String, JsonNode>> it = node.fields(); it.hasNext(); ) {
Map.Entry<String, JsonNode> e = it.next();
String key = e.getKey();
TransformationCatalogKeywords reservedKey =
TransformationCatalogKeywords.getReservedKey(key);
switch (reservedKey) {
case NAME:
String siteName = node.get(key).asText();
entry.setResourceId(siteName);
break;
case BYPASS:
entry.setForBypassStaging(node.get(key).asBoolean());
break;
case SITE_ARCHITECTURE:
String architecture = node.get(key).asText();
sysInfo.setArchitecture(SysInfo.Architecture.valueOf(architecture));
break;
case SITE_OS_TYPE:
String os = node.get(key).asText();
sysInfo.setOS(SysInfo.OS.valueOf(os));
break;
case SITE_OS_RELEASE:
String release = node.get(key).asText();
sysInfo.setOSRelease(release);
break;
case SITE_OS_VERSION:
String osVersion = node.get(key).asText();
sysInfo.setOSVersion(String.valueOf(osVersion));
break;
case TYPE:
String type = node.get(key).asText();
entry.setType(TCType.valueOf(type.toUpperCase()));
break;
case PROFILES:
JsonNode profilesNode = node.get(key);
if (profilesNode != null) {
parser = profilesNode.traverse(oc);
Profiles profiles = parser.readValueAs(Profiles.class);
entry.addProfiles(profiles);
}
break;
case METADATA:
entry.addProfiles(this.createMetadata(node.get(key)));
break;
case SITE_PFN:
String pfn = node.get(key).asText();
entry.setPhysicalTransformation(pfn);
break;
case SITE_CONTAINER_NAME:
JsonNode containerNode = node.get(key);
if (!(containerNode instanceof TextNode)) {
throw new CatalogException(
"Container node is fully defined in the tx "
+ base.getLogicalTransformation()
+ " instead of being a reference "
+ node);
}
String containerName = containerNode.asText();
entry.setContainer(new Container(containerName));
break;
default:
break;
}
}
entry.setSysInfo(sysInfo);
Abstract.modifyForFileURLS(entry);
return entry;
}
}
| Revert "PM-1820 Fix invalid constant to SITE_OS_TYPE from SITE_OS"
This reverts commit c5e4d23404a4a10d87419e3cfdc98a19522c32b4.
| src/edu/isi/pegasus/planner/catalog/transformation/classes/Transformation.java | Revert "PM-1820 Fix invalid constant to SITE_OS_TYPE from SITE_OS" | <ide><path>rc/edu/isi/pegasus/planner/catalog/transformation/classes/Transformation.java
<ide> sysInfo.setArchitecture(SysInfo.Architecture.valueOf(architecture));
<ide> break;
<ide>
<del> case SITE_OS_TYPE:
<add> case SITE_OS:
<ide> String os = node.get(key).asText();
<ide> sysInfo.setOS(SysInfo.OS.valueOf(os));
<ide> break; |
|
Java | mit | ed1f246335a288e2e9fe986f1a8c1a38e2bbc13b | 0 | UCSB-CS56-Projects/cs56-games-minesweeper,UCSB-CS56-Projects/cs56-games-minesweeper | package edu.ucsb.cs56.projects.games.minesweeper.main;
import edu.ucsb.cs56.projects.games.minesweeper.gui.MineGUI;
import edu.ucsb.cs56.projects.games.minesweeper.text.TextGame;
/**
* It allows us to execute either version of the game (Text or GUI) through the generated jar file
* by specifying an option.
* MainEntry is assigned as Main-Class in the MANIFEST.MF file by the ant target 'jar'.
*
* @author Jose Recinos.
*/
public class MainEntry{
/**
* Takes a game mode from command line argument and executes the specified version of the game.
* @param args Either of two valid options: GUI or Text.
*/
//A jar can only have one Main-Class in its MANIFEST file. Which means only one version of the game can be executed when the jar is executed.
//To remedy this we have a main function that determines based on GAMEMODE passed which main function to run.
public static void main(String[] args){
String usage="Usage: java -jar Minesweeper.java [GAME MODE]" +
"\nGAME MODE:" +
"\n GUI : Executes GUI version of the game" +
"\n Text : Executes the terminal version of the game.";
if (args.length==0){
System.err.println("Missing GAMEMODE.\n"+usage);
System.exit(1);
}
else if ("GUI".equals(args[0])){
MineGUI.main(args);
}
else if("Text".equals(args[0])){
TextGame.main(args);
}
else{
System.out.println(usage);
System.exit(1);
}
}
} | src/edu/ucsb/cs56/projects/games/minesweeper/main/MainEntry.java | package edu.ucsb.cs56.projects.games.minesweeper.main;
import edu.ucsb.cs56.projects.games.minesweeper.gui.MineGUI;
import edu.ucsb.cs56.projects.games.minesweeper.text.TextGame;
/**
* It allows us to execute either version of the game (Text or GUI) through the generated jar file
* by specifying an option.
* MainEntry is assigned as Main-Class in the MANIFEST.MF file by the ant target 'jar'.
*
* @author Jose Recinos.
*/
public class MainEntry{
/**
* Takes a game mode from command line argument and executes the specified version of the game.
* @param args Either of two valid options: GUI or Text.
*/
//A jar can only have one Main-Class in its MANIFEST file. Which means only one version of the game can be executed when the jar is executed.
//To remedy this we have a main function that determines based on GAMEMODE passed which main function to run.
public static void main(String[] args){
String usage="Usage: java -jar Minesweeper.java [GAMEMODE]" +
"\nGAMEMODE:" +
"\n GUI : Executes GUI version of the game" +
"\n Text : Executes the terminal version of the game.";
if (args.length==0){
System.err.println("Missing GAMEMODE.\n"+usage);
System.exit(1);
}
else if ("GUI".equals(args[0])){
MineGUI.main(args);
}
else if("Text".equals(args[0])){
TextGame.main(args);
}
else{
System.out.println(usage);
System.exit(1);
}
}
} | Improved doc comments
| src/edu/ucsb/cs56/projects/games/minesweeper/main/MainEntry.java | Improved doc comments | <ide><path>rc/edu/ucsb/cs56/projects/games/minesweeper/main/MainEntry.java
<ide> //A jar can only have one Main-Class in its MANIFEST file. Which means only one version of the game can be executed when the jar is executed.
<ide> //To remedy this we have a main function that determines based on GAMEMODE passed which main function to run.
<ide> public static void main(String[] args){
<del> String usage="Usage: java -jar Minesweeper.java [GAMEMODE]" +
<del> "\nGAMEMODE:" +
<add> String usage="Usage: java -jar Minesweeper.java [GAME MODE]" +
<add> "\nGAME MODE:" +
<ide> "\n GUI : Executes GUI version of the game" +
<ide> "\n Text : Executes the terminal version of the game.";
<ide> if (args.length==0){ |
|
Java | apache-2.0 | 72fdcca8999e6ff0d7d3feafd4d8847b2c20a392 | 0 | anylineorg/anyline,anylineorg/anyline | /*
* Copyright 2006-2020 www.anyline.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.anyline.web.tag;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import org.anyline.util.BasicUtil;
import org.anyline.util.BeanUtil;
import org.anyline.util.ConfigTable;
import org.anyline.util.DESUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* 是否选中 一类的单个复选
* <al:checkbox name="role${item.CODE }" value="1" data="" head="" headValue="${item.CODE }"></al:checkbox>
* value:选中值
* value="{1,2,3,4,5}" item.get(valueKey)是在1,3,4,5集合中时选中
* value="${list}" property="ID" item.get(valueKey)是在list.items.property 集合中时选中
* rely="CHK" data.item.CHK = true或1时选中 根据rely列的值 判断是否选中
*
* text 支持多列 {ID}-{NM}
*/
public class Checkbox extends BaseBodyTag {
private static final long serialVersionUID = 1L;
private String scope;
private Object data;
private String valueKey = ConfigTable.getString("DEFAULT_PRIMARY_KEY","ID");
private String textKey = "NM";
//private Object checked; //
private String property;
private String rely;
private String head;
private String headValue;
private String checkedValue = "";
private boolean checked = false;
private String border = "true";//条目border(内部包含checkox,label) true, false, div, li, dd
private String borderClazz = "al-chk-item-border";//
private String labelClazz = "al-chk-item-label";
private String label = "";//label标签体,如果未定义label则生成默认label标签体{textKey}
@SuppressWarnings({ "rawtypes", "unchecked" })
public int doEndTag() throws JspException {
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
StringBuilder html = new StringBuilder();
// valueKey = DataRow.keyCase(valueKey);
// textKey = DataRow.keyCase(textKey);
try {
if(null == rely){
rely = property;
}
if(null == rely){
rely = valueKey;
}
if (null != data) {
if (data instanceof String) {
if (data.toString().endsWith("}")) {
data = data.toString().replace("{", "").replace("}", "");
} else {
if ("servelt".equals(scope) || "application".equalsIgnoreCase(scope)) {
data = request.getSession().getServletContext().getAttribute(data.toString());
} else if ("session".equals(scope)) {
data = request.getSession().getAttribute(data.toString());
} else {
data = request.getAttribute(data.toString());
}
}
}
if (data instanceof String) {
String items[] = data.toString().split(",");
List list = new ArrayList();
for (String item : items) {
Map map = new HashMap();
String ks[] = BeanUtil.parseKeyValue(item);
map.put(valueKey, ks[0]);
map.put(textKey, ks[1]);
if(ks.length>2){
map.put("CHK", ks[2]);
}
list.add(map);
}
data = list;
}
//选中值
if (null != this.value) {
if(!(this.value instanceof String || this.value instanceof Collection)){
this.value = this.value.toString();
}
if (this.value instanceof String) {
if (this.value.toString().endsWith("}")) {
this.value = this.value.toString().replace("{", "").replace("}", "");
}
}
if (this.value instanceof String) {
this.value = new ArrayList(Arrays.asList(this.value.toString().split(",")));
}else if(this.value instanceof Collection){
List list = new ArrayList();
Collection cols = (Collection)this.value;
for(Object item:cols){
Object val = item;
if(item instanceof Map){
val = ((Map)item).get(rely);
}
list.add(val);
}
this.value = list;
}
}
Collection<Map> items = (Collection<Map>) data;
Collection<?> chks = (Collection<?>)this.value;
//条目边框
String itemBorderTagName ="";
String itemBorderStartTag = "";
String itemBorderEndTag = "";
if(BasicUtil.isNotEmpty(border) && !"false".equals(border)){
if("true".equalsIgnoreCase(border)){
itemBorderTagName = "div";
}else{
itemBorderTagName = border;
}
itemBorderStartTag = "<"+itemBorderTagName+" class=\""+borderClazz+"\">";
itemBorderEndTag = "</"+itemBorderTagName+">";
}
if(null == headValue){
headValue = "";
}
if(null != head){
String id = this.id;
if(BasicUtil.isEmpty(id)){
id = name +"_"+ headValue;
}
html.append(itemBorderStartTag);
html.append("<input type=\"checkbox\"");
if(null != headValue){
if(checked || checkedValue.equals(headValue) || "true".equalsIgnoreCase(headValue) || "checked".equalsIgnoreCase(headValue) || checked(value,headValue) ) {
html.append(" checked=\"checked\"");
}
}
Map<String,String> map = new HashMap<String,String>();
map.put(valueKey, headValue);
html.append(attribute() + crateExtraData(map) + "/>");
html.append("<label for=\"").append(id).append("\" class=\""+labelClazz+"\">").append(head).append("</label>\n");
html.append(itemBorderEndTag);
}
if (null != items)
for (Map item : items) {
Object val = item.get(valueKey);
if(this.encrypt){
val = DESUtil.encryptValue(val+"");
}
String id = this.id;
if(BasicUtil.isEmpty(id)){
id = name +"_"+ val;
}
html.append(itemBorderStartTag);
html.append("<input type=\"checkbox\" value=\"").append(val).append("\" id=\"").append(id).append("\"");
Object chk = null;
if(BasicUtil.isNotEmpty(rely)){
chk = item.get(rely);
if(null != chk){
chk = chk.toString().trim();
}
}
if(checkedValue.equals(chk) || "true".equalsIgnoreCase(chk+"") || "checked".equalsIgnoreCase(chk+"") || checked(chks,item.get(valueKey)) ) {
html.append(" checked=\"checked\"");
}
html.append(attribute()).append(crateExtraData(item)).append("/>");
if(BasicUtil.isEmpty(label)){
String labelHtml = "<label for=\""+id+ "\" class=\""+labelClazz+"\">";
String labelBody = "";
if (textKey.contains("{")) {
labelBody = BeanUtil.parseRuntimeValue(item,textKey);
} else {
Object v = item.get(textKey);
if (null != v) {
labelBody = v.toString();
}
}
labelHtml += labelBody +"</label>\n";
html.append(labelHtml);
}else{//指定label文本
String labelHtml = label;
if(labelHtml.contains("{") && labelHtml.contains("}")){
labelHtml = BeanUtil.parseRuntimeValue(item,labelHtml);
}
html.append(labelHtml);
}
html.append(itemBorderEndTag);
}
}
JspWriter out = pageContext.getOut();
out.print(html.toString());
} catch (Exception e) {
e.printStackTrace();
if(ConfigTable.isDebug() && log.isWarnEnabled()){
e.printStackTrace();
}
} finally {
release();
}
return EVAL_PAGE;
}
private boolean checked(Collection<?> chks, Object value){
if(null != chks){
for(Object chk:chks){
if(null != chk && null != value && chk.toString().equals(value.toString())){
return true;
}
}
}
return false;
}
@SuppressWarnings("rawtypes")
private boolean checked(Object chks, Object value){
if(null != chks){
if(chks instanceof Collection){
return checked((Collection)chks, value);
}else{
return chks.equals(value);
}
}
return false;
}
public Object getData() {
return data;
}
public String getProperty() {
return property;
}
public void setCheckKey(String property) {
this.property = property;
}
public void setData(Object data) {
this.data = data;
}
public String getValueKey() {
return valueKey;
}
public void setValueKey(String valueKey) {
this.valueKey = valueKey;
}
public String getTextKey() {
return textKey;
}
public void setTextKey(String textKey) {
this.textKey = textKey;
}
@Override
public void release() {
super.release();
scope = null;
data = null;
value = null;
property = null;
head= null;
headValue="";
valueKey = ConfigTable.getString("DEFAULT_PRIMARY_KEY","ID");
textKey = "NM";
rely = null;
checked = false;
border = "true";
borderClazz = "al-chk-item-border";
labelClazz = "al-chk-item-label";
label = "";
}
public String getBorder() {
return border;
}
public void setBorder(String border) {
this.border = border;
}
public String getHead() {
return head;
}
public void setHead(String head) {
this.head = head;
}
public String getHeadValue() {
return headValue;
}
public void setHeadValue(String headValue) {
this.headValue = headValue;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public void setProperty(String property) {
this.property = property;
}
public String getRely() {
return rely;
}
public void setRely(String rely) {
this.rely = rely;
}
public String getBorderClazz() {
return borderClazz;
}
public void setBorderClazz(String borderClazz) {
this.borderClazz = borderClazz;
}
public String getLabelClazz() {
return labelClazz;
}
public void setLabelClazz(String labelClazz) {
this.labelClazz = labelClazz;
}
public String getCheckedValue() {
return checkedValue;
}
public void setCheckedValue(String checkedValue) {
this.checkedValue = checkedValue;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
| anyline-web/src/main/java/org/anyline/web/tag/Checkbox.java | /*
* Copyright 2006-2020 www.anyline.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.anyline.web.tag;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import org.anyline.util.BasicUtil;
import org.anyline.util.BeanUtil;
import org.anyline.util.ConfigTable;
import org.anyline.util.DESUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* 是否选中 一类的单个复选
* <al:checkbox name="role${item.CODE }" value="1" data="" head="" headValue="${item.CODE }"></al:checkbox>
* value:选中值
* value="{1,2,3,4,5}" item.get(valueKey)是在1,3,4,5集合中时选中
* value="${list}" property="ID" item.get(valueKey)是在list.items.property 集合中时选中
* rely="CHK" data.item.CHK = true或1时选中 根据rely列的值 判断是否选中
*
* text 支持多列 {ID}-{NM}
*/
public class Checkbox extends BaseBodyTag {
private static final long serialVersionUID = 1L;
private String scope;
private Object data;
private String valueKey = ConfigTable.getString("DEFAULT_PRIMARY_KEY","ID");
private String textKey = "NM";
//private Object checked; //
private String property;
private String rely;
private String head;
private String headValue;
private String checkedValue = "";
private boolean checked = false;
private String border = "true";//条目border(内部包含checkox,label) true, false, div, li, dd
private String borderClazz = "al-chk-item-border";//
private String labelClazz = "al-chk-item-label";
private String label = "";//label标签体,如果未定义label则生成默认label标签体{textKey}
@SuppressWarnings({ "rawtypes", "unchecked" })
public int doEndTag() throws JspException {
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
StringBuilder html = new StringBuilder();
// valueKey = DataRow.keyCase(valueKey);
// textKey = DataRow.keyCase(textKey);
try {
if(null == rely){
rely = property;
}
if(null == rely){
rely = valueKey;
}
if (null != data) {
if (data instanceof String) {
if (data.toString().endsWith("}")) {
data = data.toString().replace("{", "").replace("}", "");
} else {
if ("servelt".equals(scope) || "application".equalsIgnoreCase(scope)) {
data = request.getSession().getServletContext().getAttribute(data.toString());
} else if ("session".equals(scope)) {
data = request.getSession().getAttribute(data.toString());
} else {
data = request.getAttribute(data.toString());
}
}
}
if (data instanceof String) {
String items[] = data.toString().split(",");
List list = new ArrayList();
for (String item : items) {
Map map = new HashMap();
String ks[] = BeanUtil.parseKeyValue(item);
map.put(valueKey, ks[0]);
map.put(textKey, ks[1]);
if(ks.length>2){
map.put("CHK", ks[2]);
}
list.add(map);
}
data = list;
}
//选中值
if (null != this.value) {
if(!(this.value instanceof String || this.value instanceof Collection)){
this.value = this.value.toString();
}
if (this.value instanceof String) {
if (this.value.toString().endsWith("}")) {
this.value = this.value.toString().replace("{", "").replace("}", "");
}
}
if (this.value instanceof String) {
String items[] = this.value.toString().split(",");
List list = new ArrayList();
for (String item : items) {
list.add(item);
}
this.value = list;
}else if(this.value instanceof Collection){
List list = new ArrayList();
Collection cols = (Collection)this.value;
for(Object item:cols){
Object val = item;
if(item instanceof Map){
val = ((Map)item).get(rely);
}
list.add(val);
}
this.value = list;
}
}
Collection<Map> items = (Collection<Map>) data;
Collection<?> chks = (Collection<?>)this.value;
//条目边框
String itemBorderTagName ="";
String itemBorderStartTag = "";
String itemBorderEndTag = "";
if(BasicUtil.isNotEmpty(border) && !"false".equals(border)){
if("true".equalsIgnoreCase(border)){
itemBorderTagName = "div";
}else{
itemBorderTagName = border;
}
itemBorderStartTag = "<"+itemBorderTagName+" class=\""+borderClazz+"\">";
itemBorderEndTag = "</"+itemBorderTagName+">";
}
if(null == headValue){
headValue = "";
}
if(null != head){
String id = this.id;
if(BasicUtil.isEmpty(id)){
id = name +"_"+ headValue;
}
html.append(itemBorderStartTag);
html.append("<input type=\"checkbox\"");
if(null != headValue){
if(checked || checkedValue.equals(headValue) || "true".equalsIgnoreCase(headValue) || "checked".equalsIgnoreCase(headValue) || checked(value,headValue) ) {
html.append(" checked=\"checked\"");
}
}
Map<String,String> map = new HashMap<String,String>();
map.put(valueKey, headValue);
html.append(attribute() + crateExtraData(map) + "/>");
html.append("<label for=\"").append(id).append("\" class=\""+labelClazz+"\">").append(head).append("</label>\n");
html.append(itemBorderEndTag);
}
if (null != items)
for (Map item : items) {
Object val = item.get(valueKey);
if(this.encrypt){
val = DESUtil.encryptValue(val+"");
}
String id = this.id;
if(BasicUtil.isEmpty(id)){
id = name +"_"+ val;
}
html.append(itemBorderStartTag);
html.append("<input type=\"checkbox\" value=\"").append(val).append("\" id=\"").append(id).append("\"");
Object chk = null;
if(BasicUtil.isNotEmpty(rely)){
chk = item.get(rely);
if(null != chk){
chk = chk.toString().trim();
}
}
if(checkedValue.equals(chk) || "true".equalsIgnoreCase(chk+"") || "checked".equalsIgnoreCase(chk+"") || checked(chks,item.get(valueKey)) ) {
html.append(" checked=\"checked\"");
}
html.append(attribute()).append(crateExtraData(item)).append("/>");
if(BasicUtil.isEmpty(label)){
String labelHtml = "<label for=\""+id+ "\" class=\""+labelClazz+"\">";
String labelBody = "";
if (textKey.contains("{")) {
labelBody = BeanUtil.parseRuntimeValue(item,textKey);
} else {
Object v = item.get(textKey);
if (null != v) {
labelBody = v.toString();
}
}
labelHtml += labelBody +"</label>\n";
html.append(labelHtml);
}else{//指定label文本
String labelHtml = label;
if(labelHtml.contains("{") && labelHtml.contains("}")){
labelHtml = BeanUtil.parseRuntimeValue(item,labelHtml);
}
html.append(labelHtml);
}
html.append(itemBorderEndTag);
}
}
JspWriter out = pageContext.getOut();
out.print(html.toString());
} catch (Exception e) {
e.printStackTrace();
if(ConfigTable.isDebug() && log.isWarnEnabled()){
e.printStackTrace();
}
} finally {
release();
}
return EVAL_PAGE;
}
private boolean checked(Collection<?> chks, Object value){
if(null != chks){
for(Object chk:chks){
if(null != chk && null != value && chk.toString().equals(value.toString())){
return true;
}
}
}
return false;
}
@SuppressWarnings("rawtypes")
private boolean checked(Object chks, Object value){
if(null != chks){
if(chks instanceof Collection){
return checked((Collection)chks, value);
}else{
return chks.equals(value);
}
}
return false;
}
public Object getData() {
return data;
}
public String getProperty() {
return property;
}
public void setCheckKey(String property) {
this.property = property;
}
public void setData(Object data) {
this.data = data;
}
public String getValueKey() {
return valueKey;
}
public void setValueKey(String valueKey) {
this.valueKey = valueKey;
}
public String getTextKey() {
return textKey;
}
public void setTextKey(String textKey) {
this.textKey = textKey;
}
@Override
public void release() {
super.release();
scope = null;
data = null;
value = null;
property = null;
head= null;
headValue="";
valueKey = ConfigTable.getString("DEFAULT_PRIMARY_KEY","ID");
textKey = "NM";
rely = null;
checked = false;
border = "true";
borderClazz = "al-chk-item-border";
labelClazz = "al-chk-item-label";
label = "";
}
public String getBorder() {
return border;
}
public void setBorder(String border) {
this.border = border;
}
public String getHead() {
return head;
}
public void setHead(String head) {
this.head = head;
}
public String getHeadValue() {
return headValue;
}
public void setHeadValue(String headValue) {
this.headValue = headValue;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public void setProperty(String property) {
this.property = property;
}
public String getRely() {
return rely;
}
public void setRely(String rely) {
this.rely = rely;
}
public String getBorderClazz() {
return borderClazz;
}
public void setBorderClazz(String borderClazz) {
this.borderClazz = borderClazz;
}
public String getLabelClazz() {
return labelClazz;
}
public void setLabelClazz(String labelClazz) {
this.labelClazz = labelClazz;
}
public String getCheckedValue() {
return checkedValue;
}
public void setCheckedValue(String checkedValue) {
this.checkedValue = checkedValue;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
| checkbox
| anyline-web/src/main/java/org/anyline/web/tag/Checkbox.java | checkbox | <ide><path>nyline-web/src/main/java/org/anyline/web/tag/Checkbox.java
<ide>
<ide> package org.anyline.web.tag;
<ide>
<del>import java.util.ArrayList;
<del>import java.util.Collection;
<del>import java.util.HashMap;
<del>import java.util.List;
<del>import java.util.Map;
<add>import java.util.*;
<ide>
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import javax.servlet.jsp.JspException;
<ide> this.value = this.value.toString().replace("{", "").replace("}", "");
<ide> }
<ide> }
<del> if (this.value instanceof String) {
<del> String items[] = this.value.toString().split(",");
<del> List list = new ArrayList();
<del> for (String item : items) {
<del> list.add(item);
<del> }
<del> this.value = list;
<add> if (this.value instanceof String) {
<add> this.value = new ArrayList(Arrays.asList(this.value.toString().split(",")));
<ide> }else if(this.value instanceof Collection){
<ide> List list = new ArrayList();
<ide> Collection cols = (Collection)this.value; |
|
Java | agpl-3.0 | fdca93f2d8ba5a3e964f230663bf01c600708941 | 0 | tdefilip/opennms,aihua/opennms,aihua/opennms,roskens/opennms-pre-github,tdefilip/opennms,aihua/opennms,tdefilip/opennms,rdkgit/opennms,tdefilip/opennms,rdkgit/opennms,aihua/opennms,tdefilip/opennms,tdefilip/opennms,tdefilip/opennms,aihua/opennms,roskens/opennms-pre-github,rdkgit/opennms,roskens/opennms-pre-github,rdkgit/opennms,rdkgit/opennms,rdkgit/opennms,rdkgit/opennms,tdefilip/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,rdkgit/opennms,tdefilip/opennms,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,aihua/opennms | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2011-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.smoketest;
import java.io.File;
import org.junit.After;
import org.junit.Before;
import org.opennms.test.mock.MockLogAppender;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.thoughtworks.selenium.SeleneseTestBase;
import com.thoughtworks.selenium.SeleniumException;
public class OpenNMSSeleniumTestCase extends SeleneseTestBase {
protected static final String LOAD_TIMEOUT = "60000";
protected static final String BASE_URL = "http://localhost:8980/";
@Before
public void setUp() throws Exception {
final String logLevel = System.getProperty("org.opennms.smoketest.logLevel", "DEBUG");
MockLogAppender.setupLogging(true, logLevel);
WebDriver driver = null;
// Google Chrome if chrome driver property is set
final String chromeDriverLocation = System.getProperty("webdriver.chrome.driver");
if (chromeDriverLocation != null) {
final File chromeDriverFile = new File(chromeDriverLocation);
if (chromeDriverFile.exists() && chromeDriverFile.canExecute()) {
System.err.println("using chrome driver");
driver = new ChromeDriver();
}
}
// otherwise, Firefox
if (driver == null) {
//final File phantomJS = new File("/usr/local/bin/phantomjs");
//if (phantomJS.exists()) {
// final DesiredCapabilities caps = new DesiredCapabilities();
// caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "/usr/local/bin/phantomjs");
// driver = new PhantomJSDriver(caps);
//} else {
driver = new FirefoxDriver();
//}
}
selenium = new WebDriverBackedSelenium(driver, BASE_URL);
selenium.open("/opennms/login.jsp");
selenium.type("name=j_username", "admin");
selenium.type("name=j_password", "admin");
selenium.click("name=Login");
waitForPageToLoad();
}
@After
public void tearDown() throws Exception {
if (selenium != null) {
try {
if (selenium.isElementPresent("link=Log out")) selenium.click("link=Log out");
} catch (final SeleniumException e) {
// don't worry about it, this is just for logging out
}
selenium.stop();
}
}
protected void waitForPageToLoad() {
selenium.waitForPageToLoad(LOAD_TIMEOUT);
}
}
| smoke-test/src/test/java/org/opennms/smoketest/OpenNMSSeleniumTestCase.java | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2011-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.smoketest;
import java.io.File;
import org.junit.After;
import org.junit.Before;
import org.opennms.test.mock.MockLogAppender;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.thoughtworks.selenium.SeleneseTestBase;
public class OpenNMSSeleniumTestCase extends SeleneseTestBase {
protected static final String LOAD_TIMEOUT = "60000";
protected static final String BASE_URL = "http://localhost:8980/";
@Before
public void setUp() throws Exception {
final String logLevel = System.getProperty("org.opennms.smoketest.logLevel", "DEBUG");
MockLogAppender.setupLogging(true, logLevel);
WebDriver driver = null;
// Google Chrome if chrome driver property is set
final String chromeDriverLocation = System.getProperty("webdriver.chrome.driver");
if (chromeDriverLocation != null) {
final File chromeDriverFile = new File(chromeDriverLocation);
if (chromeDriverFile.exists() && chromeDriverFile.canExecute()) {
System.err.println("using chrome driver");
driver = new ChromeDriver();
}
}
// otherwise, Firefox
if (driver == null) {
//final File phantomJS = new File("/usr/local/bin/phantomjs");
//if (phantomJS.exists()) {
// final DesiredCapabilities caps = new DesiredCapabilities();
// caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "/usr/local/bin/phantomjs");
// driver = new PhantomJSDriver(caps);
//} else {
driver = new FirefoxDriver();
//}
}
selenium = new WebDriverBackedSelenium(driver, BASE_URL);
selenium.open("/opennms/login.jsp");
selenium.type("name=j_username", "admin");
selenium.type("name=j_password", "admin");
selenium.click("name=Login");
waitForPageToLoad();
}
@After
public void tearDown() throws Exception {
if (selenium != null) {
try {
if (selenium.isElementPresent("link=Log out")) selenium.click("link=Log out");
} catch (final SeleniumException e) {
// don't worry about it, this is just for logging out
}
selenium.stop();
}
}
}
protected void waitForPageToLoad() {
selenium.waitForPageToLoad(LOAD_TIMEOUT);
}
}
| fix a merge issue
| smoke-test/src/test/java/org/opennms/smoketest/OpenNMSSeleniumTestCase.java | fix a merge issue | <ide><path>moke-test/src/test/java/org/opennms/smoketest/OpenNMSSeleniumTestCase.java
<ide> import org.openqa.selenium.firefox.FirefoxDriver;
<ide>
<ide> import com.thoughtworks.selenium.SeleneseTestBase;
<add>import com.thoughtworks.selenium.SeleniumException;
<ide>
<ide> public class OpenNMSSeleniumTestCase extends SeleneseTestBase {
<ide> protected static final String LOAD_TIMEOUT = "60000";
<ide> }
<ide> }
<ide>
<del> }
<del>
<ide> protected void waitForPageToLoad() {
<ide> selenium.waitForPageToLoad(LOAD_TIMEOUT);
<ide> } |
|
Java | apache-2.0 | 0f061f9ceb5478c0f01e4b3360ec7565426f667f | 0 | googleapis/java-bigtable-hbase,googleapis/java-bigtable-hbase,sduskis/cloud-bigtable-client,kevinsi4508/cloud-bigtable-client,sduskis/cloud-bigtable-client,googleapis/java-bigtable-hbase,kevinsi4508/cloud-bigtable-client | /*
* Copyright 2015 Google 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.google.cloud.bigtable.grpc;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLException;
import com.google.api.client.util.Strings;
import com.google.bigtable.admin.v2.ListClustersResponse;
import com.google.cloud.bigtable.config.BigtableOptions;
import com.google.cloud.bigtable.config.BigtableVersionInfo;
import com.google.cloud.bigtable.config.CredentialOptions;
import com.google.cloud.bigtable.config.Logger;
import com.google.cloud.bigtable.config.RetryOptions;
import com.google.cloud.bigtable.grpc.async.AsyncExecutor;
import com.google.cloud.bigtable.grpc.async.BulkMutation;
import com.google.cloud.bigtable.grpc.async.BulkRead;
import com.google.cloud.bigtable.grpc.async.ResourceLimiter;
import com.google.cloud.bigtable.grpc.async.OperationAccountant;
import com.google.cloud.bigtable.grpc.io.ChannelPool;
import com.google.cloud.bigtable.grpc.io.CredentialInterceptorCache;
import com.google.cloud.bigtable.grpc.io.GoogleCloudResourcePrefixInterceptor;
import com.google.cloud.bigtable.metrics.BigtableClientMetrics;
import com.google.cloud.bigtable.metrics.BigtableClientMetrics.MetricLevel;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import io.grpc.ClientInterceptor;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.internal.DnsNameResolverProvider;
import io.grpc.internal.GrpcUtil;
import io.grpc.netty.NettyChannelBuilder;
import io.netty.util.Recycler;
/**
* <p>Encapsulates the creation of Bigtable Grpc services.</p>
*
* <p>The following functionality is handled by this class:
* <ol>
* <li> Created Executors
* <li> Creates Channels - netty ChannelImpls, ReconnectingChannel and ChannelPools
* <li> Creates ChannelInterceptors - auth headers, performance interceptors.
* <li> Close anything above that needs to be closed (ExecutorService, CahnnelImpls)
* </ol>
*
* @author sduskis
* @version $Id: $Id
*/
public class BigtableSession implements Closeable {
private static ChannelPool cachedDataChannelPool = null;
private static final Logger LOG = new Logger(BigtableSession.class);
private static ResourceLimiter resourceLimiter;
// 256 MB, server has 256 MB limit.
private final static int MAX_MESSAGE_SIZE = 1 << 28;
@VisibleForTesting
static final String PROJECT_ID_EMPTY_OR_NULL = "ProjectId must not be empty or null.";
@VisibleForTesting
static final String INSTANCE_ID_EMPTY_OR_NULL = "InstanceId must not be empty or null.";
@VisibleForTesting
static final String USER_AGENT_EMPTY_OR_NULL = "UserAgent must not be empty or null";
static {
turnOffNettyRecycler();
performWarmup();
}
/**
* The netty {@link Recycler} has caused some problems for long running operations in some
* versions of netty. As of this comment (10/21/2016), we are using netty 4.1.3.Final. The
* Recycler uses a system property, "io.netty.recycler.maxCapacity" which needs to be set to "0"
* to turn off potentially problematic behavior. The string gets transformed via the shading
* process, and ends up being similar to the Recycler's package name. This method sets the value
* to "0" if the value is not set.
*/
@VisibleForTesting
static void turnOffNettyRecycler() {
String packageName = Recycler.class.getName();
String prefix = packageName.substring(0, packageName.indexOf(".util.Recycler"));
final String key = prefix + ".recycler.maxCapacity";
LOG.debug("Using prefix %s for io.netty.", prefix);
if (System.getProperty(key) == null) {
System.setProperty(key, "0");
}
}
private static void performWarmup() {
// Initialize some core dependencies in parallel. This can speed up startup by 150+ ms.
ExecutorService connectionStartupExecutor = Executors
.newCachedThreadPool(GrpcUtil.getThreadFactory("BigtableSession-startup-%d", true));
connectionStartupExecutor.execute(new Runnable() {
@Override
public void run() {
// The first invocation of BigtableSessionSharedThreadPools.getInstance() is expensive.
// Reference it so that it gets constructed asynchronously.
BigtableSessionSharedThreadPools.getInstance();
}
});
for (final String host : Arrays.asList(BigtableOptions.BIGTABLE_DATA_HOST_DEFAULT,
BigtableOptions.BIGTABLE_TABLE_ADMIN_HOST_DEFAULT)) {
connectionStartupExecutor.execute(new Runnable() {
@Override
public void run() {
// The first invocation of InetAddress retrieval is expensive.
// Reference it so that it gets constructed asynchronously.
try {
InetAddress.getByName(host);
} catch (UnknownHostException e) {
// ignore. This doesn't happen frequently, but even if it does, it's inconsequential.
}
}
});
}
connectionStartupExecutor.shutdown();
}
private synchronized static void initializeResourceLimiter(BigtableOptions options) {
if (resourceLimiter == null) {
int maxInflightRpcs = options.getBulkOptions().getMaxInflightRpcs();
long maxMemory = options.getBulkOptions().getMaxMemory();
resourceLimiter = new ResourceLimiter(maxMemory, maxInflightRpcs);
}
}
private final BigtableDataClient dataClient;
private BigtableTableAdminClient tableAdminClient;
private BigtableInstanceGrpcClient instanceAdminClient;
private final BigtableOptions options;
private final List<ManagedChannel> managedChannels = Collections
.synchronizedList(new ArrayList<ManagedChannel>());
private final ClientInterceptor[] headerInterceptors;
/**
* This cluster name is either configured via BigtableOptions' clusterId, or via a lookup of the
* clusterID based on BigtableOptions projectId and instanceId. See {@link BigtableClusterUtilities}
*/
private BigtableClusterName clusterName;
/**
* <p>Constructor for BigtableSession.</p>
*
* @param opts a {@link com.google.cloud.bigtable.config.BigtableOptions} object.
* @throws java.io.IOException if any.
*/
public BigtableSession(BigtableOptions opts) throws IOException {
this.options = resolveLegacyOptions(opts);
Preconditions.checkArgument(
!Strings.isNullOrEmpty(options.getProjectId()), PROJECT_ID_EMPTY_OR_NULL);
Preconditions.checkArgument(
!Strings.isNullOrEmpty(options.getInstanceId()), INSTANCE_ID_EMPTY_OR_NULL);
Preconditions.checkArgument(
!Strings.isNullOrEmpty(options.getUserAgent()), USER_AGENT_EMPTY_OR_NULL);
LOG.info(
"Opening connection for projectId %s, instanceId %s, "
+ "on data host %s, table admin host %s.",
options.getProjectId(), options.getInstanceId(), options.getDataHost(),
options.getTableAdminHost());
LOG.info("Bigtable options: %s.", options);
Builder<ClientInterceptor> headerInterceptorBuilder = new ImmutableList.Builder<>();
headerInterceptorBuilder.add(
new GoogleCloudResourcePrefixInterceptor(options.getInstanceName().toString()));
// Looking up Credentials takes time. Creating the retry executor and the EventLoopGroup don't
// take as long, but still take time. Get the credentials on one thread, and start up the elg
// and scheduledRetries thread pools on another thread.
CredentialInterceptorCache credentialsCache = CredentialInterceptorCache.getInstance();
RetryOptions retryOptions = options.getRetryOptions();
CredentialOptions credentialOptions = options.getCredentialOptions();
try {
ClientInterceptor headerInterceptor =
credentialsCache.getCredentialsInterceptor(credentialOptions, retryOptions);
if (headerInterceptor != null) {
headerInterceptorBuilder.add(headerInterceptor);
}
} catch (GeneralSecurityException e) {
throw new IOException("Could not initialize credentials.", e);
}
headerInterceptors = headerInterceptorBuilder.build().toArray(new ClientInterceptor[0]);
ChannelPool dataChannel = getDataChannelPool();
BigtableSessionSharedThreadPools sharedPools = BigtableSessionSharedThreadPools.getInstance();
// More often than not, users want the dataClient. Create a new one in the constructor.
this.dataClient =
new BigtableDataGrpcClient(dataChannel, sharedPools.getRetryExecutor(), options);
dataClient.setCallOptionsFactory(
new CallOptionsFactory.ConfiguredCallOptionsFactory(options.getCallOptionsConfig()));
// Defer the creation of both the tableAdminClient until we need them.
BigtableClientMetrics.counter(MetricLevel.Info, "sessions.active").inc();
initializeResourceLimiter(options);
}
private ChannelPool getDataChannelPool() throws IOException {
String host = options.getDataHost();
int channelCount = options.getChannelCount();
if (options.useCachedChannel()) {
synchronized (BigtableSession.class) {
// TODO: Ensure that the host and channelCount are the same.
if (cachedDataChannelPool == null) {
cachedDataChannelPool = createChannelPool(host, channelCount);
}
return cachedDataChannelPool;
}
}
return createManagedPool(host, channelCount);
}
/**
* Return options with legacy input options, if any, resolved into currently supported options.
*/
private BigtableOptions resolveLegacyOptions(BigtableOptions options) throws IOException {
if (options.getClusterId() != null && options.getZoneId() != null) {
String instanceId =
BigtableClusterUtilities.lookupInstanceId(
options.getProjectId(),
options.getClusterId(),
options.getZoneId()
);
if (options.getInstanceId() != null) {
Preconditions.checkArgument(
options.getInstanceId().equals(instanceId),
"Supplied instanceId: '%s', zoneId: '%s' and clusterId: '%s'. They do not match."
+ "\nFound instanceId '%s' that corresponds to the zoneId/clusterId",
options.getInstanceId(),
options.getZoneId(),
options.getClusterId(),
instanceId);
}
return options.toBuilder().setInstanceId(instanceId).build();
}
return options;
}
/**
* Snapshot operations need various aspects of a {@link BigtableClusterName}. This method gets a
* clusterId from either a lookup (projectId and instanceId translate to a single clusterId when
* an instance has only one cluster) or from {@link BigtableOptions#getClusterId()}.
*/
public synchronized BigtableClusterName getClusterName() throws IOException {
if (this.clusterName == null) {
try (BigtableClusterUtilities util =
BigtableClusterUtilities.forInstance(options.getProjectId(), options.getInstanceId())) {
ListClustersResponse clusters = util.getClusters();
Preconditions.checkState(clusters.getClustersCount() == 1,
String.format(
"Project '%s' / Instance '%s' has %d clusters. There must be exactly 1 for this operation to work.",
options.getProjectId(), options.getInstanceId(), clusters.getClustersCount()));
clusterName = new BigtableClusterName(clusters.getClusters(0).getName());
} catch (GeneralSecurityException e) {
throw new IOException("Could not get cluster Id.", e);
}
}
return clusterName;
}
/**
* <p>Getter for the field <code>dataClient</code>.</p>
*
* @return a {@link com.google.cloud.bigtable.grpc.BigtableDataClient} object.
*/
public BigtableDataClient getDataClient() {
return dataClient;
}
/**
* <p>createAsyncExecutor.</p>
*
* @return a {@link com.google.cloud.bigtable.grpc.async.AsyncExecutor} object.
*/
public AsyncExecutor createAsyncExecutor() {
return new AsyncExecutor(dataClient, new OperationAccountant(resourceLimiter));
}
/**
* <p>createBulkMutation.</p>
*
* @param tableName a {@link com.google.cloud.bigtable.grpc.BigtableTableName} object.
* @param asyncExecutor a {@link com.google.cloud.bigtable.grpc.async.AsyncExecutor} object.
* @return a {@link com.google.cloud.bigtable.grpc.async.BulkMutation} object.
*/
public BulkMutation createBulkMutation(BigtableTableName tableName, AsyncExecutor asyncExecutor) {
return new BulkMutation(
tableName,
asyncExecutor,
options.getRetryOptions(),
BigtableSessionSharedThreadPools.getInstance().getRetryExecutor(),
options.getBulkOptions().getBulkMaxRowKeyCount(),
options.getBulkOptions().getBulkMaxRequestSize(),
options.getBulkOptions().getAutoflushMs());
}
/**
* <p>createBulkRead.</p>
*
* @param tableName a {@link com.google.cloud.bigtable.grpc.BigtableTableName} object.
* @return a {@link com.google.cloud.bigtable.grpc.async.BulkRead} object.
*/
public BulkRead createBulkRead(BigtableTableName tableName) {
return new BulkRead(dataClient, tableName, options.getBulkOptions().getBulkMaxRowKeyCount(),
BigtableSessionSharedThreadPools.getInstance().getBatchThreadPool()
);
}
/**
* <p>Getter for the field <code>tableAdminClient</code>.</p>
*
* @return a {@link com.google.cloud.bigtable.grpc.BigtableTableAdminClient} object.
* @throws java.io.IOException if any.
*/
public synchronized BigtableTableAdminClient getTableAdminClient() throws IOException {
if (tableAdminClient == null) {
ManagedChannel channel = createChannelPool(options.getTableAdminHost(), 1);
tableAdminClient = new BigtableTableAdminGrpcClient(channel);
}
return tableAdminClient;
}
/**
* <p>Getter for the field <code>instanceAdminClient</code>.</p>
*
* @return a {@link com.google.cloud.bigtable.grpc.BigtableInstanceClient} object.
* @throws java.io.IOException if any.
*/
public synchronized BigtableInstanceClient getInstanceAdminClient() throws IOException {
if (instanceAdminClient == null) {
ManagedChannel channel = createChannelPool(options.getInstanceAdminHost(), 1);
instanceAdminClient = new BigtableInstanceGrpcClient(channel);
}
return instanceAdminClient;
}
/**
* Create a new {@link com.google.cloud.bigtable.grpc.io.ChannelPool}, with auth headers.
*
* @param hostString a {@link java.lang.String} object.
* @return a {@link com.google.cloud.bigtable.grpc.io.ChannelPool} object.
* @throws java.io.IOException if any.
*/
protected ChannelPool createChannelPool(final String hostString, int count) throws IOException {
ChannelPool.ChannelFactory channelFactory = new ChannelPool.ChannelFactory() {
@Override
public ManagedChannel create() throws IOException {
return createNettyChannel(hostString, options, headerInterceptors);
}
};
return new ChannelPool(channelFactory, count);
}
/**
* Create a new {@link com.google.cloud.bigtable.grpc.io.ChannelPool}, with auth headers, that
* will be cleaned up when the connection closes.
*
* @param hostString a {@link java.lang.String} object.
* @return a {@link com.google.cloud.bigtable.grpc.io.ChannelPool} object.
* @throws java.io.IOException if any.
*/
protected ChannelPool createManagedPool(String host, int channelCount) throws IOException {
ChannelPool channelPool = createChannelPool(host, channelCount);
managedChannels.add(channelPool);
return channelPool;
}
/**
* Create a new {@link com.google.cloud.bigtable.grpc.io.ChannelPool}, with auth headers.
*
* @param host a {@link String} object.
* @param options a {@link BigtableOptions} object.
* @return a {@link ChannelPool} object.
* @throws IOException if any.
* @throws GeneralSecurityException
*/
public static ChannelPool createChannelPool(final String host, final BigtableOptions options)
throws IOException, GeneralSecurityException {
return createChannelPool(host, options, 1);
}
/**
* Create a new {@link com.google.cloud.bigtable.grpc.io.ChannelPool}, with auth headers.
*
* @param host a {@link String} object specifying the host to connect to.
* @param options a {@link BigtableOptions} object with the credentials, retry and other connection options.
* @param count an int defining the number of channels to create
* @return a {@link ChannelPool} object.
* @throws IOException if any.
* @throws GeneralSecurityException
*/
public static ChannelPool createChannelPool(final String host, final BigtableOptions options, int count)
throws IOException, GeneralSecurityException {
final ClientInterceptor credentialsInterceptor = CredentialInterceptorCache.getInstance()
.getCredentialsInterceptor(options.getCredentialOptions(), options.getRetryOptions());
final ClientInterceptor prefixInterceptor =
new GoogleCloudResourcePrefixInterceptor(options.getInstanceName().toString());
return new ChannelPool(
new ChannelPool.ChannelFactory() {
@Override
public ManagedChannel create() throws IOException {
return createNettyChannel(host, options, credentialsInterceptor, prefixInterceptor);
}
}, count);
}
/**
* <p>createNettyChannel.</p>
*
* @param host a {@link String} object.
* @param options a {@link BigtableOptions} object.
* @return a {@link ManagedChannel} object.
* @throws IOException if any.
*/
public static ManagedChannel createNettyChannel(String host,
BigtableOptions options, ClientInterceptor ... interceptors) throws SSLException {
// Ideally, this should be ManagedChannelBuilder.forAddress(...) rather than an explicit
// call to NettyChannelBuilder. Unfortunately, that doesn't work for shaded artifacts.
ManagedChannelBuilder<?> builder = NettyChannelBuilder.forAddress(host, options.getPort());
if (options.usePlaintextNegotiation()) {
builder.usePlaintext(true);
}
return builder
.nameResolverFactory(new DnsNameResolverProvider())
.idleTimeout(Long.MAX_VALUE, TimeUnit.SECONDS)
.maxInboundMessageSize(MAX_MESSAGE_SIZE)
.userAgent(BigtableVersionInfo.CORE_UESR_AGENT + "," + options.getUserAgent())
.intercept(interceptors)
.build();
}
/** {@inheritDoc} */
@Override
public synchronized void close() throws IOException {
if (managedChannels.isEmpty()) {
return;
}
long timeoutNanos = TimeUnit.SECONDS.toNanos(10);
long endTimeNanos = System.nanoTime() + timeoutNanos;
for (ManagedChannel channel : managedChannels) {
channel.shutdown();
}
for (ManagedChannel channel : managedChannels) {
long awaitTimeNanos = endTimeNanos - System.nanoTime();
if (awaitTimeNanos <= 0) {
break;
}
try {
channel.awaitTermination(awaitTimeNanos, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted while closing the channelPools");
}
}
for (ManagedChannel channel : managedChannels) {
if (!channel.isTerminated()) {
// Sometimes, gRPC channels don't close properly. We cannot explain why that happens,
// nor can we reproduce the problem reliably. However, that doesn't actually cause
// problems. Synchronous RPCs will throw exceptions right away. Buffered Mutator based
// async operations are already logged. Direct async operations may have some trouble,
// but users should not currently be using them directly.
//
// NOTE: We haven't seen this problem since removing the RefreshingChannel
LOG.info("Could not close the channel after 10 seconds.");
break;
}
}
managedChannels.clear();
BigtableClientMetrics.counter(MetricLevel.Info, "sessions.active").dec();
}
/**
* <p>Getter for the field <code>options</code>.</p>
*
* @return a {@link com.google.cloud.bigtable.config.BigtableOptions} object.
*/
public BigtableOptions getOptions() {
return this.options;
}
}
| bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableSession.java | /*
* Copyright 2015 Google 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.google.cloud.bigtable.grpc;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLException;
import com.google.api.client.util.Strings;
import com.google.bigtable.admin.v2.ListClustersResponse;
import com.google.cloud.bigtable.config.BigtableOptions;
import com.google.cloud.bigtable.config.BigtableVersionInfo;
import com.google.cloud.bigtable.config.CredentialOptions;
import com.google.cloud.bigtable.config.Logger;
import com.google.cloud.bigtable.config.RetryOptions;
import com.google.cloud.bigtable.grpc.async.AsyncExecutor;
import com.google.cloud.bigtable.grpc.async.BulkMutation;
import com.google.cloud.bigtable.grpc.async.BulkRead;
import com.google.cloud.bigtable.grpc.async.ResourceLimiter;
import com.google.cloud.bigtable.grpc.async.OperationAccountant;
import com.google.cloud.bigtable.grpc.io.ChannelPool;
import com.google.cloud.bigtable.grpc.io.CredentialInterceptorCache;
import com.google.cloud.bigtable.grpc.io.GoogleCloudResourcePrefixInterceptor;
import com.google.cloud.bigtable.metrics.BigtableClientMetrics;
import com.google.cloud.bigtable.metrics.BigtableClientMetrics.MetricLevel;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import io.grpc.ClientInterceptor;
import io.grpc.ManagedChannel;
import io.grpc.internal.DnsNameResolverProvider;
import io.grpc.internal.GrpcUtil;
import io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.NegotiationType;
import io.grpc.netty.NettyChannelBuilder;
import io.netty.handler.ssl.OpenSsl;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.util.Recycler;
/**
* <p>Encapsulates the creation of Bigtable Grpc services.</p>
*
* <p>The following functionality is handled by this class:
* <ol>
* <li> Created Executors
* <li> Creates Channels - netty ChannelImpls, ReconnectingChannel and ChannelPools
* <li> Creates ChannelInterceptors - auth headers, performance interceptors.
* <li> Close anything above that needs to be closed (ExecutorService, CahnnelImpls)
* </ol>
*
* @author sduskis
* @version $Id: $Id
*/
public class BigtableSession implements Closeable {
private static ChannelPool cachedDataChannelPool = null;
private static final Logger LOG = new Logger(BigtableSession.class);
private static SslContextBuilder sslBuilder;
private static ResourceLimiter resourceLimiter;
// 256 MB, server has 256 MB limit.
private final static int MAX_MESSAGE_SIZE = 1 << 28;
// 1 MB -- TODO(sduskis): make this configurable
private final static int FLOW_CONTROL_WINDOW = 1 << 20;
@VisibleForTesting
static final String PROJECT_ID_EMPTY_OR_NULL = "ProjectId must not be empty or null.";
@VisibleForTesting
static final String INSTANCE_ID_EMPTY_OR_NULL = "InstanceId must not be empty or null.";
@VisibleForTesting
static final String USER_AGENT_EMPTY_OR_NULL = "UserAgent must not be empty or null";
static {
turnOffNettyRecycler();
performWarmup();
}
/**
* The netty {@link Recycler} has caused some problems for long running operations in some
* versions of netty. As of this comment (10/21/2016), we are using netty 4.1.3.Final. The
* Recycler uses a system property, "io.netty.recycler.maxCapacity" which needs to be set to "0"
* to turn off potentially problematic behavior. The string gets transformed via the shading
* process, and ends up being similar to the Recycler's package name. This method sets the value
* to "0" if the value is not set.
*/
@VisibleForTesting
static void turnOffNettyRecycler() {
String packageName = Recycler.class.getName();
String prefix = packageName.substring(0, packageName.indexOf(".util.Recycler"));
final String key = prefix + ".recycler.maxCapacity";
LOG.debug("Using prefix %s for io.netty.", prefix);
if (System.getProperty(key) == null) {
System.setProperty(key, "0");
}
}
private synchronized static SslContext createSslContext() throws SSLException {
if (sslBuilder == null) {
sslBuilder = GrpcSslContexts.forClient().ciphers(null);
}
return sslBuilder.build();
}
private static void performWarmup() {
// Initialize some core dependencies in parallel. This can speed up startup by 150+ ms.
ExecutorService connectionStartupExecutor = Executors
.newCachedThreadPool(GrpcUtil.getThreadFactory("BigtableSession-startup-%d", true));
connectionStartupExecutor.execute(new Runnable() {
@Override
public void run() {
// The first invocation of createSslContext() is expensive.
// Create a throw away object in order to speed up the creation of the first
// BigtableConnection which uses SslContexts under the covers.
try {
// We create multiple channels via refreshing and pooling channel implementation.
// Each one needs its own SslContext.
createSslContext();
} catch (SSLException e) {
LOG.warn("Could not asynchronously create the ssl context", e);
}
}
});
connectionStartupExecutor.execute(new Runnable() {
@Override
public void run() {
// The first invocation of BigtableSessionSharedThreadPools.getInstance() is expensive.
// Reference it so that it gets constructed asynchronously.
BigtableSessionSharedThreadPools.getInstance();
}
});
for (final String host : Arrays.asList(BigtableOptions.BIGTABLE_DATA_HOST_DEFAULT,
BigtableOptions.BIGTABLE_TABLE_ADMIN_HOST_DEFAULT)) {
connectionStartupExecutor.execute(new Runnable() {
@Override
public void run() {
// The first invocation of InetAddress retrieval is expensive.
// Reference it so that it gets constructed asynchronously.
try {
InetAddress.getByName(host);
} catch (UnknownHostException e) {
// ignore. This doesn't happen frequently, but even if it does, it's inconsequential.
}
}
});
}
connectionStartupExecutor.shutdown();
}
private synchronized static void initializeResourceLimiter(BigtableOptions options) {
if (resourceLimiter == null) {
int maxInflightRpcs = options.getBulkOptions().getMaxInflightRpcs();
long maxMemory = options.getBulkOptions().getMaxMemory();
resourceLimiter = new ResourceLimiter(maxMemory, maxInflightRpcs);
}
}
private final BigtableDataClient dataClient;
private BigtableTableAdminClient tableAdminClient;
private BigtableInstanceGrpcClient instanceAdminClient;
private final BigtableOptions options;
private final List<ManagedChannel> managedChannels = Collections
.synchronizedList(new ArrayList<ManagedChannel>());
private final ClientInterceptor[] headerInterceptors;
/**
* This cluster name is either configured via BigtableOptions' clusterId, or via a lookup of the
* clusterID based on BigtableOptions projectId and instanceId. See {@link BigtableClusterUtilities}
*/
private BigtableClusterName clusterName;
/**
* <p>Constructor for BigtableSession.</p>
*
* @param opts a {@link com.google.cloud.bigtable.config.BigtableOptions} object.
* @throws java.io.IOException if any.
*/
public BigtableSession(BigtableOptions opts) throws IOException {
this.options = resolveLegacyOptions(opts);
Preconditions.checkArgument(
!Strings.isNullOrEmpty(options.getProjectId()), PROJECT_ID_EMPTY_OR_NULL);
Preconditions.checkArgument(
!Strings.isNullOrEmpty(options.getInstanceId()), INSTANCE_ID_EMPTY_OR_NULL);
Preconditions.checkArgument(
!Strings.isNullOrEmpty(options.getUserAgent()), USER_AGENT_EMPTY_OR_NULL);
LOG.info(
"Opening connection for projectId %s, instanceId %s, "
+ "on data host %s, table admin host %s.",
options.getProjectId(), options.getInstanceId(), options.getDataHost(),
options.getTableAdminHost());
LOG.info("Bigtable options: %s.", options);
Builder<ClientInterceptor> headerInterceptorBuilder = new ImmutableList.Builder<>();
headerInterceptorBuilder.add(
new GoogleCloudResourcePrefixInterceptor(options.getInstanceName().toString()));
// Looking up Credentials takes time. Creating the retry executor and the EventLoopGroup don't
// take as long, but still take time. Get the credentials on one thread, and start up the elg
// and scheduledRetries thread pools on another thread.
CredentialInterceptorCache credentialsCache = CredentialInterceptorCache.getInstance();
RetryOptions retryOptions = options.getRetryOptions();
CredentialOptions credentialOptions = options.getCredentialOptions();
try {
ClientInterceptor headerInterceptor =
credentialsCache.getCredentialsInterceptor(credentialOptions, retryOptions);
if (headerInterceptor != null) {
headerInterceptorBuilder.add(headerInterceptor);
}
} catch (GeneralSecurityException e) {
throw new IOException("Could not initialize credentials.", e);
}
headerInterceptors = headerInterceptorBuilder.build().toArray(new ClientInterceptor[0]);
ChannelPool dataChannel = getDataChannelPool();
BigtableSessionSharedThreadPools sharedPools = BigtableSessionSharedThreadPools.getInstance();
// More often than not, users want the dataClient. Create a new one in the constructor.
this.dataClient =
new BigtableDataGrpcClient(dataChannel, sharedPools.getRetryExecutor(), options);
dataClient.setCallOptionsFactory(
new CallOptionsFactory.ConfiguredCallOptionsFactory(options.getCallOptionsConfig()));
// Defer the creation of both the tableAdminClient until we need them.
BigtableClientMetrics.counter(MetricLevel.Info, "sessions.active").inc();
initializeResourceLimiter(options);
}
private ChannelPool getDataChannelPool() throws IOException {
String host = options.getDataHost();
int channelCount = options.getChannelCount();
if (options.useCachedChannel()) {
synchronized (BigtableSession.class) {
// TODO: Ensure that the host and channelCount are the same.
if (cachedDataChannelPool == null) {
cachedDataChannelPool = createChannelPool(host, channelCount);
}
return cachedDataChannelPool;
}
}
return createManagedPool(host, channelCount);
}
/**
* Return options with legacy input options, if any, resolved into currently supported options.
*/
private BigtableOptions resolveLegacyOptions(BigtableOptions options) throws IOException {
if (options.getClusterId() != null && options.getZoneId() != null) {
String instanceId =
BigtableClusterUtilities.lookupInstanceId(
options.getProjectId(),
options.getClusterId(),
options.getZoneId()
);
if (options.getInstanceId() != null) {
Preconditions.checkArgument(
options.getInstanceId().equals(instanceId),
"Supplied instanceId: '%s', zoneId: '%s' and clusterId: '%s'. They do not match."
+ "\nFound instanceId '%s' that corresponds to the zoneId/clusterId",
options.getInstanceId(),
options.getZoneId(),
options.getClusterId(),
instanceId);
}
return options.toBuilder().setInstanceId(instanceId).build();
}
return options;
}
/**
* Snapshot operations need various aspects of a {@link BigtableClusterName}. This method gets a
* clusterId from either a lookup (projectId and instanceId translate to a single clusterId when
* an instance has only one cluster) or from {@link BigtableOptions#getClusterId()}.
*/
public synchronized BigtableClusterName getClusterName() throws IOException {
if (this.clusterName == null) {
try (BigtableClusterUtilities util =
BigtableClusterUtilities.forInstance(options.getProjectId(), options.getInstanceId())) {
ListClustersResponse clusters = util.getClusters();
Preconditions.checkState(clusters.getClustersCount() == 1,
String.format(
"Project '%s' / Instance '%s' has %d clusters. There must be exactly 1 for this operation to work.",
options.getProjectId(), options.getInstanceId(), clusters.getClustersCount()));
clusterName = new BigtableClusterName(clusters.getClusters(0).getName());
} catch (GeneralSecurityException e) {
throw new IOException("Could not get cluster Id.", e);
}
}
return clusterName;
}
/**
* <p>Getter for the field <code>dataClient</code>.</p>
*
* @return a {@link com.google.cloud.bigtable.grpc.BigtableDataClient} object.
*/
public BigtableDataClient getDataClient() {
return dataClient;
}
/**
* <p>createAsyncExecutor.</p>
*
* @return a {@link com.google.cloud.bigtable.grpc.async.AsyncExecutor} object.
*/
public AsyncExecutor createAsyncExecutor() {
return new AsyncExecutor(dataClient, new OperationAccountant(resourceLimiter));
}
/**
* <p>createBulkMutation.</p>
*
* @param tableName a {@link com.google.cloud.bigtable.grpc.BigtableTableName} object.
* @param asyncExecutor a {@link com.google.cloud.bigtable.grpc.async.AsyncExecutor} object.
* @return a {@link com.google.cloud.bigtable.grpc.async.BulkMutation} object.
*/
public BulkMutation createBulkMutation(BigtableTableName tableName, AsyncExecutor asyncExecutor) {
return new BulkMutation(
tableName,
asyncExecutor,
options.getRetryOptions(),
BigtableSessionSharedThreadPools.getInstance().getRetryExecutor(),
options.getBulkOptions().getBulkMaxRowKeyCount(),
options.getBulkOptions().getBulkMaxRequestSize(),
options.getBulkOptions().getAutoflushMs());
}
/**
* <p>createBulkRead.</p>
*
* @param tableName a {@link com.google.cloud.bigtable.grpc.BigtableTableName} object.
* @return a {@link com.google.cloud.bigtable.grpc.async.BulkRead} object.
*/
public BulkRead createBulkRead(BigtableTableName tableName) {
return new BulkRead(dataClient, tableName, options.getBulkOptions().getBulkMaxRowKeyCount(),
BigtableSessionSharedThreadPools.getInstance().getBatchThreadPool()
);
}
/**
* <p>Getter for the field <code>tableAdminClient</code>.</p>
*
* @return a {@link com.google.cloud.bigtable.grpc.BigtableTableAdminClient} object.
* @throws java.io.IOException if any.
*/
public synchronized BigtableTableAdminClient getTableAdminClient() throws IOException {
if (tableAdminClient == null) {
ManagedChannel channel = createChannelPool(options.getTableAdminHost(), 1);
tableAdminClient = new BigtableTableAdminGrpcClient(channel);
}
return tableAdminClient;
}
/**
* <p>Getter for the field <code>instanceAdminClient</code>.</p>
*
* @return a {@link com.google.cloud.bigtable.grpc.BigtableInstanceClient} object.
* @throws java.io.IOException if any.
*/
public synchronized BigtableInstanceClient getInstanceAdminClient() throws IOException {
if (instanceAdminClient == null) {
ManagedChannel channel = createChannelPool(options.getInstanceAdminHost(), 1);
instanceAdminClient = new BigtableInstanceGrpcClient(channel);
}
return instanceAdminClient;
}
/**
* Create a new {@link com.google.cloud.bigtable.grpc.io.ChannelPool}, with auth headers.
*
* @param hostString a {@link java.lang.String} object.
* @return a {@link com.google.cloud.bigtable.grpc.io.ChannelPool} object.
* @throws java.io.IOException if any.
*/
protected ChannelPool createChannelPool(final String hostString, int count) throws IOException {
ChannelPool.ChannelFactory channelFactory = new ChannelPool.ChannelFactory() {
@Override
public ManagedChannel create() throws IOException {
return createNettyChannel(hostString, options, headerInterceptors);
}
};
return new ChannelPool(channelFactory, count);
}
/**
* Create a new {@link com.google.cloud.bigtable.grpc.io.ChannelPool}, with auth headers, that
* will be cleaned up when the connection closes.
*
* @param hostString a {@link java.lang.String} object.
* @return a {@link com.google.cloud.bigtable.grpc.io.ChannelPool} object.
* @throws java.io.IOException if any.
*/
protected ChannelPool createManagedPool(String host, int channelCount) throws IOException {
ChannelPool channelPool = createChannelPool(host, channelCount);
managedChannels.add(channelPool);
return channelPool;
}
/**
* Create a new {@link com.google.cloud.bigtable.grpc.io.ChannelPool}, with auth headers.
*
* @param host a {@link String} object.
* @param options a {@link BigtableOptions} object.
* @return a {@link ChannelPool} object.
* @throws IOException if any.
* @throws GeneralSecurityException
*/
public static ChannelPool createChannelPool(final String host, final BigtableOptions options)
throws IOException, GeneralSecurityException {
return createChannelPool(host, options, 1);
}
/**
* Create a new {@link com.google.cloud.bigtable.grpc.io.ChannelPool}, with auth headers.
*
* @param host a {@link String} object specifying the host to connect to.
* @param options a {@link BigtableOptions} object with the credentials, retry and other connection options.
* @param count an int defining the number of channels to create
* @return a {@link ChannelPool} object.
* @throws IOException if any.
* @throws GeneralSecurityException
*/
public static ChannelPool createChannelPool(final String host, final BigtableOptions options, int count)
throws IOException, GeneralSecurityException {
final ClientInterceptor credentialsInterceptor = CredentialInterceptorCache.getInstance()
.getCredentialsInterceptor(options.getCredentialOptions(), options.getRetryOptions());
final ClientInterceptor prefixInterceptor =
new GoogleCloudResourcePrefixInterceptor(options.getInstanceName().toString());
return new ChannelPool(
new ChannelPool.ChannelFactory() {
@Override
public ManagedChannel create() throws IOException {
return createNettyChannel(host, options, credentialsInterceptor, prefixInterceptor);
}
}, count);
}
/**
* <p>createNettyChannel.</p>
*
* @param host a {@link String} object.
* @param options a {@link BigtableOptions} object.
* @return a {@link ManagedChannel} object.
* @throws IOException if any.
*/
public static ManagedChannel createNettyChannel(String host,
BigtableOptions options, ClientInterceptor ... interceptors) throws SSLException {
NegotiationType negotiationType = options.usePlaintextNegotiation() ?
NegotiationType.PLAINTEXT : NegotiationType.TLS;
return NettyChannelBuilder
.forAddress(host, options.getPort())
.nameResolverFactory(new DnsNameResolverProvider())
.idleTimeout(Long.MAX_VALUE, TimeUnit.SECONDS)
.maxInboundMessageSize(MAX_MESSAGE_SIZE)
.sslContext(createSslContext())
.negotiationType(negotiationType)
.userAgent(BigtableVersionInfo.CORE_UESR_AGENT + "," + options.getUserAgent())
.flowControlWindow(FLOW_CONTROL_WINDOW)
.intercept(interceptors)
.build();
}
/** {@inheritDoc} */
@Override
public synchronized void close() throws IOException {
if (managedChannels.isEmpty()) {
return;
}
long timeoutNanos = TimeUnit.SECONDS.toNanos(10);
long endTimeNanos = System.nanoTime() + timeoutNanos;
for (ManagedChannel channel : managedChannels) {
channel.shutdown();
}
for (ManagedChannel channel : managedChannels) {
long awaitTimeNanos = endTimeNanos - System.nanoTime();
if (awaitTimeNanos <= 0) {
break;
}
try {
channel.awaitTermination(awaitTimeNanos, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted while closing the channelPools");
}
}
for (ManagedChannel channel : managedChannels) {
if (!channel.isTerminated()) {
// Sometimes, gRPC channels don't close properly. We cannot explain why that happens,
// nor can we reproduce the problem reliably. However, that doesn't actually cause
// problems. Synchronous RPCs will throw exceptions right away. Buffered Mutator based
// async operations are already logged. Direct async operations may have some trouble,
// but users should not currently be using them directly.
//
// NOTE: We haven't seen this problem since removing the RefreshingChannel
LOG.info("Could not close the channel after 10 seconds.");
break;
}
}
managedChannels.clear();
BigtableClientMetrics.counter(MetricLevel.Info, "sessions.active").dec();
}
/**
* <p>Getter for the field <code>options</code>.</p>
*
* @return a {@link com.google.cloud.bigtable.config.BigtableOptions} object.
*/
public BigtableOptions getOptions() {
return this.options;
}
}
| Use the ManagedChannelBuilder public API. (#1295)
Ideally, we shouldn't care about NettyChannelBuilder vs. OkHttpChannelBuilder or any other specific implementation detail. All we should care about is using ManagedChannelBuilder. For now, use the ManagedChannelBuilder's public methods rather than resorting to NettyChannelBuilder's custom extensions. We needed those extensions back in the alpn_boot days, but don't really need them anymore. We can't use ManagedChannelBuilder.forAddress() yet, because it doesn't seem to work in shaded environments. | bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableSession.java | Use the ManagedChannelBuilder public API. (#1295) | <ide><path>igtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableSession.java
<ide>
<ide> import io.grpc.ClientInterceptor;
<ide> import io.grpc.ManagedChannel;
<add>import io.grpc.ManagedChannelBuilder;
<ide> import io.grpc.internal.DnsNameResolverProvider;
<ide> import io.grpc.internal.GrpcUtil;
<del>import io.grpc.netty.GrpcSslContexts;
<del>import io.grpc.netty.NegotiationType;
<ide> import io.grpc.netty.NettyChannelBuilder;
<del>import io.netty.handler.ssl.OpenSsl;
<del>import io.netty.handler.ssl.SslContext;
<del>import io.netty.handler.ssl.SslContextBuilder;
<ide> import io.netty.util.Recycler;
<ide>
<ide> /**
<ide>
<ide> private static ChannelPool cachedDataChannelPool = null;
<ide> private static final Logger LOG = new Logger(BigtableSession.class);
<del> private static SslContextBuilder sslBuilder;
<ide> private static ResourceLimiter resourceLimiter;
<ide>
<ide> // 256 MB, server has 256 MB limit.
<ide> private final static int MAX_MESSAGE_SIZE = 1 << 28;
<del>
<del> // 1 MB -- TODO(sduskis): make this configurable
<del> private final static int FLOW_CONTROL_WINDOW = 1 << 20;
<ide>
<ide> @VisibleForTesting
<ide> static final String PROJECT_ID_EMPTY_OR_NULL = "ProjectId must not be empty or null.";
<ide> }
<ide> }
<ide>
<del> private synchronized static SslContext createSslContext() throws SSLException {
<del> if (sslBuilder == null) {
<del> sslBuilder = GrpcSslContexts.forClient().ciphers(null);
<del> }
<del> return sslBuilder.build();
<del> }
<del>
<ide> private static void performWarmup() {
<ide> // Initialize some core dependencies in parallel. This can speed up startup by 150+ ms.
<ide> ExecutorService connectionStartupExecutor = Executors
<ide> .newCachedThreadPool(GrpcUtil.getThreadFactory("BigtableSession-startup-%d", true));
<ide>
<del> connectionStartupExecutor.execute(new Runnable() {
<del> @Override
<del> public void run() {
<del> // The first invocation of createSslContext() is expensive.
<del> // Create a throw away object in order to speed up the creation of the first
<del> // BigtableConnection which uses SslContexts under the covers.
<del> try {
<del> // We create multiple channels via refreshing and pooling channel implementation.
<del> // Each one needs its own SslContext.
<del> createSslContext();
<del> } catch (SSLException e) {
<del> LOG.warn("Could not asynchronously create the ssl context", e);
<del> }
<del> }
<del> });
<ide> connectionStartupExecutor.execute(new Runnable() {
<ide> @Override
<ide> public void run() {
<ide> */
<ide> public static ManagedChannel createNettyChannel(String host,
<ide> BigtableOptions options, ClientInterceptor ... interceptors) throws SSLException {
<del> NegotiationType negotiationType = options.usePlaintextNegotiation() ?
<del> NegotiationType.PLAINTEXT : NegotiationType.TLS;
<del> return NettyChannelBuilder
<del> .forAddress(host, options.getPort())
<add>
<add> // Ideally, this should be ManagedChannelBuilder.forAddress(...) rather than an explicit
<add> // call to NettyChannelBuilder. Unfortunately, that doesn't work for shaded artifacts.
<add> ManagedChannelBuilder<?> builder = NettyChannelBuilder.forAddress(host, options.getPort());
<add> if (options.usePlaintextNegotiation()) {
<add> builder.usePlaintext(true);
<add> }
<add> return builder
<ide> .nameResolverFactory(new DnsNameResolverProvider())
<ide> .idleTimeout(Long.MAX_VALUE, TimeUnit.SECONDS)
<ide> .maxInboundMessageSize(MAX_MESSAGE_SIZE)
<del> .sslContext(createSslContext())
<del> .negotiationType(negotiationType)
<ide> .userAgent(BigtableVersionInfo.CORE_UESR_AGENT + "," + options.getUserAgent())
<del> .flowControlWindow(FLOW_CONTROL_WINDOW)
<ide> .intercept(interceptors)
<ide> .build();
<ide> } |
|
Java | apache-2.0 | de009036b8f2159f94038038315c3850e98b105a | 0 | Rodneyxr/eventplanner | package cs3773.com.eventplanner.activities;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.LogInCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
import cs3773.com.eventplanner.R;
import cs3773.com.eventplanner.controller.Tools;
import cs3773.com.eventplanner.model.Message;
import cs3773.com.eventplanner.model.Session;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends Activity {
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
//parse Login
private String userName;
private String password;
// UI references.
private AutoCompleteTextView mUsernameView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//parse
userName = "ParseUser";
password = "wg498nodpf228hg";
// Set up the login form.
mUsernameView = (AutoCompleteTextView) findViewById(R.id.email);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
parseCreateUser();
parseLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
public void parseCreateUser() {
//CREATE PARSE USER
ParseUser user = new ParseUser();
user.setUsername("ParseUser");
user.setPassword("wg498nodpf228hg");
user.setEmail("[email protected]");
//Add Parse USER
user.signUpInBackground(new SignUpCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
//we are good!
Toast.makeText(getApplicationContext(), "Parse is up and Running", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Parse Connected.(ERROR !)", Toast.LENGTH_LONG).show();
}
}
});
}
public void parseLogin() {
String uName = userName;
String pWord = password;
if (!uName.equals("") || !pWord.equals("")) {
ParseUser.logInInBackground(uName, pWord, new LogInCallback() {
@Override
public void done(ParseUser parseUser, ParseException e) {
if (e == null) {
Toast.makeText(getApplicationContext(), "Login Successfully!"
, Toast.LENGTH_LONG).show();
//startActivity(new Intent(LoginActivity.this, ChatActivity.class));
} else {
Toast.makeText(getApplicationContext(), "Not logged in",
Toast.LENGTH_LONG).show();
}
}
});
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mUsernameView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String username = mUsernameView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
String message;
if ((message = isPasswordValid(password)) != null) {
mPasswordView.setError(message);
focusView = mPasswordView;
cancel = true;
}
// Check for a valid username.
if ((message = isUsernameValid(username)) != null) {
mUsernameView.setError(message);
focusView = mUsernameView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask();
mAuthTask.execute(username, password);
}
}
private String isUsernameValid(String username) {
if (username.length() < 5)
return "This username must be at least 5 characters";
if (username.length() > 20)
return "This username must be less than 20 characters";
if (!username.matches("[a-zA-Z0-9_]{5,20}"))
return "This username is invalid";
return null;
}
private String isPasswordValid(String password) {
if (password.length() < 5)
return "This password must be at least 5 characters";
if (password.length() > 20)
return "This password must be less than 20 characters";
return null;
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<String, Void, Boolean> {
UserLoginTask() {
}
@Override
protected Boolean doInBackground(String... params) {
// if (true) return true; // temporary to avoid accessing server
String username = params[0];
String password = params[1];
password = Tools.sha256Base64(password);
return Session.setAccount(username, password);
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
Intent menuIntent = new Intent(LoginActivity.this, CalendarActivity.class);
startActivity(menuIntent);
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
| app/src/main/java/cs3773/com/eventplanner/activities/LoginActivity.java | package cs3773.com.eventplanner.activities;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.LogInCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
import cs3773.com.eventplanner.R;
import cs3773.com.eventplanner.controller.Tools;
import cs3773.com.eventplanner.model.Message;
import cs3773.com.eventplanner.model.Session;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends Activity {
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
//Parse Keys
public static final String APP_KEY_ID = "rcOmi6CtnvAiirDXzxycyvpV9286NQFzLGpCdE8L";
public static final String APP_CLIENT_ID = "jJna9Mx1osBR8chefTVg4fzOpTGFjAIUI0DAYf7W";
//parse Login
private String userName;
private String password;
// UI references.
private AutoCompleteTextView mUsernameView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Parse.enableLocalDatastore(this);
ParseObject.registerSubclass(Message.class);
Parse.initialize(this, APP_KEY_ID, APP_CLIENT_ID);
//parse
userName = "ParseUser";
password = "wg498nodpf228hg";
// Set up the login form.
mUsernameView = (AutoCompleteTextView) findViewById(R.id.email);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
parseCreateUser();
parseLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
public void parseCreateUser() {
//CREATE PARSE USER
ParseUser user = new ParseUser();
user.setUsername("ParseUser");
user.setPassword("wg498nodpf228hg");
user.setEmail("[email protected]");
//Add Parse USER
user.signUpInBackground(new SignUpCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
//we are good!
Toast.makeText(getApplicationContext(), "Parse is up and Running", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Parse Connected.(ERROR !)", Toast.LENGTH_LONG).show();
}
}
});
}
public void parseLogin() {
String uName = userName;
String pWord = password;
if (!uName.equals("") || !pWord.equals("")) {
ParseUser.logInInBackground(uName, pWord, new LogInCallback() {
@Override
public void done(ParseUser parseUser, ParseException e) {
if (e == null) {
Toast.makeText(getApplicationContext(), "Login Successfully!"
, Toast.LENGTH_LONG).show();
//startActivity(new Intent(LoginActivity.this, ChatActivity.class));
} else {
Toast.makeText(getApplicationContext(), "Not logged in",
Toast.LENGTH_LONG).show();
}
}
});
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mUsernameView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String username = mUsernameView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
String message;
if ((message = isPasswordValid(password)) != null) {
mPasswordView.setError(message);
focusView = mPasswordView;
cancel = true;
}
// Check for a valid username.
if ((message = isUsernameValid(username)) != null) {
mUsernameView.setError(message);
focusView = mUsernameView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask();
mAuthTask.execute(username, password);
}
}
private String isUsernameValid(String username) {
if (username.length() < 5)
return "This username must be at least 5 characters";
if (username.length() > 20)
return "This username must be less than 20 characters";
if (!username.matches("[a-zA-Z0-9_]{5,20}"))
return "This username is invalid";
return null;
}
private String isPasswordValid(String password) {
if (password.length() < 5)
return "This password must be at least 5 characters";
if (password.length() > 20)
return "This password must be less than 20 characters";
return null;
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<String, Void, Boolean> {
UserLoginTask() {
}
@Override
protected Boolean doInBackground(String... params) {
// if (true) return true; // temporary to avoid accessing server
String username = params[0];
String password = params[1];
password = Tools.sha256Base64(password);
return Session.setAccount(username, password);
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
Intent menuIntent = new Intent(LoginActivity.this, CalendarActivity.class);
startActivity(menuIntent);
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
| Chat logout error fixed
| app/src/main/java/cs3773/com/eventplanner/activities/LoginActivity.java | Chat logout error fixed | <ide><path>pp/src/main/java/cs3773/com/eventplanner/activities/LoginActivity.java
<ide> */
<ide> private UserLoginTask mAuthTask = null;
<ide>
<del> //Parse Keys
<del> public static final String APP_KEY_ID = "rcOmi6CtnvAiirDXzxycyvpV9286NQFzLGpCdE8L";
<del> public static final String APP_CLIENT_ID = "jJna9Mx1osBR8chefTVg4fzOpTGFjAIUI0DAYf7W";
<ide> //parse Login
<ide> private String userName;
<ide> private String password;
<ide> protected void onCreate(Bundle savedInstanceState) {
<ide> super.onCreate(savedInstanceState);
<ide> setContentView(R.layout.activity_login);
<del> Parse.enableLocalDatastore(this);
<del> ParseObject.registerSubclass(Message.class);
<del> Parse.initialize(this, APP_KEY_ID, APP_CLIENT_ID);
<ide>
<ide> //parse
<ide> userName = "ParseUser"; |
|
Java | mit | e6034e78481ea7603010fccb4a909071634ce2cd | 0 | bcgit/bc-java,bcgit/bc-java,bcgit/bc-java | package org.bouncycastle.jsse.provider;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContextSpi;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;
import org.bouncycastle.jcajce.util.JcaJceHelper;
import org.bouncycastle.jsse.BCX509ExtendedTrustManager;
import org.bouncycastle.jsse.java.security.BCAlgorithmConstraints;
import org.bouncycastle.jsse.java.security.BCCryptoPrimitive;
import org.bouncycastle.tls.CipherSuite;
import org.bouncycastle.tls.ProtocolVersion;
import org.bouncycastle.tls.TlsUtils;
import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCrypto;
import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCryptoProvider;
class ProvSSLContextSpi
extends SSLContextSpi
{
private static final Logger LOG = Logger.getLogger(ProvSSLContextSpi.class.getName());
private static final String PROPERTY_CLIENT_PROTOCOLS = "jdk.tls.client.protocols";
private static final String PROPERTY_SERVER_PROTOCOLS = "jdk.tls.server.protocols";
private static final Set<BCCryptoPrimitive> TLS_CRYPTO_PRIMITIVES_BC = JsseUtils.KEY_AGREEMENT_CRYPTO_PRIMITIVES_BC;
/*
* TODO[jsse] Should separate this into "understood" cipher suite int<->String maps
* and a Set of supported cipher suite values, so we can cover TLS_NULL_WITH_NULL_NULL and
* the SCSV values.
*/
private static final Map<String, CipherSuiteInfo> SUPPORTED_CIPHERSUITE_MAP = createSupportedCipherSuiteMap();
private static final Map<String, CipherSuiteInfo> SUPPORTED_CIPHERSUITE_MAP_FIPS = createSupportedCipherSuiteMapFips(SUPPORTED_CIPHERSUITE_MAP);
private static final Map<String, ProtocolVersion> SUPPORTED_PROTOCOL_MAP = createSupportedProtocolMap();
private static final Map<String, ProtocolVersion> SUPPORTED_PROTOCOL_MAP_FIPS = createSupportedProtocolMapFips(SUPPORTED_PROTOCOL_MAP);
private static final List<String> DEFAULT_CIPHERSUITE_LIST = createDefaultCipherSuiteList(SUPPORTED_CIPHERSUITE_MAP.keySet());
private static final List<String> DEFAULT_CIPHERSUITE_LIST_FIPS = createDefaultCipherSuiteListFips(DEFAULT_CIPHERSUITE_LIST);
// private static final String[] DEFAULT_ENABLED_PROTOCOLS = BouncyCastleJsseProvider.PROVIDER_TLS13_ENABLED
// ? new String[]{ "TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1" }
// : new String[]{ "TLSv1.2", "TLSv1.1", "TLSv1" };
private static final String[] DEFAULT_ENABLED_PROTOCOLS = new String[]{ "TLSv1.2", "TLSv1.1", "TLSv1" };
private static void addCipherSuite(Map<String, CipherSuiteInfo> cs, String name, int cipherSuite)
{
CipherSuiteInfo cipherSuiteInfo = CipherSuiteInfo.forCipherSuite(cipherSuite, name);
if (null != cs.put(name, cipherSuiteInfo))
{
throw new IllegalStateException("Duplicate names in supported-cipher-suites");
}
}
private static List<String> createDefaultCipherSuiteList(Set<String> supportedCipherSuiteSet)
{
ArrayList<String> cs = new ArrayList<String>();
if (BouncyCastleJsseProvider.PROVIDER_TLS13_ENABLED)
{
cs.add("TLS_CHACHA20_POLY1305_SHA256");
cs.add("TLS_AES_256_GCM_SHA384");
cs.add("TLS_AES_128_GCM_SHA256");
}
cs.add("TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256");
cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384");
cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256");
cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384");
cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256");
cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA");
cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA");
cs.add("TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256");
cs.add("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384");
cs.add("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
cs.add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384");
cs.add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256");
cs.add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA");
cs.add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA");
cs.add("TLS_RSA_WITH_AES_256_GCM_SHA384");
cs.add("TLS_RSA_WITH_AES_128_GCM_SHA256");
cs.add("TLS_RSA_WITH_AES_256_CBC_SHA256");
cs.add("TLS_RSA_WITH_AES_128_CBC_SHA256");
cs.add("TLS_RSA_WITH_AES_256_CBC_SHA");
cs.add("TLS_RSA_WITH_AES_128_CBC_SHA");
cs.retainAll(supportedCipherSuiteSet);
cs.trimToSize();
return Collections.unmodifiableList(cs);
}
private static List<String> createDefaultCipherSuiteListFips(List<String> defaultCipherSuiteList)
{
ArrayList<String> cs = new ArrayList<String>(defaultCipherSuiteList);
FipsUtils.removeNonFipsCipherSuites(cs);
cs.trimToSize();
return Collections.unmodifiableList(cs);
}
private static Map<String, CipherSuiteInfo> createSupportedCipherSuiteMap()
{
Map<String, CipherSuiteInfo> cs = new TreeMap<String, CipherSuiteInfo>();
if (BouncyCastleJsseProvider.PROVIDER_TLS13_ENABLED)
{
addCipherSuite(cs, "TLS_AES_128_CCM_8_SHA256", CipherSuite.TLS_AES_128_CCM_8_SHA256);
addCipherSuite(cs, "TLS_AES_128_CCM_SHA256", CipherSuite.TLS_AES_128_CCM_SHA256);
addCipherSuite(cs, "TLS_AES_128_GCM_SHA256", CipherSuite.TLS_AES_128_GCM_SHA256);
addCipherSuite(cs, "TLS_AES_256_GCM_SHA384", CipherSuite.TLS_AES_256_GCM_SHA384);
addCipherSuite(cs, "TLS_CHACHA20_POLY1305_SHA256", CipherSuite.TLS_CHACHA20_POLY1305_SHA256);
}
addCipherSuite(cs, "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA);
addCipherSuite(cs, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA);
addCipherSuite(cs, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256);
addCipherSuite(cs, "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256);
addCipherSuite(cs, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA);
addCipherSuite(cs, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256);
addCipherSuite(cs, "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA", CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_128_CCM", CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_128_CCM_8", CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_256_CCM", CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_256_CCM_8", CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256", CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA", CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_NULL_SHA", CipherSuite.TLS_ECDHE_ECDSA_WITH_NULL_SHA);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_NULL_SHA", CipherSuite.TLS_ECDHE_RSA_WITH_NULL_SHA);
addCipherSuite(cs, "TLS_RSA_WITH_3DES_EDE_CBC_SHA", CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA);
addCipherSuite(cs, "TLS_RSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA);
addCipherSuite(cs, "TLS_RSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256);
addCipherSuite(cs, "TLS_RSA_WITH_AES_128_CCM", CipherSuite.TLS_RSA_WITH_AES_128_CCM);
addCipherSuite(cs, "TLS_RSA_WITH_AES_128_CCM_8", CipherSuite.TLS_RSA_WITH_AES_128_CCM_8);
addCipherSuite(cs, "TLS_RSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256);
addCipherSuite(cs, "TLS_RSA_WITH_AES_256_CBC_SHA", CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA);
addCipherSuite(cs, "TLS_RSA_WITH_AES_256_CBC_SHA256", CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256);
addCipherSuite(cs, "TLS_RSA_WITH_AES_256_CCM", CipherSuite.TLS_RSA_WITH_AES_256_CCM);
addCipherSuite(cs, "TLS_RSA_WITH_AES_256_CCM_8", CipherSuite.TLS_RSA_WITH_AES_256_CCM_8);
addCipherSuite(cs, "TLS_RSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384);
addCipherSuite(cs, "TLS_RSA_WITH_NULL_SHA", CipherSuite.TLS_RSA_WITH_NULL_SHA);
addCipherSuite(cs, "TLS_RSA_WITH_NULL_SHA256", CipherSuite.TLS_RSA_WITH_NULL_SHA256);
return Collections.unmodifiableMap(cs);
}
private static Map<String, CipherSuiteInfo> createSupportedCipherSuiteMapFips(
Map<String, CipherSuiteInfo> supportedCipherSuiteMap)
{
final Map<String, CipherSuiteInfo> cs = new LinkedHashMap<String, CipherSuiteInfo>(supportedCipherSuiteMap);
FipsUtils.removeNonFipsCipherSuites(cs.keySet());
return Collections.unmodifiableMap(cs);
}
private static Map<String, ProtocolVersion> createSupportedProtocolMap()
{
Map<String, ProtocolVersion> ps = new LinkedHashMap<String, ProtocolVersion>();
if (BouncyCastleJsseProvider.PROVIDER_TLS13_ENABLED)
{
ps.put("TLSv1.3", ProtocolVersion.TLSv13);
}
ps.put("TLSv1.2", ProtocolVersion.TLSv12);
ps.put("TLSv1.1", ProtocolVersion.TLSv11);
ps.put("TLSv1", ProtocolVersion.TLSv10);
ps.put("SSLv3", ProtocolVersion.SSLv3);
return Collections.unmodifiableMap(ps);
}
private static Map<String, ProtocolVersion> createSupportedProtocolMapFips(
Map<String, ProtocolVersion> supportedProtocolMap)
{
final Map<String, ProtocolVersion> ps = new LinkedHashMap<String, ProtocolVersion>(supportedProtocolMap);
FipsUtils.removeNonFipsProtocols(ps.keySet());
return Collections.unmodifiableMap(ps);
}
private static String[] getDefaultEnabledCipherSuites(boolean isInFipsMode)
{
/*
* TODO[jsse] SunJSSE also filters this initial list based on the default protocol versions.
*/
List<String> candidates = isInFipsMode ? DEFAULT_CIPHERSUITE_LIST_FIPS : DEFAULT_CIPHERSUITE_LIST;
String[] result = new String[candidates.size()];
int count = 0;
for (String candidate : candidates)
{
if (ProvAlgorithmConstraints.DEFAULT.permits(TLS_CRYPTO_PRIMITIVES_BC, candidate, null))
{
result[count++] = candidate;
}
}
return JsseUtils.resize(result, count);
}
private static String[] getDefaultEnabledProtocolCandidates(String[] specifiedProtocols,
String protocolsPropertyName)
{
if (specifiedProtocols != null)
{
return specifiedProtocols;
}
String[] propertyProtocols = getJdkTlsProtocols(protocolsPropertyName);
if (propertyProtocols != null)
{
return propertyProtocols;
}
return DEFAULT_ENABLED_PROTOCOLS;
}
private static String[] getDefaultEnabledProtocols(Map<String, ProtocolVersion> supportedProtocols,
String[] specifiedProtocols, String protocolsPropertyName)
{
String[] candidates = getDefaultEnabledProtocolCandidates(specifiedProtocols, protocolsPropertyName);
String[] result = new String[candidates.length];
int count = 0;
for (String candidate : candidates)
{
if (!supportedProtocols.containsKey(candidate))
{
continue;
}
if (!ProvAlgorithmConstraints.DEFAULT_TLS_ONLY.permits(TLS_CRYPTO_PRIMITIVES_BC, candidate, null))
{
continue;
}
result[count++] = candidate;
}
return JsseUtils.resize(result, count);
}
private static String[] getDefaultEnabledProtocolsClient(Map<String, ProtocolVersion> supportedProtocols,
String[] specifiedProtocols)
{
return getDefaultEnabledProtocols(supportedProtocols, specifiedProtocols, PROPERTY_CLIENT_PROTOCOLS);
}
private static String[] getDefaultEnabledProtocolsServer(Map<String, ProtocolVersion> supportedProtocols)
{
return getDefaultEnabledProtocols(supportedProtocols, null, PROPERTY_SERVER_PROTOCOLS);
}
private static String[] getJdkTlsProtocols(String protocolsPropertyName)
{
String[] protocols = PropertyUtils.getStringArraySystemProperty(protocolsPropertyName);
if (null == protocols)
{
return null;
}
String[] result = new String[protocols.length];
int count = 0;
for (String protocol : protocols)
{
if (!SUPPORTED_PROTOCOL_MAP.containsKey(protocol))
{
LOG.warning("'" + protocolsPropertyName + "' contains unsupported protocol: " + protocol);
}
else if (!JsseUtils.contains(result, protocol))
{
result[count++] = protocol;
}
}
if (count < 1)
{
LOG.severe("'" + protocolsPropertyName + "' contained no supported protocol values (ignoring)");
return null;
}
return JsseUtils.resize(result, count);
}
private static String[] getArray(Collection<String> c)
{
return c.toArray(new String[c.size()]);
}
private static String[] getKeysArray(Map<String, ?> m)
{
return getArray(m.keySet());
}
static CipherSuiteInfo getCipherSuiteInfo(String cipherSuiteName)
{
return SUPPORTED_CIPHERSUITE_MAP.get(cipherSuiteName);
}
static String getCipherSuiteName(int cipherSuite)
{
// TODO[jsse] Place into "understood" cipher suite map
if (CipherSuite.TLS_NULL_WITH_NULL_NULL == cipherSuite)
{
return "SSL_NULL_WITH_NULL_NULL";
}
if (TlsUtils.isValidUint16(cipherSuite))
{
// TODO[jsse] Add CipherSuiteInfo index by 'int'
for (CipherSuiteInfo cipherSuiteInfo : SUPPORTED_CIPHERSUITE_MAP.values())
{
if (cipherSuiteInfo.getCipherSuite() == cipherSuite)
{
return cipherSuiteInfo.getName();
}
}
}
return null;
}
static KeyManager[] getDefaultKeyManagers() throws Exception
{
KeyStoreConfig keyStoreConfig = ProvKeyManagerFactorySpi.getDefaultKeyStore();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStoreConfig.keyStore, keyStoreConfig.password);
return kmf.getKeyManagers();
}
static TrustManager[] getDefaultTrustManagers() throws Exception
{
KeyStore trustStore = ProvTrustManagerFactorySpi.getDefaultTrustStore();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
return tmf.getTrustManagers();
}
static ProtocolVersion getProtocolVersion(String protocolVersionName)
{
return SUPPORTED_PROTOCOL_MAP.get(protocolVersionName);
}
static String getProtocolVersionName(ProtocolVersion protocolVersion)
{
if (null != protocolVersion)
{
for (Map.Entry<String, ProtocolVersion> entry : SUPPORTED_PROTOCOL_MAP.entrySet())
{
if (entry.getValue().equals(protocolVersion))
{
return entry.getKey();
}
}
}
return "NONE";
}
protected final boolean isInFipsMode;
protected final JcaTlsCryptoProvider cryptoProvider;
protected final Map<String, CipherSuiteInfo> supportedCipherSuites;
protected final Map<String, ProtocolVersion> supportedProtocols;
protected final String[] defaultCipherSuites;
protected final String[] defaultProtocolsClient;
protected final String[] defaultProtocolsServer;
private ContextData contextData = null;
ProvSSLContextSpi(boolean isInFipsMode, JcaTlsCryptoProvider cryptoProvider, String[] specifiedProtocolsClient)
{
this.isInFipsMode = isInFipsMode;
this.cryptoProvider = cryptoProvider;
this.supportedCipherSuites = isInFipsMode ? SUPPORTED_CIPHERSUITE_MAP_FIPS : SUPPORTED_CIPHERSUITE_MAP;
this.supportedProtocols = isInFipsMode ? SUPPORTED_PROTOCOL_MAP_FIPS : SUPPORTED_PROTOCOL_MAP;
this.defaultCipherSuites = getDefaultEnabledCipherSuites(isInFipsMode);
this.defaultProtocolsClient = getDefaultEnabledProtocolsClient(supportedProtocols, specifiedProtocolsClient);
this.defaultProtocolsServer = getDefaultEnabledProtocolsServer(supportedProtocols);
}
int[] getActiveCipherSuites(JcaTlsCrypto crypto, ProvSSLParameters sslParameters,
ProtocolVersion[] activeProtocolVersions)
{
String[] enabledCipherSuites = sslParameters.getCipherSuitesArray();
BCAlgorithmConstraints algorithmConstraints = sslParameters.getAlgorithmConstraints();
int[] candidates = new int[enabledCipherSuites.length];
int count = 0;
for (String enabledCipherSuite : enabledCipherSuites)
{
CipherSuiteInfo candidate = supportedCipherSuites.get(enabledCipherSuite);
if (null == candidate)
{
continue;
}
if (!algorithmConstraints.permits(TLS_CRYPTO_PRIMITIVES_BC, enabledCipherSuite, null))
{
continue;
}
/*
* TODO[jsse] SunJSSE also checks that the cipher suite is usable for at least one of
* the active protocol versions. Also, if the cipher suite involves a key exchange,
* there must be at least one suitable NamedGroup available.
*/
candidates[count++] = candidate.getCipherSuite();
}
int[] result = TlsUtils.getSupportedCipherSuites(crypto, candidates, count);
if (result.length < 1)
{
// TODO[jsse] Refactor so that this can be an SSLHandshakeException?
throw new IllegalStateException("No usable cipher suites enabled");
}
return result;
}
ProtocolVersion[] getActiveProtocolVersions(ProvSSLParameters sslParameters)
{
// String[] enabledCipherSuites = sslParameters.getCipherSuitesArray();
String[] enabledProtocols = sslParameters.getProtocolsArray();
BCAlgorithmConstraints algorithmConstraints = sslParameters.getAlgorithmConstraints();
SortedSet<ProtocolVersion> result = new TreeSet<ProtocolVersion>(new Comparator<ProtocolVersion>(){
public int compare(ProtocolVersion o1, ProtocolVersion o2)
{
return o1.isLaterVersionOf(o2) ? -1 : o2.isLaterVersionOf(o1) ? 1 : 0;
}
});
for (String enabledProtocol : enabledProtocols)
{
ProtocolVersion candidate = supportedProtocols.get(enabledProtocol);
if (null == candidate)
{
continue;
}
if (!algorithmConstraints.permits(TLS_CRYPTO_PRIMITIVES_BC, enabledProtocol, null))
{
continue;
}
/*
* TODO[jsse] SunJSSE also checks that there is at least one "activatable" cipher suite
* that could be used for this protocol version.
*/
result.add(candidate);
}
if (result.isEmpty())
{
// TODO[jsse] Refactor so that this can be an SSLHandshakeException?
throw new IllegalStateException("No usable protocols enabled");
}
return result.toArray(new ProtocolVersion[result.size()]);
}
String[] getDefaultCipherSuites(boolean isClient)
{
return implGetDefaultCipherSuites(isClient).clone();
}
String[] getDefaultProtocols(boolean isClient)
{
return implGetDefaultProtocols(isClient).clone();
}
ProvSSLParameters getDefaultSSLParameters(boolean isClient)
{
return new ProvSSLParameters(this, implGetDefaultCipherSuites(isClient), implGetDefaultProtocols(isClient));
}
String[] getSupportedCipherSuites()
{
return getKeysArray(supportedCipherSuites);
}
String[] getSupportedCipherSuites(String[] cipherSuites)
{
if (null == cipherSuites)
{
throw new NullPointerException("'cipherSuites' cannot be null");
}
ArrayList<String> result = new ArrayList<String>(cipherSuites.length);
for (String cipherSuite : cipherSuites)
{
if (null == cipherSuite || cipherSuite.length() < 1)
{
throw new IllegalArgumentException("'cipherSuites' cannot contain null or empty string elements");
}
if (supportedCipherSuites.containsKey(cipherSuite))
{
result.add(cipherSuite);
}
}
// NOTE: This method must always return a copy, so no fast path when all supported
return getArray(result);
}
String[] getSupportedProtocols()
{
return getKeysArray(supportedProtocols);
}
ProvSSLParameters getSupportedSSLParameters(boolean isClient)
{
return new ProvSSLParameters(this, getSupportedCipherSuites(), getSupportedProtocols());
}
boolean isFips()
{
return isInFipsMode;
}
boolean isSupportedProtocols(String[] protocols)
{
if (protocols == null)
{
return false;
}
for (String protocol : protocols)
{
if (protocol == null || !supportedProtocols.containsKey(protocol))
{
return false;
}
}
return true;
}
void updateDefaultSSLParameters(ProvSSLParameters sslParameters, boolean isClient)
{
if (sslParameters.getCipherSuitesArray() == implGetDefaultCipherSuites(!isClient))
{
sslParameters.setCipherSuitesArray(implGetDefaultCipherSuites(isClient));
}
if (sslParameters.getProtocolsArray() == implGetDefaultProtocols(!isClient))
{
sslParameters.setProtocolsArray(implGetDefaultProtocols(isClient));
}
}
String validateNegotiatedCipherSuite(ProvSSLParameters sslParameters, int cipherSuite)
{
// NOTE: The redundancy among these various checks is intentional
String name = getCipherSuiteName(cipherSuite);
if (null == name
|| !JsseUtils.contains(sslParameters.getCipherSuitesArray(), name)
|| !sslParameters.getAlgorithmConstraints().permits(TLS_CRYPTO_PRIMITIVES_BC, name, null)
|| !supportedCipherSuites.containsKey(name)
|| (isInFipsMode && !FipsUtils.isFipsCipherSuite(name)))
{
throw new IllegalStateException("SSL connection negotiated unsupported ciphersuite: " + cipherSuite);
}
return name;
}
String validateNegotiatedProtocol(ProvSSLParameters sslParameters, ProtocolVersion protocol)
{
// NOTE: The redundancy among these various checks is intentional
String name = getProtocolVersionName(protocol);
if (null == name
|| !JsseUtils.contains(sslParameters.getProtocolsArray(), name)
|| !sslParameters.getAlgorithmConstraints().permits(TLS_CRYPTO_PRIMITIVES_BC, name, null)
|| !supportedProtocols.containsKey(name)
|| (isInFipsMode && !FipsUtils.isFipsProtocol(name)))
{
throw new IllegalStateException("SSL connection negotiated unsupported protocol: " + protocol);
}
return name;
}
@Override
protected synchronized SSLEngine engineCreateSSLEngine()
{
return SSLEngineUtil.create(getContextData());
}
@Override
protected synchronized SSLEngine engineCreateSSLEngine(String host, int port)
{
return SSLEngineUtil.create(getContextData(), host, port);
}
@Override
protected synchronized SSLSessionContext engineGetClientSessionContext()
{
return getContextData().getClientSessionContext();
}
@Override
protected synchronized SSLSessionContext engineGetServerSessionContext()
{
return getContextData().getServerSessionContext();
}
@Override
protected SSLServerSocketFactory engineGetServerSocketFactory()
{
return new ProvSSLServerSocketFactory(getContextData());
}
@Override
protected SSLSocketFactory engineGetSocketFactory()
{
return new ProvSSLSocketFactory(getContextData());
}
// An SSLContextSpi method from JDK 6
protected SSLParameters engineGetDefaultSSLParameters()
{
// Fail if uninitialized
getContextData();
// Implicitly for a client socket
return SSLParametersUtil.getSSLParameters(getDefaultSSLParameters(true));
}
// An SSLContextSpi method from JDK 6
protected SSLParameters engineGetSupportedSSLParameters()
{
// Fail if uninitialized
getContextData();
// Implicitly for a client socket
return SSLParametersUtil.getSSLParameters(getSupportedSSLParameters(true));
}
@Override
protected synchronized void engineInit(KeyManager[] kms, TrustManager[] tms, SecureRandom sr) throws KeyManagementException
{
this.contextData = null;
JcaTlsCrypto crypto = cryptoProvider.create(sr);
X509ExtendedKeyManager x509KeyManager = selectX509KeyManager(crypto.getHelper(), kms);
BCX509ExtendedTrustManager x509TrustManager = selectX509TrustManager(crypto.getHelper(), tms);
// Trigger (possibly expensive) RNG initialization here to avoid timeout in an actual handshake
crypto.getSecureRandom().nextInt();
this.contextData = new ContextData(this, crypto, x509KeyManager, x509TrustManager);
}
protected synchronized ContextData getContextData()
{
if (null == contextData)
{
throw new IllegalStateException("SSLContext has not been initialized.");
}
return contextData;
}
protected X509ExtendedKeyManager selectX509KeyManager(JcaJceHelper helper, KeyManager[] kms)
throws KeyManagementException
{
if (kms != null)
{
for (KeyManager km : kms)
{
if (km instanceof X509KeyManager)
{
return X509KeyManagerUtil.importX509KeyManager(helper, (X509KeyManager)km);
}
}
}
return DummyX509KeyManager.INSTANCE;
}
protected BCX509ExtendedTrustManager selectX509TrustManager(JcaJceHelper helper, TrustManager[] tms)
throws KeyManagementException
{
if (tms == null)
{
try
{
/*
* "[...] the installed security providers will be searched for the highest priority
* implementation of the appropriate factory."
*/
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init((KeyStore)null);
tms = tmf.getTrustManagers();
}
catch (Exception e)
{
LOG.log(Level.WARNING, "Failed to load default trust managers", e);
}
}
if (tms != null)
{
for (TrustManager tm : tms)
{
if (tm instanceof X509TrustManager)
{
return X509TrustManagerUtil.importX509TrustManager(helper, (X509TrustManager)tm);
}
}
}
return DummyX509TrustManager.INSTANCE;
}
private String[] implGetDefaultCipherSuites(boolean isClient)
{
return defaultCipherSuites;
}
private String[] implGetDefaultProtocols(boolean isClient)
{
return isClient ? defaultProtocolsClient : defaultProtocolsServer;
}
}
| tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLContextSpi.java | package org.bouncycastle.jsse.provider;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContextSpi;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;
import org.bouncycastle.jcajce.util.JcaJceHelper;
import org.bouncycastle.jsse.BCX509ExtendedTrustManager;
import org.bouncycastle.jsse.java.security.BCAlgorithmConstraints;
import org.bouncycastle.jsse.java.security.BCCryptoPrimitive;
import org.bouncycastle.tls.CipherSuite;
import org.bouncycastle.tls.ProtocolVersion;
import org.bouncycastle.tls.TlsUtils;
import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCrypto;
import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCryptoProvider;
class ProvSSLContextSpi
extends SSLContextSpi
{
private static final Logger LOG = Logger.getLogger(ProvSSLContextSpi.class.getName());
private static final String PROPERTY_CLIENT_PROTOCOLS = "jdk.tls.client.protocols";
private static final String PROPERTY_SERVER_PROTOCOLS = "jdk.tls.server.protocols";
private static final Set<BCCryptoPrimitive> TLS_CRYPTO_PRIMITIVES_BC = JsseUtils.KEY_AGREEMENT_CRYPTO_PRIMITIVES_BC;
/*
* TODO[jsse] Should separate this into "understood" cipher suite int<->String maps
* and a Set of supported cipher suite values, so we can cover TLS_NULL_WITH_NULL_NULL and
* the SCSV values.
*/
private static final Map<String, CipherSuiteInfo> SUPPORTED_CIPHERSUITE_MAP = createSupportedCipherSuiteMap();
private static final Map<String, CipherSuiteInfo> SUPPORTED_CIPHERSUITE_MAP_FIPS = createSupportedCipherSuiteMapFips(SUPPORTED_CIPHERSUITE_MAP);
private static final Map<String, ProtocolVersion> SUPPORTED_PROTOCOL_MAP = createSupportedProtocolMap();
private static final Map<String, ProtocolVersion> SUPPORTED_PROTOCOL_MAP_FIPS = createSupportedProtocolMapFips(SUPPORTED_PROTOCOL_MAP);
private static final List<String> DEFAULT_CIPHERSUITE_LIST = createDefaultCipherSuiteList(SUPPORTED_CIPHERSUITE_MAP.keySet());
private static final List<String> DEFAULT_CIPHERSUITE_LIST_FIPS = createDefaultCipherSuiteListFips(DEFAULT_CIPHERSUITE_LIST);
private static final String[] DEFAULT_ENABLED_PROTOCOLS = BouncyCastleJsseProvider.PROVIDER_TLS13_ENABLED
? new String[]{ "TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1" }
: new String[]{ "TLSv1.2", "TLSv1.1", "TLSv1" };
private static void addCipherSuite(Map<String, CipherSuiteInfo> cs, String name, int cipherSuite)
{
CipherSuiteInfo cipherSuiteInfo = CipherSuiteInfo.forCipherSuite(cipherSuite, name);
if (null != cs.put(name, cipherSuiteInfo))
{
throw new IllegalStateException("Duplicate names in supported-cipher-suites");
}
}
private static List<String> createDefaultCipherSuiteList(Set<String> supportedCipherSuiteSet)
{
ArrayList<String> cs = new ArrayList<String>();
if (BouncyCastleJsseProvider.PROVIDER_TLS13_ENABLED)
{
cs.add("TLS_CHACHA20_POLY1305_SHA256");
cs.add("TLS_AES_256_GCM_SHA384");
cs.add("TLS_AES_128_GCM_SHA256");
}
cs.add("TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256");
cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384");
cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256");
cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384");
cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256");
cs.add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA");
cs.add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA");
cs.add("TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256");
cs.add("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384");
cs.add("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
cs.add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384");
cs.add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256");
cs.add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA");
cs.add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA");
cs.add("TLS_RSA_WITH_AES_256_GCM_SHA384");
cs.add("TLS_RSA_WITH_AES_128_GCM_SHA256");
cs.add("TLS_RSA_WITH_AES_256_CBC_SHA256");
cs.add("TLS_RSA_WITH_AES_128_CBC_SHA256");
cs.add("TLS_RSA_WITH_AES_256_CBC_SHA");
cs.add("TLS_RSA_WITH_AES_128_CBC_SHA");
cs.retainAll(supportedCipherSuiteSet);
cs.trimToSize();
return Collections.unmodifiableList(cs);
}
private static List<String> createDefaultCipherSuiteListFips(List<String> defaultCipherSuiteList)
{
ArrayList<String> cs = new ArrayList<String>(defaultCipherSuiteList);
FipsUtils.removeNonFipsCipherSuites(cs);
cs.trimToSize();
return Collections.unmodifiableList(cs);
}
private static Map<String, CipherSuiteInfo> createSupportedCipherSuiteMap()
{
Map<String, CipherSuiteInfo> cs = new TreeMap<String, CipherSuiteInfo>();
if (BouncyCastleJsseProvider.PROVIDER_TLS13_ENABLED)
{
addCipherSuite(cs, "TLS_AES_128_CCM_8_SHA256", CipherSuite.TLS_AES_128_CCM_8_SHA256);
addCipherSuite(cs, "TLS_AES_128_CCM_SHA256", CipherSuite.TLS_AES_128_CCM_SHA256);
addCipherSuite(cs, "TLS_AES_128_GCM_SHA256", CipherSuite.TLS_AES_128_GCM_SHA256);
addCipherSuite(cs, "TLS_AES_256_GCM_SHA384", CipherSuite.TLS_AES_256_GCM_SHA384);
addCipherSuite(cs, "TLS_CHACHA20_POLY1305_SHA256", CipherSuite.TLS_CHACHA20_POLY1305_SHA256);
}
addCipherSuite(cs, "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA);
addCipherSuite(cs, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA);
addCipherSuite(cs, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256);
addCipherSuite(cs, "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256);
addCipherSuite(cs, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA);
addCipherSuite(cs, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256);
addCipherSuite(cs, "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA", CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_128_CCM", CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_128_CCM_8", CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_256_CCM", CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_256_CCM_8", CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384);
addCipherSuite(cs, "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256", CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA", CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256);
addCipherSuite(cs, "TLS_ECDHE_ECDSA_WITH_NULL_SHA", CipherSuite.TLS_ECDHE_ECDSA_WITH_NULL_SHA);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256);
addCipherSuite(cs, "TLS_ECDHE_RSA_WITH_NULL_SHA", CipherSuite.TLS_ECDHE_RSA_WITH_NULL_SHA);
addCipherSuite(cs, "TLS_RSA_WITH_3DES_EDE_CBC_SHA", CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA);
addCipherSuite(cs, "TLS_RSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA);
addCipherSuite(cs, "TLS_RSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256);
addCipherSuite(cs, "TLS_RSA_WITH_AES_128_CCM", CipherSuite.TLS_RSA_WITH_AES_128_CCM);
addCipherSuite(cs, "TLS_RSA_WITH_AES_128_CCM_8", CipherSuite.TLS_RSA_WITH_AES_128_CCM_8);
addCipherSuite(cs, "TLS_RSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256);
addCipherSuite(cs, "TLS_RSA_WITH_AES_256_CBC_SHA", CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA);
addCipherSuite(cs, "TLS_RSA_WITH_AES_256_CBC_SHA256", CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256);
addCipherSuite(cs, "TLS_RSA_WITH_AES_256_CCM", CipherSuite.TLS_RSA_WITH_AES_256_CCM);
addCipherSuite(cs, "TLS_RSA_WITH_AES_256_CCM_8", CipherSuite.TLS_RSA_WITH_AES_256_CCM_8);
addCipherSuite(cs, "TLS_RSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384);
addCipherSuite(cs, "TLS_RSA_WITH_NULL_SHA", CipherSuite.TLS_RSA_WITH_NULL_SHA);
addCipherSuite(cs, "TLS_RSA_WITH_NULL_SHA256", CipherSuite.TLS_RSA_WITH_NULL_SHA256);
return Collections.unmodifiableMap(cs);
}
private static Map<String, CipherSuiteInfo> createSupportedCipherSuiteMapFips(
Map<String, CipherSuiteInfo> supportedCipherSuiteMap)
{
final Map<String, CipherSuiteInfo> cs = new LinkedHashMap<String, CipherSuiteInfo>(supportedCipherSuiteMap);
FipsUtils.removeNonFipsCipherSuites(cs.keySet());
return Collections.unmodifiableMap(cs);
}
private static Map<String, ProtocolVersion> createSupportedProtocolMap()
{
Map<String, ProtocolVersion> ps = new LinkedHashMap<String, ProtocolVersion>();
if (BouncyCastleJsseProvider.PROVIDER_TLS13_ENABLED)
{
ps.put("TLSv1.3", ProtocolVersion.TLSv13);
}
ps.put("TLSv1.2", ProtocolVersion.TLSv12);
ps.put("TLSv1.1", ProtocolVersion.TLSv11);
ps.put("TLSv1", ProtocolVersion.TLSv10);
ps.put("SSLv3", ProtocolVersion.SSLv3);
return Collections.unmodifiableMap(ps);
}
private static Map<String, ProtocolVersion> createSupportedProtocolMapFips(
Map<String, ProtocolVersion> supportedProtocolMap)
{
final Map<String, ProtocolVersion> ps = new LinkedHashMap<String, ProtocolVersion>(supportedProtocolMap);
FipsUtils.removeNonFipsProtocols(ps.keySet());
return Collections.unmodifiableMap(ps);
}
private static String[] getDefaultEnabledCipherSuites(boolean isInFipsMode)
{
/*
* TODO[jsse] SunJSSE also filters this initial list based on the default protocol versions.
*/
List<String> candidates = isInFipsMode ? DEFAULT_CIPHERSUITE_LIST_FIPS : DEFAULT_CIPHERSUITE_LIST;
String[] result = new String[candidates.size()];
int count = 0;
for (String candidate : candidates)
{
if (ProvAlgorithmConstraints.DEFAULT.permits(TLS_CRYPTO_PRIMITIVES_BC, candidate, null))
{
result[count++] = candidate;
}
}
return JsseUtils.resize(result, count);
}
private static String[] getDefaultEnabledProtocolCandidates(String[] specifiedProtocols,
String protocolsPropertyName)
{
if (specifiedProtocols != null)
{
return specifiedProtocols;
}
String[] propertyProtocols = getJdkTlsProtocols(protocolsPropertyName);
if (propertyProtocols != null)
{
return propertyProtocols;
}
return DEFAULT_ENABLED_PROTOCOLS;
}
private static String[] getDefaultEnabledProtocols(Map<String, ProtocolVersion> supportedProtocols,
String[] specifiedProtocols, String protocolsPropertyName)
{
String[] candidates = getDefaultEnabledProtocolCandidates(specifiedProtocols, protocolsPropertyName);
String[] result = new String[candidates.length];
int count = 0;
for (String candidate : candidates)
{
if (!supportedProtocols.containsKey(candidate))
{
continue;
}
if (!ProvAlgorithmConstraints.DEFAULT_TLS_ONLY.permits(TLS_CRYPTO_PRIMITIVES_BC, candidate, null))
{
continue;
}
result[count++] = candidate;
}
return JsseUtils.resize(result, count);
}
private static String[] getDefaultEnabledProtocolsClient(Map<String, ProtocolVersion> supportedProtocols,
String[] specifiedProtocols)
{
return getDefaultEnabledProtocols(supportedProtocols, specifiedProtocols, PROPERTY_CLIENT_PROTOCOLS);
}
private static String[] getDefaultEnabledProtocolsServer(Map<String, ProtocolVersion> supportedProtocols)
{
return getDefaultEnabledProtocols(supportedProtocols, null, PROPERTY_SERVER_PROTOCOLS);
}
private static String[] getJdkTlsProtocols(String protocolsPropertyName)
{
String[] protocols = PropertyUtils.getStringArraySystemProperty(protocolsPropertyName);
if (null == protocols)
{
return null;
}
String[] result = new String[protocols.length];
int count = 0;
for (String protocol : protocols)
{
if (!SUPPORTED_PROTOCOL_MAP.containsKey(protocol))
{
LOG.warning("'" + protocolsPropertyName + "' contains unsupported protocol: " + protocol);
}
else if (!JsseUtils.contains(result, protocol))
{
result[count++] = protocol;
}
}
if (count < 1)
{
LOG.severe("'" + protocolsPropertyName + "' contained no supported protocol values (ignoring)");
return null;
}
return JsseUtils.resize(result, count);
}
private static String[] getArray(Collection<String> c)
{
return c.toArray(new String[c.size()]);
}
private static String[] getKeysArray(Map<String, ?> m)
{
return getArray(m.keySet());
}
static CipherSuiteInfo getCipherSuiteInfo(String cipherSuiteName)
{
return SUPPORTED_CIPHERSUITE_MAP.get(cipherSuiteName);
}
static String getCipherSuiteName(int cipherSuite)
{
// TODO[jsse] Place into "understood" cipher suite map
if (CipherSuite.TLS_NULL_WITH_NULL_NULL == cipherSuite)
{
return "SSL_NULL_WITH_NULL_NULL";
}
if (TlsUtils.isValidUint16(cipherSuite))
{
// TODO[jsse] Add CipherSuiteInfo index by 'int'
for (CipherSuiteInfo cipherSuiteInfo : SUPPORTED_CIPHERSUITE_MAP.values())
{
if (cipherSuiteInfo.getCipherSuite() == cipherSuite)
{
return cipherSuiteInfo.getName();
}
}
}
return null;
}
static KeyManager[] getDefaultKeyManagers() throws Exception
{
KeyStoreConfig keyStoreConfig = ProvKeyManagerFactorySpi.getDefaultKeyStore();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStoreConfig.keyStore, keyStoreConfig.password);
return kmf.getKeyManagers();
}
static TrustManager[] getDefaultTrustManagers() throws Exception
{
KeyStore trustStore = ProvTrustManagerFactorySpi.getDefaultTrustStore();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
return tmf.getTrustManagers();
}
static ProtocolVersion getProtocolVersion(String protocolVersionName)
{
return SUPPORTED_PROTOCOL_MAP.get(protocolVersionName);
}
static String getProtocolVersionName(ProtocolVersion protocolVersion)
{
if (null != protocolVersion)
{
for (Map.Entry<String, ProtocolVersion> entry : SUPPORTED_PROTOCOL_MAP.entrySet())
{
if (entry.getValue().equals(protocolVersion))
{
return entry.getKey();
}
}
}
return "NONE";
}
protected final boolean isInFipsMode;
protected final JcaTlsCryptoProvider cryptoProvider;
protected final Map<String, CipherSuiteInfo> supportedCipherSuites;
protected final Map<String, ProtocolVersion> supportedProtocols;
protected final String[] defaultCipherSuites;
protected final String[] defaultProtocolsClient;
protected final String[] defaultProtocolsServer;
private ContextData contextData = null;
ProvSSLContextSpi(boolean isInFipsMode, JcaTlsCryptoProvider cryptoProvider, String[] specifiedProtocolsClient)
{
this.isInFipsMode = isInFipsMode;
this.cryptoProvider = cryptoProvider;
this.supportedCipherSuites = isInFipsMode ? SUPPORTED_CIPHERSUITE_MAP_FIPS : SUPPORTED_CIPHERSUITE_MAP;
this.supportedProtocols = isInFipsMode ? SUPPORTED_PROTOCOL_MAP_FIPS : SUPPORTED_PROTOCOL_MAP;
this.defaultCipherSuites = getDefaultEnabledCipherSuites(isInFipsMode);
this.defaultProtocolsClient = getDefaultEnabledProtocolsClient(supportedProtocols, specifiedProtocolsClient);
this.defaultProtocolsServer = getDefaultEnabledProtocolsServer(supportedProtocols);
}
int[] getActiveCipherSuites(JcaTlsCrypto crypto, ProvSSLParameters sslParameters,
ProtocolVersion[] activeProtocolVersions)
{
String[] enabledCipherSuites = sslParameters.getCipherSuitesArray();
BCAlgorithmConstraints algorithmConstraints = sslParameters.getAlgorithmConstraints();
int[] candidates = new int[enabledCipherSuites.length];
int count = 0;
for (String enabledCipherSuite : enabledCipherSuites)
{
CipherSuiteInfo candidate = supportedCipherSuites.get(enabledCipherSuite);
if (null == candidate)
{
continue;
}
if (!algorithmConstraints.permits(TLS_CRYPTO_PRIMITIVES_BC, enabledCipherSuite, null))
{
continue;
}
/*
* TODO[jsse] SunJSSE also checks that the cipher suite is usable for at least one of
* the active protocol versions. Also, if the cipher suite involves a key exchange,
* there must be at least one suitable NamedGroup available.
*/
candidates[count++] = candidate.getCipherSuite();
}
int[] result = TlsUtils.getSupportedCipherSuites(crypto, candidates, count);
if (result.length < 1)
{
// TODO[jsse] Refactor so that this can be an SSLHandshakeException?
throw new IllegalStateException("No usable cipher suites enabled");
}
return result;
}
ProtocolVersion[] getActiveProtocolVersions(ProvSSLParameters sslParameters)
{
// String[] enabledCipherSuites = sslParameters.getCipherSuitesArray();
String[] enabledProtocols = sslParameters.getProtocolsArray();
BCAlgorithmConstraints algorithmConstraints = sslParameters.getAlgorithmConstraints();
SortedSet<ProtocolVersion> result = new TreeSet<ProtocolVersion>(new Comparator<ProtocolVersion>(){
public int compare(ProtocolVersion o1, ProtocolVersion o2)
{
return o1.isLaterVersionOf(o2) ? -1 : o2.isLaterVersionOf(o1) ? 1 : 0;
}
});
for (String enabledProtocol : enabledProtocols)
{
ProtocolVersion candidate = supportedProtocols.get(enabledProtocol);
if (null == candidate)
{
continue;
}
if (!algorithmConstraints.permits(TLS_CRYPTO_PRIMITIVES_BC, enabledProtocol, null))
{
continue;
}
/*
* TODO[jsse] SunJSSE also checks that there is at least one "activatable" cipher suite
* that could be used for this protocol version.
*/
result.add(candidate);
}
if (result.isEmpty())
{
// TODO[jsse] Refactor so that this can be an SSLHandshakeException?
throw new IllegalStateException("No usable protocols enabled");
}
return result.toArray(new ProtocolVersion[result.size()]);
}
String[] getDefaultCipherSuites(boolean isClient)
{
return implGetDefaultCipherSuites(isClient).clone();
}
String[] getDefaultProtocols(boolean isClient)
{
return implGetDefaultProtocols(isClient).clone();
}
ProvSSLParameters getDefaultSSLParameters(boolean isClient)
{
return new ProvSSLParameters(this, implGetDefaultCipherSuites(isClient), implGetDefaultProtocols(isClient));
}
String[] getSupportedCipherSuites()
{
return getKeysArray(supportedCipherSuites);
}
String[] getSupportedCipherSuites(String[] cipherSuites)
{
if (null == cipherSuites)
{
throw new NullPointerException("'cipherSuites' cannot be null");
}
ArrayList<String> result = new ArrayList<String>(cipherSuites.length);
for (String cipherSuite : cipherSuites)
{
if (null == cipherSuite || cipherSuite.length() < 1)
{
throw new IllegalArgumentException("'cipherSuites' cannot contain null or empty string elements");
}
if (supportedCipherSuites.containsKey(cipherSuite))
{
result.add(cipherSuite);
}
}
// NOTE: This method must always return a copy, so no fast path when all supported
return getArray(result);
}
String[] getSupportedProtocols()
{
return getKeysArray(supportedProtocols);
}
ProvSSLParameters getSupportedSSLParameters(boolean isClient)
{
return new ProvSSLParameters(this, getSupportedCipherSuites(), getSupportedProtocols());
}
boolean isFips()
{
return isInFipsMode;
}
boolean isSupportedProtocols(String[] protocols)
{
if (protocols == null)
{
return false;
}
for (String protocol : protocols)
{
if (protocol == null || !supportedProtocols.containsKey(protocol))
{
return false;
}
}
return true;
}
void updateDefaultSSLParameters(ProvSSLParameters sslParameters, boolean isClient)
{
if (sslParameters.getCipherSuitesArray() == implGetDefaultCipherSuites(!isClient))
{
sslParameters.setCipherSuitesArray(implGetDefaultCipherSuites(isClient));
}
if (sslParameters.getProtocolsArray() == implGetDefaultProtocols(!isClient))
{
sslParameters.setProtocolsArray(implGetDefaultProtocols(isClient));
}
}
String validateNegotiatedCipherSuite(ProvSSLParameters sslParameters, int cipherSuite)
{
// NOTE: The redundancy among these various checks is intentional
String name = getCipherSuiteName(cipherSuite);
if (null == name
|| !JsseUtils.contains(sslParameters.getCipherSuitesArray(), name)
|| !sslParameters.getAlgorithmConstraints().permits(TLS_CRYPTO_PRIMITIVES_BC, name, null)
|| !supportedCipherSuites.containsKey(name)
|| (isInFipsMode && !FipsUtils.isFipsCipherSuite(name)))
{
throw new IllegalStateException("SSL connection negotiated unsupported ciphersuite: " + cipherSuite);
}
return name;
}
String validateNegotiatedProtocol(ProvSSLParameters sslParameters, ProtocolVersion protocol)
{
// NOTE: The redundancy among these various checks is intentional
String name = getProtocolVersionName(protocol);
if (null == name
|| !JsseUtils.contains(sslParameters.getProtocolsArray(), name)
|| !sslParameters.getAlgorithmConstraints().permits(TLS_CRYPTO_PRIMITIVES_BC, name, null)
|| !supportedProtocols.containsKey(name)
|| (isInFipsMode && !FipsUtils.isFipsProtocol(name)))
{
throw new IllegalStateException("SSL connection negotiated unsupported protocol: " + protocol);
}
return name;
}
@Override
protected synchronized SSLEngine engineCreateSSLEngine()
{
return SSLEngineUtil.create(getContextData());
}
@Override
protected synchronized SSLEngine engineCreateSSLEngine(String host, int port)
{
return SSLEngineUtil.create(getContextData(), host, port);
}
@Override
protected synchronized SSLSessionContext engineGetClientSessionContext()
{
return getContextData().getClientSessionContext();
}
@Override
protected synchronized SSLSessionContext engineGetServerSessionContext()
{
return getContextData().getServerSessionContext();
}
@Override
protected SSLServerSocketFactory engineGetServerSocketFactory()
{
return new ProvSSLServerSocketFactory(getContextData());
}
@Override
protected SSLSocketFactory engineGetSocketFactory()
{
return new ProvSSLSocketFactory(getContextData());
}
// An SSLContextSpi method from JDK 6
protected SSLParameters engineGetDefaultSSLParameters()
{
// Fail if uninitialized
getContextData();
// Implicitly for a client socket
return SSLParametersUtil.getSSLParameters(getDefaultSSLParameters(true));
}
// An SSLContextSpi method from JDK 6
protected SSLParameters engineGetSupportedSSLParameters()
{
// Fail if uninitialized
getContextData();
// Implicitly for a client socket
return SSLParametersUtil.getSSLParameters(getSupportedSSLParameters(true));
}
@Override
protected synchronized void engineInit(KeyManager[] kms, TrustManager[] tms, SecureRandom sr) throws KeyManagementException
{
this.contextData = null;
JcaTlsCrypto crypto = cryptoProvider.create(sr);
X509ExtendedKeyManager x509KeyManager = selectX509KeyManager(crypto.getHelper(), kms);
BCX509ExtendedTrustManager x509TrustManager = selectX509TrustManager(crypto.getHelper(), tms);
// Trigger (possibly expensive) RNG initialization here to avoid timeout in an actual handshake
crypto.getSecureRandom().nextInt();
this.contextData = new ContextData(this, crypto, x509KeyManager, x509TrustManager);
}
protected synchronized ContextData getContextData()
{
if (null == contextData)
{
throw new IllegalStateException("SSLContext has not been initialized.");
}
return contextData;
}
protected X509ExtendedKeyManager selectX509KeyManager(JcaJceHelper helper, KeyManager[] kms)
throws KeyManagementException
{
if (kms != null)
{
for (KeyManager km : kms)
{
if (km instanceof X509KeyManager)
{
return X509KeyManagerUtil.importX509KeyManager(helper, (X509KeyManager)km);
}
}
}
return DummyX509KeyManager.INSTANCE;
}
protected BCX509ExtendedTrustManager selectX509TrustManager(JcaJceHelper helper, TrustManager[] tms)
throws KeyManagementException
{
if (tms == null)
{
try
{
/*
* "[...] the installed security providers will be searched for the highest priority
* implementation of the appropriate factory."
*/
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init((KeyStore)null);
tms = tmf.getTrustManagers();
}
catch (Exception e)
{
LOG.log(Level.WARNING, "Failed to load default trust managers", e);
}
}
if (tms != null)
{
for (TrustManager tm : tms)
{
if (tm instanceof X509TrustManager)
{
return X509TrustManagerUtil.importX509TrustManager(helper, (X509TrustManager)tm);
}
}
}
return DummyX509TrustManager.INSTANCE;
}
private String[] implGetDefaultCipherSuites(boolean isClient)
{
return defaultCipherSuites;
}
private String[] implGetDefaultProtocols(boolean isClient)
{
return isClient ? defaultProtocolsClient : defaultProtocolsServer;
}
}
| Even with tls13 "master switch", off by default
| tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLContextSpi.java | Even with tls13 "master switch", off by default | <ide><path>ls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLContextSpi.java
<ide> private static final List<String> DEFAULT_CIPHERSUITE_LIST = createDefaultCipherSuiteList(SUPPORTED_CIPHERSUITE_MAP.keySet());
<ide> private static final List<String> DEFAULT_CIPHERSUITE_LIST_FIPS = createDefaultCipherSuiteListFips(DEFAULT_CIPHERSUITE_LIST);
<ide>
<del> private static final String[] DEFAULT_ENABLED_PROTOCOLS = BouncyCastleJsseProvider.PROVIDER_TLS13_ENABLED
<del> ? new String[]{ "TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1" }
<del> : new String[]{ "TLSv1.2", "TLSv1.1", "TLSv1" };
<add>// private static final String[] DEFAULT_ENABLED_PROTOCOLS = BouncyCastleJsseProvider.PROVIDER_TLS13_ENABLED
<add>// ? new String[]{ "TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1" }
<add>// : new String[]{ "TLSv1.2", "TLSv1.1", "TLSv1" };
<add> private static final String[] DEFAULT_ENABLED_PROTOCOLS = new String[]{ "TLSv1.2", "TLSv1.1", "TLSv1" };
<ide>
<ide> private static void addCipherSuite(Map<String, CipherSuiteInfo> cs, String name, int cipherSuite)
<ide> { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.